spur-board 0.38.3 → 0.39.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 { F as ERRORS, J as SLACK_BOT_SCOPES, K as configSchema, l as roleCanUseOperation, q as requiredSecretKeys, r as SYSTEMD_SERVICE_SETTINGS, u as OPERATIONS } from "./src-CzmL-_Vf.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-DAWhcbvn.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-D9spr6M_.mjs";
1
+ import { F as ERRORS, J as SLACK_BOT_SCOPES, K as configSchema, l as roleCanUseOperation, q as requiredSecretKeys, r as SYSTEMD_SERVICE_SETTINGS, u as OPERATIONS } from "./src-X9r7Gx21.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-CfA-Snt_.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-035Sq4n3.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";
@@ -1,4 +1,4 @@
1
- import { B as successEnvelopeSchema, F as ERRORS, L as errorContextSchema, R as errorEnvelopeSchema, p as renderJsonError } from "./src-CzmL-_Vf.mjs";
1
+ import { B as successEnvelopeSchema, F as ERRORS, L as errorContextSchema, R as errorEnvelopeSchema, p as renderJsonError } from "./src-X9r7Gx21.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-DAWhcbvn.mjs";
1
+ import { i as requestTokenEnrollment, n as fetchTokenStatus, r as requestOperation, t as fetchCatalogVersion } from "./client-CfA-Snt_.mjs";
2
2
  export { fetchCatalogVersion, fetchTokenStatus, requestOperation, requestTokenEnrollment };
@@ -1,5 +1,5 @@
1
- import { K as configSchema, c as buildCatalogSnapshot, u as OPERATIONS } from "./src-CzmL-_Vf.mjs";
2
- import { a as CliError, t as fetchCatalogVersion } from "./client-DAWhcbvn.mjs";
1
+ import { K as configSchema, c as buildCatalogSnapshot, u as OPERATIONS } from "./src-X9r7Gx21.mjs";
2
+ import { a as CliError, t as fetchCatalogVersion } from "./client-CfA-Snt_.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,4 +1,4 @@
1
- import { A as encodeActorId, B as successEnvelopeSchema, C as SESSION_HEALTH_STATES, D as sessionFactsSchema, E as prRefSchema, F as ERRORS, G as RESERVED_PROJECT, H as DEFAULT_LINK, I as err, J as SLACK_BOT_SCOPES, K as configSchema, M as parseActorId, N as parseRef$1, O as ticketFactsSchema, P as taskKeySchema, S as eventPayloadSchemas, T as prFactsSchema, W as DEFAULT_SLACK_COMMAND, _ as inboundEventSchema, a as batchSchema, b as userIdSchema, c as buildCatalogSnapshot, d as turnHandedSchema, f as renderHttpProblem, g as conversationRefSchema, h as SPACE_IDS, i as AdapterError, j as errorCodeOf, k as actorIdSchema, l as roleCanUseOperation, n as BOARD_TICK_MS, o as entityRefSchema, q as requiredSecretKeys, s as sourceCursorSchema, t as assertNever, u as OPERATIONS, v as interactionRefSchema, w as SESSION_STATUSES, x as EVENT_KINDS, y as messageRefSchema, z as ok } from "./src-CzmL-_Vf.mjs";
1
+ import { A as encodeActorId, B as successEnvelopeSchema, C as SESSION_HEALTH_STATES, D as sessionFactsSchema, E as prRefSchema, F as ERRORS, G as RESERVED_PROJECT, H as DEFAULT_LINK, I as err, J as SLACK_BOT_SCOPES, K as configSchema, M as parseActorId, N as parseRef$1, O as ticketFactsSchema, P as taskKeySchema, S as eventPayloadSchemas, T as prFactsSchema, W as DEFAULT_SLACK_COMMAND, _ as inboundEventSchema, a as batchSchema, b as userIdSchema, c as buildCatalogSnapshot, d as turnHandedSchema, f as renderHttpProblem, g as conversationRefSchema, h as SPACE_IDS, i as AdapterError, j as errorCodeOf, k as actorIdSchema, l as roleCanUseOperation, n as BOARD_TICK_MS, o as entityRefSchema, q as requiredSecretKeys, s as sourceCursorSchema, t as assertNever, u as OPERATIONS, v as interactionRefSchema, w as SESSION_STATUSES, x as EVENT_KINDS, y as messageRefSchema, z as ok } from "./src-X9r7Gx21.mjs";
2
2
  import { createRequire } from "node:module";
3
3
  import { createHash, randomUUID } from "node:crypto";
4
4
  import { closeSync, existsSync, fstatSync, fsyncSync, ftruncateSync, linkSync, mkdirSync, openSync, readFileSync, readdirSync, renameSync, rmSync, statSync, writeSync } from "node:fs";
@@ -7900,6 +7900,10 @@ async function scanTransaction(store, config, fn) {
7900
7900
  function trackerSource(project) {
7901
7901
  return project.tracker.type === "jira" ? `jira:${project.id}` : `github-issues:${project.id}:${project.tracker.repo.toLowerCase()}`;
7902
7902
  }
7903
+ /** Whether a ticket status is done: a Jira done status, or a closed GitHub Issue. */
7904
+ function ticketDone(project, status) {
7905
+ return project.tracker.type === "jira" ? project.tracker.doneStatuses.includes(status) : status === "closed";
7906
+ }
7903
7907
  /** The project whose tracker or repo source wrote an observation. */
7904
7908
  function projectForSource(config, source) {
7905
7909
  return config.projects.find((project) => source === trackerSource(project) || project.repos.some((repo) => source === `github:${project.id}:${repo.toLowerCase()}`));
@@ -8246,7 +8250,9 @@ const ITEM_KINDS = [
8246
8250
  "inbound_gap",
8247
8251
  "board_observation",
8248
8252
  "worker_ended",
8249
- "turn"
8253
+ "turn",
8254
+ "anomaly",
8255
+ "cycle_limit"
8250
8256
  ];
8251
8257
  const ITEM_POLICY = {
8252
8258
  token_request: {
@@ -8254,77 +8260,88 @@ const ITEM_POLICY = {
8254
8260
  feed: true,
8255
8261
  priority: 4,
8256
8262
  buttons: "approve_deny",
8257
- reconciled: false
8263
+ reconciled: false,
8264
+ block: false
8258
8265
  },
8259
8266
  post_blocked: {
8260
8267
  retry: "never_sent",
8261
8268
  feed: true,
8262
8269
  priority: 4,
8263
8270
  buttons: "item",
8264
- reconciled: false
8271
+ reconciled: false,
8272
+ block: false
8265
8273
  },
8266
8274
  post_failed: {
8267
8275
  retry: "requeue_post",
8268
8276
  feed: false,
8269
8277
  priority: 1,
8270
8278
  buttons: "item",
8271
- reconciled: true
8279
+ reconciled: true,
8280
+ block: false
8272
8281
  },
8273
8282
  transport_health: {
8274
8283
  retry: "probe_transport",
8275
8284
  feed: false,
8276
8285
  priority: 1,
8277
8286
  buttons: "item",
8278
- reconciled: false
8287
+ reconciled: false,
8288
+ block: false
8279
8289
  },
8280
8290
  answer_undelivered: {
8281
8291
  retry: "restart_ring",
8282
8292
  feed: false,
8283
8293
  priority: 4,
8284
8294
  buttons: "item",
8285
- reconciled: false
8295
+ reconciled: false,
8296
+ block: false
8286
8297
  },
8287
8298
  worker_not_reading: {
8288
8299
  retry: "restart_ring",
8289
8300
  feed: true,
8290
8301
  priority: 4,
8291
8302
  buttons: "item",
8292
- reconciled: false
8303
+ reconciled: false,
8304
+ block: false
8293
8305
  },
8294
8306
  answer_author_unavailable: {
8295
8307
  retry: "none",
8296
8308
  feed: true,
8297
8309
  priority: 4,
8298
8310
  buttons: "item",
8299
- reconciled: false
8311
+ reconciled: false,
8312
+ block: false
8300
8313
  },
8301
8314
  inbound_failure: {
8302
8315
  retry: "reapply_inbound",
8303
8316
  feed: true,
8304
8317
  priority: 4,
8305
8318
  buttons: "item",
8306
- reconciled: false
8319
+ reconciled: false,
8320
+ block: false
8307
8321
  },
8308
8322
  inbound_gap: {
8309
8323
  retry: "none",
8310
8324
  feed: true,
8311
8325
  priority: 4,
8312
8326
  buttons: "item",
8313
- reconciled: false
8327
+ reconciled: false,
8328
+ block: false
8314
8329
  },
8315
8330
  board_observation: {
8316
8331
  retry: "none",
8317
8332
  feed: true,
8318
8333
  priority: 4,
8319
8334
  buttons: "item",
8320
- reconciled: true
8335
+ reconciled: true,
8336
+ block: false
8321
8337
  },
8322
8338
  worker_ended: {
8323
8339
  retry: "none",
8324
8340
  feed: false,
8325
8341
  priority: 4,
8326
8342
  buttons: "item",
8327
- reconciled: true
8343
+ reconciled: true,
8344
+ block: false
8328
8345
  },
8329
8346
  /** A turn whose executor is the operator; `closeTurns` clears it. */
8330
8347
  turn: {
@@ -8332,7 +8349,26 @@ const ITEM_POLICY = {
8332
8349
  feed: true,
8333
8350
  priority: 4,
8334
8351
  buttons: "item",
8335
- reconciled: false
8352
+ reconciled: false,
8353
+ block: false
8354
+ },
8355
+ /** A task-scoped condition only the operator can fix; `reconcileItems` owns its block. */
8356
+ anomaly: {
8357
+ retry: "none",
8358
+ feed: false,
8359
+ priority: 4,
8360
+ buttons: "item",
8361
+ reconciled: true,
8362
+ block: true
8363
+ },
8364
+ /** A task that reached its column's cycle limit; the operator's close resets it. */
8365
+ cycle_limit: {
8366
+ retry: "none",
8367
+ feed: false,
8368
+ priority: 4,
8369
+ buttons: "item",
8370
+ reconciled: false,
8371
+ block: true
8336
8372
  }
8337
8373
  };
8338
8374
  /** Guards a stored kind: the column is free text and old or hand-written rows may hold others. */
@@ -8346,6 +8382,8 @@ function hasRetryButton(kind) {
8346
8382
  }
8347
8383
  /** The kinds `reconcileItems` owns: it clears an active one whose candidate is gone. */
8348
8384
  const RECONCILED_KINDS = ITEM_KINDS.filter((kind) => ITEM_POLICY[kind].reconciled);
8385
+ /** The kinds whose item is the ledger of an operator block. */
8386
+ const BLOCK_ITEM_KINDS = ITEM_KINDS.filter((kind) => ITEM_POLICY[kind].block);
8349
8387
  function fingerprint(candidate) {
8350
8388
  return createHash("sha256").update(JSON.stringify([
8351
8389
  candidate.key,
@@ -8925,6 +8963,31 @@ async function clearItem(trx, itemId, at, actor = "system") {
8925
8963
  at
8926
8964
  });
8927
8965
  }
8966
+ /**
8967
+ * Dismiss an item as `actor`: record its fingerprint, so `reconcileItems` raises it again only
8968
+ * when the fingerprint changes, then clear it. An item raised before fingerprints were stored is
8969
+ * fingerprinted from its key, text and source.
8970
+ */
8971
+ async function dismissItem(trx, item, actor, at) {
8972
+ const hash = item.fingerprint ?? fingerprint({
8973
+ key: item.item_key,
8974
+ summary: item.text,
8975
+ source: item.source,
8976
+ revision: null
8977
+ });
8978
+ const dismissedAt = at.toISOString();
8979
+ await trx.insertInto("dismissal").values({
8980
+ item_key: item.item_key,
8981
+ fingerprint: hash,
8982
+ dismissed_by: actor,
8983
+ dismissed_at: dismissedAt
8984
+ }).onConflict((oc) => oc.column("item_key").doUpdateSet({
8985
+ fingerprint: hash,
8986
+ dismissed_by: actor,
8987
+ dismissed_at: dismissedAt
8988
+ })).execute();
8989
+ await clearItem(trx, item.id, at, actor);
8990
+ }
8928
8991
  function resolvedLine(by, at, config) {
8929
8992
  const parsed = parseActorId(by);
8930
8993
  if (parsed === null || parsed.actor === "system") return [{
@@ -9473,6 +9536,64 @@ async function registerBlockNotification(trx, block, at) {
9473
9536
  created_at: at.toISOString()
9474
9537
  }).onConflict((oc) => oc.column("source_key").doNothing()).execute();
9475
9538
  }
9539
+ /**
9540
+ * The key of the reminder to `session` about a turn it took at `takenAt`. The take time names the
9541
+ * ownership episode, so a session that loses the turn and takes it again gets a new reminder.
9542
+ */
9543
+ const turnReminderKey = (turnId, session, takenAt) => `turn:${String(turnId)}:reminder:${session}:${takenAt}`;
9544
+ const isTurnKind = (kind) => kind === "turn" || kind === "turn_reminder";
9545
+ /**
9546
+ * Whether a reminder was cancelled before it was ever sent, as a link removal does: it counts as
9547
+ * no reminder for its take, so a restored link reminds the holder again. A ring of it still
9548
+ * queued or in flight, or one that may have reached Spur (`uncertain`), keeps it: the outcome is
9549
+ * not known yet or the reminder may be out, and one reminder per take wins over a missed one.
9550
+ * Only rings the sender killed unsent leave it re-armable.
9551
+ */
9552
+ async function reminderCancelledUnsent(trx, n) {
9553
+ return await cancelledRingState(trx, n) === "unsent";
9554
+ }
9555
+ /**
9556
+ * The rings of a reminder acked before any delivery was counted: `unsent` when the sender killed
9557
+ * them all unsent, `maybe_out` when all are dead and one may have reached Spur, and null while one
9558
+ * is queued or in flight, or for a reminder that was delivered, exhausted or never acked. A
9559
+ * `maybe_out` reminder counts as delivered for the stuck-turn rule, so the one-ring limit does not
9560
+ * hide a stuck turn.
9561
+ */
9562
+ async function cancelledRingState(trx, n) {
9563
+ if (n.acked_at === null || n.rings !== 0 || n.exhausted_at !== null) return null;
9564
+ const rows = await trx.selectFrom("outbox").select(["state", "uncertain"]).where("kind", "=", "doorbell").where(sql`json_extract(payload, '$.notificationId')`, "=", n.id).execute();
9565
+ if (rows.some((row) => row.state !== "dead")) return null;
9566
+ return rows.some((row) => row.uncertain === 1) ? "maybe_out" : "unsent";
9567
+ }
9568
+ /**
9569
+ * Register the single reminder to the session holding a quiet turn. The key names the holder and
9570
+ * its take, so each ownership episode gets its own reminder and no episode gets a second. A
9571
+ * reminder of the take cancelled unsent is replaced by a fresh one: its row gets a new id, so the
9572
+ * new ring does not reuse the outbox key of a ring the sender already killed.
9573
+ */
9574
+ async function registerTurnReminder(trx, turn, session, at) {
9575
+ if (turn.acked_at === null) throw new Error(`turn ${String(turn.id)} is not taken`);
9576
+ const key = turnReminderKey(turn.id, session, turn.acked_at);
9577
+ const earlier = await trx.selectFrom("notification").selectAll().where("source_key", "=", key).executeTakeFirst();
9578
+ if (earlier !== void 0 && await reminderCancelledUnsent(trx, earlier)) await trx.deleteFrom("notification").where("id", "=", earlier.id).execute();
9579
+ await trx.insertInto("notification").values({
9580
+ source_key: key,
9581
+ kind: "turn_reminder",
9582
+ task_id: turn.task_id,
9583
+ block_id: null,
9584
+ turn_id: turn.id,
9585
+ comment_id: null,
9586
+ revision: null,
9587
+ role: turn.role,
9588
+ author_session: session,
9589
+ recipient_session: null,
9590
+ next_at: at.toISOString(),
9591
+ last_outbox_id: null,
9592
+ acked_at: null,
9593
+ exhausted_at: null,
9594
+ created_at: at.toISOString()
9595
+ }).onConflict((oc) => oc.column("source_key").doNothing()).execute();
9596
+ }
9476
9597
  /** The block of a block-owned notification; the store CHECK gives every non-turn kind one. */
9477
9598
  function noticeBlockId(n) {
9478
9599
  if (n.block_id === null) throw new Error(`notification of kind ${n.kind} has no block`);
@@ -9480,7 +9601,7 @@ function noticeBlockId(n) {
9480
9601
  }
9481
9602
  /** What a notification is about, as the operator item names it. */
9482
9603
  function noticeRef(n, task) {
9483
- return n.kind === "turn" ? `turn T${String(n.turn_id)} on ${task.key}` : `block B${String(noticeBlockId(n))} on ${task.key}`;
9604
+ return isTurnKind(n.kind) ? `turn T${String(n.turn_id)} on ${task.key}` : `block B${String(noticeBlockId(n))} on ${task.key}`;
9484
9605
  }
9485
9606
  /** Register a one-ring notice that a block its addressee held was closed by someone else. */
9486
9607
  async function registerRemovedNotification(trx, block, at) {
@@ -9616,8 +9737,12 @@ function columnOrchestratorProject(config, projectId, column) {
9616
9737
  const name = config.projects.find((project) => project.id === projectId)?.columns.find((entry) => entry.id === column)?.orchestrator;
9617
9738
  return name === void 0 || name === "none" || name === "operator" ? null : name;
9618
9739
  }
9619
- /** Select the current live recipient for a semantic notification. */
9740
+ /**
9741
+ * Select the current live recipient for a semantic notification. A turn reminder reaches only
9742
+ * the session it names, while that session lives.
9743
+ */
9620
9744
  async function selectNotificationRecipient(trx, n, config) {
9745
+ if (n.kind === "turn_reminder") return n.author_session === null ? void 0 : liveSession(trx, n.author_session);
9621
9746
  const addressee = parseAddressee(n.role);
9622
9747
  switch (addressee.kind) {
9623
9748
  case "curator": return curatorSession(trx, config, await taskProject(trx, n.task_id));
@@ -9655,8 +9780,8 @@ async function restartNotification(trx, sourceKey, at) {
9655
9780
  }).where("source_key", "=", sourceKey).where("acked_at", "is", null).where("exhausted_at", "is not", null).returning("id").executeTakeFirst() === void 0) throw new CommandError("retry_not_applicable", "The doorbell was read or is still ringing; close the item instead.");
9656
9781
  }
9657
9782
  /**
9658
- * Ends a notification's ring series. A curator block moves to the operator; a removal or a ring
9659
- * with no session to name ends alone; anything else raises the operator item, whose Retry restarts
9783
+ * Ends a notification's ring series. A curator block moves to the operator; a removal, a turn
9784
+ * reminder or a ring with no session to name ends alone; anything else raises the operator item, whose Retry restarts
9660
9785
  * the series (`restartNotification`). Every end journals `doorbell_undelivered`.
9661
9786
  */
9662
9787
  async function endNotification(trx, n, task, end) {
@@ -9674,7 +9799,7 @@ async function endNotification(trx, n, task, end) {
9674
9799
  },
9675
9800
  config
9676
9801
  });
9677
- else if (n.kind !== "removed" && session !== null) {
9802
+ else if (n.kind !== "removed" && n.kind !== "turn_reminder" && session !== null) {
9678
9803
  const blockRef = noticeRef(n, task);
9679
9804
  const answer = `Answer to ${blockRef} was not`;
9680
9805
  const holder = `${addressee.kind} ${session}`;
@@ -9730,13 +9855,14 @@ async function ringUndelivered(trx, input) {
9730
9855
  }
9731
9856
  /** Why a notification with no recipient ends now, or null when it stays due for a next session. */
9732
9857
  function noRecipientEnd(n) {
9733
- if (n.kind === "removed" || n.kind === "answer" && n.role === "operator") return "no live addressee";
9858
+ if (n.kind === "removed" || n.kind === "turn_reminder" || n.kind === "answer" && n.role === "operator") return "no live addressee";
9734
9859
  return n.kind === "block" && n.role === "curator" ? "no live curator session" : null;
9735
9860
  }
9736
9861
  /** A ring never carries comment or reason text: only where to look. */
9737
9862
  async function ringText(trx, n, task, ring) {
9738
9863
  const suffix = `(N${String(n.id)}-${String(ring)})`;
9739
9864
  if (n.kind === "turn") return `${task.key} turn T${String(n.turn_id)}: check board inbox ${suffix}`;
9865
+ if (n.kind === "turn_reminder") return `${task.key} turn T${String(n.turn_id)} is still open: check board inbox ${suffix}`;
9740
9866
  const blockId = noticeBlockId(n);
9741
9867
  if (n.kind !== "removed") return `${task.key} block B${String(blockId)}: check board inbox ${suffix}`;
9742
9868
  const block = await trx.selectFrom("block").select("unblocked_by").where("id", "=", blockId).executeTakeFirstOrThrow();
@@ -9826,7 +9952,7 @@ async function reconcileDoorbells(trx, at, config) {
9826
9952
  /** Count one confirmed Spur send, regardless of transport attempts for its outbox row. */
9827
9953
  async function recordRingDelivery(trx, notificationId, ring, session, at, config) {
9828
9954
  const n = await trx.selectFrom("notification").selectAll().where("id", "=", notificationId).executeTakeFirst();
9829
- if (n === void 0 || n.acked_at !== null || n.recipient_session !== session || n.rings >= ring) return;
9955
+ if (n === void 0 || n.acked_at !== null && n.kind !== "turn_reminder" || n.recipient_session !== session || n.rings >= ring) return;
9830
9956
  const pauses = [
9831
9957
  config.doorbells.firstRetryMs,
9832
9958
  config.doorbells.secondRetryMs,
@@ -9835,7 +9961,7 @@ async function recordRingDelivery(trx, notificationId, ring, session, at, config
9835
9961
  await trx.updateTable("notification").set({
9836
9962
  rings: ring,
9837
9963
  next_at: new Date(at.getTime() + (pauses[ring - 1] ?? 0)).toISOString(),
9838
- ...n.kind === "removed" ? { acked_at: at.toISOString() } : {}
9964
+ ...n.kind === "removed" || n.kind === "turn_reminder" ? { acked_at: at.toISOString() } : {}
9839
9965
  }).where("id", "=", notificationId).execute();
9840
9966
  await journal$2(trx, n, "doorbell_rung", {
9841
9967
  doorbell: `N${String(n.id)}`,
@@ -9909,12 +10035,15 @@ async function workerNotificationAddressedTo(trx, n, session, config) {
9909
10035
  async function closeBlockNotification(trx, blockId, at) {
9910
10036
  await closeOwnedNotifications(trx, "block", blockId, at);
9911
10037
  }
9912
- /** Ends a turn's ring series for good: acked, and its exhaustion item cleared by the system. */
10038
+ /**
10039
+ * Ends a turn's ring series and reminders for good: acked, and its exhaustion item cleared by the
10040
+ * system.
10041
+ */
9913
10042
  async function closeTurnNotification(trx, turnId, at) {
9914
10043
  await closeOwnedNotifications(trx, "turn", turnId, at);
9915
10044
  }
9916
10045
  async function closeOwnedNotifications(trx, kind, ownerId, at) {
9917
- const closed = await trx.updateTable("notification").set({ acked_at: at.toISOString() }).where(kind === "block" ? "block_id" : "turn_id", "=", ownerId).where("kind", "=", kind).where("acked_at", "is", null).returning(["kind", "source_key"]).execute();
10046
+ const closed = await trx.updateTable("notification").set({ acked_at: at.toISOString() }).where(kind === "block" ? "block_id" : "turn_id", "=", ownerId).where("kind", "in", kind === "block" ? ["block"] : ["turn", "turn_reminder"]).where("acked_at", "is", null).returning(["kind", "source_key"]).execute();
9918
10047
  for (const row of closed) {
9919
10048
  const item = await trx.selectFrom("operator_item").select("id").where("item_key", "=", exhaustedItemKey(row)).where("cleared_at", "is", null).executeTakeFirst();
9920
10049
  if (item !== void 0) await clearItem(trx, item.id, at);
@@ -9936,6 +10065,8 @@ async function turnNotification(trx, turnId) {
9936
10065
  * Takes a turn for `actor`. False for a missing, closed, operator or taken worker turn. An
9937
10066
  * untaken turn needs its unread notification addressed to the actor; a taken orchestrator turn
9938
10067
  * may be taken over by whoever its notification is now addressed to. Others get `forbidden`.
10068
+ * Every take starts a new ownership episode: an unsent reminder of an earlier one is acked, so
10069
+ * `ringStillCurrent` drops its ring.
9939
10070
  */
9940
10071
  async function takeTurn(trx, input) {
9941
10072
  const { turnId, actor, at, config } = input;
@@ -9957,6 +10088,7 @@ async function takeTurn(trx, input) {
9957
10088
  acked_by: actor,
9958
10089
  acked_at: at.toISOString()
9959
10090
  }).where("id", "=", turnId).execute();
10091
+ await trx.updateTable("notification").set({ acked_at: at.toISOString() }).where("turn_id", "=", turnId).where("kind", "=", "turn_reminder").where("acked_at", "is", null).where("exhausted_at", "is", null).execute();
9960
10092
  return true;
9961
10093
  }
9962
10094
  /**
@@ -9975,6 +10107,105 @@ async function closeTurns(trx, input) {
9975
10107
  if (item !== void 0) await clearItem(trx, item.id, at);
9976
10108
  }
9977
10109
  }
10110
+ /** How long the holder of a taken turn may sit quiet before it is reminded, then flagged. */
10111
+ function stuckTurnAfterMs(config) {
10112
+ return config.health.idleInDevAfterMs;
10113
+ }
10114
+ /**
10115
+ * Since when a holder session sits idle: from its end, or from when it began `waiting` at its
10116
+ * prompt. Null for any other health, an unknown one, or a detail that does not parse.
10117
+ */
10118
+ function idleSince(session) {
10119
+ if (session.ended_at !== null) return session.ended_at;
10120
+ let detail;
10121
+ try {
10122
+ detail = JSON.parse(session.detail);
10123
+ } catch {
10124
+ return null;
10125
+ }
10126
+ const fact = sessionFactsSchema.safeParse(detail);
10127
+ return fact.success && fact.data.health === "waiting" ? fact.data.healthSince : null;
10128
+ }
10129
+ /** The latest of ISO instants, compared as instants. */
10130
+ function latest(values) {
10131
+ return new Date(Math.max(...values.map((value) => Date.parse(value)))).toISOString();
10132
+ }
10133
+ /**
10134
+ * Every taken, unclosed agent turn with its holder's session id, whether that session ended, and
10135
+ * the reminder of the current holder's current take, so an earlier episode's reminder never counts
10136
+ * and one cancelled unsent counts as none. `delivered` is whether that reminder reached the holder
10137
+ * or may have: a ring killed after an uncertain send counts, so the one-ring limit hides no stuck
10138
+ * turn.
10139
+ * `quietSince` is when the holder last had something to do: the take, the start of its idle
10140
+ * spell, or the close of its last question on the task. Null while the holder works, has an open
10141
+ * question on the task, or has no readable snapshot. A worker turn whose holder's session link
10142
+ * the operator removed is left out: the holder no longer works the task. An orchestrator turn is
10143
+ * addressed through the column config, so a link removal does not end its hold.
10144
+ */
10145
+ async function quietTurns(trx) {
10146
+ const turns = await trx.selectFrom("turn").selectAll().where("closed_at", "is", null).where("acked_at", "is not", null).where("role", "!=", "operator").orderBy("id").execute();
10147
+ const removed = await trx.selectFrom("link").select(["task_id", "session_id"]).where("entity", "=", "session").where("banned", "=", 1).execute();
10148
+ const unlinked = new Set(removed.map((link) => `${String(link.task_id)}:${link.session_id ?? ""}`));
10149
+ const quiet = [];
10150
+ for (const turn of turns) {
10151
+ if (turn.acked_by === null || turn.acked_at === null) continue;
10152
+ const holder = parseActorId(turn.acked_by);
10153
+ if (holder?.actor !== "agent") continue;
10154
+ const sessionId = holder.actorRef.session;
10155
+ if (turn.role === "worker" && unlinked.has(`${String(turn.task_id)}:${sessionId}`)) continue;
10156
+ const session = await trx.selectFrom("session_snapshot").selectAll().where("id", "=", sessionId).executeTakeFirst();
10157
+ const idle = session === void 0 ? null : idleSince(session);
10158
+ const blocks = await trx.selectFrom("block").select(["state", "unblocked_at"]).where("task_id", "=", turn.task_id).where("author", "=", turn.acked_by).execute();
10159
+ const asking = blocks.some((block) => block.state === "open");
10160
+ const unblocked = blocks.flatMap((block) => block.unblocked_at === null ? [] : [block.unblocked_at]);
10161
+ const row = await trx.selectFrom("notification").selectAll().where("source_key", "=", turnReminderKey(turn.id, sessionId, turn.acked_at)).executeTakeFirst();
10162
+ const cancelled = row === void 0 ? null : await cancelledRingState(trx, row);
10163
+ quiet.push({
10164
+ turn,
10165
+ sessionId,
10166
+ ended: session !== void 0 && session.ended_at !== null,
10167
+ quietSince: idle === null || asking ? null : latest([
10168
+ turn.acked_at,
10169
+ idle,
10170
+ ...unblocked
10171
+ ]),
10172
+ reminder: cancelled === "unsent" ? void 0 : row,
10173
+ delivered: row !== void 0 && (row.rings >= 1 || cancelled === "maybe_out")
10174
+ });
10175
+ }
10176
+ return quiet;
10177
+ }
10178
+ /** Whether Spur is blind, so a holder's health is unknown. */
10179
+ async function spurBlind(trx) {
10180
+ const spur = await trx.selectFrom("source_state").select("blind_reason").where("source", "=", "spur").executeTakeFirst();
10181
+ return spur !== void 0 && spur.blind_reason !== null;
10182
+ }
10183
+ /**
10184
+ * Registers one reminder per take to the holder of each turn quiet for `stuckTurnAfterMs`;
10185
+ * `takeTurn` drops the unsent reminder of an earlier take. Nothing while Spur is blind, since the holder's health
10186
+ * is then unknown.
10187
+ */
10188
+ async function remindStuckTurns(trx, config, at) {
10189
+ if (await spurBlind(trx)) return;
10190
+ for (const { turn, sessionId, ended, quietSince, reminder } of await quietTurns(trx)) {
10191
+ if (ended || quietSince === null || reminder !== void 0) continue;
10192
+ if (at.getTime() < Date.parse(quietSince) + stuckTurnAfterMs(config)) continue;
10193
+ await registerTurnReminder(trx, turn, sessionId, at);
10194
+ }
10195
+ }
10196
+ /**
10197
+ * Whether a queued ring may go out at `at`. A turn reminder goes out only under the rule
10198
+ * `remindStuckTurns` registers it by: its holder's current take is quiet for `stuckTurnAfterMs`.
10199
+ * Otherwise the sender defers it, so a question opened after it was queued holds it until the
10200
+ * question closes and a fresh quiet period passes, and blind Spur holds it until Spur reports again.
10201
+ * Every other ring is due.
10202
+ */
10203
+ async function ringDue(trx, notificationId, config, at) {
10204
+ if ((await trx.selectFrom("notification").select("kind").where("id", "=", notificationId).executeTakeFirst())?.kind !== "turn_reminder") return true;
10205
+ if (await spurBlind(trx)) return false;
10206
+ const quiet = (await quietTurns(trx)).find((entry) => entry.reminder?.id === notificationId);
10207
+ return quiet !== void 0 && !quiet.ended && quiet.quietSince !== null && at.getTime() >= Date.parse(quiet.quietSince) + stuckTurnAfterMs(config);
10208
+ }
9978
10209
  /** Whether `left` is newer than `right` by `postedAt` instant, then by id. Compared, not subtracted. */
9979
10210
  function isNewer(left, right) {
9980
10211
  const a = Date.parse(left.postedAt);
@@ -10194,8 +10425,8 @@ async function addComment(trx, task, block, text, ctx, addressee, config, option
10194
10425
  });
10195
10426
  return row;
10196
10427
  }
10197
- async function openBlock(trx, task, type, reason, ctx, config) {
10198
- const addressee = await routeBlock(trx, task, {
10428
+ async function openBlock(trx, task, type, reason, ctx, config, addressee) {
10429
+ addressee ??= await routeBlock(trx, task, {
10199
10430
  type,
10200
10431
  author: ctx.actor
10201
10432
  }, config);
@@ -10226,7 +10457,25 @@ async function openBlock(trx, task, type, reason, ctx, config) {
10226
10457
  }, new Date(ctx.at));
10227
10458
  return row;
10228
10459
  }
10229
- /** Unblocks one block with its journal entry, thread close, doorbell close and item clears. */
10460
+ /**
10461
+ * Opens a `system` question to the operator on a condition only the operator can fix, with its
10462
+ * thread. The caller raises the ledger item that names the block.
10463
+ */
10464
+ async function openSystemBlock(trx, input) {
10465
+ const { task, reason, at, config } = input;
10466
+ const ctx = {
10467
+ actor: "system",
10468
+ at
10469
+ };
10470
+ const block = await openBlock(trx, task, "needs_input", reason, ctx, config, "operator");
10471
+ await queueBlockOpen(trx, task, block, ctx, config);
10472
+ return block;
10473
+ }
10474
+ /**
10475
+ * Unblocks one block with its journal entry, thread close, doorbell close and item clears. An
10476
+ * operator or agent close of a reconciled ledger block dismisses its item, so the condition
10477
+ * raises again only once it changes; a `system` or archive close only clears it.
10478
+ */
10230
10479
  async function closeOpenBlock(trx, task, block, ctx, outcome, outcomeReason) {
10231
10480
  const updated = await trx.updateTable("block").set({
10232
10481
  state: "unblocked",
@@ -10247,10 +10496,18 @@ async function closeOpenBlock(trx, task, block, ctx, outcome, outcomeReason) {
10247
10496
  at: new Date(ctx.at)
10248
10497
  });
10249
10498
  await closeBlockNotification(trx, block.id, new Date(ctx.at));
10250
- const blockedItems = await trx.selectFrom("operator_item").select("id").where("kind", "=", "post_blocked").where("block_id", "=", block.id).where("cleared_at", "is", null).execute();
10251
- for (const item of blockedItems) await clearItem(trx, item.id, new Date(ctx.at));
10499
+ const items = await trx.selectFrom("operator_item").selectAll().where("kind", "in", ["post_blocked", ...BLOCK_ITEM_KINDS]).where("block_id", "=", block.id).where("cleared_at", "is", null).execute();
10500
+ for (const item of items) if (item.kind === "post_blocked") await clearItem(trx, item.id, new Date(ctx.at));
10501
+ else if (ctx.actor !== "system" && outcome !== "archived" && isItemKind(item.kind) && ITEM_POLICY[item.kind].reconciled) await dismissItem(trx, item, ctx.actor, new Date(ctx.at));
10502
+ else await clearItem(trx, item.id, new Date(ctx.at), ctx.actor);
10252
10503
  return updated;
10253
10504
  }
10505
+ /** Closes block `blockId` through `closeOpenBlock` when it is still open. */
10506
+ async function closeBlockIfOpen(trx, blockId, ctx, outcome, outcomeReason) {
10507
+ const block = await trx.selectFrom("block").selectAll().where("id", "=", blockId).where("state", "=", "open").executeTakeFirst();
10508
+ if (block === void 0) return;
10509
+ await closeOpenBlock(trx, await trx.selectFrom("task").selectAll().where("id", "=", block.task_id).executeTakeFirstOrThrow(), block, ctx, outcome, outcomeReason);
10510
+ }
10254
10511
  /** Applies an operator message to the block selected by its conversation, without echoing it. */
10255
10512
  async function recordInboundBlockMessage(trx, input) {
10256
10513
  const block = await trx.selectFrom("block").selectAll().where("id", "=", input.blockId).executeTakeFirstOrThrow();
@@ -11035,7 +11292,8 @@ function createSender(options) {
11035
11292
  };
11036
11293
  }
11037
11294
  if (c.body.kind === "doorbell" && c.body.payload.notificationId !== void 0) {
11038
- const status = await ringStillCurrent(trx, c.body.payload.notificationId, c.body.payload.session, options.config);
11295
+ let status = await ringStillCurrent(trx, c.body.payload.notificationId, c.body.payload.session, options.config);
11296
+ if (status === "send" && !await ringDue(trx, c.body.payload.notificationId, options.config, new Date(at))) status = "defer";
11039
11297
  if (status === "dead") {
11040
11298
  await kill(trx, [c.id], "notification no longer current");
11041
11299
  return {
@@ -11413,27 +11671,15 @@ function createItemMutations(deps) {
11413
11671
  async run(trx, input, ctx) {
11414
11672
  const { item, task } = await loadItem(trx, input.item);
11415
11673
  if (item.cleared_at === null) {
11416
- const hash = item.fingerprint ?? fingerprint({
11417
- key: item.item_key,
11418
- summary: item.text,
11419
- source: item.source,
11420
- revision: null
11421
- });
11422
- await trx.insertInto("dismissal").values({
11423
- item_key: item.item_key,
11424
- fingerprint: hash,
11425
- dismissed_by: ctx.actor,
11426
- dismissed_at: ctx.at
11427
- }).onConflict((oc) => oc.column("item_key").doUpdateSet({
11428
- fingerprint: hash,
11429
- dismissed_by: ctx.actor,
11430
- dismissed_at: ctx.at
11431
- })).execute();
11432
11674
  if (item.kind === "post_failed") await trx.updateTable("outbox").set({
11433
11675
  state: "dead",
11434
11676
  last_error: `closed by ${ctx.actor} (I${String(item.id)})`
11435
11677
  }).where("id", "=", Number(item.item_key.slice(9))).where("state", "=", "post_failed").execute();
11436
- await clearItem(trx, item.id, new Date(ctx.at), ctx.actor);
11678
+ await dismissItem(trx, item, ctx.actor, new Date(ctx.at));
11679
+ if (item.block_id !== null && isItemKind(item.kind) && ITEM_POLICY[item.kind].block) {
11680
+ const reason = `closed as item I${String(item.id)}`;
11681
+ await closeBlockIfOpen(trx, item.block_id, ctx, "reason", reason);
11682
+ }
11437
11683
  }
11438
11684
  return view(item, task);
11439
11685
  }
@@ -11535,6 +11781,7 @@ async function run(trx, input, ctx, config, remove) {
11535
11781
  pr_open: pr === null ? null : open ? 1 : 0
11536
11782
  }).execute();
11537
11783
  else await trx.updateTable("link").set({ banned: 1 }).where("id", "=", current.id).execute();
11784
+ if (input.mode === "session") await trx.updateTable("notification").set({ acked_at: ctx.at }).where("task_id", "=", task.id).where("kind", "=", "turn_reminder").where("role", "=", "worker").where("author_session", "=", input.session).where("acked_at", "is", null).where("exhausted_at", "is", null).execute();
11538
11785
  await emit(trx, "link_removed", task.project, task.id, ctx.at, input.mode === "pr" ? {
11539
11786
  entity: "pr",
11540
11787
  repo: pr?.repo ?? "",
@@ -12484,6 +12731,15 @@ function evaluateSessionHealth(input) {
12484
12731
  seen.add(identity);
12485
12732
  const task = tasks[session.taskId];
12486
12733
  if (session.endedAt !== null) {
12734
+ if (session.role === "worker" && (session.endReason === "kill" || session.endReason === "vanished") && task?.turnSessions?.includes(session.id) === true && !liveWorkerTasks.has(session.taskId)) {
12735
+ const flag = {
12736
+ taskId: session.taskId,
12737
+ sessionId: session.id,
12738
+ kind: "worker_lost"
12739
+ };
12740
+ (spur.observationComplete ? flags : held).push(flag);
12741
+ continue;
12742
+ }
12487
12743
  if (session.role === "worker" && (session.endReason === "complete" || session.endReason === "kill" || session.endReason === "vanished") && task !== void 0 && !task.hasOpenPr && !task.hasMergedPr && !liveWorkerTasks.has(session.taskId)) {
12488
12744
  const flag = {
12489
12745
  taskId: session.taskId,
@@ -12528,8 +12784,17 @@ const episodeSchema = z.object({ startedAt: z.number() }).nullable();
12528
12784
  const ENDED_WORKER_LABELS = {
12529
12785
  worker_completed: "worker ended (completed), no PR",
12530
12786
  worker_killed: "worker ended (killed), no PR",
12531
- worker_vanished: "worker vanished, no PR"
12787
+ worker_vanished: "worker vanished, no PR",
12788
+ worker_lost: "worker ended during its open turn"
12532
12789
  };
12790
+ /** Health flags only the operator can resolve; each opens an operator block. */
12791
+ const ANOMALY_FLAGS = /* @__PURE__ */ new Set([
12792
+ "stuck_worker",
12793
+ "stuck_orchestrator",
12794
+ "needs_input",
12795
+ "worker_completed",
12796
+ "worker_lost"
12797
+ ]);
12533
12798
  /** Reconciles every item in the caller's observation or tick transaction. */
12534
12799
  async function reconcileItems(trx, config, now, spurComplete) {
12535
12800
  const candidates = [];
@@ -12584,21 +12849,14 @@ async function reconcileItems(trx, config, now, spurComplete) {
12584
12849
  priority: 4
12585
12850
  });
12586
12851
  }
12587
- for (const task of tasks) if (task.membership === "out_of_filter") candidates.push({
12588
- key: `filter:${String(task.id)}`,
12589
- kind: "board_observation",
12590
- taskId: task.id,
12591
- summary: `${task.key} left the tracker filter while work is still linked`,
12592
- factAt: task.last_change_at,
12593
- source: null,
12594
- priority: 4
12595
- });
12596
12852
  const blocks = await trx.selectFrom("block").selectAll().where("state", "=", "open").execute();
12597
12853
  const blockedRoots = await trx.selectFrom("operator_item").select("block_id").where("kind", "=", "post_blocked").where("source", "=", "conversation.open").execute();
12598
12854
  const blockedIds = new Set(blockedRoots.map((item) => item.block_id));
12855
+ const ledgerRoots = await trx.selectFrom("operator_item").select("block_id").where("kind", "in", BLOCK_ITEM_KINDS).where("cleared_at", "is", null).execute();
12856
+ const ledgerIds = new Set(ledgerRoots.map((item) => item.block_id));
12599
12857
  for (const block of blocks) {
12600
12858
  const task = taskById.get(block.task_id);
12601
- if (task === void 0) continue;
12859
+ if (task === void 0 || ledgerIds.has(block.id)) continue;
12602
12860
  if (block.addressee_role === "operator" && block.author !== "operator" && !blockedIds.has(block.id)) candidates.push({
12603
12861
  key: `operator-block:${String(block.id)}`,
12604
12862
  kind: "board_observation",
@@ -12628,6 +12886,8 @@ async function reconcileItems(trx, config, now, spurComplete) {
12628
12886
  source: null,
12629
12887
  priority: ITEM_POLICY.post_failed.priority
12630
12888
  });
12889
+ const spur = sourceById.get("spur");
12890
+ const spurBlind = spur !== void 0 && spur.blind_reason !== null;
12631
12891
  const subjects = (await trx.selectFrom("link").innerJoin("session_snapshot", "session_snapshot.id", "link.session_id").select([
12632
12892
  "link.task_id",
12633
12893
  "link.role",
@@ -12640,11 +12900,20 @@ async function reconcileItems(trx, config, now, spurComplete) {
12640
12900
  role: link.role
12641
12901
  }];
12642
12902
  });
12643
- const prs = await trx.selectFrom("link").leftJoin("pr_snapshot", (join) => join.on(sql`lower(pr_snapshot.repo) = lower(link.repo)`).onRef("pr_snapshot.number", "=", "link.number")).select(["link.task_id", "pr_snapshot.state"]).where("link.entity", "=", "pr").where("link.banned", "=", 0).execute();
12903
+ const liveSessionTasks = new Set(subjects.filter((subject) => subject.endedAt === null).map((subject) => subject.taskId));
12904
+ const prs = await trx.selectFrom("link").leftJoin("pr_snapshot", (join) => join.on(sql`lower(pr_snapshot.repo) = lower(link.repo)`).onRef("pr_snapshot.number", "=", "link.number")).select([
12905
+ "link.task_id",
12906
+ "link.repo",
12907
+ "link.number",
12908
+ "pr_snapshot.state",
12909
+ "pr_snapshot.source",
12910
+ "pr_snapshot.observed_at"
12911
+ ]).where("link.entity", "=", "pr").where("link.banned", "=", 0).execute();
12644
12912
  const taskPrs = {};
12645
12913
  for (const task of tasks) taskPrs[String(task.id)] = {
12646
12914
  hasOpenPr: false,
12647
- hasMergedPr: false
12915
+ hasMergedPr: false,
12916
+ turnSessions: []
12648
12917
  };
12649
12918
  for (const pr of prs) {
12650
12919
  const state = taskPrs[String(pr.task_id)];
@@ -12652,13 +12921,81 @@ async function reconcileItems(trx, config, now, spurComplete) {
12652
12921
  if (pr.state === "open") state.hasOpenPr = true;
12653
12922
  if (pr.state === "merged") state.hasMergedPr = true;
12654
12923
  }
12924
+ const workerTurns = await trx.selectFrom("turn").select(["task_id", "acked_by"]).where("role", "=", "worker").where("closed_at", "is", null).where("acked_at", "is not", null).execute();
12925
+ for (const turn of workerTurns) {
12926
+ const holder = turn.acked_by === null ? null : parseActorId(turn.acked_by);
12927
+ if (holder?.actor === "agent") taskPrs[String(turn.task_id)]?.turnSessions.push(holder.actorRef.session);
12928
+ }
12929
+ for (const task of tasks) {
12930
+ const state = taskPrs[String(task.id)];
12931
+ if (state === void 0 || state.hasOpenPr || state.hasMergedPr) continue;
12932
+ const closed = prs.filter((pr) => pr.task_id === task.id && pr.state === "closed").map((pr) => ({
12933
+ ...pr,
12934
+ ref: `${pr.repo ?? ""}#${String(pr.number)}`
12935
+ })).sort((left, right) => left.ref.localeCompare(right.ref));
12936
+ const first = closed[0];
12937
+ if (first === void 0) continue;
12938
+ const refs = closed.map((pr) => pr.ref);
12939
+ candidates.push({
12940
+ key: `pr-closed:${String(task.id)}`,
12941
+ kind: "anomaly",
12942
+ taskId: task.id,
12943
+ summary: `${task.key}: linked pull request ${refs.join(", ")} closed without merge, no open PR`,
12944
+ factAt: first.observed_at,
12945
+ source: `github:${task.project}:${(first.repo ?? "").toLowerCase()}`,
12946
+ priority: 4,
12947
+ revision: refs.join(",")
12948
+ });
12949
+ }
12950
+ const tickets = await trx.selectFrom("ticket_snapshot").select([
12951
+ "task_id",
12952
+ "status",
12953
+ "detail",
12954
+ "source"
12955
+ ]).execute();
12956
+ const unpolledTickets = [];
12957
+ for (const task of tasks) {
12958
+ const state = taskPrs[String(task.id)];
12959
+ const project = config.projects.find((entry) => entry.id === task.project);
12960
+ const ticket = tickets.find((entry) => entry.task_id === task.id);
12961
+ const closedWhileLive = state !== void 0 && project !== void 0 && ticket !== void 0 && ticketDone(project, ticket.status) && (state.hasOpenPr || liveSessionTasks.has(String(task.id))) && !state.hasMergedPr;
12962
+ if (task.membership === "out_of_filter" && !closedWhileLive) candidates.push({
12963
+ key: `filter:${String(task.id)}`,
12964
+ kind: "board_observation",
12965
+ taskId: task.id,
12966
+ summary: `${task.key} left the tracker filter while work is still linked`,
12967
+ factAt: task.last_change_at,
12968
+ source: null,
12969
+ priority: 4
12970
+ });
12971
+ if (!closedWhileLive) continue;
12972
+ const { updatedAt } = parseJson(ticketFactsSchema, ticket.detail);
12973
+ const polled = project.repos.every((repo) => {
12974
+ const repoSource = sourceById.get(`github:${project.id}:${repo.toLowerCase()}`);
12975
+ return repoSource !== void 0 && repoSource.blind_reason === null && repoSource.last_complete_at !== null && Date.parse(repoSource.last_complete_at) > Date.parse(updatedAt);
12976
+ });
12977
+ const key = `ticket-closed:${String(task.id)}`;
12978
+ if (!polled) {
12979
+ unpolledTickets.push(key);
12980
+ continue;
12981
+ }
12982
+ candidates.push({
12983
+ key,
12984
+ kind: "anomaly",
12985
+ taskId: task.id,
12986
+ summary: `${task.key}: ticket closed while work is live and no PR merged`,
12987
+ factAt: updatedAt,
12988
+ source: ticket.source,
12989
+ priority: 4,
12990
+ revision: "closed"
12991
+ });
12992
+ }
12655
12993
  const previousEpisode = await trx.selectFrom("meta").select("value").where("key", "=", "host_load_episode").executeTakeFirst();
12656
- const spur = sourceById.get("spur");
12657
12994
  const health = evaluateSessionHealth({
12658
12995
  sessions: subjects,
12659
12996
  tasks: taskPrs,
12660
12997
  spur: {
12661
- blind: spur?.blind_reason !== null && spur !== void 0,
12998
+ blind: spurBlind,
12662
12999
  observationComplete: spurComplete
12663
13000
  },
12664
13001
  config: config.health,
@@ -12674,9 +13011,13 @@ async function reconcileItems(trx, config, now, spurComplete) {
12674
13011
  if (task === void 0) continue;
12675
13012
  const fact = subjects.find((subject) => subject.taskId === flag.taskId && subject.id === flag.sessionId);
12676
13013
  const endedLabel = ENDED_WORKER_LABELS[flag.kind];
13014
+ const asking = flag.kind === "needs_input" && fact !== void 0 && blocks.some((block) => {
13015
+ const author = parseActorId(block.author);
13016
+ return block.task_id === task.id && author?.actor === "agent" && author.actorRef.project === fact.spurProject && author.actorRef.session === fact.id;
13017
+ });
12677
13018
  candidates.push({
12678
13019
  key: healthKey(task.id, flag),
12679
- kind: flag.kind === "worker_completed" || flag.kind === "worker_killed" ? "worker_ended" : "board_observation",
13020
+ kind: ANOMALY_FLAGS.has(flag.kind) && !asking ? "anomaly" : flag.kind === "worker_killed" ? "worker_ended" : "board_observation",
12680
13021
  taskId: task.id,
12681
13022
  summary: `${task.key}: ${endedLabel ?? flag.kind.replaceAll("_", " ")} (${flag.sessionId})`,
12682
13023
  factAt: fact?.healthSince ?? null,
@@ -12685,20 +13026,54 @@ async function reconcileItems(trx, config, now, spurComplete) {
12685
13026
  revision: endedLabel === void 0 ? fact?.healthSince ?? null : fact?.endedAt ?? null
12686
13027
  });
12687
13028
  }
13029
+ if (!spurBlind) {
13030
+ const flagged = new Set([...health.flags, ...health.held].filter((flag) => ANOMALY_FLAGS.has(flag.kind)).map((flag) => flag.sessionId));
13031
+ const threshold = stuckTurnAfterMs(config);
13032
+ for (const { turn, sessionId, ended, quietSince, reminder, delivered } of await quietTurns(trx)) {
13033
+ const task = taskById.get(turn.task_id);
13034
+ if (task === void 0 || quietSince === null || flagged.has(sessionId)) continue;
13035
+ const quiet = Date.parse(quietSince);
13036
+ const reminded = reminder !== void 0 && delivered && reminder.acked_at !== null && now >= Math.max(Date.parse(reminder.acked_at), quiet) + threshold;
13037
+ const unreached = reminder !== void 0 && reminder.exhausted_at !== null && now >= quiet + threshold;
13038
+ if (!reminded && !unreached && !(ended && now >= quiet + threshold)) continue;
13039
+ candidates.push({
13040
+ key: `stuck-turn:${String(turn.id)}`,
13041
+ kind: "anomaly",
13042
+ taskId: task.id,
13043
+ summary: `${task.key}: turn T${String(turn.id)} taken by ${sessionId} has no submit or question`,
13044
+ factAt: quietSince,
13045
+ source: "spur",
13046
+ priority: 4,
13047
+ revision: turn.acked_at
13048
+ });
13049
+ }
13050
+ }
12688
13051
  const ordered = orderItems(candidates);
12689
- const seen = new Set(ordered.map((item) => item.key));
13052
+ const seen = /* @__PURE__ */ new Set([...ordered.map((item) => item.key), ...unpolledTickets]);
12690
13053
  for (const flag of health.held) {
12691
13054
  const task = taskById.get(Number(flag.taskId));
12692
13055
  if (task !== void 0) seen.add(healthKey(task.id, flag));
12693
13056
  }
12694
13057
  const existing = await trx.selectFrom("operator_item").selectAll().where("kind", "in", RECONCILED_KINDS).where("cleared_at", "is", null).execute();
12695
- for (const item of existing) if (!seen.has(item.item_key)) await clearItem(trx, item.id, new Date(now));
13058
+ const stillInError = new Set(health.hostLoad === null ? [] : subjects.filter((subject) => subject.endedAt === null && subject.health === "error" && subject.role !== "other").map((subject) => healthKey(Number(subject.taskId), {
13059
+ taskId: subject.taskId,
13060
+ sessionId: subject.id,
13061
+ kind: subject.role === "worker" ? "stuck_worker" : "stuck_orchestrator"
13062
+ })));
13063
+ const spurHeld = spurBlind ? await blindHeldKeys(trx, subjects) : /* @__PURE__ */ new Set();
13064
+ for (const item of existing) {
13065
+ if (item.kind !== "anomaly") continue;
13066
+ if (item.source === "spur" && spurHeld.has(item.item_key) || stillInError.has(item.item_key)) seen.add(item.item_key);
13067
+ }
13068
+ for (const item of existing) if (!seen.has(item.item_key)) await clearReconciled(trx, item, new Date(now));
13069
+ const ended = (await trx.selectFrom("dismissal").select("item_key").where((eb) => eb.or([eb("item_key", "like", "pr-closed:%"), eb("item_key", "like", "ticket-closed:%")])).execute()).map((row) => row.item_key).filter((key) => !seen.has(key));
13070
+ if (ended.length > 0) await trx.deleteFrom("dismissal").where("item_key", "in", ended).execute();
12696
13071
  for (const candidate of ordered) {
12697
13072
  const hash = fingerprint(candidate);
12698
13073
  const old = existing.find((item) => item.item_key === candidate.key);
12699
13074
  const dismissal = await trx.selectFrom("dismissal").select("fingerprint").where("item_key", "=", candidate.key).executeTakeFirst();
12700
13075
  const kept = old !== void 0 && old.fingerprint === hash && old.kind === candidate.kind;
12701
- if (old !== void 0 && (dismissal?.fingerprint === hash || !kept)) await clearItem(trx, old.id, new Date(now));
13076
+ if (old !== void 0 && (dismissal?.fingerprint === hash || !kept)) await clearReconciled(trx, old, new Date(now));
12702
13077
  if (dismissal?.fingerprint === hash) continue;
12703
13078
  if (kept) {
12704
13079
  if (old.fact_at !== candidate.factAt || old.source !== candidate.source) await trx.updateTable("operator_item").set({
@@ -12708,21 +13083,71 @@ async function reconcileItems(trx, config, now, spurComplete) {
12708
13083
  continue;
12709
13084
  }
12710
13085
  const task = candidate.taskId === null ? null : taskById.get(candidate.taskId);
12711
- await raiseItem(trx, {
13086
+ const input = {
12712
13087
  itemKey: candidate.key,
12713
13088
  kind: candidate.kind,
12714
13089
  text: candidate.summary,
12715
13090
  url: task === null || task === void 0 ? "https://github.com" : taskUrl(task, config),
12716
- taskId: candidate.taskId,
12717
- blockId: null,
12718
13091
  at: new Date(now),
12719
13092
  fingerprint: hash,
12720
13093
  factAt: candidate.factAt,
12721
13094
  source: candidate.source,
12722
13095
  priority: candidate.priority
13096
+ };
13097
+ if (ITEM_POLICY[candidate.kind].block && task !== null && task !== void 0) await raiseAnomaly(trx, config, task, input);
13098
+ else await raiseItem(trx, {
13099
+ ...input,
13100
+ taskId: candidate.taskId,
13101
+ blockId: null
12723
13102
  });
12724
13103
  }
12725
13104
  }
13105
+ /**
13106
+ * Raises a ledger item with the operator block it stands for. An active item of the key is
13107
+ * returned as it is, so a repeated raise opens no second block.
13108
+ */
13109
+ async function raiseAnomaly(trx, config, task, input) {
13110
+ const active = await trx.selectFrom("operator_item").selectAll().where("item_key", "=", input.itemKey).where("cleared_at", "is", null).executeTakeFirst();
13111
+ if (active !== void 0) return active;
13112
+ const prefix = `${task.key}: `;
13113
+ const block = await openSystemBlock(trx, {
13114
+ task,
13115
+ reason: input.text.startsWith(prefix) ? input.text.slice(prefix.length) : input.text,
13116
+ at: input.at.toISOString(),
13117
+ config
13118
+ });
13119
+ return raiseItem(trx, {
13120
+ ...input,
13121
+ taskId: task.id,
13122
+ blockId: block.id
13123
+ });
13124
+ }
13125
+ /** Clears a reconciled item; a ledger item's open block is withdrawn by the board first. */
13126
+ async function clearReconciled(trx, item, at) {
13127
+ if (item.block_id !== null) {
13128
+ const ctx = {
13129
+ actor: "system",
13130
+ at: at.toISOString()
13131
+ };
13132
+ await closeBlockIfOpen(trx, item.block_id, ctx, "withdrawn", "condition ended");
13133
+ }
13134
+ await clearItem(trx, item.id, at);
13135
+ }
13136
+ /**
13137
+ * The Spur-derived anomaly keys a blind Spur holds open: a health flag of a session still linked
13138
+ * to its task, and a stuck turn `quietTurns` still lists, so a removed worker holder's link ends
13139
+ * the hold by the same rule that keeps its block closed after Spur recovers.
13140
+ */
13141
+ async function blindHeldKeys(trx, subjects) {
13142
+ const held = /* @__PURE__ */ new Set();
13143
+ for (const subject of subjects) for (const kind of ANOMALY_FLAGS) held.add(healthKey(Number(subject.taskId), {
13144
+ taskId: subject.taskId,
13145
+ sessionId: subject.id,
13146
+ kind
13147
+ }));
13148
+ for (const { turn } of await quietTurns(trx)) held.add(`stuck-turn:${String(turn.id)}`);
13149
+ return held;
13150
+ }
12726
13151
  function healthKey(taskId, flag) {
12727
13152
  return `health:${String(taskId)}:${flag.sessionId}:${flag.kind}`;
12728
13153
  }
@@ -12747,7 +13172,7 @@ async function updateTerminal(trx, config, taskId, at, completeSince, blind) {
12747
13172
  const linked = await trx.selectFrom("link").innerJoin("pr_snapshot", (join) => join.on(sql`lower(pr_snapshot.repo) = lower(link.repo)`).onRef("pr_snapshot.number", "=", "link.number")).select("pr_snapshot.state").where("link.task_id", "=", taskId).where("link.entity", "=", "pr").where("link.banned", "=", 0).execute();
12748
13173
  const hasOpen = linked.some((pr) => pr.state === "open");
12749
13174
  const merged = linked.some((pr) => pr.state === "merged");
12750
- const doneTicket = ticket !== void 0 && (project.tracker.type === "jira" ? project.tracker.doneStatuses.includes(ticket.status) : ticket.status === "closed");
13175
+ const doneTicket = ticket !== void 0 && ticketDone(project, ticket.status);
12751
13176
  const githubComplete = project.repos.every((repo) => {
12752
13177
  const source = `github:${project.id}:${repo.toLowerCase()}`;
12753
13178
  const complete = completeSince.get(source);
@@ -13399,6 +13824,7 @@ async function tickBoard(deps) {
13399
13824
  at
13400
13825
  });
13401
13826
  }
13827
+ await remindStuckTurns(trx, config, new Date(now));
13402
13828
  await reconcileItems(trx, config, now, completeSince.has("spur"));
13403
13829
  });
13404
13830
  }
@@ -13625,6 +14051,7 @@ async function linkedComment(trx, event) {
13625
14051
  }
13626
14052
  /** The answer's notification is already registered; this raises the item when nobody can read it. */
13627
14053
  async function ringAuthor(trx, input) {
14054
+ if (await trx.selectFrom("operator_item").select("id").where("block_id", "=", input.block.id).where("kind", "in", BLOCK_ITEM_KINDS).executeTakeFirst() !== void 0) return;
13628
14055
  const key = `doorbell:comment:${String(input.comment.id)}:revision:${String(input.comment.revision)}`;
13629
14056
  const parsed = parseActorId(input.block.author);
13630
14057
  if (parsed?.actor === "agent") {
package/dist/mcp.mjs CHANGED
@@ -1,6 +1,6 @@
1
- import { F as ERRORS, m as renderMcpError, u as OPERATIONS } from "./src-CzmL-_Vf.mjs";
2
- import { a as CliError, r as requestOperation } from "./client-DAWhcbvn.mjs";
3
- import { a as memoryVerdictCache, c as loadClientConfig, r as compareCatalogs, t as checkCatalog } from "./config-D9spr6M_.mjs";
1
+ import { F as ERRORS, m as renderMcpError, u as OPERATIONS } from "./src-X9r7Gx21.mjs";
2
+ import { a as CliError, r as requestOperation } from "./client-CfA-Snt_.mjs";
3
+ import { a as memoryVerdictCache, c as loadClientConfig, r as compareCatalogs, t as checkCatalog } from "./config-035Sq4n3.mjs";
4
4
  import { randomUUID } from "node:crypto";
5
5
  import { readFileSync } from "node:fs";
6
6
  import { z } from "zod";
@@ -0,0 +1,44 @@
1
+ -- Kind `turn_reminder` is the single reminder ring to the holder of a quiet turn; like `turn` it
2
+ -- belongs to a turn, not a block. Keep every id, and keep the sequence: outbox payloads name
3
+ -- notification ids above the largest one still stored.
4
+ CREATE TABLE notification_new (
5
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
6
+ source_key TEXT NOT NULL UNIQUE,
7
+ kind TEXT NOT NULL,
8
+ task_id INTEGER NOT NULL REFERENCES task (id),
9
+ block_id INTEGER REFERENCES block (id),
10
+ comment_id INTEGER REFERENCES comment (id),
11
+ revision INTEGER,
12
+ role TEXT NOT NULL,
13
+ author_session TEXT,
14
+ recipient_session TEXT,
15
+ rings INTEGER NOT NULL DEFAULT 0,
16
+ next_at TEXT NOT NULL,
17
+ last_outbox_id INTEGER REFERENCES outbox (id),
18
+ acked_at TEXT,
19
+ created_at TEXT NOT NULL,
20
+ exhausted_at TEXT,
21
+ turn_id INTEGER REFERENCES turn (id),
22
+ CHECK (kind NOT IN ('turn', 'turn_reminder') OR (turn_id IS NOT NULL AND block_id IS NULL)),
23
+ CHECK (kind IN ('turn', 'turn_reminder') OR (block_id IS NOT NULL AND turn_id IS NULL))
24
+ ) STRICT;
25
+
26
+ INSERT INTO notification_new (id, source_key, kind, task_id, block_id, comment_id, revision, role,
27
+ author_session, recipient_session, rings, next_at, last_outbox_id, acked_at, created_at,
28
+ exhausted_at, turn_id)
29
+ SELECT id, source_key, kind, task_id, block_id, comment_id, revision, role, author_session,
30
+ recipient_session, rings, next_at, last_outbox_id, acked_at, created_at, exhausted_at, turn_id
31
+ FROM notification;
32
+
33
+ INSERT INTO sqlite_sequence (name, seq)
34
+ SELECT 'notification_new', 0
35
+ WHERE NOT EXISTS (SELECT 1 FROM sqlite_sequence WHERE name = 'notification_new');
36
+ UPDATE sqlite_sequence
37
+ SET seq = max(seq, coalesce((SELECT seq FROM sqlite_sequence WHERE name = 'notification'), 0))
38
+ WHERE name = 'notification_new';
39
+
40
+ DROP TABLE notification;
41
+ ALTER TABLE notification_new RENAME TO notification;
42
+ CREATE INDEX notification_due ON notification (acked_at, next_at);
43
+ CREATE INDEX notification_block ON notification (block_id, id);
44
+ CREATE INDEX notification_turn ON notification (turn_id, id);
@@ -414,7 +414,7 @@ const configSchema = z.strictObject({
414
414
  health: z.strictObject({
415
415
  errorAfterMs: durationMs(9e4, "How long a session stays in error before it is flagged"),
416
416
  needsInputAfterMs: durationMs(12e4, "How long a session waits for input before it is flagged"),
417
- idleInDevAfterMs: durationMs(18e5, "How long a worker session without an open PR waits at its prompt before it is flagged"),
417
+ idleInDevAfterMs: durationMs(18e5, "How long a worker session without an open PR, or the executor of a taken turn, waits at its prompt before it is flagged"),
418
418
  flipSmoothingMs: durationMs(3e4, "How long a new session health value must hold before it is reported"),
419
419
  hostLoad: z.strictObject({
420
420
  sessions: z.int().min(1).default(3).describe("Sessions entering error within the window that start an episode."),
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "spur-board",
3
- "version": "0.38.3",
3
+ "version": "0.39.0",
4
4
  "license": "MIT",
5
5
  "engines": {
6
6
  "node": "^24.12.0 || ^26.0.0"