spur-board 0.47.0 → 0.48.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/cli.mjs CHANGED
@@ -1,6 +1,6 @@
1
- import { $ as configSchema, H as ERRORS, f as roleCanUseOperation, it as SLACK_BOT_SCOPES, o as SYSTEMD_SERVICE_SETTINGS, p as OPERATIONS, r as requestHashOf, tt as requiredSecretKeys } from "./src-DGT9Wspi.mjs";
2
- import { a as CliError, c as escapeTerminalControls, i as requestTokenEnrollment, n as fetchTokenStatus, o as errorExitCode, r as requestOperation, s as renderCliError } from "./client-D8BEfeGz.mjs";
3
- import { a as memoryVerdictCache, c as loadClientConfig, d as resolveDaemonAddress, f as tokenInFolder, i as fileVerdictCache, l as loadEnrollmentConfig, n as cliPackageVersion, o as configFile, s as dataDirectory, t as checkCatalog, u as readConfiguredPort } from "./config-Chv5ZHE8.mjs";
1
+ import { $ as configSchema, H as ERRORS, f as roleCanUseOperation, it as SLACK_BOT_SCOPES, o as SYSTEMD_SERVICE_SETTINGS, p as OPERATIONS, r as requestHashOf, tt as requiredSecretKeys } from "./src-Cj3-z45G.mjs";
2
+ import { a as CliError, c as escapeTerminalControls, i as requestTokenEnrollment, n as fetchTokenStatus, o as errorExitCode, r as requestOperation, s as renderCliError } from "./client-DJ0swpg5.mjs";
3
+ import { a as memoryVerdictCache, c as loadClientConfig, d as resolveDaemonAddress, f as tokenInFolder, i as fileVerdictCache, l as loadEnrollmentConfig, n as cliPackageVersion, o as configFile, s as dataDirectory, t as checkCatalog, u as readConfiguredPort } from "./config-BMYEBQfk.mjs";
4
4
  import { createHash, randomBytes, randomUUID } from "node:crypto";
5
5
  import { accessSync, chmodSync, closeSync, constants, cpSync, existsSync, ftruncateSync, lstatSync, mkdirSync, openSync, readFileSync, readdirSync, readlinkSync, realpathSync, renameSync, rmSync, statSync, unlinkSync, writeFileSync, writeSync } from "node:fs";
6
6
  import { homedir, hostname, userInfo } from "node:os";
@@ -319,6 +319,7 @@ const remoteBaseIds = [
319
319
  "spur.api",
320
320
  "spur.send",
321
321
  "operator.path",
322
+ "operator.tokens",
322
323
  "curator.sessions"
323
324
  ];
324
325
  const remoteSlackIds = [
@@ -1,4 +1,4 @@
1
- import { G as errorEnvelopeSchema, H as ERRORS, W as errorContextSchema, g as renderJsonError, q as successEnvelopeSchema } from "./src-DGT9Wspi.mjs";
1
+ import { G as errorEnvelopeSchema, H as ERRORS, W as errorContextSchema, g as renderJsonError, q as successEnvelopeSchema } from "./src-Cj3-z45G.mjs";
2
2
  import { randomUUID } from "node:crypto";
3
3
  import { z } from "zod";
4
4
  import { request } from "node:http";
package/dist/client.mjs CHANGED
@@ -1,2 +1,2 @@
1
- import { i as requestTokenEnrollment, n as fetchTokenStatus, r as requestOperation, t as fetchCatalogVersion } from "./client-D8BEfeGz.mjs";
1
+ import { i as requestTokenEnrollment, n as fetchTokenStatus, r as requestOperation, t as fetchCatalogVersion } from "./client-DJ0swpg5.mjs";
2
2
  export { fetchCatalogVersion, fetchTokenStatus, requestOperation, requestTokenEnrollment };
@@ -1,5 +1,5 @@
1
- import { $ as configSchema, d as buildCatalogSnapshot, et as plainHttpAllowed, p as OPERATIONS } from "./src-DGT9Wspi.mjs";
2
- import { a as CliError, t as fetchCatalogVersion } from "./client-D8BEfeGz.mjs";
1
+ import { $ as configSchema, d as buildCatalogSnapshot, et as plainHttpAllowed, p as OPERATIONS } from "./src-Cj3-z45G.mjs";
2
+ import { a as CliError, t as fetchCatalogVersion } from "./client-DJ0swpg5.mjs";
3
3
  import { randomUUID } from "node:crypto";
4
4
  import { closeSync, constants, fstatSync, lstatSync, mkdirSync, openSync, readFileSync, realpathSync, renameSync, statSync, unlinkSync, writeFileSync } from "node:fs";
5
5
  import { homedir } from "node:os";
package/dist/daemon.mjs CHANGED
@@ -1,13 +1,14 @@
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-DGT9Wspi.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-Cj3-z45G.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";
5
- import { homedir } from "node:os";
5
+ import { homedir, hostname } from "node:os";
6
6
  import path, { basename, dirname, isAbsolute, join, normalize, resolve } from "node:path";
7
7
  import { z } from "zod";
8
8
  import YAML from "yaml";
9
9
  import { spawn, spawnSync } from "node:child_process";
10
10
  import { parseEnv } from "node:util";
11
+ import { lstat } from "node:fs/promises";
11
12
  import Database from "better-sqlite3";
12
13
  import { Kysely, SqliteDialect, sql } from "kysely";
13
14
  import { AsyncLocalStorage } from "node:async_hooks";
@@ -15,6 +16,7 @@ import perf_hooks from "node:perf_hooks";
15
16
  import Fastify from "fastify";
16
17
  import { pino } from "pino";
17
18
  import { WebAPIHTTPError, WebAPIPlatformError, WebAPIRateLimitedError, WebClient } from "@slack/web-api";
19
+ import { setTimeout as setTimeout$1 } from "node:timers/promises";
18
20
  import { SocketModeClient } from "@slack/socket-mode";
19
21
  //#region \0rolldown/runtime.js
20
22
  var __create = Object.create;
@@ -9212,6 +9214,10 @@ const MAX_PENDING_REQUESTS = 10;
9212
9214
  /** Days an expired or denied request stays after its decision before the daily purge drops it. */
9213
9215
  const TOKEN_REQUEST_RETENTION_DAYS = 7;
9214
9216
  const DAY_MS$1 = 864e5;
9217
+ /** An approved token's last use is written at most once per token per this interval. */
9218
+ const TOKEN_USE_INTERVAL_MS = 5 * 6e4;
9219
+ /** The longest attention line; the doctor fix limit is the same. */
9220
+ const ATTENTION_LINE_MAX = 300;
9215
9221
  function effectiveStatus(row, at) {
9216
9222
  return row.status === "pending" && row.expires_at <= at.toISOString() ? "expired" : row.status;
9217
9223
  }
@@ -9308,7 +9314,8 @@ async function decideTokenInTransaction(trx, itemId, decision, at) {
9308
9314
  const next = decision === "approve" ? "approved" : "denied";
9309
9315
  await trx.updateTable("operator_token").set({
9310
9316
  status: next,
9311
- decided_at: at.toISOString()
9317
+ decided_at: at.toISOString(),
9318
+ ...next === "approved" ? { approved_at: at.toISOString() } : {}
9312
9319
  }).where("id", "=", row.id).execute();
9313
9320
  await journalToken(trx, decision === "approve" ? "token_approved" : "token_denied", row.name, at);
9314
9321
  await clearItem(trx, row.item_id, at, "operator");
@@ -9342,11 +9349,27 @@ async function purgeEndedTokenRequests(store, at) {
9342
9349
  return Number(deleted.numDeletedRows);
9343
9350
  });
9344
9351
  }
9345
- /** Hash lookup uses the unique index and checks durable state on every call. */
9346
- async function verifyOperatorToken(store, token) {
9352
+ /**
9353
+ * Hash lookup uses the unique index and checks durable state on every call. An approved token's
9354
+ * use at `at` is recorded when its last recorded use is older than `TOKEN_USE_INTERVAL_MS`; a
9355
+ * failed write goes to `onUseError` and never changes the result.
9356
+ */
9357
+ async function verifyOperatorToken(store, token, at, onUseError) {
9347
9358
  const hash = createHash("sha256").update(token).digest("hex");
9348
- const row = await store.db.selectFrom("operator_token").select(["name", "status"]).where("hash", "=", hash).executeTakeFirst();
9349
- return row?.status === "approved" ? { name: row.name } : null;
9359
+ const row = await store.db.selectFrom("operator_token").select([
9360
+ "name",
9361
+ "status",
9362
+ "last_used_at"
9363
+ ]).where("hash", "=", hash).executeTakeFirst();
9364
+ if (row?.status !== "approved") return null;
9365
+ const usedAt = at.toISOString();
9366
+ const staleBy = (/* @__PURE__ */ new Date(at.getTime() - TOKEN_USE_INTERVAL_MS)).toISOString();
9367
+ if (row.last_used_at === null || row.last_used_at <= staleBy) try {
9368
+ 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());
9369
+ } catch (err) {
9370
+ onUseError(err);
9371
+ }
9372
+ return { name: row.name };
9350
9373
  }
9351
9374
  /** Read-only: an expired pending row is reported as expired but left for the sweep. */
9352
9375
  async function tokenStatusByHash(store, hash, at) {
@@ -9363,7 +9386,10 @@ function tokenListQuery(clock) {
9363
9386
  return { tokens: rows.map((row) => ({
9364
9387
  name: row.name,
9365
9388
  folder: row.folder,
9366
- status: effectiveStatus(row, at)
9389
+ status: effectiveStatus(row, at),
9390
+ createdAt: row.requested_at,
9391
+ approvedAt: row.approved_at,
9392
+ lastUsedAt: row.last_used_at
9367
9393
  })) };
9368
9394
  }
9369
9395
  };
@@ -9389,6 +9415,65 @@ const tokenRevokeMutation = {
9389
9415
  };
9390
9416
  }
9391
9417
  };
9418
+ /**
9419
+ * Approved tokens unused for `unusedAfterDays` days (last use, else approval, else request time)
9420
+ * or whose token file is gone. `probe` answers whether the token file is present, or null when
9421
+ * it cannot tell (another host, an unreadable folder); it runs after the read, outside any
9422
+ * transaction.
9423
+ */
9424
+ async function tokenAttention(store, at, unusedAfterDays, probe) {
9425
+ const rows = await store.db.selectFrom("operator_token").select([
9426
+ "name",
9427
+ "folder",
9428
+ "host",
9429
+ "requested_at",
9430
+ "approved_at",
9431
+ "last_used_at"
9432
+ ]).where("status", "=", "approved").orderBy("id").execute();
9433
+ const cutoff = (/* @__PURE__ */ new Date(at.getTime() - unusedAfterDays * DAY_MS$1)).toISOString();
9434
+ const attention = {
9435
+ fileMissing: [],
9436
+ unused: []
9437
+ };
9438
+ for (const row of rows) if (await probe({
9439
+ folder: row.folder,
9440
+ host: row.host
9441
+ }) === false) attention.fileMissing.push(row.name);
9442
+ else if ((row.last_used_at ?? row.approved_at ?? row.requested_at) <= cutoff) attention.unused.push(row.name);
9443
+ return attention;
9444
+ }
9445
+ /**
9446
+ * One line naming the tokens in `attention`, at most 300 characters, or null when none needs
9447
+ * attention. Shared by `board doctor` and the daily digest. A name enrollment would refuse today
9448
+ * is counted, never printed; trailing names that do not fit become "and N more".
9449
+ */
9450
+ function tokenAttentionLine(attention, unusedAfterDays) {
9451
+ const total = attention.fileMissing.length + attention.unused.length;
9452
+ if (total === 0) return null;
9453
+ const head = `${String(total)} operator ${total === 1 ? "token needs" : "tokens need"} attention (revoke any that nothing uses with \`board token revoke <name>\`)`;
9454
+ const printableNames = (names) => names.filter((name) => tokenRequestSchema.shape.name.safeParse(name).success);
9455
+ const printable = [{
9456
+ label: "no token file",
9457
+ names: printableNames(attention.fileMissing)
9458
+ }, {
9459
+ label: `unused for ${String(unusedAfterDays)}+ days`,
9460
+ names: printableNames(attention.unused)
9461
+ }];
9462
+ const named = printable.reduce((n, group) => n + group.names.length, 0);
9463
+ for (let shown = named; shown > 0; shown -= 1) {
9464
+ let left = shown;
9465
+ const parts = [];
9466
+ for (const { label, names } of printable) {
9467
+ const listed = names.slice(0, left);
9468
+ left -= listed.length;
9469
+ if (listed.length > 0) parts.push(`${label}: ${listed.join(", ")}`);
9470
+ }
9471
+ const more = total - shown;
9472
+ const line = `${head}: ${parts.join("; ")}${more > 0 ? ` and ${String(more)} more` : ""}`;
9473
+ if (line.length <= ATTENTION_LINE_MAX) return line;
9474
+ }
9475
+ return `${head}: ${String(total)} not named`;
9476
+ }
9392
9477
  //#endregion
9393
9478
  //#region ../core/src/api/identity.ts
9394
9479
  function sessionActor(project, session, config) {
@@ -9591,7 +9676,8 @@ async function createApiServer(options) {
9591
9676
  const body = inputBody(request.body);
9592
9677
  const parsed = operation.input.safeParse(body.input);
9593
9678
  if (!parsed.success) throw new CommandError(errorCodeOf(parsed.error), "Fix the operation input.");
9594
- const result = await dispatchOperation(options, operation.id, parsed.data, caller.actor, body.key);
9679
+ const dispatch = () => dispatchOperation(options, operation.id, parsed.data, caller.actor, body.key);
9680
+ const result = await (options.runOperation === void 0 ? dispatch() : options.runOperation(operation.id, parsed.data, dispatch));
9595
9681
  await options.afterOperation?.(reply.raw);
9596
9682
  return reply.send(successEnvelopeSchema.parse({
9597
9683
  ok: true,
@@ -15677,6 +15763,25 @@ async function skip(trx, input) {
15677
15763
  });
15678
15764
  return { status: "ignored" };
15679
15765
  }
15766
+ /**
15767
+ * The journal is the comment's edit cursor: a deletion, or a later edit, was already applied.
15768
+ * Times compare in milliseconds, since `at` precision varies. Distinct edits can share a
15769
+ * millisecond, so an edit at the same millisecond counts as applied only when the comment
15770
+ * already holds its text.
15771
+ */
15772
+ async function alreadyApplied(trx, event) {
15773
+ if (event.kind !== "message_edited" && event.kind !== "message_deleted") return false;
15774
+ const comment = await linkedComment(trx, event);
15775
+ if (comment === void 0 || comment.author !== "operator") return false;
15776
+ const rows = await trx.selectFrom("event").select(["kind", "at"]).where("task_id", "=", comment.task_id).where("kind", "in", ["comment_deleted", "comment_edited"]).where(sql`json_extract(payload, '$.comment')`, "=", `C${String(comment.id)}`).execute();
15777
+ if (rows.some((row) => row.kind === "comment_deleted")) return true;
15778
+ if (event.kind === "message_deleted") return false;
15779
+ const editedAt = Date.parse(event.at);
15780
+ return rows.some((row) => {
15781
+ const rowAt = Date.parse(row.at);
15782
+ return rowAt > editedAt || rowAt === editedAt && comment.text === event.text;
15783
+ });
15784
+ }
15680
15785
  async function linkedComment(trx, event) {
15681
15786
  return trx.selectFrom("comment").selectAll().where("conversation_ref", "=", event.conversation).where("message_ref", "=", event.message).executeTakeFirst();
15682
15787
  }
@@ -15713,11 +15818,20 @@ async function ringAuthor(trx, input) {
15713
15818
  retry: false
15714
15819
  });
15715
15820
  }
15821
+ function first(set) {
15822
+ for (const value of set) return value;
15823
+ }
15716
15824
  function createInbound(input) {
15717
15825
  const { store, gateway, config } = input;
15718
15826
  const clock = input.clock ?? { now: () => Date.now() };
15719
15827
  const registry = input.registry ?? {};
15720
15828
  let running = Promise.resolve();
15829
+ const stopping = new AbortController();
15830
+ const stopped = () => stopping.signal.aborted;
15831
+ /** Conversations the current or stopped scan selected and has not read yet. */
15832
+ const pending = /* @__PURE__ */ new Set();
15833
+ let since = new Date(clock.now());
15834
+ let scan;
15721
15835
  async function sourceContext(trx, event, at) {
15722
15836
  if (!("conversation" in event)) return void 0;
15723
15837
  const resolved = await resolveBlockConversation(trx, {
@@ -15739,6 +15853,7 @@ function createInbound(input) {
15739
15853
  return resolved?.conversation;
15740
15854
  }
15741
15855
  async function processMessage(trx, event, at) {
15856
+ if (await alreadyApplied(trx, event)) return void 0;
15742
15857
  const conversation = await sourceContext(trx, event, at);
15743
15858
  if (conversation?.block_id === null || conversation === void 0) return skip(trx, {
15744
15859
  event,
@@ -16107,41 +16222,174 @@ function createInbound(input) {
16107
16222
  });
16108
16223
  }
16109
16224
  async function applyEvent(event) {
16110
- if (event.kind === "connection") {
16111
- if (event.state === "up") await scan();
16112
- return;
16113
- }
16114
16225
  if (event.kind === "gap") return applyGap(event);
16115
16226
  return applyUser(event);
16116
16227
  }
16117
- async function scan() {
16118
- const selected = await conversationsForRecovery(store.db, gateway.kind, new Date(clock.now()));
16119
- const conversations = selected.rows.map((row) => ({
16120
- ref: conversationRefSchema.parse(row.ref),
16121
- ...row.after_message_ref === null ? {} : { after: messageRefSchema.parse(row.after_message_ref) }
16122
- }));
16228
+ /** Reads one conversation, or none to let a history-less gateway report its gap. */
16229
+ async function readSlice(ref) {
16230
+ let conversations = [];
16231
+ if (ref !== void 0) {
16232
+ const row = await store.db.selectFrom("conversation").select("after_message_ref").where("gateway", "=", gateway.kind).where("ref", "=", ref).executeTakeFirst();
16233
+ if (row === void 0) return;
16234
+ conversations = [{
16235
+ ref: conversationRefSchema.parse(ref),
16236
+ ...row.after_message_ref === null ? {} : { after: messageRefSchema.parse(row.after_message_ref) }
16237
+ }];
16238
+ }
16123
16239
  for await (const event of gateway.recover({
16124
16240
  conversations,
16125
- since: selected.since
16126
- })) await applyEvent(event);
16241
+ since,
16242
+ signal: stopping.signal
16243
+ })) {
16244
+ if (stopped()) return;
16245
+ if (event.kind === "connection") continue;
16246
+ await applyEvent(event);
16247
+ }
16248
+ }
16249
+ /** Reads `ref` now when the scan has not read it yet; a stopped scan leaves it unread. */
16250
+ async function sliceIfPending(ref) {
16251
+ if (!pending.has(ref) || stopped()) return;
16252
+ try {
16253
+ await readSlice(ref);
16254
+ } catch (error) {
16255
+ pending.delete(ref);
16256
+ throw error;
16257
+ }
16258
+ if (!stopped()) pending.delete(ref);
16259
+ }
16260
+ /**
16261
+ * Adds the selected conversations to `pending`. A selection merged into a running scan reads
16262
+ * from the earliest `since` of its selections, so no selection's window shrinks.
16263
+ */
16264
+ async function select(state) {
16265
+ if (scan !== state) return;
16266
+ const selected = await conversationsForRecovery(store.db, gateway.kind, new Date(clock.now()));
16267
+ since = state.selected && since.getTime() < selected.since.getTime() ? since : selected.since;
16268
+ state.selected = true;
16269
+ for (const row of selected.rows) pending.add(row.ref);
16270
+ if (selected.rows.length === 0) state.readEmpty = true;
16271
+ }
16272
+ /**
16273
+ * One slot per conversation, so live events run between slices, until `pending` is empty.
16274
+ * The scan ends where this decides to stop, in the same microtask, so a later request starts
16275
+ * a fresh scan instead of joining one that will not read again.
16276
+ */
16277
+ async function drain(state) {
16278
+ const end = () => {
16279
+ if (scan === state) scan = void 0;
16280
+ };
16281
+ try {
16282
+ for (;;) {
16283
+ const selection = state.selection;
16284
+ await selection;
16285
+ for (let ref = first(pending); ref !== void 0 && !stopped(); ref = first(pending)) {
16286
+ const next = ref;
16287
+ await serial(() => sliceIfPending(next));
16288
+ }
16289
+ if (state.readEmpty && !stopped()) {
16290
+ state.readEmpty = false;
16291
+ await serial(() => readSlice(void 0));
16292
+ }
16293
+ if (stopped() || state.selection === selection) {
16294
+ end();
16295
+ return;
16296
+ }
16297
+ }
16298
+ } catch (error) {
16299
+ end();
16300
+ pending.clear();
16301
+ throw error;
16302
+ }
16303
+ }
16304
+ /**
16305
+ * A request during a scan queues its selection at once, so later live events wait for it;
16306
+ * every caller waits until the merged selections are read.
16307
+ */
16308
+ function requestScan() {
16309
+ if (stopped()) return Promise.resolve();
16310
+ if (scan !== void 0) {
16311
+ queueSelection(scan);
16312
+ return scan.promise;
16313
+ }
16314
+ const state = {
16315
+ selected: false,
16316
+ readEmpty: false,
16317
+ selection: Promise.resolve(),
16318
+ promise: Promise.resolve()
16319
+ };
16320
+ scan = state;
16321
+ queueSelection(state);
16322
+ state.promise = drain(state);
16323
+ return state.promise;
16324
+ }
16325
+ function queueSelection(state) {
16326
+ const queued = serial(() => select(state));
16327
+ state.selection = state.selection.then(() => queued);
16328
+ state.selection.catch(() => void 0);
16329
+ }
16330
+ /** The conversation of the event an item stored for retry, if it has one. */
16331
+ async function storedConversation(itemId) {
16332
+ if (pending.size === 0) return void 0;
16333
+ const item = await store.db.selectFrom("operator_item").select("inbound_event_json").where("id", "=", itemId).executeTakeFirst();
16334
+ if (item?.inbound_event_json == null) return void 0;
16335
+ const stored = inboundEventSchema.safeParse(JSON.parse(item.inbound_event_json));
16336
+ return stored.success && "conversation" in stored.data ? stored.data.conversation : void 0;
16337
+ }
16338
+ /** The item a feed Retry button re-applies, so its stored event's thread is read first. */
16339
+ function retriedItem(event) {
16340
+ if (event.kind !== "action") return void 0;
16341
+ const { id, item } = interactionOperation(event);
16342
+ return id === "item.retry" && item !== void 0 ? Number(item.slice(1)) : void 0;
16343
+ }
16344
+ /** Reads `ref`'s unread history, or raises its gap once the scan stopped. */
16345
+ async function readPending(ref) {
16346
+ if (ref === void 0 || !pending.has(ref)) return;
16347
+ if (!stopped()) return sliceIfPending(ref);
16348
+ pending.delete(ref);
16349
+ await applyGap({
16350
+ kind: "gap",
16351
+ dedupeKey: `inbound:stopped-scan:${randomUUID()}`,
16352
+ conversation: conversationRefSchema.parse(ref)
16353
+ });
16354
+ }
16355
+ /**
16356
+ * Before a live event: its conversation's unread history, and for a Retry button the stored
16357
+ * event's, since re-applying that event can move its conversation's cursor.
16358
+ */
16359
+ async function beforeLive(event) {
16360
+ await readPending("conversation" in event ? event.conversation : void 0);
16361
+ const itemId = retriedItem(event);
16362
+ if (itemId !== void 0) await readPending(await storedConversation(itemId));
16127
16363
  }
16128
16364
  function serial(work) {
16129
16365
  const next = running.then(work);
16130
- running = next.catch(() => void 0);
16366
+ running = next.then(() => void 0, () => void 0);
16131
16367
  return next;
16132
16368
  }
16133
16369
  return {
16134
16370
  sink(event) {
16135
- return serial(() => applyEvent(event));
16371
+ if (event.kind === "connection") return event.state === "up" ? requestScan() : Promise.resolve();
16372
+ return serial(async () => {
16373
+ await beforeLive(event);
16374
+ await applyEvent(event);
16375
+ });
16136
16376
  },
16137
- recover() {
16138
- return serial(scan);
16377
+ recover: requestScan,
16378
+ async stop() {
16379
+ stopping.abort();
16380
+ await scan?.promise.catch(() => void 0);
16381
+ await running;
16139
16382
  },
16140
- stop() {
16141
- return running;
16383
+ retrying(item, run) {
16384
+ return serial(async () => {
16385
+ const itemId = /^I[1-9]\d*$/.test(item) ? Number(item.slice(1)) : void 0;
16386
+ if (itemId !== void 0) await readPending(await storedConversation(itemId));
16387
+ return run();
16388
+ });
16142
16389
  },
16143
16390
  retryStored(itemId) {
16144
16391
  return serial(async () => {
16392
+ await readPending(await storedConversation(itemId));
16145
16393
  const at = new Date(clock.now()).toISOString();
16146
16394
  await scanTransaction(store, config, async (trx) => {
16147
16395
  await reapply(trx, itemId, at);
@@ -18684,7 +18932,7 @@ function runSource(entry, options, runnerStartMs) {
18684
18932
  }
18685
18933
  const requested = [...context.observe.prs, ...context.observe.tickets];
18686
18934
  step = "poll";
18687
- const batch = await untilAborted(adapter.poll({
18935
+ const batch = await untilAborted$1(adapter.poll({
18688
18936
  ...context,
18689
18937
  signal: abort.signal
18690
18938
  }), abort.signal);
@@ -18797,13 +19045,13 @@ function runSource(entry, options, runnerStartMs) {
18797
19045
  const aborted = () => abort.signal.aborted;
18798
19046
  let step = "context";
18799
19047
  try {
18800
- const received = await untilAborted(core.context(source), abort.signal);
19048
+ const received = await untilAborted$1(core.context(source), abort.signal);
18801
19049
  if (aborted() || received === void 0) return err(stoppedError);
18802
19050
  const own = ({ ref: held }) => held.number === ref.number && held.repo.toLowerCase() === ref.repo.toLowerCase();
18803
19051
  const feedbackCursors = received.feedbackCursors?.filter(own) ?? [];
18804
19052
  const continuations = received.continuations?.filter(own) ?? [];
18805
19053
  step = "poll";
18806
- const batch = await untilAborted(adapter.pollPr(ref, {
19054
+ const batch = await untilAborted$1(adapter.pollPr(ref, {
18807
19055
  signal: abort.signal,
18808
19056
  ...feedbackCursors.length === 0 ? {} : { feedbackCursors },
18809
19057
  ...continuations.length === 0 ? {} : { continuations }
@@ -18940,7 +19188,7 @@ function demandValue(batch, observedAt) {
18940
19188
  * for an adapter that ignores its signal. A late result or rejection is dropped. The abort
18941
19189
  * listener is removed once either side settles, so a retained signal holds nothing.
18942
19190
  */
18943
- function untilAborted(work, signal) {
19191
+ function untilAborted$1(work, signal) {
18944
19192
  let settle = () => void 0;
18945
19193
  const abortion = new Promise((resolve) => {
18946
19194
  settle = resolve;
@@ -19314,7 +19562,10 @@ var IncompleteHistoryError = class extends Error {};
19314
19562
  function messageTs$1(message) {
19315
19563
  return typeof message === "object" && message !== null && "ts" in message && typeof message.ts === "string" ? message.ts : void 0;
19316
19564
  }
19317
- /** Read every page. An incomplete response is unknown, never an empty history. */
19565
+ /**
19566
+ * Read every page. An incomplete response is unknown, never an empty history. Once `signal`
19567
+ * aborts, no further page is requested.
19568
+ */
19318
19569
  async function readMessages(client, query) {
19319
19570
  const found = [];
19320
19571
  const seen = /* @__PURE__ */ new Set();
@@ -19345,6 +19596,7 @@ async function readMessages(client, query) {
19345
19596
  if (seen.has(key)) throw new IncompleteHistoryError("repeated cursor");
19346
19597
  seen.add(key);
19347
19598
  cursor = nextCursor;
19599
+ if (query.signal?.aborted === true) throw new IncompleteHistoryError("read aborted");
19348
19600
  continue;
19349
19601
  }
19350
19602
  if (!page.has_more) return found;
@@ -19355,6 +19607,7 @@ async function readMessages(client, query) {
19355
19607
  seen.add(key);
19356
19608
  cursor = void 0;
19357
19609
  latest = lastTs;
19610
+ if (query.signal?.aborted === true) throw new IncompleteHistoryError("read aborted");
19358
19611
  }
19359
19612
  }
19360
19613
  const DEFAULT_TIMEOUT_MS = 1e4;
@@ -20107,16 +20360,52 @@ function inInterval(ts, from, until) {
20107
20360
  const at = tsMillis(ts);
20108
20361
  return Number.isFinite(at) && at >= from && at <= until;
20109
20362
  }
20110
- async function readThread(client, channel, threadTs) {
20111
- for (;;) try {
20112
- return await readMessages(client, {
20113
- channel,
20114
- threadTs
20115
- });
20116
- } catch (error) {
20117
- const result = apiFailure(error);
20118
- if (result.status !== "retry" || result.uncertain) throw error;
20119
- await new Promise((resolve) => setTimeout(resolve, result.afterMs ?? 1e3));
20363
+ /** Total time one thread read may spend waiting on rate limits before it becomes a `gap`. */
20364
+ const READ_WAIT_BUDGET_MS = 1e4;
20365
+ /** Least budget one retry costs, so a `Retry-After: 0` cannot retry forever. */
20366
+ const MIN_RETRY_CHARGE_MS = 1e3;
20367
+ const ABORTED = Symbol("aborted");
20368
+ /**
20369
+ * Settles with `promise`, or with `ABORTED` once `signal` aborts. The SDK call cannot be
20370
+ * cancelled, so a losing read is left to its own timeout and its outcome is dropped.
20371
+ */
20372
+ function untilAborted(promise, signal) {
20373
+ if (signal === void 0) return promise;
20374
+ promise.catch(() => {});
20375
+ if (signal.aborted) return Promise.resolve(ABORTED);
20376
+ const abort = Promise.withResolvers();
20377
+ const onAbort = () => {
20378
+ abort.resolve(ABORTED);
20379
+ };
20380
+ signal.addEventListener("abort", onAbort, { once: true });
20381
+ return Promise.race([promise, abort.promise]).finally(() => {
20382
+ signal.removeEventListener("abort", onAbort);
20383
+ });
20384
+ }
20385
+ /**
20386
+ * Waits out rate limits within `READ_WAIT_BUDGET_MS`, each retry costing at least
20387
+ * `MIN_RETRY_CHARGE_MS`; a wait past what remains throws
20388
+ * `IncompleteHistoryError` without sleeping. Returns `ABORTED` once `signal` aborts.
20389
+ */
20390
+ async function readThread(client, channel, threadTs, signal) {
20391
+ let budget = READ_WAIT_BUDGET_MS;
20392
+ for (;;) {
20393
+ if (signal?.aborted === true) return ABORTED;
20394
+ try {
20395
+ return await untilAborted(readMessages(client, {
20396
+ channel,
20397
+ threadTs,
20398
+ signal
20399
+ }), signal);
20400
+ } catch (error) {
20401
+ const result = apiFailure(error);
20402
+ if (result.status !== "retry" || result.uncertain) throw error;
20403
+ const wait = result.afterMs ?? 1e3;
20404
+ const charge = Math.max(wait, MIN_RETRY_CHARGE_MS);
20405
+ if (charge > budget) throw new IncompleteHistoryError("rate limit wait exceeds the read budget");
20406
+ budget -= charge;
20407
+ await setTimeout$1(wait, void 0, { signal }).catch(() => void 0);
20408
+ }
20120
20409
  }
20121
20410
  }
20122
20411
  function gap(conversation) {
@@ -20131,8 +20420,11 @@ async function* recoverThreads(client, request, botIdentity, now) {
20131
20420
  const until = now();
20132
20421
  const from = request.since.getTime();
20133
20422
  if (!Number.isFinite(from) || from > until) return;
20134
- const bot = await botIdentity();
20423
+ const signal = request.signal;
20424
+ const bot = await untilAborted(botIdentity(), signal);
20425
+ if (bot === ABORTED) return;
20135
20426
  for (const conversation of request.conversations) {
20427
+ if (signal?.aborted === true) return;
20136
20428
  const addressed = parseRef(conversation.ref);
20137
20429
  if (addressed === null) {
20138
20430
  yield gap(conversation.ref);
@@ -20140,7 +20432,7 @@ async function* recoverThreads(client, request, botIdentity, now) {
20140
20432
  }
20141
20433
  let history;
20142
20434
  try {
20143
- history = await readThread(client, addressed.channel, addressed.threadTs);
20435
+ history = await readThread(client, addressed.channel, addressed.threadTs, signal);
20144
20436
  } catch (error) {
20145
20437
  const result = apiFailure(error);
20146
20438
  if (error instanceof IncompleteHistoryError || result.status === "failed") {
@@ -20149,6 +20441,7 @@ async function* recoverThreads(client, request, botIdentity, now) {
20149
20441
  }
20150
20442
  throw error;
20151
20443
  }
20444
+ if (history === ABORTED) return;
20152
20445
  const root = history.find((message) => string(record(message)?.ts) === addressed.threadTs);
20153
20446
  if (root === void 0) {
20154
20447
  yield gap(conversation.ref);
@@ -20773,6 +21066,29 @@ function warning(id, fix) {
20773
21066
  fix
20774
21067
  };
20775
21068
  }
21069
+ /**
21070
+ * Whether a token's folder on this host still holds `.spur-board/token` as a regular file. Null
21071
+ * for a token of another host, or when the folder cannot be read for another reason.
21072
+ */
21073
+ async function tokenFilePresent(token) {
21074
+ if (token.host !== hostname()) return null;
21075
+ try {
21076
+ return (await lstat(join(token.folder, ".spur-board", "token"))).isFile();
21077
+ } catch (err) {
21078
+ const code = err instanceof Error && "code" in err ? err.code : void 0;
21079
+ return code === "ENOENT" || code === "ENOTDIR" ? false : null;
21080
+ }
21081
+ }
21082
+ async function operatorTokensCheck(ctx, config) {
21083
+ const days = config.operatorAccess.unusedAfterDays;
21084
+ const line = tokenAttentionLine(await tokenAttention(ctx.store, new Date(ctx.clock.now()), days, tokenFilePresent), days);
21085
+ return line === null ? {
21086
+ id: "operator.tokens",
21087
+ status: "pass",
21088
+ blocking: false,
21089
+ fix: null
21090
+ } : warning("operator.tokens", line);
21091
+ }
20776
21092
  async function request(ctx, fetcher, deadlineMs, id, url, init = {}) {
20777
21093
  try {
20778
21094
  return await ctx.logCall(`doctor.${id}`, () => fetcher(url, {
@@ -20901,6 +21217,7 @@ async function runDaemonDoctor(ctx, productVersion, fetcher = fetch, { deadlineM
20901
21217
  const operatorProject = config.projects.some((project) => project.spurProjects.some((spurProject) => spurProject.role === "operator"));
20902
21218
  const token = operatorProject ? void 0 : await ctx.store.db.selectFrom("operator_token").select("id").where("status", "=", "approved").executeTakeFirst();
20903
21219
  checks.push(check("operator.path", operatorProject || token !== void 0, "Configure a Spur project with the operator role or approve a named operator token."));
21220
+ checks.push(await operatorTokensCheck(ctx, config));
20904
21221
  checks.push(curatorSessionsCheck(await curatorSessions(ctx.store.db, config)));
20905
21222
  return {
20906
21223
  version: productVersion,
@@ -20940,9 +21257,12 @@ function createHttpModule(ctx, options = {}) {
20940
21257
  stopping: () => ctx.state() === "stopping",
20941
21258
  clock: ctx.clock,
20942
21259
  lookupSession: (id) => ctx.logCall("spur.session.lookup", () => lookupLiveSession(ctx.config.adapters.spur.baseUrl, id, options.fetcher)),
20943
- verifyToken: (token) => verifyOperatorToken(ctx.store, token),
21260
+ verifyToken: (token) => verifyOperatorToken(ctx.store, token, new Date(ctx.clock.now()), (err) => {
21261
+ ctx.log.warn({ err }, "token use not recorded");
21262
+ }),
20944
21263
  registry: options.registry ?? {},
20945
21264
  ...options.afterOperation === void 0 ? {} : { afterOperation: options.afterOperation },
21265
+ ...options.runOperation === void 0 ? {} : { runOperation: options.runOperation },
20946
21266
  doctor: options.doctor ?? (() => runDaemonDoctor(ctx, options.productVersion ?? "unknown", options.fetcher)),
20947
21267
  ...options.firstPollDone === void 0 ? {} : { firstPollDone: options.firstPollDone },
20948
21268
  logRequest: ({ requestId, method, url, status, tokenName }) => {
@@ -21002,11 +21322,13 @@ function createInboundModule(ctx, gateway, registry = {}) {
21002
21322
  return {
21003
21323
  sink: (event) => inbound.sink(event),
21004
21324
  reapply: inbound.reapply,
21325
+ retrying: (item, run) => inbound.retrying(item, run),
21005
21326
  awaitRecovery: () => recovery.settled(),
21006
21327
  start: (signal) => recovery.start(signal),
21007
21328
  async stop() {
21329
+ const draining = inbound.stop();
21008
21330
  await recovery.stop();
21009
- await inbound.stop();
21331
+ await draining;
21010
21332
  }
21011
21333
  };
21012
21334
  }
@@ -21326,6 +21648,7 @@ function createDaemonModules(ctxFor, ports = {}) {
21326
21648
  stopStage: "final",
21327
21649
  module: createHttpModule(ctxFor("http"), {
21328
21650
  registry,
21651
+ runOperation: (id, input, run) => id === "item.retry" && inbound !== void 0 && isItemInput(input) ? inbound.retrying(input.item, run) : run(),
21329
21652
  firstPollDone: () => firstPollDone(board.store.db, board.config, core.completeSince),
21330
21653
  ...ports.productVersion === void 0 ? {} : { productVersion: ports.productVersion },
21331
21654
  ...ports.sessionFetcher === void 0 ? {} : { fetcher: ports.sessionFetcher },
@@ -21345,6 +21668,9 @@ function createDaemonModules(ctxFor, ports = {}) {
21345
21668
  tick: boardModules.tick
21346
21669
  };
21347
21670
  }
21671
+ function isItemInput(input) {
21672
+ return typeof input === "object" && input !== null && "item" in input && typeof input.item === "string";
21673
+ }
21348
21674
  //#endregion
21349
21675
  //#region ../daemon/src/main.ts
21350
21676
  const KEEPALIVE_MS = 36e5;
package/dist/mcp.mjs CHANGED
@@ -1,6 +1,6 @@
1
- import { H as ERRORS, _ as renderMcpError, p as OPERATIONS } from "./src-DGT9Wspi.mjs";
2
- import { a as CliError, r as requestOperation } from "./client-D8BEfeGz.mjs";
3
- import { a as memoryVerdictCache, c as loadClientConfig, r as compareCatalogs, t as checkCatalog } from "./config-Chv5ZHE8.mjs";
1
+ import { H as ERRORS, _ as renderMcpError, p as OPERATIONS } from "./src-Cj3-z45G.mjs";
2
+ import { a as CliError, r as requestOperation } from "./client-DJ0swpg5.mjs";
3
+ import { a as memoryVerdictCache, c as loadClientConfig, r as compareCatalogs, t as checkCatalog } from "./config-BMYEBQfk.mjs";
4
4
  import { randomUUID } from "node:crypto";
5
5
  import { readFileSync } from "node:fs";
6
6
  import { z } from "zod";
@@ -0,0 +1,7 @@
1
+ -- When an operator token was approved, and when an authenticated call last used it. Revoke
2
+ -- overwrites `decided_at`, so the backfill sets `approved_at` only for rows still approved: a token
3
+ -- revoked before this migration keeps `approved_at` NULL. `last_used_at` is NULL until the first
4
+ -- call with the token and is written at most once per token per few minutes.
5
+ ALTER TABLE operator_token ADD COLUMN approved_at TEXT;
6
+ ALTER TABLE operator_token ADD COLUMN last_used_at TEXT;
7
+ UPDATE operator_token SET approved_at = decided_at WHERE status = 'approved';
@@ -444,6 +444,7 @@ const configSchema = z.strictObject({
444
444
  archive: z.strictObject({ doneWeekday: z.enum(WEEKDAYS).default("saturday").describe("Weekday whose local midnight, in digest.tz, is the weekly archive slot: tasks done before it are archived then, once their repos have a complete poll since their last change. A slot missed while the daemon was down is applied on the next tick.") }).prefault({}),
445
445
  digest: z.strictObject({ tz: z.string().refine(isTimeZone, "Unknown IANA time zone").describe("IANA time zone, such as Europe/Berlin, for the archive.doneWeekday slot and the times shown in resolved feed lines.") }),
446
446
  commands: z.strictObject({ retentionDays: z.int().min(1).default(7).describe("Days the board keeps each caller's mutation --key with its input and result. In that time the same caller and key with the same input returns the stored result, and with a different input the call is refused. A daily job deletes older keys.") }).prefault({}),
447
+ operatorAccess: z.strictObject({ unusedAfterDays: z.int().min(1).max(3650).default(14).describe("Days an approved operator access key from board token create may go unused before board doctor warns about it.") }).prefault({}),
447
448
  doorbells: z.strictObject({
448
449
  firstRetryMs: durationMs(12e4, "Wait after the first unanswered doorbell"),
449
450
  secondRetryMs: durationMs(3e5, "Wait after the second unanswered doorbell"),
@@ -2586,16 +2587,19 @@ const OPERATIONS = [
2586
2587
  defineOperation({
2587
2588
  id: "token.list",
2588
2589
  kind: "query",
2589
- description: "List named operator tokens and their current status.",
2590
+ description: "List named operator tokens with their status and when each was created, approved and last used.",
2590
2591
  mcp: {
2591
- whenToUse: "Inspect named operator tokens and their current status.",
2592
+ whenToUse: "Inspect named operator tokens, their status, and when each was approved and last used.",
2592
2593
  whenNotToUse: "Use token_revoke to disable a token."
2593
2594
  },
2594
2595
  input: z.strictObject({}),
2595
2596
  output: z.strictObject({ tokens: z.array(z.strictObject({
2596
2597
  name: tokenName,
2597
2598
  folder: z.string().min(1).describe("Folder where the token file was created."),
2598
- status: tokenStatus
2599
+ status: tokenStatus,
2600
+ createdAt: z.iso.datetime().describe("When the token was requested, ISO 8601 UTC."),
2601
+ approvedAt: z.iso.datetime().nullable().describe("When the token was approved, ISO 8601 UTC; null when it never was, or was revoked before approval times were kept."),
2602
+ lastUsedAt: z.iso.datetime().nullable().describe("When a call last authenticated with the token, ISO 8601 UTC, recorded at most once every 5 minutes; null before the first call.")
2599
2603
  })).describe("Named tokens in creation order.") }),
2600
2604
  grants: operatorOnly,
2601
2605
  errors: [],
@@ -2610,7 +2614,10 @@ const OPERATIONS = [
2610
2614
  output: { tokens: [{
2611
2615
  name: "desk",
2612
2616
  folder: "workspace/desk",
2613
- status: "approved"
2617
+ status: "approved",
2618
+ createdAt: "2026-11-04T10:00:00.000Z",
2619
+ approvedAt: "2026-11-04T10:02:00.000Z",
2620
+ lastUsedAt: "2026-11-05T09:30:00.000Z"
2614
2621
  }] }
2615
2622
  }]
2616
2623
  }),
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "spur-board",
3
- "version": "0.47.0",
3
+ "version": "0.48.0",
4
4
  "license": "MIT",
5
5
  "engines": {
6
6
  "node": "^24.12.0 || ^26.0.0"