spur-board 0.75.0 → 0.77.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,15 +1,15 @@
1
- import { $ as err, A as prSourceId, B as prFactsSchema, C as userIdSchema, D as AdapterError, E as eventPayloadSchemas, F as REVIEW_STATES, G as JIRA_PROJECT_KEY, H as ringMarker, I as SESSION_HEALTH_STATES, J as encodeActorId, K as REF_NUMBER, L as SESSION_STATUSES, M as sourceCursorSchema, N as trackerSourceId, O as batchSchema, P as PR_STATES, Q as ERRORS, R as isExternalAuthor, S as messageRefSchema, T as GATE_REASONS, U as sessionFactsSchema, V as prRefSchema, W as ticketFactsSchema, X as parseActorId, Y as errorCodeOf, Z as parseRef$1, _t as COLUMN_IDS, a as requestHashOf, at as DEFAULT_LINK, b as inboundEventSchema, bt as TASK_HOLDS, c as tokenRequestStatusSchema, d as buildCatalogSnapshot, dt as configBindings, f as roleCanUseOperation, ft as configSchema, h as renderHttpProblem, ht as requiredSecretKeys, i as TOKEN_REQUEST_LIMITS, j as sessionTransitionSchema, k as entityRefSchema, l as BOARD_TICK_MS, lt as RESERVED_PROJECT, m as turnHandedSchema, mt as plainHttpAllowed, n as doctorReportSchema, nt as ok, o as tokenRequestResultSchema, p as OPERATIONS, pt as defaultAddressee, q as actorIdSchema, rt as successEnvelopeSchema, s as tokenRequestSchema, st as DEFAULT_SLACK_COMMAND, t as assertNever, ut as boardWideSpurProject, v as SPACE_IDS, vt as DISPATCHER_MODES, w as EVENT_KINDS, x as interactionRefSchema, xt as VIAS, y as conversationRefSchema, yt as SLACK_BOT_SCOPES, z as parseRingMarker } from "./chunk-CvY4Vfxu.mjs";
1
+ import { $ as err, A as prSourceId, B as prFactsSchema, C as userIdSchema, D as AdapterError, E as eventPayloadSchemas, F as REVIEW_STATES, G as JIRA_PROJECT_KEY, H as ringMarker, I as SESSION_HEALTH_STATES, J as encodeActorId, K as REF_NUMBER, L as SESSION_STATUSES, M as sourceCursorSchema, N as trackerSourceId, O as batchSchema, P as PR_STATES, Q as ERRORS, R as isExternalAuthor, S as messageRefSchema, St as VIAS, T as GATE_REASONS, U as sessionFactsSchema, V as prRefSchema, W as ticketFactsSchema, X as parseActorId, Y as errorCodeOf, Z as parseRef$1, _t as COLUMN_IDS, a as requestHashOf, at as DEFAULT_LINK, b as inboundEventSchema, bt as SLACK_BOT_SCOPES, c as tokenRequestStatusSchema, d as buildCatalogSnapshot, dt as configBindings, f as roleCanUseOperation, ft as configSchema, gt as resolveWebOrigin, h as renderHttpProblem, ht as requiredSecretKeys, i as TOKEN_REQUEST_LIMITS, j as sessionTransitionSchema, k as entityRefSchema, l as BOARD_TICK_MS, lt as RESERVED_PROJECT, m as turnHandedSchema, mt as plainHttpAllowed, n as doctorReportSchema, nt as ok, o as tokenRequestResultSchema, p as OPERATIONS, pt as defaultAddressee, q as actorIdSchema, rt as successEnvelopeSchema, s as tokenRequestSchema, st as DEFAULT_SLACK_COMMAND, t as assertNever, ut as boardWideSpurProject, v as SPACE_IDS, vt as DISPATCHER_MODES, w as EVENT_KINDS, x as interactionRefSchema, xt as TASK_HOLDS, y as conversationRefSchema, yt as ITEM_KINDS, z as parseRingMarker } from "./chunk-tFE-9H7j.mjs";
2
2
  import { t as apiBaseUrl } from "./chunk-DAMwWWmT.mjs";
3
3
  import { createRequire } from "node:module";
4
4
  import { createHash, randomUUID } from "node:crypto";
5
5
  import { chmodSync, closeSync, existsSync, fchmodSync, fstatSync, fsyncSync, ftruncateSync, linkSync, mkdirSync, openSync, readFileSync, readdirSync, renameSync, rmSync, statSync, writeSync } from "node:fs";
6
6
  import { homedir, hostname } from "node:os";
7
- import path, { basename, dirname, isAbsolute, join, normalize, resolve } from "node:path";
7
+ import path, { basename, dirname, extname, isAbsolute, join, normalize, resolve } from "node:path";
8
8
  import { z } from "zod";
9
9
  import YAML from "yaml";
10
10
  import { spawn, spawnSync } from "node:child_process";
11
11
  import { parseEnv } from "node:util";
12
- import { lstat } from "node:fs/promises";
12
+ import { lstat, readFile, readdir } from "node:fs/promises";
13
13
  import Database from "better-sqlite3";
14
14
  import { Kysely, SqliteDialect, sql } from "kysely";
15
15
  import { AsyncLocalStorage } from "node:async_hooks";
@@ -8587,25 +8587,6 @@ async function blockSubject(trx, block) {
8587
8587
  }
8588
8588
  //#endregion
8589
8589
  //#region ../core/src/domain/fromYou.ts
8590
- /** Every operator item kind; `ITEM_POLICY` must give each one a policy. */
8591
- const ITEM_KINDS = [
8592
- "token_request",
8593
- "post_blocked",
8594
- "post_failed",
8595
- "transport_health",
8596
- "answer_undelivered",
8597
- "worker_not_reading",
8598
- "answer_author_unavailable",
8599
- "inbound_failure",
8600
- "inbound_gap",
8601
- "board_observation",
8602
- "worker_ended",
8603
- "turn",
8604
- "anomaly",
8605
- "cycle_limit",
8606
- "course_check",
8607
- "conversation_waiting"
8608
- ];
8609
8590
  const ITEM_POLICY = {
8610
8591
  token_request: {
8611
8592
  retry: "none",
@@ -8613,7 +8594,8 @@ const ITEM_POLICY = {
8613
8594
  priority: 4,
8614
8595
  buttons: "approve_deny",
8615
8596
  reconciled: false,
8616
- block: false
8597
+ block: false,
8598
+ severity: "attention"
8617
8599
  },
8618
8600
  post_blocked: {
8619
8601
  retry: "never_sent",
@@ -8621,7 +8603,8 @@ const ITEM_POLICY = {
8621
8603
  priority: 4,
8622
8604
  buttons: "item",
8623
8605
  reconciled: false,
8624
- block: false
8606
+ block: false,
8607
+ severity: "attention"
8625
8608
  },
8626
8609
  post_failed: {
8627
8610
  retry: "requeue_post",
@@ -8629,7 +8612,8 @@ const ITEM_POLICY = {
8629
8612
  priority: 1,
8630
8613
  buttons: "item",
8631
8614
  reconciled: true,
8632
- block: false
8615
+ block: false,
8616
+ severity: "failure"
8633
8617
  },
8634
8618
  transport_health: {
8635
8619
  retry: "probe_transport",
@@ -8637,7 +8621,8 @@ const ITEM_POLICY = {
8637
8621
  priority: 1,
8638
8622
  buttons: "item",
8639
8623
  reconciled: false,
8640
- block: false
8624
+ block: false,
8625
+ severity: "failure"
8641
8626
  },
8642
8627
  answer_undelivered: {
8643
8628
  retry: "restart_ring",
@@ -8645,7 +8630,8 @@ const ITEM_POLICY = {
8645
8630
  priority: 4,
8646
8631
  buttons: "item",
8647
8632
  reconciled: false,
8648
- block: false
8633
+ block: false,
8634
+ severity: "failure"
8649
8635
  },
8650
8636
  worker_not_reading: {
8651
8637
  retry: "restart_ring",
@@ -8653,7 +8639,8 @@ const ITEM_POLICY = {
8653
8639
  priority: 4,
8654
8640
  buttons: "item",
8655
8641
  reconciled: false,
8656
- block: false
8642
+ block: false,
8643
+ severity: "failure"
8657
8644
  },
8658
8645
  answer_author_unavailable: {
8659
8646
  retry: "none",
@@ -8661,7 +8648,8 @@ const ITEM_POLICY = {
8661
8648
  priority: 4,
8662
8649
  buttons: "item",
8663
8650
  reconciled: false,
8664
- block: false
8651
+ block: false,
8652
+ severity: "attention"
8665
8653
  },
8666
8654
  inbound_failure: {
8667
8655
  retry: "reapply_inbound",
@@ -8669,7 +8657,8 @@ const ITEM_POLICY = {
8669
8657
  priority: 4,
8670
8658
  buttons: "item",
8671
8659
  reconciled: false,
8672
- block: false
8660
+ block: false,
8661
+ severity: "failure"
8673
8662
  },
8674
8663
  inbound_gap: {
8675
8664
  retry: "none",
@@ -8677,7 +8666,8 @@ const ITEM_POLICY = {
8677
8666
  priority: 4,
8678
8667
  buttons: "item",
8679
8668
  reconciled: false,
8680
- block: false
8669
+ block: false,
8670
+ severity: "failure"
8681
8671
  },
8682
8672
  board_observation: {
8683
8673
  retry: "none",
@@ -8685,7 +8675,8 @@ const ITEM_POLICY = {
8685
8675
  priority: 4,
8686
8676
  buttons: "item",
8687
8677
  reconciled: true,
8688
- block: false
8678
+ block: false,
8679
+ severity: "attention"
8689
8680
  },
8690
8681
  worker_ended: {
8691
8682
  retry: "none",
@@ -8693,7 +8684,8 @@ const ITEM_POLICY = {
8693
8684
  priority: 4,
8694
8685
  buttons: "item",
8695
8686
  reconciled: true,
8696
- block: false
8687
+ block: false,
8688
+ severity: "attention"
8697
8689
  },
8698
8690
  /** A turn whose executor is the operator; `closeTurns` clears it. */
8699
8691
  turn: {
@@ -8702,7 +8694,8 @@ const ITEM_POLICY = {
8702
8694
  priority: 4,
8703
8695
  buttons: "item",
8704
8696
  reconciled: false,
8705
- block: false
8697
+ block: false,
8698
+ severity: "attention"
8706
8699
  },
8707
8700
  /** A task-scoped condition only the operator can fix; `reconcileItems` owns its block. */
8708
8701
  anomaly: {
@@ -8711,7 +8704,8 @@ const ITEM_POLICY = {
8711
8704
  priority: 4,
8712
8705
  buttons: "item",
8713
8706
  reconciled: true,
8714
- block: true
8707
+ block: true,
8708
+ severity: "attention"
8715
8709
  },
8716
8710
  /** A task that reached its column's cycle limit; the operator's close resets it. */
8717
8711
  cycle_limit: {
@@ -8720,7 +8714,8 @@ const ITEM_POLICY = {
8720
8714
  priority: 4,
8721
8715
  buttons: "item",
8722
8716
  reconciled: false,
8723
- block: true
8717
+ block: true,
8718
+ severity: "attention"
8724
8719
  },
8725
8720
  /**
8726
8721
  * A task whose returns from a column reached its course check; the answer to its block, sent to
@@ -8732,7 +8727,8 @@ const ITEM_POLICY = {
8732
8727
  priority: 4,
8733
8728
  buttons: "item",
8734
8729
  reconciled: false,
8735
- block: true
8730
+ block: true,
8731
+ severity: "attention"
8736
8732
  },
8737
8733
  /** An operator conversation whose ring waits for a live session of its Spur project. */
8738
8734
  conversation_waiting: {
@@ -8741,9 +8737,32 @@ const ITEM_POLICY = {
8741
8737
  priority: 4,
8742
8738
  buttons: "item",
8743
8739
  reconciled: true,
8744
- block: false
8740
+ block: false,
8741
+ severity: "attention"
8745
8742
  }
8746
8743
  };
8744
+ /** The `inbox.operator` severity of an item; a blind source's item is a failure. */
8745
+ function itemSeverity(kind, key) {
8746
+ return key.startsWith("source:") ? "failure" : ITEM_POLICY[kind].severity;
8747
+ }
8748
+ /** Key prefixes of the items `reconcileItems` raises about a source or a block. */
8749
+ const SOURCE_KEY = "source:";
8750
+ const OPERATOR_BLOCK_KEY = "operator-block:";
8751
+ const BLOCK_KEY = "block:";
8752
+ const CONVERSATION_KEY = "conversation:";
8753
+ /** The block an item is about: its ledger block, else the block its key names. */
8754
+ function itemBlockRef(item) {
8755
+ if (item.block_id !== null) return item.block_id;
8756
+ for (const prefix of [
8757
+ OPERATOR_BLOCK_KEY,
8758
+ BLOCK_KEY,
8759
+ CONVERSATION_KEY
8760
+ ]) {
8761
+ if (!item.item_key.startsWith(prefix)) continue;
8762
+ const id = Number(item.item_key.slice(prefix.length));
8763
+ return Number.isSafeInteger(id) && id > 0 ? id : void 0;
8764
+ }
8765
+ }
8747
8766
  /** Guards a stored kind: the column is free text and old or hand-written rows may hold others. */
8748
8767
  function isItemKind(kind) {
8749
8768
  return Object.hasOwn(ITEM_POLICY, kind);
@@ -10545,13 +10564,18 @@ async function ringStillCurrent(trx, notificationId, sessionId, config) {
10545
10564
  if (await trx.selectFrom("notification").select("id").where("id", "=", n.id).where(courseHold).executeTakeFirst() !== void 0) return "defer";
10546
10565
  return recipientBusy(session) && !await spurBlind$1(trx) ? "defer" : "send";
10547
10566
  }
10567
+ /** The comment of an inbound author ring, named in its `doorbell:comment:<id>:` key. */
10568
+ function ringCommentId(dedupeKey) {
10569
+ const id = /^doorbell:comment:(\d+):/.exec(dedupeKey)?.[1];
10570
+ return id === void 0 ? void 0 : Number(id);
10571
+ }
10548
10572
  /**
10549
10573
  * The task of a ring: through its notification, or for an inbound author ring (no notification)
10550
10574
  * through the comment in its `doorbell:comment:<id>:` key. Archive kills only unclaimed rings;
10551
10575
  * the sender drops a claimed one of an archived task before its send starts.
10552
10576
  */
10553
10577
  async function ringTask(trx, notificationId, dedupeKey) {
10554
- const commentId = /^doorbell:comment:(\d+):/.exec(dedupeKey)?.[1];
10578
+ const commentId = ringCommentId(dedupeKey);
10555
10579
  if (notificationId === void 0 && commentId === void 0) return void 0;
10556
10580
  const owner = notificationId !== void 0 ? trx.selectFrom("notification").select("task_id").where("id", "=", notificationId) : trx.selectFrom("comment").select("task_id").where("id", "=", Number(commentId));
10557
10581
  return trx.selectFrom("task").selectAll().where("id", "in", owner).executeTakeFirst();
@@ -11082,6 +11106,68 @@ function tokenAttentionLine(attention, unusedAfterDays) {
11082
11106
  return `${head}: ${String(total)} not named`;
11083
11107
  }
11084
11108
  //#endregion
11109
+ //#region ../core/src/api/ops-route.ts
11110
+ function inputBody(body) {
11111
+ if (body === null || typeof body !== "object" || Array.isArray(body)) throw new CommandError("usage", "Send a JSON object with input and optional key.");
11112
+ const record = body;
11113
+ 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.");
11114
+ return {
11115
+ input: record["input"],
11116
+ key: record["key"]
11117
+ };
11118
+ }
11119
+ function installOperationErrors(app, options) {
11120
+ const handler = (error, request, reply) => {
11121
+ let code = "unexpected";
11122
+ let hint;
11123
+ if (error instanceof CommandError) {
11124
+ code = error.code;
11125
+ hint = error.hint;
11126
+ } else if (error instanceof Error && "statusCode" in error) {
11127
+ if (error.statusCode === 400 || error.statusCode === 413) code = "usage";
11128
+ if (error.statusCode === 413) hint = "Send a smaller JSON body.";
11129
+ }
11130
+ if (code === "unexpected") options.logError?.({
11131
+ requestId: request.id,
11132
+ err: error
11133
+ });
11134
+ const problem = renderHttpProblem({
11135
+ code,
11136
+ requestId: request.id
11137
+ });
11138
+ reply.code(problem.status).type("application/problem+json").send(hint === void 0 ? problem.body : {
11139
+ ...problem.body,
11140
+ hint
11141
+ });
11142
+ };
11143
+ app.setErrorHandler(handler);
11144
+ return handler;
11145
+ }
11146
+ function createOpsRoute(app, options, callers = /* @__PURE__ */ new WeakMap()) {
11147
+ const notReady = () => options.stopping?.() === true ? new CommandError("stopping", "Wait until the daemon is running again.") : new CommandError("starting", "Wait until the daemon is ready.");
11148
+ app.post("/v1/ops/:id", { onRequest: async (request) => {
11149
+ if (!options.ready()) throw notReady();
11150
+ callers.set(request, await options.identify(request));
11151
+ } }, async (request, reply) => {
11152
+ const caller = callers.get(request);
11153
+ if (caller === void 0) throw new Error("Operation identity was not resolved.");
11154
+ const operation = OPERATIONS.find((entry) => entry.id === request.params.id);
11155
+ 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.");
11156
+ if (options.allow?.(operation) === false) throw new CommandError("forbidden", "This operation is not available on the web.");
11157
+ const body = inputBody(request.body);
11158
+ const parsed = operation.input.safeParse(body.input);
11159
+ if (!parsed.success) throw new CommandError(errorCodeOf(parsed.error), "Fix the operation input.");
11160
+ const dispatch = () => dispatchOperation(options, operation.id, parsed.data, caller.actor, body.key);
11161
+ const result = await (options.runOperation === void 0 ? dispatch() : options.runOperation(operation.id, parsed.data, dispatch));
11162
+ await options.afterOperation?.(reply.raw);
11163
+ return reply.send(successEnvelopeSchema.parse({
11164
+ ok: true,
11165
+ requestId: request.id,
11166
+ value: result
11167
+ }));
11168
+ });
11169
+ }
11170
+ //#endregion
11085
11171
  //#region ../core/src/api/identity.ts
11086
11172
  function sessionActor(project, session, config) {
11087
11173
  const actor = actorIdSchema.safeParse(`agent:${project}/${session}`);
@@ -11140,15 +11226,6 @@ const skillReloadsSchema = z.strictObject({
11140
11226
  function header(value) {
11141
11227
  return Array.isArray(value) ? void 0 : value;
11142
11228
  }
11143
- function inputBody(body) {
11144
- if (body === null || typeof body !== "object" || Array.isArray(body)) throw new CommandError("usage", "Send a JSON object with input and optional key.");
11145
- const record = body;
11146
- 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.");
11147
- return {
11148
- input: record["input"],
11149
- key: record["key"]
11150
- };
11151
- }
11152
11229
  /** Construct the local HTTP transport; the caller owns listen and close. */
11153
11230
  async function createApiServer(options) {
11154
11231
  const app = Fastify({
@@ -11186,29 +11263,7 @@ async function createApiServer(options) {
11186
11263
  });
11187
11264
  done();
11188
11265
  });
11189
- app.setErrorHandler((error, request, reply) => {
11190
- let code = "unexpected";
11191
- let hint;
11192
- if (error instanceof CommandError) {
11193
- code = error.code;
11194
- hint = error.hint;
11195
- } else if (error instanceof Error && "statusCode" in error) {
11196
- if (error.statusCode === 400 || error.statusCode === 413) code = "usage";
11197
- if (error.statusCode === 413) hint = "Send a smaller JSON body.";
11198
- }
11199
- if (code === "unexpected") options.logError?.({
11200
- requestId: request.id,
11201
- err: error
11202
- });
11203
- const problem = renderHttpProblem({
11204
- code,
11205
- requestId: request.id
11206
- });
11207
- reply.code(problem.status).type("application/problem+json").send(hint === void 0 ? problem.body : {
11208
- ...problem.body,
11209
- hint
11210
- });
11211
- });
11266
+ installOperationErrors(app, options);
11212
11267
  app.setNotFoundHandler(() => {
11213
11268
  throw new CommandError("not_found", "This API route is not available.");
11214
11269
  });
@@ -11293,31 +11348,17 @@ async function createApiServer(options) {
11293
11348
  }
11294
11349
  }));
11295
11350
  });
11296
- app.post("/v1/ops/:id", { onRequest: async (request) => {
11297
- if (!options.ready()) throw notReady();
11298
- const sessionHeader = request.headers["x-board-session"];
11299
- if (Array.isArray(sessionHeader)) throw new CommandError("forbidden", "Use one session identity header.");
11300
- callers.set(request, await identifyCaller(options, {
11301
- session: sessionHeader,
11302
- authorization: header(request.headers.authorization)
11303
- }));
11304
- } }, async (request, reply) => {
11305
- const caller = callers.get(request);
11306
- if (caller === void 0) throw new Error("Operation identity was not resolved.");
11307
- const operation = OPERATIONS.find((entry) => entry.id === request.params.id);
11308
- 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.");
11309
- const body = inputBody(request.body);
11310
- const parsed = operation.input.safeParse(body.input);
11311
- if (!parsed.success) throw new CommandError(errorCodeOf(parsed.error), "Fix the operation input.");
11312
- const dispatch = () => dispatchOperation(options, operation.id, parsed.data, caller.actor, body.key);
11313
- const result = await (options.runOperation === void 0 ? dispatch() : options.runOperation(operation.id, parsed.data, dispatch));
11314
- await options.afterOperation?.(reply.raw);
11315
- return reply.send(successEnvelopeSchema.parse({
11316
- ok: true,
11317
- requestId: request.id,
11318
- value: result
11319
- }));
11320
- });
11351
+ createOpsRoute(app, {
11352
+ ...options,
11353
+ identify: async (request) => {
11354
+ const sessionHeader = request.headers["x-board-session"];
11355
+ if (Array.isArray(sessionHeader)) throw new CommandError("forbidden", "Use one session identity header.");
11356
+ return identifyCaller(options, {
11357
+ session: sessionHeader,
11358
+ authorization: header(request.headers.authorization)
11359
+ });
11360
+ }
11361
+ }, callers);
11321
11362
  return app;
11322
11363
  }
11323
11364
  /** The only supported listener for the local API. */
@@ -11840,6 +11881,30 @@ function blockView(block, subject) {
11840
11881
  unblockedAt: block.unblocked_at
11841
11882
  };
11842
11883
  }
11884
+ /** A task's blocks, oldest first, each with the `via` of its closing write. */
11885
+ async function taskBlockViews(trx, task) {
11886
+ const subject = taskSubject(task);
11887
+ return (await trx.selectFrom("block").selectAll().select(answeredViaColumn).where("task_id", "=", task.id).orderBy("id").execute()).map(({ answered_via, ...block }) => ({
11888
+ ...blockView(block, subject),
11889
+ answeredVia: answeredVia(answered_via)
11890
+ }));
11891
+ }
11892
+ /**
11893
+ * The `via` of the `block_unblocked` event that closed the `block` row in scope: `closeOpenBlock`
11894
+ * journals it at the block's `unblocked_at`, so the `event_at` index finds it. Select it from a
11895
+ * query over `block` and read the value with `answeredVia`.
11896
+ */
11897
+ const answeredViaColumn = sql`(
11898
+ select event.via from event
11899
+ where event.kind = 'block_unblocked'
11900
+ and event.at = block.unblocked_at
11901
+ and json_extract(event.payload, '$.block') = 'B' || block.id
11902
+ order by event.id desc limit 1
11903
+ )`.as("answered_via");
11904
+ /** The `via` of a block's closing write; null while open or when it came another way. */
11905
+ function answeredVia(value) {
11906
+ return VIAS.find((via) => via === value) ?? null;
11907
+ }
11843
11908
  function commentView(comment, subject) {
11844
11909
  return {
11845
11910
  id: commentId(comment.id),
@@ -13580,19 +13645,63 @@ const deliveryPayloadSchema = z.object({
13580
13645
  taskId: z.unknown().optional(),
13581
13646
  notificationId: z.unknown().optional()
13582
13647
  });
13583
- /** The task a `delivery:<outbox id>` item's row belongs to; the item itself has no task. */
13584
- async function deliveryTask(trx, item) {
13585
- if (item.kind !== "post_failed") return void 0;
13586
- const row = await trx.selectFrom("outbox").select([
13648
+ /** The outbox row of a `delivery:<outbox id>` item; the item itself has no task. */
13649
+ function deliveryId(item) {
13650
+ return item.kind === "post_failed" && item.task_id === null ? Number(item.item_key.slice(9)) : void 0;
13651
+ }
13652
+ /**
13653
+ * The task each failed delivery item's outbox row belongs to: the payload's task, else for a
13654
+ * doorbell its ring's (`ringTask`). Reads at most four statements, whatever the item count.
13655
+ */
13656
+ async function deliveryOwners(trx, items) {
13657
+ const owners = /* @__PURE__ */ new Map();
13658
+ const outboxIds = items.flatMap((item) => deliveryId(item) ?? []);
13659
+ if (outboxIds.length === 0) return owners;
13660
+ const rows = await trx.selectFrom("outbox").select([
13661
+ "id",
13587
13662
  "kind",
13588
13663
  "dedupe_key",
13589
13664
  "payload"
13590
- ]).where("id", "=", Number(item.item_key.slice(9))).executeTakeFirst();
13591
- if (row === void 0) return void 0;
13592
- const payload = parseJson(deliveryPayloadSchema, row.payload);
13593
- if (typeof payload.taskId === "number") return trx.selectFrom("task").selectAll().where("id", "=", payload.taskId).executeTakeFirst();
13594
- if (row.kind !== "doorbell") return void 0;
13595
- return ringTask(trx, typeof payload.notificationId === "number" ? payload.notificationId : void 0, row.dedupe_key);
13665
+ ]).where("id", "in", outboxIds).execute();
13666
+ const refs = /* @__PURE__ */ new Map();
13667
+ for (const row of rows) {
13668
+ const payload = parseJson(deliveryPayloadSchema, row.payload);
13669
+ if (typeof payload.taskId === "number") refs.set(row.id, { task: payload.taskId });
13670
+ else if (row.kind !== "doorbell") continue;
13671
+ else if (typeof payload.notificationId === "number") refs.set(row.id, { notification: payload.notificationId });
13672
+ else {
13673
+ const comment = ringCommentId(row.dedupe_key);
13674
+ if (comment !== void 0) refs.set(row.id, { comment });
13675
+ }
13676
+ }
13677
+ const ids = (pick) => [...refs.values()].flatMap((ref) => ref[pick] ?? []);
13678
+ const [notifications, comments] = await Promise.all(["notification", "comment"].map((table) => {
13679
+ const wanted = ids(table);
13680
+ return wanted.length === 0 ? Promise.resolve([]) : trx.selectFrom(table).select(["id", "task_id"]).where("id", "in", wanted).execute();
13681
+ }));
13682
+ const taskOf = {
13683
+ notification: new Map(notifications?.map((row) => [row.id, row.task_id])),
13684
+ comment: new Map(comments?.map((row) => [row.id, row.task_id]))
13685
+ };
13686
+ const taskIds = /* @__PURE__ */ new Map();
13687
+ for (const [outboxId, ref] of refs) {
13688
+ const taskId = ref.task ?? (ref.notification === void 0 ? void 0 : taskOf.notification.get(ref.notification)) ?? (ref.comment === void 0 ? void 0 : taskOf.comment.get(ref.comment));
13689
+ if (typeof taskId === "number") taskIds.set(outboxId, taskId);
13690
+ }
13691
+ if (taskIds.size === 0) return owners;
13692
+ const tasks = await trx.selectFrom("task").selectAll().where("id", "in", [...new Set(taskIds.values())]).execute();
13693
+ const taskById = new Map(tasks.map((task) => [task.id, task]));
13694
+ for (const item of items) {
13695
+ const outboxId = deliveryId(item);
13696
+ const taskId = outboxId === void 0 ? void 0 : taskIds.get(outboxId);
13697
+ const task = taskId === void 0 ? void 0 : taskById.get(taskId);
13698
+ if (task !== void 0) owners.set(item.id, task);
13699
+ }
13700
+ return owners;
13701
+ }
13702
+ /** The task a `delivery:<outbox id>` item's row belongs to; the item itself has no task. */
13703
+ async function deliveryTask(trx, item) {
13704
+ return (await deliveryOwners(trx, [item])).get(item.id);
13596
13705
  }
13597
13706
  /** The task an item belongs to: its own, else its delivery's; undefined for a board item. */
13598
13707
  async function itemOwner(trx, item) {
@@ -13939,6 +14048,199 @@ function createLinkMutations(config, deps = {}) {
13939
14048
  };
13940
14049
  }
13941
14050
  //#endregion
14051
+ //#region ../core/src/app/operator-inbox.ts
14052
+ /** How far back `handled` reaches, and how many entries it keeps. */
14053
+ const HANDLED_WINDOW_MS = 1440 * 60 * 1e3;
14054
+ const HANDLED_MAX = 20;
14055
+ /** What a failure item asks the operator to check; a `source:` item gets its own text. */
14056
+ const CHECK_HINTS = {
14057
+ transport_health: (item) => `the ${capitalized(item.item_key.slice(10))} app tokens`,
14058
+ post_failed: () => "the chat gateway, then retry the item",
14059
+ inbound_failure: () => "the daemon log, then retry the item",
14060
+ inbound_gap: () => "the conversation for missed messages",
14061
+ answer_undelivered: () => "the asking session, then retry the item",
14062
+ worker_not_reading: () => "the worker session, then retry the item"
14063
+ };
14064
+ const PROBLEMS = {
14065
+ auth: "auth failed",
14066
+ config: "config rejected",
14067
+ stale: "unreachable"
14068
+ };
14069
+ function capitalized(text) {
14070
+ return text.charAt(0).toUpperCase() + text.slice(1);
14071
+ }
14072
+ function serviceOf(source) {
14073
+ if (source === "spur") return "Spur";
14074
+ if (source.startsWith("github:") || source.startsWith("github-issues:")) return "GitHub";
14075
+ return source.startsWith("jira:") ? "Jira" : void 0;
14076
+ }
14077
+ /**
14078
+ * The text of a source item: built from the source's state while it is open and blind; a cleared
14079
+ * or unknown one keeps its stored text, which names the failure it had.
14080
+ */
14081
+ function sourceText(item, state) {
14082
+ const source = item.item_key.slice(7);
14083
+ const stored = `${item.text}: check the ${source} source`;
14084
+ const reason = state?.blind_reason ?? null;
14085
+ const service = serviceOf(source);
14086
+ if (item.cleared_at !== null || reason === null || service === void 0) return stored;
14087
+ const problem = PROBLEMS[reason];
14088
+ const thing = reason === "auth" ? `the ${service} token` : reason === "config" ? `the ${source} settings in the board config` : reason === "stale" && source === "spur" ? "the Spur daemon" : void 0;
14089
+ if (problem === void 0 || thing === void 0) return stored;
14090
+ const message = state?.blind_message ?? null;
14091
+ return `${service} ${problem}${message === null ? "" : ` (${message})`}: check ${thing}`;
14092
+ }
14093
+ /** Newest first by `at`, ties by id as text. */
14094
+ function newestFirst(at) {
14095
+ return (left, right) => at(right).localeCompare(at(left)) || (left.id < right.id ? -1 : left.id > right.id ? 1 : 0);
14096
+ }
14097
+ function owner(row) {
14098
+ return row.task_key === null || row.task_project === null || row.task_membership === null ? null : {
14099
+ key: row.task_key,
14100
+ project: row.task_project,
14101
+ membership: row.task_membership
14102
+ };
14103
+ }
14104
+ const taskColumns = [
14105
+ "task.key as task_key",
14106
+ "task.project as task_project",
14107
+ "task.membership as task_membership"
14108
+ ];
14109
+ /**
14110
+ * The operator's inbox across every project the caller is operator of: open operator items,
14111
+ * blocks addressed to the operator and operator turns, and what of them was handled in the last
14112
+ * day. A block or turn is listed once, without the items that mirror it.
14113
+ */
14114
+ function createOperatorInbox(deps) {
14115
+ const { config, clock } = deps;
14116
+ const configured = new Set(config.projects.map((project) => project.id));
14117
+ /** A project-level block's project, or `_board` once the project has left the config. */
14118
+ const blockProject = (project) => project !== null && configured.has(project) ? project : RESERVED_PROJECT;
14119
+ return {
14120
+ id: "inbox.operator",
14121
+ resolveTargets(_trx, _input, actor) {
14122
+ return Promise.resolve(config.projects.filter((project) => isOperator(actor, config, project.id)).map((project) => projectTarget(project.id)));
14123
+ },
14124
+ async run(trx, _input, actor) {
14125
+ const since = (/* @__PURE__ */ new Date(clock.now() - HANDLED_WINDOW_MS)).toISOString();
14126
+ const boardScope = authorize([{ grant: "operator" }], actor, {
14127
+ config,
14128
+ target: { kind: "missing" }
14129
+ }).status === "allowed";
14130
+ const operatorProjects = new Set(config.projects.filter((project) => isOperator(actor, config, project.id)).map((project) => project.id));
14131
+ const visible = (entry) => entry.project === "_board" ? boardScope : operatorProjects.has(entry.project);
14132
+ const [openItems, clearedItems, openBlocks, closedBlocks, openTurns, closedTurns] = await Promise.all([
14133
+ itemRows(trx).where("operator_item.cleared_at", "is", null).execute(),
14134
+ itemRows(trx).where("operator_item.cleared_at", ">=", since).orderBy("operator_item.cleared_at").orderBy("operator_item.id").execute(),
14135
+ blockRows(trx).where("block.state", "=", "open").execute(),
14136
+ blockRows(trx).select(answeredViaColumn).where("block.state", "=", "unblocked").where("block.unblocked_at", ">=", since).execute(),
14137
+ turnRows(trx).where("turn.closed_at", "is", null).execute(),
14138
+ turnRows(trx).where("turn.closed_at", ">=", since).execute()
14139
+ ]);
14140
+ const openKeys = new Set(openItems.map((item) => item.item_key));
14141
+ const lastCleared = /* @__PURE__ */ new Map();
14142
+ for (const item of clearedItems) {
14143
+ if (openKeys.has(item.item_key)) continue;
14144
+ lastCleared.set(item.item_key, item);
14145
+ }
14146
+ const items = [...openItems, ...lastCleared.values()];
14147
+ const blockIds = [...new Set(items.flatMap((item) => itemBlockRef(item) ?? []))];
14148
+ const sourceIds = items.flatMap((item) => item.item_key.startsWith("source:") ? [item.item_key.slice(7)] : []);
14149
+ const [referenced, owners, sources] = await Promise.all([
14150
+ blockIds.length === 0 ? Promise.resolve([]) : trx.selectFrom("block").leftJoin("task", "task.id", "block.task_id").select([
14151
+ "block.id",
14152
+ "block.addressee_role",
14153
+ "block.project",
14154
+ ...taskColumns
14155
+ ]).where("block.id", "in", blockIds).execute(),
14156
+ deliveryOwners(trx, items),
14157
+ sourceIds.length === 0 ? Promise.resolve([]) : trx.selectFrom("source_state").select([
14158
+ "source",
14159
+ "blind_reason",
14160
+ "blind_message"
14161
+ ]).where("source", "in", sourceIds).execute()
14162
+ ]);
14163
+ const blockById = new Map(referenced.map((block) => [block.id, block]));
14164
+ const sourceById = new Map(sources.map((state) => [state.source, state]));
14165
+ const itemEntry = (item) => {
14166
+ const kind = item.kind;
14167
+ if (!isItemKind(kind) || kind === "turn") return void 0;
14168
+ const ref = itemBlockRef(item);
14169
+ const block = ref === void 0 ? void 0 : blockById.get(ref);
14170
+ if (block?.addressee_role === "operator" && (ITEM_POLICY[kind].block || item.item_key.startsWith("operator-block:") || item.item_key.startsWith("block:"))) return void 0;
14171
+ const task = owner(item) ?? owners.get(item.id) ?? (block === void 0 ? null : owner(block));
14172
+ if (task?.membership === "archived") return void 0;
14173
+ const hint = CHECK_HINTS[kind];
14174
+ return {
14175
+ id: `I${String(item.id)}`,
14176
+ project: task?.project ?? (block === void 0 ? "_board" : blockProject(block.project)),
14177
+ kind,
14178
+ severity: itemSeverity(kind, item.item_key),
14179
+ text: item.item_key.startsWith("source:") ? sourceText(item, sourceById.get(item.item_key.slice(7))) : hint === void 0 ? item.text : `${item.text}: check ${hint(item)}`,
14180
+ at: item.raised_at,
14181
+ task: task?.key ?? null,
14182
+ ...item.cleared_at === null ? {} : { handledAt: item.cleared_at }
14183
+ };
14184
+ };
14185
+ const blockEntry = (block, via) => {
14186
+ const task = owner(block);
14187
+ if (task?.membership === "archived") return void 0;
14188
+ return {
14189
+ id: `B${String(block.id)}`,
14190
+ project: task?.project ?? blockProject(block.project),
14191
+ kind: "block",
14192
+ severity: "attention",
14193
+ text: block.reason,
14194
+ at: block.created_at,
14195
+ task: task?.key ?? null,
14196
+ answeredVia: via,
14197
+ ...block.unblocked_at === null || block.state === "open" ? {} : { handledAt: block.unblocked_at }
14198
+ };
14199
+ };
14200
+ const turnEntry = (turn) => {
14201
+ const task = owner(turn);
14202
+ if (task === null || task.membership === "archived") return void 0;
14203
+ return {
14204
+ id: `T${String(turn.id)}`,
14205
+ project: task.project,
14206
+ kind: "turn",
14207
+ severity: "attention",
14208
+ text: `Your turn T${String(turn.id)}: ${turn.reason}`,
14209
+ at: turn.created_at,
14210
+ task: task.key,
14211
+ column: turn.column,
14212
+ ...turn.closed_at === null ? {} : { handledAt: turn.closed_at }
14213
+ };
14214
+ };
14215
+ const listed = (entries) => entries.filter((entry) => entry !== void 0 && visible(entry));
14216
+ return {
14217
+ items: listed([
14218
+ ...openItems.map(itemEntry),
14219
+ ...openBlocks.map((block) => blockEntry(block, null)),
14220
+ ...openTurns.map(turnEntry)
14221
+ ]).sort(newestFirst((entry) => entry.at)),
14222
+ handled: listed([
14223
+ ...[...lastCleared.values()].map(itemEntry),
14224
+ ...closedBlocks.map(({ answered_via, ...block }) => blockEntry(block, answeredVia(answered_via))),
14225
+ ...closedTurns.map(turnEntry)
14226
+ ]).sort(newestFirst((entry) => entry.handledAt ?? entry.at)).slice(0, HANDLED_MAX).map(({ handledAt, ...entry }) => ({
14227
+ ...entry,
14228
+ handledAt: handledAt ?? entry.at
14229
+ }))
14230
+ };
14231
+ }
14232
+ };
14233
+ }
14234
+ function itemRows(trx) {
14235
+ return trx.selectFrom("operator_item").leftJoin("task", "task.id", "operator_item.task_id").selectAll("operator_item").select(taskColumns);
14236
+ }
14237
+ function blockRows(trx) {
14238
+ return trx.selectFrom("block").leftJoin("task", "task.id", "block.task_id").selectAll("block").select(taskColumns).where("block.addressee_role", "=", "operator");
14239
+ }
14240
+ function turnRows(trx) {
14241
+ return trx.selectFrom("turn").innerJoin("task", "task.id", "turn.task_id").selectAll("turn").select(taskColumns).where("turn.role", "=", "operator");
14242
+ }
14243
+ //#endregion
13942
14244
  //#region ../core/src/app/status-views.ts
13943
14245
  /** Factual PR rollup; the caller owns snapshot freshness and all reads. */
13944
14246
  function summarizePr(fact, factAt, unconfirmed) {
@@ -15055,7 +15357,7 @@ async function conversationWaiting(trx, config, block, subject) {
15055
15357
  if (await trx.selectFrom("notification").select("id").where("block_id", "=", block.id).where("kind", "in", ["block", "answer"]).where("acked_at", "is", null).where("exhausted_at", "is", null).executeTakeFirst() === void 0 || await bestProjectSession(trx, spur) !== void 0) return void 0;
15056
15358
  const shortName = config.projects.flatMap((project) => project.spurProjects).find((entry) => entry.name === spur)?.shortName ?? spur;
15057
15359
  return {
15058
- key: `conversation:${String(block.id)}`,
15360
+ key: `${CONVERSATION_KEY}${String(block.id)}`,
15059
15361
  kind: "conversation_waiting",
15060
15362
  taskId: subject.task?.id ?? null,
15061
15363
  summary: `${subject.key}: message to @${shortName} waits for a live ${spur} session`,
@@ -15073,7 +15375,7 @@ async function reconcileItems(trx, config, now, spurComplete, warnSkipped, spurC
15073
15375
  if (source.blind_reason === null) continue;
15074
15376
  if (source.blind_reason === "stale" && source.source !== "spur") continue;
15075
15377
  candidates.push({
15076
- key: `source:${source.source}`,
15378
+ key: `${SOURCE_KEY}${source.source}`,
15077
15379
  kind: "board_observation",
15078
15380
  taskId: null,
15079
15381
  summary: `${source.source}: ${source.blind_message ?? source.blind_reason}`,
@@ -15138,7 +15440,7 @@ async function reconcileItems(trx, config, now, spurComplete, warnSkipped, spurC
15138
15440
  if (subject === void 0 || ledgerIds.has(block.id)) continue;
15139
15441
  const taskId = subject.task?.id ?? null;
15140
15442
  if (block.addressee_role === "operator" && block.author !== "operator" && !blockedIds.has(block.id)) candidates.push({
15141
- key: `operator-block:${String(block.id)}`,
15443
+ key: `${OPERATOR_BLOCK_KEY}${String(block.id)}`,
15142
15444
  kind: "board_observation",
15143
15445
  taskId,
15144
15446
  summary: `${subject.key}: ${block.reason}`,
@@ -15151,7 +15453,7 @@ async function reconcileItems(trx, config, now, spurComplete, warnSkipped, spurC
15151
15453
  if (waiting !== void 0) candidates.push(waiting);
15152
15454
  }
15153
15455
  if (now - Date.parse(block.created_at) >= config.thresholds.blockOpenMs) candidates.push({
15154
- key: `block:${String(block.id)}`,
15456
+ key: `${BLOCK_KEY}${String(block.id)}`,
15155
15457
  kind: "board_observation",
15156
15458
  taskId,
15157
15459
  summary: `${subject.key}: block has been open for more than a day`,
@@ -16658,7 +16960,7 @@ function createTaskQueries(deps) {
16658
16960
  async run(trx, input) {
16659
16961
  const task = await taskByKey(trx, taskKey(input.task));
16660
16962
  const [blocks, comments, links] = await Promise.all([
16661
- trx.selectFrom("block").selectAll().where("task_id", "=", task.id).orderBy("id").execute(),
16963
+ taskBlockViews(trx, task),
16662
16964
  trx.selectFrom("comment").selectAll().where("task_id", "=", task.id).orderBy("id").execute(),
16663
16965
  trx.selectFrom("link").leftJoin("pr_snapshot", (join) => join.on(sql`lower(pr_snapshot.repo) = lower(link.repo)`).onRef("pr_snapshot.number", "=", "link.number")).selectAll("link").select("pr_snapshot.state").where("link.task_id", "=", task.id).where("link.banned", "=", 0).orderBy("link.id").execute()
16664
16966
  ]);
@@ -16674,7 +16976,7 @@ function createTaskQueries(deps) {
16674
16976
  ...observed === void 0 ? {} : { state: observed }
16675
16977
  };
16676
16978
  }),
16677
- blocks: blocks.map((block) => blockView(block, subject)),
16979
+ blocks,
16678
16980
  comments: comments.map((comment) => commentView(comment, subject)),
16679
16981
  ...input.why === true ? { why: await why(trx, task) } : {}
16680
16982
  };
@@ -17255,6 +17557,10 @@ function createOperationRegistry(deps) {
17255
17557
  "task.get": taskQueries.get,
17256
17558
  "task.history": taskQueries.history,
17257
17559
  "inbox.get": taskQueries.inbox,
17560
+ "inbox.operator": createOperatorInbox({
17561
+ config,
17562
+ clock
17563
+ }),
17258
17564
  "token.list": tokenListQuery(clock),
17259
17565
  "token.revoke": tokenRevokeMutation,
17260
17566
  "task.add": membership.add,
@@ -19313,6 +19619,132 @@ function createInbound(input) {
19313
19619
  };
19314
19620
  }
19315
19621
  //#endregion
19622
+ //#region ../core/src/api/web-server.ts
19623
+ const mime = {
19624
+ ".html": "text/html; charset=utf-8",
19625
+ ".js": "text/javascript; charset=utf-8",
19626
+ ".css": "text/css; charset=utf-8",
19627
+ ".json": "application/json",
19628
+ ".svg": "image/svg+xml",
19629
+ ".png": "image/png",
19630
+ ".ico": "image/x-icon",
19631
+ ".woff2": "font/woff2",
19632
+ ".webp": "image/webp"
19633
+ };
19634
+ async function loadFiles(root) {
19635
+ const files = /* @__PURE__ */ new Map();
19636
+ async function walk(dir, prefix) {
19637
+ for (const entry of await readdir(dir, { withFileTypes: true })) {
19638
+ const path = typeof dir === "string" ? join(dir, entry.name) : new URL(entry.name + (entry.isDirectory() ? "/" : ""), dir);
19639
+ const key = `${prefix}/${entry.name}`;
19640
+ if (entry.isDirectory()) await walk(path, key);
19641
+ else if (entry.isFile()) files.set(key, await readFile(path));
19642
+ }
19643
+ }
19644
+ try {
19645
+ await walk(root, "");
19646
+ } catch (err) {
19647
+ if (!(err instanceof Error && "code" in err && (err.code === "ENOENT" || err.code === "ENOTDIR"))) throw err;
19648
+ files.clear();
19649
+ }
19650
+ return files;
19651
+ }
19652
+ /** Independent browser transport; the caller owns listening and shutdown. */
19653
+ async function createWebServer(options) {
19654
+ const files = await loadFiles(options.webRoot);
19655
+ const app = Fastify({
19656
+ logger: false,
19657
+ genReqId: () => randomUUID(),
19658
+ trustProxy: false,
19659
+ frameworkErrors(error, request, reply) {
19660
+ secure(reply);
19661
+ reply.raw.once("finish", () => {
19662
+ audit(request, reply);
19663
+ });
19664
+ try {
19665
+ guard(request, reply);
19666
+ } catch (err) {
19667
+ errorHandler(err, request, reply);
19668
+ return;
19669
+ }
19670
+ errorHandler(error.code === "FST_ERR_MAX_PARAM_LENGTH" ? new CommandError("usage", "Use a shorter web path.") : error, request, reply);
19671
+ }
19672
+ });
19673
+ const errorHandler = installOperationErrors(app, options);
19674
+ function guard(request, reply) {
19675
+ reply.header("x-request-id", request.id);
19676
+ const address = app.server.address();
19677
+ const origin = resolveWebOrigin(options.config.web, address !== null && typeof address === "object" ? address.port : void 0);
19678
+ if (origin === void 0 || request.headers.host !== new URL(origin).host) throw new CommandError("forbidden", "Use the configured web host.");
19679
+ if (request.headers["sec-fetch-site"] === "cross-site") throw new CommandError("forbidden", "Cross-site requests are not accepted.");
19680
+ if (request.method !== "GET" && request.method !== "HEAD" && request.headers.origin !== origin) throw new CommandError("forbidden", "Use the configured web origin.");
19681
+ if (request.method === "POST" && request.headers["content-type"]?.split(";", 1)[0]?.trim().toLowerCase() !== "application/json") throw new CommandError("forbidden", "Use application/json.");
19682
+ const rawPath = request.raw.url?.split("?", 1)[0] ?? "";
19683
+ let decoded;
19684
+ try {
19685
+ decoded = decodeURIComponent(rawPath);
19686
+ } catch {
19687
+ throw new CommandError("not_found", "Invalid web path.");
19688
+ }
19689
+ if (decoded.split(/[\\/]/).some((part) => part === ".." || part === ".")) throw new CommandError("not_found", "Invalid web path.");
19690
+ }
19691
+ function secure(reply) {
19692
+ reply.header("content-security-policy", "default-src 'self'; frame-ancestors 'none'");
19693
+ reply.header("x-frame-options", "DENY");
19694
+ reply.header("x-content-type-options", "nosniff");
19695
+ reply.header("referrer-policy", "no-referrer");
19696
+ }
19697
+ function audit(request, reply) {
19698
+ const forwardedFor = request.headers["x-forwarded-for"];
19699
+ const userAgent = request.headers["user-agent"];
19700
+ options.logRequest({
19701
+ requestId: request.id,
19702
+ method: request.method,
19703
+ path: request.url.split("?", 1)[0] ?? "/",
19704
+ status: reply.statusCode,
19705
+ via: "web",
19706
+ ...typeof forwardedFor === "string" ? { forwardedFor } : {},
19707
+ ...userAgent === void 0 ? {} : { userAgent }
19708
+ });
19709
+ }
19710
+ app.addHook("onRequest", async (request, reply) => {
19711
+ guard(request, reply);
19712
+ });
19713
+ app.addHook("onSend", async (_request, reply) => {
19714
+ secure(reply);
19715
+ });
19716
+ app.addHook("onResponse", (request, reply, done) => {
19717
+ audit(request, reply);
19718
+ done();
19719
+ });
19720
+ createOpsRoute(app, {
19721
+ ...options,
19722
+ identify: () => Promise.resolve({ actor: "operator" }),
19723
+ allow: (operation) => operation.web !== null,
19724
+ runOperation: (id, input, run) => withVia("web", () => options.runOperation === void 0 ? run() : options.runOperation(id, input, run))
19725
+ });
19726
+ app.get("/v1/health", async () => {
19727
+ if (!options.ready()) throw new CommandError(options.stopping?.() === true ? "stopping" : "starting", "Wait until the daemon is ready.");
19728
+ if (options.firstPollDone === void 0) throw new CommandError("not_found", "Health is unavailable.");
19729
+ return { firstPollDone: await options.firstPollDone() };
19730
+ });
19731
+ app.setNotFoundHandler(async (request, reply) => {
19732
+ const path = request.url.split("?", 1)[0] ?? "/";
19733
+ if (request.method !== "GET" && request.method !== "HEAD" || path === "/v1" || path.startsWith("/v1/")) throw new CommandError("not_found", "This web route is not available.");
19734
+ const key = path === "/" ? "/index.html" : path;
19735
+ const file = key === "/index.html" || path.startsWith("/assets/") ? files.get(key) : void 0;
19736
+ const fallback = extname(path) === "" ? files.get("/index.html") : void 0;
19737
+ if (file === void 0 && fallback === void 0) {
19738
+ if (!files.has("/index.html")) return reply.code(503).type("text/html").send("UI is not built: run `pnpm --filter @spur-board/web build`");
19739
+ throw new CommandError("not_found", "This web asset is not available.");
19740
+ }
19741
+ const index = key === "/index.html" || file === void 0;
19742
+ reply.header("cache-control", index ? "no-cache" : /[.-][a-z0-9_-]{8,}\.[^.]+$/i.test(key) ? "public, max-age=31536000, immutable" : "no-cache");
19743
+ return reply.type(index ? "text/html; charset=utf-8" : mime[extname(key)] ?? "application/octet-stream").send(request.method === "HEAD" ? void 0 : file ?? fallback);
19744
+ });
19745
+ return app;
19746
+ }
19747
+ //#endregion
19316
19748
  //#region ../daemon/src/config.ts
19317
19749
  /** A config or secrets file the daemon cannot use. The message is meant for the operator. */
19318
19750
  var ConfigError = class extends Error {
@@ -24553,9 +24985,10 @@ async function slackBody(response, wire) {
24553
24985
  }
24554
24986
  }
24555
24987
  /** Bounded daemon-side checks; no response body or exception text leaves this module. */
24556
- async function runDaemonDoctor(ctx, productVersion, fetcher = fetch, { deadlineMs = DEADLINE_MS } = {}) {
24988
+ async function runDaemonDoctor(ctx, productVersion, fetcher = fetch, { deadlineMs = DEADLINE_MS, webListening } = {}) {
24557
24989
  const { config, secrets } = ctx;
24558
24990
  const checks = [];
24991
+ if (config.web.port !== void 0) checks.push(check("web.listening", webListening?.() === true, "Free the configured web port and restart the daemon."));
24559
24992
  const jiraTrackers = config.projects.flatMap((project) => project.tracker.type === "jira" ? [project.tracker] : []);
24560
24993
  const slackConfigured = Boolean(config.slack.channels.feed || config.slack.channels.orchestrators);
24561
24994
  const linkSamples = sampleLinks(ctx, fetcher, deadlineMs, secrets["GITHUB_TOKEN"]);
@@ -24676,7 +25109,7 @@ function createHttpModule(ctx, options = {}) {
24676
25109
  registry: options.registry ?? {},
24677
25110
  ...options.afterOperation === void 0 ? {} : { afterOperation: options.afterOperation },
24678
25111
  ...options.runOperation === void 0 ? {} : { runOperation: options.runOperation },
24679
- doctor: options.doctor ?? (() => runDaemonDoctor(ctx, options.productVersion ?? "unknown", options.fetcher)),
25112
+ doctor: options.doctor ?? (() => runDaemonDoctor(ctx, options.productVersion ?? "unknown", options.fetcher, { webListening: options.webListening })),
24680
25113
  ...options.firstPollDone === void 0 ? {} : { firstPollDone: options.firstPollDone },
24681
25114
  ...options.productVersion === void 0 ? {} : { productVersion: options.productVersion },
24682
25115
  logRequest: ({ requestId, method, url, status, tokenName }) => {
@@ -24714,6 +25147,62 @@ function createHttpModule(ctx, options = {}) {
24714
25147
  }
24715
25148
  };
24716
25149
  }
25150
+ /** Optional browser listener: a bind failure must not take down the agent API. */
25151
+ function createWebModule(ctx, options) {
25152
+ let app;
25153
+ return {
25154
+ listening: () => app !== void 0,
25155
+ async start(signal) {
25156
+ const aborted = () => signal.aborted;
25157
+ if (aborted()) return;
25158
+ let server;
25159
+ try {
25160
+ server = await createWebServer({
25161
+ store: ctx.store,
25162
+ config: ctx.config,
25163
+ clock: ctx.clock,
25164
+ registry: options.registry,
25165
+ ready: () => ctx.state() === "ready",
25166
+ stopping: () => ctx.state() === "stopping",
25167
+ ...options.runOperation === void 0 ? {} : { runOperation: options.runOperation },
25168
+ ...options.afterOperation === void 0 ? {} : { afterOperation: options.afterOperation },
25169
+ ...options.firstPollDone === void 0 ? {} : { firstPollDone: options.firstPollDone },
25170
+ webRoot: options.webRoot ?? new URL("./web/", import.meta.url),
25171
+ logRequest: (entry) => {
25172
+ ctx.log.info(entry, "web request");
25173
+ },
25174
+ logError: ({ requestId, err }) => {
25175
+ ctx.log.error({
25176
+ requestId,
25177
+ err
25178
+ }, "web request failed");
25179
+ }
25180
+ });
25181
+ if (aborted()) return;
25182
+ const address = await server.listen({
25183
+ host: "127.0.0.1",
25184
+ port: ctx.config.web.port ?? 0
25185
+ });
25186
+ if (aborted()) return;
25187
+ options.onListening?.(address);
25188
+ app = server;
25189
+ ctx.log.info({ port: Number(new URL(address).port) }, "web listening");
25190
+ } catch (err) {
25191
+ ctx.log.error({
25192
+ err,
25193
+ port: ctx.config.web.port
25194
+ }, "web listener failed");
25195
+ } finally {
25196
+ if (server !== void 0 && app !== server) await server.close();
25197
+ }
25198
+ },
25199
+ async stop() {
25200
+ const server = app;
25201
+ app = void 0;
25202
+ await server?.close();
25203
+ }
25204
+ };
25205
+ }
24717
25206
  //#endregion
24718
25207
  //#region ../daemon/src/inbound-module.ts
24719
25208
  const RECOVERY_MS = 5 * 6e4;
@@ -25063,12 +25552,27 @@ function createDaemonModules(ctxFor, ports = {}) {
25063
25552
  stopStage: "outbox",
25064
25553
  module: outbox
25065
25554
  });
25555
+ const runOperation = (id, input, run) => id === "item.retry" && inbound !== void 0 && isItemInput(input) ? inbound.retrying(input.item, run) : run();
25556
+ const web = board.config.web.port === void 0 ? void 0 : createWebModule(ctxFor("web"), {
25557
+ registry,
25558
+ runOperation,
25559
+ firstPollDone: () => firstPollDone(board.store.db, board.config, core.completeSince),
25560
+ ...ports.afterOperation === void 0 ? {} : { afterOperation: ports.afterOperation },
25561
+ ...ports.webRoot === void 0 ? {} : { webRoot: ports.webRoot },
25562
+ ...ports.onWebListening === void 0 ? {} : { onListening: ports.onWebListening }
25563
+ });
25564
+ if (web !== void 0) entries.push({
25565
+ name: "web",
25566
+ stopStage: "final",
25567
+ module: web
25568
+ });
25066
25569
  entries.push({
25067
25570
  name: "http",
25068
25571
  stopStage: "final",
25069
25572
  module: createHttpModule(ctxFor("http"), {
25070
25573
  registry,
25071
- runOperation: (id, input, run) => id === "item.retry" && inbound !== void 0 && isItemInput(input) ? inbound.retrying(input.item, run) : run(),
25574
+ runOperation,
25575
+ webListening: () => web?.listening() === true,
25072
25576
  firstPollDone: () => firstPollDone(board.store.db, board.config, core.completeSince),
25073
25577
  ...ports.productVersion === void 0 ? {} : { productVersion: ports.productVersion },
25074
25578
  ...ports.sessionFetcher === void 0 ? {} : { fetcher: ports.sessionFetcher },