spur-board 0.145.0 → 0.146.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/daemon.mjs CHANGED
@@ -1,4 +1,4 @@
1
- import { $ as ringMarker, A as eventPayloadSchemas, At as resolveWebOrigin, B as sourceCursorSchema, Bt as isTodoGroupColumn, C as messageRefSchema, Ct as columnTurnTimings, D as sortSkillFiles, Dt as plainHttpAllowed, E as skillReloadFilesSchema, Et as defaultAddressee, F as defaultBranchFactSchema, Ft as ITEM_KINDS, G as SESSION_HEALTH_STATES, H as PR_STATES, I as entityRefSchema, It as SLACK_BOT_SCOPES, J as parseRingMarker, K as SESSION_STATUSES, L as mirrorSourceId, Lt as TASK_HOLDS, M as MIRROR_FAILURES, Mt as COLUMN_GROUPS, N as MIRROR_FAILURE_CODES, Nt as COLUMN_IDS, O as EVENT_KINDS, Ot as readyMirrorOf, P as batchSchema, Pt as DISPATCHER_MODES, Q as prReviewRuleSchema, R as prSourceId, Rt as TODO_GROUP_COLUMN_IDS, S as interactionRefSchema, St as boardWideSpurProject, Tt as configSchema, U as REVIEW_DECISIONS, V as trackerSourceId, W as REVIEW_STATES, X as prFactsSchema, Y as prApprovalPairSchema, Z as prRefSchema, a as requestHashOf, at as encodeActorId, b as conversationRefSchema, bt as RESERVED_PROJECT, c as tokenRequestStatusSchema, ct as parseRef$1, d as buildCatalogSnapshot, et as sessionFactsSchema, f as roleCanUseOperation, g as renderHttpProblem, gt as DEFAULT_LINK, h as turnHandedSchema, i as TOKEN_REQUEST_LIMITS, it as actorIdSchema, j as AdapterError, jt as COLUMNS, k as GATE_REASONS, kt as requiredSecretKeys, l as BOARD_TICK_MS, lt as ERRORS, m as defaultBranchViewSchema, mt as successEnvelopeSchema, n as doctorReportSchema, nt as JIRA_PROJECT_KEY, o as tokenRequestResultSchema, ot as errorCodeOf, p as OPERATIONS, pt as ok, q as isExternalAuthor, rt as REF_NUMBER, s as tokenRequestSchema, st as parseActorId, t as assertNever, tt as ticketFactsSchema, ut as err, vt as DEFAULT_SLACK_COMMAND, w as userIdSchema, wt as configBindings, x as inboundEventSchema, xt as approvalRuleOf, y as SPACE_IDS, z as sessionTransitionSchema, zt as VIAS } from "./chunk-CVVzwHUN.mjs";
1
+ import { $ as ringMarker, A as eventPayloadSchemas, At as resolveWebOrigin, B as sourceCursorSchema, Bt as isTodoGroupColumn, C as messageRefSchema, Ct as columnTurnTimings, D as sortSkillFiles, Dt as plainHttpAllowed, E as skillReloadFilesSchema, Et as defaultAddressee, F as defaultBranchFactSchema, Ft as ITEM_KINDS, G as SESSION_HEALTH_STATES, H as PR_STATES, I as entityRefSchema, It as SLACK_BOT_SCOPES, J as parseRingMarker, K as SESSION_STATUSES, L as mirrorSourceId, Lt as TASK_HOLDS, M as MIRROR_FAILURES, Mt as COLUMN_GROUPS, N as MIRROR_FAILURE_CODES, Nt as COLUMN_IDS, O as EVENT_KINDS, Ot as readyMirrorOf, P as batchSchema, Pt as DISPATCHER_MODES, Q as prReviewRuleSchema, R as prSourceId, Rt as TODO_GROUP_COLUMN_IDS, S as interactionRefSchema, St as boardWideSpurProject, Tt as configSchema, U as REVIEW_DECISIONS, V as trackerSourceId, W as REVIEW_STATES, X as prFactsSchema, Y as prApprovalPairSchema, Z as prRefSchema, a as requestHashOf, at as encodeActorId, b as conversationRefSchema, bt as RESERVED_PROJECT, c as tokenRequestStatusSchema, ct as parseRef$1, d as buildCatalogSnapshot, et as sessionFactsSchema, f as roleCanUseOperation, g as renderHttpProblem, gt as DEFAULT_LINK, h as turnHandedSchema, i as TOKEN_REQUEST_LIMITS, it as actorIdSchema, j as AdapterError, jt as COLUMNS, k as GATE_REASONS, kt as requiredSecretKeys, l as BOARD_TICK_MS, lt as ERRORS, m as defaultBranchViewSchema, mt as successEnvelopeSchema, n as doctorReportSchema, nt as JIRA_PROJECT_KEY, o as tokenRequestResultSchema, ot as errorCodeOf, p as OPERATIONS, pt as ok, q as isExternalAuthor, rt as REF_NUMBER, s as tokenRequestSchema, st as parseActorId, t as assertNever, tt as ticketFactsSchema, ut as err, vt as DEFAULT_SLACK_COMMAND, w as userIdSchema, wt as configBindings, x as inboundEventSchema, xt as approvalRuleOf, y as SPACE_IDS, z as sessionTransitionSchema, zt as VIAS } from "./chunk-BS5xzBWL.mjs";
2
2
  import { t as apiBaseUrl } from "./chunk-Bzb7aI8R.mjs";
3
3
  import { createRequire } from "node:module";
4
4
  import { createHash, randomUUID } from "node:crypto";
@@ -10063,6 +10063,13 @@ async function heldForOpener(trx, turn, opts) {
10063
10063
  * ownership episode, so a session that loses the turn and takes it again gets a new reminder.
10064
10064
  */
10065
10065
  const turnReminderKey = (turnId, session, takenAt) => `turn:${String(turnId)}:reminder:${session}:${takenAt}`;
10066
+ /**
10067
+ * The key of the ring that wakes `session` when its wait on a turn, started at `since`, ends. A
10068
+ * `turn_reminder` row too, so it rings once and drops with the turn's other reminders.
10069
+ */
10070
+ const turnWakeKey = (turnId, session, since) => `turn:${String(turnId)}:wake:${session}:${since}`;
10071
+ /** Whether a `turn_reminder` row is the wake ring of a wait. */
10072
+ const isTurnWakeKey = (key) => /^turn:\d+:wake:/.test(key);
10066
10073
  const isTurnKind = (kind) => kind === "turn" || kind === "turn_reminder";
10067
10074
  /**
10068
10075
  * Whether a reminder was cancelled before it was ever sent, as a link removal does: it counts as
@@ -10091,11 +10098,12 @@ async function cancelledRingState(trx, n) {
10091
10098
  * Register the single reminder to the session holding a quiet turn. The key names the holder and
10092
10099
  * its take, so each ownership episode gets its own reminder and no episode gets a second. A
10093
10100
  * reminder of the take cancelled unsent is replaced by a fresh one: its row gets a new id, so the
10094
- * new ring does not reuse the outbox key of a ring the sender already killed.
10101
+ * new ring does not reuse the outbox key of a ring the sender already killed. A wait's wake ring
10102
+ * passes its own `wakeKey` (`turnWakeKey`).
10095
10103
  */
10096
- async function registerTurnReminder(trx, turn, session, at) {
10104
+ async function registerTurnReminder(trx, turn, session, at, wakeKey) {
10097
10105
  if (turn.acked_at === null) throw new Error(`turn ${String(turn.id)} is not taken`);
10098
- const key = turnReminderKey(turn.id, session, turn.acked_at);
10106
+ const key = wakeKey ?? turnReminderKey(turn.id, session, turn.acked_at);
10099
10107
  const earlier = await trx.selectFrom("notification").selectAll().where("source_key", "=", key).executeTakeFirst();
10100
10108
  if (earlier !== void 0 && await reminderCancelledUnsent(trx, earlier)) await trx.deleteFrom("notification").where("id", "=", earlier.id).execute();
10101
10109
  await trx.insertInto("notification").values({
@@ -10488,10 +10496,17 @@ async function noRecipientEnd(trx, n) {
10488
10496
  if (parseAddressee(n.role).kind !== "orchestrator") return null;
10489
10497
  return await trx.selectFrom("operator_item").select("id").where("kind", "=", "course_check").where("block_id", "=", noticeBlockId(n)).executeTakeFirst() === void 0 ? null : "no live orchestrator session";
10490
10498
  }
10491
- /** A ring never carries comment or reason text: only where to look. */
10499
+ /**
10500
+ * A ring never carries comment or reason text, only where to look; the one exception is a wait's
10501
+ * wake ring, which repeats the reason the holder gave itself, on one line.
10502
+ */
10492
10503
  async function ringText(trx, n, { key }, ring) {
10493
10504
  const suffix = ringMarker(n.id, ring);
10494
10505
  if (n.kind === "turn") return `${key} turn T${String(n.turn_id)}: check board inbox ${suffix}`;
10506
+ if (n.kind === "turn_reminder" && n.turn_id !== null && isTurnWakeKey(n.source_key)) {
10507
+ const reason = ((await trx.selectFrom("turn").select("wait_reason").where("id", "=", n.turn_id).executeTakeFirst())?.wait_reason ?? "").replace(/\s+/g, " ").trim();
10508
+ return `${key} turn T${String(n.turn_id)} wait ended: ${reason}; check board inbox ${suffix}`;
10509
+ }
10495
10510
  if (n.kind === "turn_reminder") return `${key} turn T${String(n.turn_id)} is still open: check board inbox ${suffix}`;
10496
10511
  const blockId = noticeBlockId(n);
10497
10512
  if (n.kind !== "removed") return `${key} block B${String(blockId)}: check board inbox ${suffix}`;
@@ -12169,6 +12184,164 @@ function turnReason(turn, rerouted) {
12169
12184
  if (turn.kind === "reroute" && rerouted !== void 0) return rerouted;
12170
12185
  return `${turn.column}: ${turn.reasons.join(", ")}`;
12171
12186
  }
12187
+ // ../core/src/app/turn-waits.ts
12188
+ const turnRef$1 = (turnId) => `T${String(turnId)}`;
12189
+ /**
12190
+ * Ends the active wait of `turn` as `outcome` at `at`: the time it lasted, up to its wake, joins
12191
+ * the turn's total. Nothing for a turn that is not waiting. Returns the new total.
12192
+ */
12193
+ async function endTurnWait(trx, input) {
12194
+ const { turn, project, outcome, at, actor } = input;
12195
+ if (turn.wait_until === null || turn.wait_since === null) return turn.waited_ms;
12196
+ const end = Math.min(at.getTime(), Date.parse(turn.wait_until));
12197
+ const waitedMs = turn.waited_ms + Math.max(0, end - Date.parse(turn.wait_since));
12198
+ await trx.updateTable("turn").set({
12199
+ wait_until: null,
12200
+ wait_ended_at: at.toISOString(),
12201
+ waited_ms: waitedMs
12202
+ }).where("id", "=", turn.id).execute();
12203
+ const payload = {
12204
+ turn: turnRef$1(turn.id),
12205
+ outcome,
12206
+ waitedMs,
12207
+ waits: turn.wait_count
12208
+ };
12209
+ await emit(trx, "turn_wait_ended", project, turn.task_id, at.toISOString(), payload, actor);
12210
+ return waitedMs;
12211
+ }
12212
+ /** Ends the wait of every unclosed turn of a task, before a close. */
12213
+ async function endTaskTurnWaits(trx, input) {
12214
+ const waiting = await trx.selectFrom("turn").innerJoin("task", "task.id", "turn.task_id").selectAll("turn").select("task.project").where("turn.task_id", "=", input.taskId).where("turn.closed_at", "is", null).where("turn.wait_until", "is not", null).execute();
12215
+ for (const turn of waiting) await endTurnWait(trx, {
12216
+ ...input,
12217
+ turn,
12218
+ project: turn.project
12219
+ });
12220
+ }
12221
+ /** Whether the turn's waits reached the count or the total time limit. */
12222
+ function waitsUsed(config, turn) {
12223
+ const { maxWaits, maxTotalMs } = config.health.turnWait;
12224
+ return turn.wait_count >= maxWaits || turn.waited_ms >= maxTotalMs;
12225
+ }
12226
+ /** The holder session of a turn an agent took, or null. */
12227
+ function holderSession(turn) {
12228
+ const holder = turn.acked_by === null ? null : parseActorId(turn.acked_by);
12229
+ return holder?.actor === "agent" ? holder.actorRef.session : null;
12230
+ }
12231
+ /** Whether the snapshot of `session` says it ended; false without a snapshot. */
12232
+ async function sessionEnded(trx, session) {
12233
+ return (await trx.selectFrom("session_snapshot").select("ended_at").where("id", "=", session).executeTakeFirst())?.ended_at != null;
12234
+ }
12235
+ /**
12236
+ * Whether the holder `session` of a worker turn has lost the task: `unlinked` holds the
12237
+ * `taskId:sessionId` pairs whose session link the operator removed. An orchestrator turn is
12238
+ * addressed through the column config, so a link removal does not end its hold.
12239
+ */
12240
+ function workerUnlinked(unlinked, turn, session) {
12241
+ return turn.role === "worker" && unlinked.has(`${String(turn.task_id)}:${session}`);
12242
+ }
12243
+ /** The `taskId:sessionId` pairs whose session link the operator removed. */
12244
+ async function unlinkedSessions(trx) {
12245
+ const removed = await trx.selectFrom("link").select(["task_id", "session_id"]).where("entity", "=", "session").where("banned", "=", 1).execute();
12246
+ return new Set(removed.map((link) => `${String(link.task_id)}:${link.session_id ?? ""}`));
12247
+ }
12248
+ /**
12249
+ * The tick's wait ends. A wait whose agent holder's session ended ends `closed` with no ring.
12250
+ * Otherwise, once its wake time passes, it ends `limit` when the turn's waits reached a limit,
12251
+ * else `woken`, and an agent holder gets one wake ring, unless it holds a worker turn whose session
12252
+ * link the operator removed.
12253
+ */
12254
+ async function wakeWaitingTurns(trx, config, at) {
12255
+ const waiting = await trx.selectFrom("turn").innerJoin("task", "task.id", "turn.task_id").selectAll("turn").select("task.project").where("turn.closed_at", "is", null).where("turn.wait_until", "is not", null).orderBy("turn.id").execute();
12256
+ const unlinked = waiting.length === 0 ? /* @__PURE__ */ new Set() : await unlinkedSessions(trx);
12257
+ for (const turn of waiting) {
12258
+ const session = holderSession(turn);
12259
+ if (session !== null && await sessionEnded(trx, session)) {
12260
+ await endTurnWait(trx, {
12261
+ turn,
12262
+ project: turn.project,
12263
+ outcome: "closed",
12264
+ at
12265
+ });
12266
+ continue;
12267
+ }
12268
+ if (turn.wait_until === null || turn.wait_since === null) continue;
12269
+ if (at.getTime() < Date.parse(turn.wait_until)) continue;
12270
+ const lasted = Date.parse(turn.wait_until) - Date.parse(turn.wait_since);
12271
+ const outcome = waitsUsed(config, {
12272
+ ...turn,
12273
+ waited_ms: turn.waited_ms + lasted
12274
+ }) ? "limit" : "woken";
12275
+ await endTurnWait(trx, {
12276
+ turn,
12277
+ project: turn.project,
12278
+ outcome,
12279
+ at
12280
+ });
12281
+ if (session !== null && !workerUnlinked(unlinked, turn, session)) await registerTurnReminder(trx, turn, session, at, turnWakeKey(turn.id, session, turn.wait_since));
12282
+ }
12283
+ }
12284
+ /**
12285
+ * The `taskId:sessionId` pairs whose `worker_idle` stays off: the agent holder of an unclosed turn
12286
+ * while it waits, and for `health.idleInDevAfterMs` after a wait that ran out (`woken` or
12287
+ * `limit`). Only those ends come after the take with the holder still live: a take ends the wait
12288
+ * at its own time, and submit or close leave no unclosed turn. A holder whose session ended gets
12289
+ * none.
12290
+ */
12291
+ async function restingHolders(trx, config, now) {
12292
+ const turns = await trx.selectFrom("turn").select([
12293
+ "task_id",
12294
+ "acked_by",
12295
+ "acked_at",
12296
+ "wait_until",
12297
+ "wait_ended_at"
12298
+ ]).where("closed_at", "is", null).where("acked_at", "is not", null).execute();
12299
+ const resting = /* @__PURE__ */ new Set();
12300
+ for (const turn of turns) {
12301
+ const session = holderSession(turn);
12302
+ if (session === null || turn.acked_at === null || await sessionEnded(trx, session)) continue;
12303
+ const ended = turn.wait_ended_at === null ? null : Date.parse(turn.wait_ended_at);
12304
+ const grace = ended !== null && ended > Date.parse(turn.acked_at) && now < ended + config.health.idleInDevAfterMs;
12305
+ if (turn.wait_until !== null || grace) resting.add(`${String(turn.task_id)}:${session}`);
12306
+ }
12307
+ return resting;
12308
+ }
12309
+ /** Whole minutes and hours: `45m`, `2h`, `1h 30m`. */
12310
+ function waitDuration(ms) {
12311
+ const minutes = Math.floor(ms / 6e4);
12312
+ const hours = Math.floor(minutes / 60);
12313
+ const rest = minutes % 60;
12314
+ if (hours === 0) return `${String(rest)}m`;
12315
+ return rest === 0 ? `${String(hours)}h` : `${String(hours)}h ${String(rest)}m`;
12316
+ }
12317
+ /**
12318
+ * One operator item per unclosed turn of a live task whose waits reached a limit and that is not
12319
+ * waiting now: the holder keeps the turn, and the operator decides what happens next.
12320
+ */
12321
+ async function turnWaitItems(trx, config, taskById) {
12322
+ return (await trx.selectFrom("turn").selectAll().where("closed_at", "is", null).where("wait_until", "is", null).where("wait_count", ">", 0).orderBy("id").execute()).flatMap((turn) => {
12323
+ const task = taskById.get(turn.task_id);
12324
+ if (task === void 0 || !waitsUsed(config, turn)) return [];
12325
+ return [{
12326
+ key: `turn-wait:${String(turn.id)}`,
12327
+ kind: "board_observation",
12328
+ taskId: task.id,
12329
+ summary: `${task.key}: turn ${turnRef$1(turn.id)} has waited ${waitDuration(turn.waited_ms)} for ${(turn.wait_reason ?? "").replace(/\s+/g, " ").trim()}`,
12330
+ factAt: turn.wait_ended_at,
12331
+ source: null,
12332
+ priority: 4
12333
+ }];
12334
+ });
12335
+ }
12336
+ /** The active wait a turn view shows; nothing while the turn is not waiting. */
12337
+ function turnWaitView(turn) {
12338
+ if (turn.wait_until === null || turn.wait_since === null || turn.wait_reason === null) return {};
12339
+ return { wait: {
12340
+ reason: turn.wait_reason,
12341
+ since: turn.wait_since,
12342
+ wakesAt: turn.wait_until
12343
+ } };
12344
+ }
12172
12345
  // ../core/src/app/turns.ts
12173
12346
  const handedSchema = z.array(turnHandedSchema);
12174
12347
  const turnItemKey = (turnId) => `turn:${String(turnId)}`;
@@ -12246,7 +12419,7 @@ async function openTurn(trx, input) {
12246
12419
  * not, with no notification step; anyone else gets false for an operator turn. Others get
12247
12420
  * `forbidden`.
12248
12421
  * Every take starts a new ownership episode: an unsent reminder of an earlier one is acked, so
12249
- * `ringStillCurrent` drops its ring.
12422
+ * `ringStillCurrent` drops its ring, and an active wait ends `closed`.
12250
12423
  */
12251
12424
  async function takeTurn(trx, input) {
12252
12425
  const { turnId, actor, at, config } = input;
@@ -12267,6 +12440,13 @@ async function takeTurn(trx, input) {
12267
12440
  const notice = await turnNotification(trx, turnId);
12268
12441
  if (notice === void 0 || !await notificationAddressedTo(trx, notice, actor, config)) throw new CommandError("forbidden", "Only the addressed task role can take this turn.");
12269
12442
  }
12443
+ await endTurnWait(trx, {
12444
+ turn,
12445
+ project,
12446
+ outcome: "closed",
12447
+ at,
12448
+ actor
12449
+ });
12270
12450
  await trx.updateTable("turn").set({
12271
12451
  acked_by: actor,
12272
12452
  acked_at: at.toISOString()
@@ -12279,12 +12459,19 @@ async function takeTurn(trx, input) {
12279
12459
  return true;
12280
12460
  }
12281
12461
  /**
12282
- * Closes every unclosed turn of a task: its rings stop and its items end as "condition ended".
12462
+ * Closes every unclosed turn of a task: its wait ends (`submitted` for a submit, else `closed`),
12463
+ * its rings stop and its items end as "condition ended".
12283
12464
  * A ring already queued is dropped by the sender (`ringStillCurrent`). `turn_closed` names
12284
12465
  * `actor` when given, else `system`.
12285
12466
  */
12286
12467
  async function closeTurns(trx, input) {
12287
12468
  const { taskId, reason, at, actor } = input;
12469
+ await endTaskTurnWaits(trx, {
12470
+ taskId,
12471
+ outcome: reason === "submitted" ? "submitted" : "closed",
12472
+ at,
12473
+ actor
12474
+ });
12288
12475
  const closed = await trx.updateTable("turn").set({
12289
12476
  closed_at: at.toISOString(),
12290
12477
  closed_reason: reason
@@ -12332,112 +12519,6 @@ async function rerouteDemotedWorkerTurn(trx, input) {
12332
12519
  });
12333
12520
  return true;
12334
12521
  }
12335
- /**
12336
- * How long the holder of a taken turn may sit quiet before it is reminded, then flagged: the column
12337
- * `quietTurnAfterMs` for its named orchestrator's turn (by role: a worker turn can stay in a column
12338
- * a config change named), else `health.idleInDevAfterMs`.
12339
- */
12340
- function stuckTurnAfterMs(config, projectId, turn) {
12341
- return (turn.role === `orchestrator:${turn.column}` ? columnTurnTimings(config, projectId, turn.column) : null)?.quietTurnAfterMs ?? config.health.idleInDevAfterMs;
12342
- }
12343
- /**
12344
- * Since when a holder session sits idle: from its end, or from when it began `waiting` at its
12345
- * prompt. Null for any other health, an unknown one, or a detail that does not parse.
12346
- */
12347
- function idleSince(session) {
12348
- if (session.ended_at !== null) return session.ended_at;
12349
- let detail;
12350
- try {
12351
- detail = JSON.parse(session.detail);
12352
- } catch {
12353
- return null;
12354
- }
12355
- const fact = sessionFactsSchema.safeParse(detail);
12356
- return fact.success && fact.data.health === "waiting" ? fact.data.healthSince : null;
12357
- }
12358
- /** The latest of ISO instants, compared as instants. */
12359
- function latest(values) {
12360
- return new Date(Math.max(...values.map((value) => Date.parse(value)))).toISOString();
12361
- }
12362
- /**
12363
- * Every taken, unclosed agent turn with its holder's session id, whether that session ended, and
12364
- * the reminder of the current holder's current take, so an earlier episode's reminder never counts
12365
- * and one cancelled unsent counts as none. `delivered` is whether that reminder reached the holder
12366
- * or may have: a ring killed after an uncertain send counts, so the one-ring limit hides no stuck
12367
- * turn.
12368
- * `quietSince` is when the holder last had something to do: the take, the start of its idle
12369
- * spell, or the close of its last question on the task. Null while the holder works, has an open
12370
- * question on the task, or has no readable snapshot. A worker turn whose holder's session link
12371
- * the operator removed is left out: the holder no longer works the task. An orchestrator turn is
12372
- * addressed through the column config, so a link removal does not end its hold.
12373
- */
12374
- async function quietTurns(trx) {
12375
- const turns = await trx.selectFrom("turn").selectAll().where("closed_at", "is", null).where("acked_at", "is not", null).where("role", "!=", "operator").orderBy("id").execute();
12376
- const removed = await trx.selectFrom("link").select(["task_id", "session_id"]).where("entity", "=", "session").where("banned", "=", 1).execute();
12377
- const unlinked = new Set(removed.map((link) => `${String(link.task_id)}:${link.session_id ?? ""}`));
12378
- const quiet = [];
12379
- for (const turn of turns) {
12380
- if (turn.acked_by === null || turn.acked_at === null) continue;
12381
- const holder = parseActorId(turn.acked_by);
12382
- if (holder?.actor !== "agent") continue;
12383
- const sessionId = holder.actorRef.session;
12384
- if (turn.role === "worker" && unlinked.has(`${String(turn.task_id)}:${sessionId}`)) continue;
12385
- const session = await trx.selectFrom("session_snapshot").selectAll().where("id", "=", sessionId).executeTakeFirst();
12386
- const idle = session === void 0 ? null : idleSince(session);
12387
- const blocks = await trx.selectFrom("block").select(["state", "unblocked_at"]).where("task_id", "=", turn.task_id).where("author", "=", turn.acked_by).execute();
12388
- const asking = blocks.some((block) => block.state === "open");
12389
- const unblocked = blocks.flatMap((block) => block.unblocked_at === null ? [] : [block.unblocked_at]);
12390
- const row = await trx.selectFrom("notification").selectAll().where("source_key", "=", turnReminderKey(turn.id, sessionId, turn.acked_at)).executeTakeFirst();
12391
- const cancelled = row === void 0 ? null : await cancelledRingState(trx, row);
12392
- quiet.push({
12393
- turn,
12394
- sessionId,
12395
- ended: session !== void 0 && session.ended_at !== null,
12396
- quietSince: idle === null || asking ? null : latest([
12397
- turn.acked_at,
12398
- idle,
12399
- ...unblocked
12400
- ]),
12401
- reminder: cancelled === "unsent" ? void 0 : row,
12402
- delivered: row !== void 0 && (row.rings >= 1 || cancelled === "maybe_out")
12403
- });
12404
- }
12405
- return quiet;
12406
- }
12407
- /** Whether Spur is blind, so a holder's health is unknown. */
12408
- async function spurBlind(trx) {
12409
- const spur = await trx.selectFrom("source_state").select("blind_reason").where("source", "=", "spur").executeTakeFirst();
12410
- return spur !== void 0 && spur.blind_reason !== null;
12411
- }
12412
- /**
12413
- * Registers one reminder per take to the holder of each turn quiet for `stuckTurnAfterMs`;
12414
- * `takeTurn` drops the unsent reminder of an earlier take. Nothing while Spur is blind, since the holder's health
12415
- * is then unknown.
12416
- */
12417
- async function remindStuckTurns(trx, config, at) {
12418
- if (await spurBlind(trx)) return;
12419
- for (const { turn, sessionId, ended, quietSince, reminder } of await quietTurns(trx)) {
12420
- if (ended || quietSince === null || reminder !== void 0) continue;
12421
- const threshold = stuckTurnAfterMs(config, await taskProject(trx, turn.task_id), turn);
12422
- if (at.getTime() < Date.parse(quietSince) + threshold) continue;
12423
- await registerTurnReminder(trx, turn, sessionId, at);
12424
- }
12425
- }
12426
- /**
12427
- * Whether a queued ring may go out at `at`. A turn reminder goes out only under the rule
12428
- * `remindStuckTurns` registers it by: its holder's current take is quiet for `stuckTurnAfterMs`.
12429
- * Otherwise the sender defers it, so a question opened after it was queued holds it until the
12430
- * question closes and a fresh quiet period passes, and blind Spur holds it until Spur reports again.
12431
- * Every other ring is due.
12432
- */
12433
- async function ringDue(trx, notificationId, config, at) {
12434
- if ((await trx.selectFrom("notification").select("kind").where("id", "=", notificationId).executeTakeFirst())?.kind !== "turn_reminder") return true;
12435
- if (await spurBlind(trx)) return false;
12436
- const quiet = (await quietTurns(trx)).find((entry) => entry.reminder?.id === notificationId);
12437
- if (quiet === void 0 || quiet.ended || quiet.quietSince === null) return false;
12438
- const project = await taskProject(trx, quiet.turn.task_id);
12439
- return at.getTime() >= Date.parse(quiet.quietSince) + stuckTurnAfterMs(config, project, quiet.turn);
12440
- }
12441
12522
  /** Close reasons of a turn whose untaken feedback goes back to a later turn. */
12442
12523
  const recalled = /* @__PURE__ */ new Set(["corrected", "rerouted"]);
12443
12524
  /** Whether `left` is newer than `right` by `postedAt` instant, then by id. Compared, not subtracted. */
@@ -14180,7 +14261,10 @@ async function readStatusTurns(db, projectIds) {
14180
14261
  "turn.head_sha",
14181
14262
  "turn.created_at",
14182
14263
  "turn.acked_by",
14183
- "turn.acked_at"
14264
+ "turn.acked_at",
14265
+ "turn.wait_reason",
14266
+ "turn.wait_since",
14267
+ "turn.wait_until"
14184
14268
  ]).select(["task.key as task_key", "notification.recipient_session"]).select((eb) => eb.selectFrom("operator_item").select((eb) => eb.fn.min("operator_item.fact_at").as("fact_at")).where("operator_item.cleared_at", "is", null).where("operator_item.item_key", ">=", sql`'turn-stall:' || ${sql.ref("turn.id")} || ':'`).where("operator_item.item_key", "<", sql`'turn-stall:' || ${sql.ref("turn.id")} || ';'`).as("stalled_since")).where("turn.closed_at", "is", null).where("task.membership", "!=", "archived").where("task.project", "in", [...projectIds]).execute();
14185
14269
  return new Map(turnRows.map((turn) => [turn.task_id, {
14186
14270
  id: `T${String(turn.id)}`,
@@ -14194,6 +14278,7 @@ async function readStatusTurns(db, projectIds) {
14194
14278
  by: turn.acked_by,
14195
14279
  at: turn.acked_at
14196
14280
  },
14281
+ ...turnWaitView(turn),
14197
14282
  addressedTo: turn.acked_at === null ? turn.recipient_session : null,
14198
14283
  stalledSince: turn.stalled_since
14199
14284
  }]));
@@ -14865,6 +14950,116 @@ function evaluateSessionHealth(input) {
14865
14950
  function prsPolledSince(task, since) {
14866
14951
  return task.prCompleteAt !== null && task.prCompleteAt >= Date.parse(since);
14867
14952
  }
14953
+ // ../core/src/app/quiet-turns.ts
14954
+ /**
14955
+ * How long the holder of a taken turn may sit quiet before it is reminded, then flagged: the column
14956
+ * `quietTurnAfterMs` for its named orchestrator's turn (by role: a worker turn can stay in a column
14957
+ * a config change named), else `health.idleInDevAfterMs`.
14958
+ */
14959
+ function stuckTurnAfterMs(config, projectId, turn) {
14960
+ return (turn.role === `orchestrator:${turn.column}` ? columnTurnTimings(config, projectId, turn.column) : null)?.quietTurnAfterMs ?? config.health.idleInDevAfterMs;
14961
+ }
14962
+ /**
14963
+ * Since when a holder session sits idle: from its end, or from when it began `waiting` at its
14964
+ * prompt. Null for any other health, an unknown one, or a detail that does not parse.
14965
+ */
14966
+ function idleSince(session) {
14967
+ if (session.ended_at !== null) return session.ended_at;
14968
+ let detail;
14969
+ try {
14970
+ detail = JSON.parse(session.detail);
14971
+ } catch {
14972
+ return null;
14973
+ }
14974
+ const fact = sessionFactsSchema.safeParse(detail);
14975
+ return fact.success && fact.data.health === "waiting" ? fact.data.healthSince : null;
14976
+ }
14977
+ /** The latest of ISO instants, compared as instants. */
14978
+ function latest(values) {
14979
+ return new Date(Math.max(...values.map((value) => Date.parse(value)))).toISOString();
14980
+ }
14981
+ /**
14982
+ * Every taken, unclosed agent turn with its holder's session id, whether that session ended, and
14983
+ * the reminder of the current holder's current take, so an earlier episode's reminder never counts
14984
+ * and one cancelled unsent counts as none. `delivered` is whether that reminder reached the holder
14985
+ * or may have: a ring killed after an uncertain send counts, so the one-ring limit hides no stuck
14986
+ * turn.
14987
+ * `quietSince` is when the holder last had something to do: the take, the start of its idle
14988
+ * spell, the end of its last wait, or the close of its last question on the task. Null while the
14989
+ * holder works, waits (`task.wait`), has an open question on the task, or has no readable
14990
+ * snapshot. A worker turn whose holder's session link the operator removed is left out: the holder
14991
+ * no longer works the task. An orchestrator turn is addressed through the column config, so a link
14992
+ * removal does not end its hold.
14993
+ */
14994
+ async function quietTurns(trx) {
14995
+ const turns = await trx.selectFrom("turn").selectAll().where("closed_at", "is", null).where("acked_at", "is not", null).where("role", "!=", "operator").orderBy("id").execute();
14996
+ const unlinked = await unlinkedSessions(trx);
14997
+ const quiet = [];
14998
+ for (const turn of turns) {
14999
+ if (turn.acked_by === null || turn.acked_at === null) continue;
15000
+ const holder = parseActorId(turn.acked_by);
15001
+ if (holder?.actor !== "agent") continue;
15002
+ const sessionId = holder.actorRef.session;
15003
+ if (workerUnlinked(unlinked, turn, sessionId)) continue;
15004
+ const session = await trx.selectFrom("session_snapshot").selectAll().where("id", "=", sessionId).executeTakeFirst();
15005
+ const idle = session === void 0 ? null : idleSince(session);
15006
+ const blocks = await trx.selectFrom("block").select(["state", "unblocked_at"]).where("task_id", "=", turn.task_id).where("author", "=", turn.acked_by).execute();
15007
+ const asking = blocks.some((block) => block.state === "open");
15008
+ const unblocked = blocks.flatMap((block) => block.unblocked_at === null ? [] : [block.unblocked_at]);
15009
+ const row = await trx.selectFrom("notification").selectAll().where("source_key", "=", turnReminderKey(turn.id, sessionId, turn.acked_at)).executeTakeFirst();
15010
+ const cancelled = row === void 0 ? null : await cancelledRingState(trx, row);
15011
+ quiet.push({
15012
+ turn,
15013
+ sessionId,
15014
+ ended: session !== void 0 && session.ended_at !== null,
15015
+ quietSince: idle === null || asking || turn.wait_until !== null ? null : latest([
15016
+ turn.acked_at,
15017
+ idle,
15018
+ ...unblocked,
15019
+ ...turn.wait_ended_at === null ? [] : [turn.wait_ended_at]
15020
+ ]),
15021
+ reminder: cancelled === "unsent" ? void 0 : row,
15022
+ delivered: row !== void 0 && (row.rings >= 1 || cancelled === "maybe_out")
15023
+ });
15024
+ }
15025
+ return quiet;
15026
+ }
15027
+ /** Whether Spur is blind, so a holder's health is unknown. */
15028
+ async function spurBlind(trx) {
15029
+ const spur = await trx.selectFrom("source_state").select("blind_reason").where("source", "=", "spur").executeTakeFirst();
15030
+ return spur !== void 0 && spur.blind_reason !== null;
15031
+ }
15032
+ /**
15033
+ * Registers one reminder per take to the holder of each turn quiet for `stuckTurnAfterMs`;
15034
+ * `takeTurn` drops the unsent reminder of an earlier take. Nothing while Spur is blind, since the holder's health
15035
+ * is then unknown.
15036
+ */
15037
+ async function remindStuckTurns(trx, config, at) {
15038
+ if (await spurBlind(trx)) return;
15039
+ for (const { turn, sessionId, ended, quietSince, reminder } of await quietTurns(trx)) {
15040
+ if (ended || quietSince === null || reminder !== void 0) continue;
15041
+ const threshold = stuckTurnAfterMs(config, await taskProject(trx, turn.task_id), turn);
15042
+ if (at.getTime() < Date.parse(quietSince) + threshold) continue;
15043
+ await registerTurnReminder(trx, turn, sessionId, at);
15044
+ }
15045
+ }
15046
+ /**
15047
+ * Whether a queued ring may go out at `at`. A turn reminder goes out only under the rule
15048
+ * `remindStuckTurns` registers it by: its holder's current take is quiet for `stuckTurnAfterMs`.
15049
+ * Otherwise the sender defers it, so a question opened after it was queued holds it until the
15050
+ * question closes and a fresh quiet period passes, and blind Spur holds it until Spur reports again.
15051
+ * A wait's wake ring is due unless Spur is blind. Every other ring is due.
15052
+ */
15053
+ async function ringDue(trx, notificationId, config, at) {
15054
+ const n = await trx.selectFrom("notification").select(["kind", "source_key"]).where("id", "=", notificationId).executeTakeFirst();
15055
+ if (n?.kind !== "turn_reminder") return true;
15056
+ if (await spurBlind(trx)) return false;
15057
+ if (isTurnWakeKey(n.source_key)) return true;
15058
+ const quiet = (await quietTurns(trx)).find((entry) => entry.reminder?.id === notificationId);
15059
+ if (quiet === void 0 || quiet.ended || quiet.quietSince === null) return false;
15060
+ const project = await taskProject(trx, quiet.turn.task_id);
15061
+ return at.getTime() >= Date.parse(quiet.quietSince) + stuckTurnAfterMs(config, project, quiet.turn);
15062
+ }
14868
15063
  // ../core/src/app/fromYou.ts
14869
15064
  const episodeSchema = z.object({ startedAt: z.number() }).nullable();
14870
15065
  const stallEpisodeSchema = z.object({
@@ -15462,8 +15657,10 @@ async function reconcileItems(trx, config, now, spurComplete, warnSkipped, spurC
15462
15657
  key: "host_load_episode",
15463
15658
  value: toJson(episodeSchema, health.episode)
15464
15659
  }).onConflict((oc) => oc.column("key").doUpdateSet({ value: toJson(episodeSchema, health.episode) })).execute();
15660
+ const resting = await restingHolders(trx, config, now);
15661
+ const restingIdle = (flag) => flag.kind === "worker_idle" && resting.has(`${flag.taskId}:${flag.sessionId}`);
15465
15662
  for (const flag of health.flags) {
15466
- if (endedHolders.has(`${flag.taskId}:${flag.sessionId}`)) continue;
15663
+ if (endedHolders.has(`${flag.taskId}:${flag.sessionId}`) || restingIdle(flag)) continue;
15467
15664
  const task = taskById.get(Number(flag.taskId));
15468
15665
  if (task === void 0) continue;
15469
15666
  const fact = subjects.find((subject) => subject.taskId === flag.taskId && subject.id === flag.sessionId);
@@ -15516,10 +15713,11 @@ async function reconcileItems(trx, config, now, spurComplete, warnSkipped, spurC
15516
15713
  heldKeys.push(...held.map((item) => item.item_key));
15517
15714
  } else candidates.push(...await turnsWithoutSession(trx, config, now, taskById));
15518
15715
  candidates.push(...await reviewRuleItems(trx, config, now, tasks));
15716
+ candidates.push(...await turnWaitItems(trx, config, taskById));
15519
15717
  const ordered = orderItems(candidates);
15520
15718
  const seen = /* @__PURE__ */ new Set([...ordered.map((item) => item.key), ...heldKeys]);
15521
15719
  for (const flag of health.held) {
15522
- if (endedHolders.has(`${flag.taskId}:${flag.sessionId}`)) continue;
15720
+ if (endedHolders.has(`${flag.taskId}:${flag.sessionId}`) || restingIdle(flag)) continue;
15523
15721
  const task = taskById.get(Number(flag.taskId));
15524
15722
  if (task !== void 0 && !stalled.has(`${flag.taskId}:${flag.sessionId}`)) seen.add(healthKey(task.id, flag));
15525
15723
  }
@@ -18255,6 +18453,7 @@ async function taskTurnView(trx, turn) {
18255
18453
  by: turn.acked_by,
18256
18454
  at: turn.acked_at
18257
18455
  },
18456
+ ...turnWaitView(turn),
18258
18457
  handed: turnHanded(turn),
18259
18458
  ...returned === void 0 ? {} : { returned },
18260
18459
  closed: turn.closed_at === null || turn.closed_reason === null ? null : {
@@ -18332,6 +18531,8 @@ const EVENT_SUMMARIES = {
18332
18531
  turn_opened: "Turn opened",
18333
18532
  turn_taken: "Turn taken",
18334
18533
  turn_closed: "Turn closed",
18534
+ turn_wait_started: "Turn wait started",
18535
+ turn_wait_ended: "Turn wait ended",
18335
18536
  block_opened: "Block opened",
18336
18537
  block_escalated: "Block escalated",
18337
18538
  block_unblocked: "Block unblocked",
@@ -18533,6 +18734,8 @@ const SUMMARIES = {
18533
18734
  block_unblocked: (p) => `Block ${p.block} unblocked: ${p.outcome}${optional(", ", p.reason)}`,
18534
18735
  comment_added: (p) => `Comment ${p.comment} for ${p.addressee}${optional(", forwarded from ", p.forwardedFrom)}`,
18535
18736
  comment_edited: (p) => `Comment ${p.comment} edited, revision ${String(p.revision)}${p.clarification ? ", clarification" : ""}`,
18737
+ turn_wait_started: (p) => `Turn ${p.turn} waits until ${p.until}: ${p.reason}`,
18738
+ turn_wait_ended: (p) => `Turn ${p.turn} wait ended: ${p.outcome}`,
18536
18739
  comment_deleted: (p) => `Comment ${p.comment} deleted`,
18537
18740
  comment_acked: (p) => `Comment ${p.comment} acknowledged`,
18538
18741
  doorbell_rung: (p) => `Doorbell rung: ${p.doorbell} for ${p.addressee}, attempt ${String(p.attempt)}`,
@@ -18647,6 +18850,7 @@ async function turnView(trx, turn, task, project) {
18647
18850
  by: turn.acked_by,
18648
18851
  at: turn.acked_at
18649
18852
  },
18853
+ ...turnWaitView(turn),
18650
18854
  ...threads === void 0 ? {} : { threads }
18651
18855
  };
18652
18856
  }
@@ -20143,6 +20347,60 @@ function createTurnMutations(deps) {
20143
20347
  }
20144
20348
  };
20145
20349
  }
20350
+ // ../core/src/app/turn-wait-commands.ts
20351
+ /**
20352
+ * `task.wait`: the holder of a taken, open turn waits on an outside condition. An active wait is
20353
+ * replaced: it ends `closed` and its time counts. Past the turn's count or total time limit the
20354
+ * call is refused; otherwise the wait lasts `for` minutes, cut to the time left of the total, and
20355
+ * the turn's unsent reminders are dropped, so the board stays quiet until the tick wakes it.
20356
+ */
20357
+ function createTurnWaitMutation({ config }) {
20358
+ return {
20359
+ id: "task.wait",
20360
+ resolveTargets: (trx, input) => turnVisitTarget(trx, input.turn),
20361
+ async run(trx, input, ctx) {
20362
+ const { turn, task } = await takenTurn(trx, input.turn, ctx);
20363
+ const at = new Date(ctx.at);
20364
+ const waitedMs = await endTurnWait(trx, {
20365
+ turn,
20366
+ project: task.project,
20367
+ outcome: "closed",
20368
+ at,
20369
+ actor: ctx.actor
20370
+ });
20371
+ if (waitsUsed(config, {
20372
+ wait_count: turn.wait_count,
20373
+ waited_ms: waitedMs
20374
+ })) throw new CommandError("turn_wait_limit", `Turn ${input.turn} has used its waits; submit or return it.`);
20375
+ const left = config.health.turnWait.maxTotalMs - waitedMs;
20376
+ const until = new Date(at.getTime() + Math.min(input.for * 6e4, left)).toISOString();
20377
+ const waits = turn.wait_count + 1;
20378
+ await trx.updateTable("turn").set({
20379
+ wait_reason: input.reason,
20380
+ wait_since: ctx.at,
20381
+ wait_until: until,
20382
+ wait_count: waits
20383
+ }).where("id", "=", turn.id).execute();
20384
+ await trx.updateTable("notification").set({ acked_at: ctx.at }).where("turn_id", "=", turn.id).where("kind", "=", "turn_reminder").where("acked_at", "is", null).where("exhausted_at", "is", null).execute();
20385
+ const payload = {
20386
+ turn: input.turn,
20387
+ reason: input.reason,
20388
+ until,
20389
+ waits
20390
+ };
20391
+ await emit(trx, "turn_wait_started", task.project, task.id, ctx.at, payload, ctx.actor);
20392
+ return {
20393
+ turn: input.turn,
20394
+ wait: {
20395
+ reason: input.reason,
20396
+ since: ctx.at,
20397
+ wakesAt: until
20398
+ },
20399
+ waits
20400
+ };
20401
+ }
20402
+ };
20403
+ }
20146
20404
  // ../core/src/app/registry.ts
20147
20405
  const catalog = await buildCatalogSnapshot(OPERATIONS);
20148
20406
  const MANUAL_SOURCE = { kind: "manual" };
@@ -20353,6 +20611,7 @@ function createOperationRegistry(deps) {
20353
20611
  "item.close": items.close,
20354
20612
  "task.submit": turns.submit,
20355
20613
  "task.return": turns.return,
20614
+ "task.wait": createTurnWaitMutation({ config }),
20356
20615
  "task.move": turns.move,
20357
20616
  "task.order": createOrderMutations(config).order
20358
20617
  };
@@ -21475,6 +21734,7 @@ async function tickBoard(deps) {
21475
21734
  at: new Date(now),
21476
21735
  complete: completeSince
21477
21736
  });
21737
+ await wakeWaitingTurns(trx, config, new Date(now));
21478
21738
  await remindStuckTurns(trx, config, new Date(now));
21479
21739
  await reconcileItems(trx, config, now, completeSince.has("spur"), deps.warnSkipped);
21480
21740
  }, clock);
package/dist/mcp.mjs CHANGED
@@ -1,6 +1,6 @@
1
- import { lt as ERRORS, p as OPERATIONS, v as renderMcpError } from "./chunk-CVVzwHUN.mjs";
2
- import { o as CliError, r as requestOperation } from "./chunk-BbRoZyZW.mjs";
3
- import { a as memoryVerdictCache, c as loadClientConfig, r as compareCatalogs, t as checkCatalog } from "./chunk-7gaKVc6L.mjs";
1
+ import { lt as ERRORS, p as OPERATIONS, v as renderMcpError } from "./chunk-BS5xzBWL.mjs";
2
+ import { o as CliError, r as requestOperation } from "./chunk-DEbPRDF0.mjs";
3
+ import { a as memoryVerdictCache, c as loadClientConfig, r as compareCatalogs, t as checkCatalog } from "./chunk-CTCKroE3.mjs";
4
4
  import { randomUUID } from "node:crypto";
5
5
  import { readFileSync } from "node:fs";
6
6
  import { z } from "zod";