@songsid/agend 2.4.0-beta.27 → 2.4.0-beta.29

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.
Files changed (175) hide show
  1. package/dist/agent-cli-instructions.md +2 -1
  2. package/dist/agent-cli.js +6 -0
  3. package/dist/agent-cli.js.map +1 -1
  4. package/dist/build-provenance.json +1 -1
  5. package/dist/channel/adapters/discord.d.ts +13 -1
  6. package/dist/channel/adapters/discord.js +51 -21
  7. package/dist/channel/adapters/discord.js.map +1 -1
  8. package/dist/channel/mcp-tools.js +1 -1
  9. package/dist/channel/mcp-tools.js.map +1 -1
  10. package/dist/claude-turn-boundaries.d.ts +15 -0
  11. package/dist/claude-turn-boundaries.js +88 -0
  12. package/dist/claude-turn-boundaries.js.map +1 -0
  13. package/dist/contact-auth-service.js +3 -0
  14. package/dist/contact-auth-service.js.map +1 -1
  15. package/dist/contact-auth-store.d.ts +16 -0
  16. package/dist/contact-auth-store.js +61 -1
  17. package/dist/contact-auth-store.js.map +1 -1
  18. package/dist/daemon.d.ts +12 -1
  19. package/dist/daemon.js +130 -19
  20. package/dist/daemon.js.map +1 -1
  21. package/dist/delivery-outbox.d.ts +38 -0
  22. package/dist/delivery-outbox.js +81 -1
  23. package/dist/delivery-outbox.js.map +1 -1
  24. package/dist/fleet-manager.d.ts +17 -1
  25. package/dist/fleet-manager.js +239 -16
  26. package/dist/fleet-manager.js.map +1 -1
  27. package/dist/general-knowledge/skills/concepts/SKILL.md +5 -0
  28. package/dist/general-knowledge/skills/task-board/SKILL.md +14 -0
  29. package/dist/general-knowledge/skills/web-dashboard/SKILL.md +1 -1
  30. package/dist/host-memory.d.ts +21 -1
  31. package/dist/host-memory.js +30 -4
  32. package/dist/host-memory.js.map +1 -1
  33. package/dist/host-monitoring/linux/interpretation.js +1 -1
  34. package/dist/host-monitoring/linux/interpretation.js.map +1 -1
  35. package/dist/host-monitoring/wsl/interpretation.js +1 -1
  36. package/dist/host-monitoring/wsl/interpretation.js.map +1 -1
  37. package/dist/host-monitoring.d.ts +3 -1
  38. package/dist/hub/compose/server.js +1 -1
  39. package/dist/hub/compose/server.js.map +1 -1
  40. package/dist/hub/group-policy/resources.d.ts +1 -1
  41. package/dist/hub/http/compose.js +100 -56
  42. package/dist/hub/http/compose.js.map +1 -1
  43. package/dist/hub/http/core.d.ts +2 -0
  44. package/dist/hub/http/core.js +17 -7
  45. package/dist/hub/http/core.js.map +1 -1
  46. package/dist/hub/policy.js +56 -27
  47. package/dist/hub/policy.js.map +1 -1
  48. package/dist/hub/roles/clock.d.ts +1 -1
  49. package/dist/hub/roles/clock.js +8 -6
  50. package/dist/hub/roles/clock.js.map +1 -1
  51. package/dist/hub/roles/cutover-clock-facts.d.ts +13 -0
  52. package/dist/hub/roles/cutover-clock-facts.js +25 -0
  53. package/dist/hub/roles/cutover-clock-facts.js.map +1 -0
  54. package/dist/hub/roles/read.d.ts +2 -0
  55. package/dist/hub/roles/read.js +15 -6
  56. package/dist/hub/roles/read.js.map +1 -1
  57. package/dist/hub/rooms.d.ts +8 -4
  58. package/dist/hub/rooms.js +18 -5
  59. package/dist/hub/rooms.js.map +1 -1
  60. package/dist/hub/send-timing.d.ts +6 -0
  61. package/dist/hub/send-timing.js +39 -0
  62. package/dist/hub/send-timing.js.map +1 -0
  63. package/dist/hub/settings-directory-decision.js +11 -5
  64. package/dist/hub/settings-directory-decision.js.map +1 -1
  65. package/dist/hub/settings-member-address-decision.js +1 -1
  66. package/dist/hub/settings-member-address-decision.js.map +1 -1
  67. package/dist/hub/store.d.ts +4 -0
  68. package/dist/hub/store.js +19 -4
  69. package/dist/hub/store.js.map +1 -1
  70. package/dist/locale.js +19 -1
  71. package/dist/locale.js.map +1 -1
  72. package/dist/memory-pressure.js +8 -1
  73. package/dist/memory-pressure.js.map +1 -1
  74. package/dist/outbound-schemas.d.ts +3 -0
  75. package/dist/outbound-schemas.js +4 -2
  76. package/dist/outbound-schemas.js.map +1 -1
  77. package/dist/request-context-activation.js +14 -3
  78. package/dist/request-context-activation.js.map +1 -1
  79. package/dist/request-context-call.d.ts +1 -0
  80. package/dist/request-context-call.js.map +1 -1
  81. package/dist/request-context-compatibility.js +10 -2
  82. package/dist/request-context-compatibility.js.map +1 -1
  83. package/dist/request-context-control-api.d.ts +18 -0
  84. package/dist/request-context-control-api.js +4 -2
  85. package/dist/request-context-control-api.js.map +1 -1
  86. package/dist/request-context-drain-projection.d.ts +8 -0
  87. package/dist/request-context-drain-projection.js +40 -0
  88. package/dist/request-context-drain-projection.js.map +1 -0
  89. package/dist/request-context-drain.d.ts +9 -0
  90. package/dist/request-context-drain.js +63 -4
  91. package/dist/request-context-drain.js.map +1 -1
  92. package/dist/request-context-human.d.ts +6 -0
  93. package/dist/request-context-human.js +24 -1
  94. package/dist/request-context-human.js.map +1 -1
  95. package/dist/request-context-migration.d.ts +11 -0
  96. package/dist/request-context-migration.js +16 -3
  97. package/dist/request-context-migration.js.map +1 -1
  98. package/dist/request-context-reply-pending.d.ts +16 -0
  99. package/dist/request-context-reply-pending.js +77 -0
  100. package/dist/request-context-reply-pending.js.map +1 -0
  101. package/dist/request-context-resolution.d.ts +35 -0
  102. package/dist/request-context-resolution.js +86 -0
  103. package/dist/request-context-resolution.js.map +1 -0
  104. package/dist/request-context-retirement.d.ts +2 -0
  105. package/dist/request-context-retirement.js.map +1 -1
  106. package/dist/runtime-build-info.js +1 -1
  107. package/dist/runtime-build-info.js.map +1 -1
  108. package/dist/scheduler/db.js +9 -0
  109. package/dist/scheduler/db.js.map +1 -1
  110. package/dist/scheduler/task-board-text.d.ts +3 -6
  111. package/dist/scheduler/task-board-text.js +15 -10
  112. package/dist/scheduler/task-board-text.js.map +1 -1
  113. package/dist/scheduler/task-board-unread.d.ts +90 -0
  114. package/dist/scheduler/task-board-unread.js +192 -0
  115. package/dist/scheduler/task-board-unread.js.map +1 -0
  116. package/dist/scheduler/task-board.d.ts +324 -6
  117. package/dist/scheduler/task-board.js +786 -47
  118. package/dist/scheduler/task-board.js.map +1 -1
  119. package/dist/settings-effect.js +17 -2
  120. package/dist/settings-effect.js.map +1 -1
  121. package/dist/task-board-tool.js +24 -3
  122. package/dist/task-board-tool.js.map +1 -1
  123. package/dist/task-board-waker.d.ts +53 -2
  124. package/dist/task-board-waker.js +183 -12
  125. package/dist/task-board-waker.js.map +1 -1
  126. package/dist/transcript-monitor.d.ts +6 -1
  127. package/dist/transcript-monitor.js +59 -4
  128. package/dist/transcript-monitor.js.map +1 -1
  129. package/dist/transcript-turns.d.ts +3 -0
  130. package/dist/transcript-turns.js +5 -0
  131. package/dist/transcript-turns.js.map +1 -1
  132. package/dist/ui/fleet-task-activity.js +164 -24
  133. package/dist/ui/fleet-task-card.js +77 -13
  134. package/dist/ui/fleet-task-common.js +14 -0
  135. package/dist/ui/fleet-task-flow.js +353 -0
  136. package/dist/ui/fleet-task-md.js +1 -1
  137. package/dist/ui/fleet-task-run.js +98 -22
  138. package/dist/ui/fleet-task-thread.js +245 -0
  139. package/dist/ui/fleet-task-unread.js +100 -0
  140. package/dist/ui/fleet-task-view.js +6 -5
  141. package/dist/ui/fleet-task-wake.js +140 -0
  142. package/dist/ui/fleet-tasks.js +13 -6
  143. package/dist/ui/host-health.js +3 -3
  144. package/dist/ui/host-monitoring-linux.js +2 -2
  145. package/dist/ui/host-monitoring-wsl.js +2 -2
  146. package/dist/ui/panel-windows-cli.js +2 -2
  147. package/dist/ui/request-context-control.js +51 -13
  148. package/dist/ui/shared/access-overview.css +1 -1
  149. package/dist/ui/shared/app-i18n.js +2 -2
  150. package/dist/ui/shared/app-shell.js +4 -1
  151. package/dist/ui/shared/app-stream.js +3 -1
  152. package/dist/ui/shared/app.css +8 -2
  153. package/dist/ui/shared/app.js +3 -0
  154. package/dist/ui/shared/task-board.css +164 -0
  155. package/dist/ui/shared/ui-icons.js +3 -0
  156. package/dist/ui/task-unread.js +70 -0
  157. package/dist/ui/windows-cli-catalog.js +33 -6
  158. package/dist/update-goback.js +3 -1
  159. package/dist/update-goback.js.map +1 -1
  160. package/dist/web-api.d.ts +45 -1
  161. package/dist/web-api.js +184 -6
  162. package/dist/web-api.js.map +1 -1
  163. package/dist/windows-cli-api.js +4 -2
  164. package/dist/windows-cli-api.js.map +1 -1
  165. package/dist/windows-cli.d.ts +40 -1
  166. package/dist/windows-cli.js +93 -11
  167. package/dist/windows-cli.js.map +1 -1
  168. package/dist/windows-shortcuts.d.ts +3 -22
  169. package/dist/windows-shortcuts.js +5 -45
  170. package/dist/windows-shortcuts.js.map +1 -1
  171. package/dist/workflow-templates/default.md +3 -2
  172. package/dist/wsl-host.d.ts +52 -0
  173. package/dist/wsl-host.js +97 -0
  174. package/dist/wsl-host.js.map +1 -0
  175. package/package.json +1 -1
@@ -1,5 +1,6 @@
1
1
  import { randomUUID } from "node:crypto";
2
2
  import { parseMentions } from "./task-board-mentions.js";
3
+ import { markRead, unreadFor, UnreadCache } from "./task-board-unread.js";
3
4
  import { TASK_FILE_LIMITS, TaskFileError } from "./task-files.js";
4
5
  export const CARD_STATUSES = ["open", "claimed", "blocked", "review", "done", "cancelled"];
5
6
  /** Statuses still on the board (not finished). */
@@ -53,6 +54,8 @@ const BATCH_MAX = 30;
53
54
  export const AGENT_COMMENT_CHAIN = 4; // turns
54
55
  export const AGENT_COMMENT_WINDOW_MS = 30 * 60_000;
55
56
  export const MAX_COMMENT_WAKES = 5;
57
+ /** How many recipients one comment may name with `to` (the comment box's chip names one). */
58
+ export const MAX_RECIPIENTS = 5;
56
59
  /**
57
60
  * Following a card (docs/design/task-board.md, "Following a card"): the instances that handed it out, watch it, or lead
58
61
  * its project hear how it moved on — finished, waiting for confirmation, sent back, blocked, or given to someone else.
@@ -63,6 +66,7 @@ export const MAX_COMMENT_WAKES = 5;
63
66
  export const AGENT_PROGRESS_CHAIN = 6;
64
67
  /** How many instances may watch one card. */
65
68
  export const MAX_WATCHERS = 10;
69
+ export const WAKE_SKIPS = ["board_off", "contact_held", "loop_guard", "unknown", "cap", "wakes_off", "not_waiting", "not_taken", "lost"];
66
70
  /**
67
71
  * A refusal. `code` is its kind (and the HTTP status the dashboard gets); `key` and `args`, when set, name the same
68
72
  * sentence for the dashboard to say in its own language (tasks.err.<key> with {0}, {1}… = args). Refusals only an
@@ -94,6 +98,17 @@ const FIELD_KEY = {
94
98
  "the blocked reason": "blockedReason", "the reason": "reason", "the log line": "log", "the comment": "comment",
95
99
  "an acceptance item": "acceptance", "the description": "projectDescription", "the project's name": "projectName",
96
100
  };
101
+ /** How many different emoji one comment may carry. */
102
+ export const MAX_REACTION_KINDS = 20;
103
+ /** Emoji, joiners, variation selectors, skin tones, keycaps and flags — and nothing else: a reaction is never markup. */
104
+ const EMOJI_RE = /^(?:\p{Extended_Pictographic}|\p{Regional_Indicator}|[\u200D\uFE0E\uFE0F\u20E3]|\p{Emoji_Modifier}|[0-9#*](?=\uFE0F?\u20E3))+$/u;
105
+ function checkEmoji(raw) {
106
+ const mark = typeof raw === "string" ? raw.trim() : "";
107
+ if (!mark || length(mark) > 16 || !EMOJI_RE.test(mark) || !/[\p{Extended_Pictographic}\p{Regional_Indicator}\u20E3]/u.test(mark)) {
108
+ throw new TaskBoardError("invalid", "a reaction is one emoji", "reaction_invalid");
109
+ }
110
+ return mark;
111
+ }
97
112
  function checkText(field, value, max) {
98
113
  const v = value.trim();
99
114
  if (length(v) > max)
@@ -204,6 +219,21 @@ export function wrapUpGap(card) {
204
219
  const noResult = !card.result.trim();
205
220
  return unchecked || noResult ? { unchecked, noResult } : null;
206
221
  }
222
+ /** A comment's `wakes` as stored: only well-formed rows (an older release never wrote the column; a hand-edit cannot break a page). */
223
+ function parseWakes(raw) {
224
+ return parseJsonArray(raw, []).flatMap((w) => {
225
+ if (!w || typeof w !== "object" || typeof w.to !== "string" || !w.to || typeof w.at !== "string")
226
+ return [];
227
+ const why = w.why === "assignee" || w.why === "addressed" || w.why === "mention" ? w.why : "mention";
228
+ const skip = typeof w.skip === "string" && WAKE_SKIPS.includes(w.skip) ? w.skip : undefined;
229
+ return [{ to: w.to, why, at: w.at, ...(typeof w.key === "string" && w.key ? { key: w.key } : {}), ...(skip ? { skip } : {}) }];
230
+ });
231
+ }
232
+ /** "3 definition-of-done items unchecked, no result": what {@link wrapUpGap} found, as an agent is told it. */
233
+ export function gapText(gap, main) {
234
+ const items = gap.unchecked ? `${gap.unchecked} ${main ? "definition-of-done" : "acceptance"} item${gap.unchecked === 1 ? "" : "s"} unchecked` : "";
235
+ return [items, gap.noResult ? "no result" : ""].filter(Boolean).join(", ");
236
+ }
207
237
  function parseJsonArray(raw, fallback) {
208
238
  if (typeof raw !== "string" || raw === "")
209
239
  return fallback;
@@ -293,12 +323,18 @@ export class TaskBoard {
293
323
  routing = { instances: () => [], enabled: () => true };
294
324
  following = { enabled: () => true, leader: () => null };
295
325
  contactGate = () => true;
326
+ /** How far the board's notices got in the fleet's delivery outbox, by key (setNoticeProgress); none: nothing is known of any (a bare board). */
327
+ noticeProgress = () => new Map();
296
328
  pending = [];
297
329
  projectsChanged = false;
298
330
  notes = [];
299
331
  /** The notes of the last write, until a caller of the `task` tool's old actions takes them (takeNotes). */
300
332
  lastNotes = [];
301
333
  codes = new Map();
334
+ /** Each person's unread, until the board moves (unreadFor). */
335
+ unread = new UnreadCache();
336
+ /** Moves each time a comment's wake record is settled outside a write (wakeHanded, wakeDropped): unreadFor's answer reads those. */
337
+ entryWakesGen = 0;
302
338
  /** Where files on cards live (task-files.ts); none: this process cannot take attachments (a bare board in a test, the CLI). */
303
339
  fileStore = null;
304
340
  /** What undoes this write's file moves, when the write fails after them. */
@@ -412,6 +448,58 @@ export class TaskBoard {
412
448
  at TEXT NOT NULL
413
449
  );
414
450
  CREATE INDEX IF NOT EXISTS idx_task_attachments_task ON task_attachments(task_id, at);
451
+ `);
452
+ // Comment threads (docs/design/task-board.md, "Comment threads"): columns added to the comments in place, and a table of
453
+ // reactions. A release without them neither reads nor writes these; they are NULL on every older row.
454
+ const entryCols = new Set(this.db.prepare("PRAGMA table_info(task_entries)").all().map((c) => c.name));
455
+ for (const [name, decl] of [["parent_id", "INTEGER"], ["edited_at", "TEXT"], ["deleted_at", "TEXT"], ["deleted_by", "TEXT"], ["resolved_at", "TEXT"], ["resolved_by", "TEXT"], ["notify", "TEXT"], ["author_key", "TEXT"], ["wakes", "TEXT"]]) {
456
+ if (entryCols.has(name))
457
+ continue;
458
+ try {
459
+ this.db.exec(`ALTER TABLE task_entries ADD COLUMN ${name} ${decl}`);
460
+ }
461
+ catch (err) {
462
+ if (!/duplicate column/i.test(String(err)))
463
+ throw err;
464
+ }
465
+ }
466
+ this.db.exec(`
467
+ CREATE INDEX IF NOT EXISTS idx_task_entries_parent ON task_entries(parent_id);
468
+ CREATE TABLE IF NOT EXISTS task_entry_reactions (
469
+ entry_id INTEGER NOT NULL,
470
+ emoji TEXT NOT NULL,
471
+ by TEXT NOT NULL,
472
+ by_kind TEXT NOT NULL,
473
+ who TEXT NOT NULL,
474
+ at TEXT NOT NULL,
475
+ PRIMARY KEY (entry_id, emoji, who, by_kind)
476
+ );
477
+ CREATE TABLE IF NOT EXISTS task_card_reads (
478
+ person TEXT NOT NULL,
479
+ task_id TEXT NOT NULL,
480
+ seen_entry INTEGER NOT NULL DEFAULT 0,
481
+ seen_event INTEGER NOT NULL DEFAULT 0,
482
+ at TEXT NOT NULL,
483
+ PRIMARY KEY (person, task_id)
484
+ );
485
+ CREATE TABLE IF NOT EXISTS task_handoffs (
486
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
487
+ task_id TEXT NOT NULL,
488
+ instance TEXT NOT NULL,
489
+ why TEXT NOT NULL,
490
+ after_id TEXT,
491
+ at TEXT NOT NULL,
492
+ notice_key TEXT,
493
+ skip TEXT
494
+ );
495
+ CREATE INDEX IF NOT EXISTS idx_task_handoffs_task ON task_handoffs(task_id, id);
496
+ CREATE TABLE IF NOT EXISTS task_reads_floor (
497
+ person TEXT PRIMARY KEY,
498
+ entry_floor INTEGER NOT NULL,
499
+ event_floor INTEGER NOT NULL,
500
+ at TEXT NOT NULL
501
+ );
502
+ CREATE INDEX IF NOT EXISTS idx_task_entries_at ON task_entries(at);
415
503
  `);
416
504
  // #2352: a project's lead instance, added in place (null: its waiting cards' buttons stay in General).
417
505
  const projectCols = new Set(this.db.prepare("PRAGMA table_info(task_projects)").all().map((c) => c.name));
@@ -799,12 +887,22 @@ export class TaskBoard {
799
887
  }
800
888
  const by = this.notBy(scope, "author"), eBy = this.notBy(scope, "e.author");
801
889
  const comments = new Map(this.db.prepare(`SELECT e.task_id AS task_id, n.n AS n, e.author AS author, e.author_kind AS author_kind, e.at AS at FROM task_entries e
802
- JOIN (SELECT task_id, COUNT(*) AS n, MAX(id) AS last FROM task_entries WHERE kind IN ('comment', 'reject', 'approve')${by.sql} GROUP BY task_id) n ON e.id = n.last`).all(...by.args).map((r) => [r.task_id, r]));
890
+ JOIN (SELECT task_id, COUNT(*) AS n, MAX(id) AS last FROM task_entries WHERE kind IN ('comment', 'reject', 'approve') AND deleted_at IS NULL${by.sql} GROUP BY task_id) n ON e.id = n.last`).all(...by.args).map((r) => [r.task_id, r]));
803
891
  const files = new Map(this.db.prepare(`SELECT task_id, COUNT(*) AS n FROM task_attachments WHERE 1 = 1${by.sql} GROUP BY task_id`)
804
892
  .all(...by.args).map((r) => [r.task_id, r.n]));
805
893
  const unseen = new Map(this.db.prepare(`SELECT t.id AS id, COUNT(e.id) AS n FROM tasks t JOIN task_entries e
806
- ON e.task_id = t.id AND e.id > t.seen_entry_id AND e.kind IN ('comment', 'reject') AND e.author IS NOT t.assignee${eBy.sql}
894
+ ON e.task_id = t.id AND e.id > t.seen_entry_id AND e.kind IN ('comment', 'reject') AND e.deleted_at IS NULL AND e.author IS NOT t.assignee${eBy.sql}
807
895
  GROUP BY t.id`).all(...eBy.args).map((r) => [r.id, r.n]));
896
+ // `handedAt`: for the open cards among these, when the board last told their current assignee the card could start — only a hand-over the
897
+ // fleet took (handed to delivery: a key, no skip), and only while its notice reached the instance or nothing says otherwise (delivered,
898
+ // read, or no record in the outbox: the page's `handoffAllows`), not one still queued, failed, unconfirmed or withdrawn. One statement for
899
+ // all, and one read of the outbox for their notices.
900
+ const wanted = new Set(cards.map((c) => c.uuid));
901
+ const taken = this.db.prepare(`SELECT h.task_id AS id, h.at AS at, h.notice_key AS key FROM task_handoffs h JOIN (
902
+ SELECT h.task_id AS task_id, MAX(h.id) AS last FROM task_handoffs h JOIN tasks t ON t.id = h.task_id AND t.assignee = h.instance
903
+ WHERE t.status = 'open' AND h.skip IS NULL AND h.notice_key IS NOT NULL GROUP BY h.task_id) n ON h.id = n.last`).all().filter((r) => wanted.has(r.id));
904
+ const reached = taken.length ? this.noticeProgress([...new Set(taken.map((r) => r.key))]) : new Map();
905
+ const handed = new Map(taken.filter((r) => { const p = reached.get(r.key); return !p || p.state === "delivered"; }).map((r) => [r.id, r.at]));
808
906
  const code = (uuid) => all.get(uuid)?.code ?? uuid.slice(0, 8);
809
907
  /** unmetDeps(), on the light rows: own dependencies not done, then the main task's, each once. */
810
908
  const unmet = (deps, parent, seen = new Set()) => {
@@ -858,6 +956,7 @@ export class TaskBoard {
858
956
  attachmentCount: files.get(card.uuid) ?? 0,
859
957
  newCommentCount: unseen.get(card.uuid) ?? 0,
860
958
  lastComment: c ? { author: c.author, authorKind: c.author_kind, at: c.at } : null,
959
+ ...(card.status === "open" && handed.has(card.uuid) ? { handedAt: handed.get(card.uuid) } : {}),
861
960
  };
862
961
  });
863
962
  }
@@ -871,6 +970,7 @@ export class TaskBoard {
871
970
  comments: this.entries(card.uuid, ["comment", "reject", "approve"], 200),
872
971
  logs: this.entries(card.uuid, ["log"], 200),
873
972
  history: this.events(card.uuid, 200).filter((e) => e.type !== "reordered"),
973
+ subEvents: card.kind === "main" ? this.subEvents(card.uuid) : [],
874
974
  attachments: this.attachments(card.uuid, scope),
875
975
  watchers: this.watchersOf(card.uuid),
876
976
  inheritedWatchers: card.parent ? this.watchersOf(card.parent) : [],
@@ -892,11 +992,34 @@ export class TaskBoard {
892
992
  entries(uuid, kinds, limit = 20) {
893
993
  const rows = this.db.prepare(`SELECT * FROM task_entries WHERE task_id = ? AND kind IN (${kinds.map(() => "?").join(", ")}) ORDER BY id DESC LIMIT ?`)
894
994
  .all(uuid, ...kinds, limit);
895
- return rows.map((r) => this.toEntry(r)).reverse();
995
+ return this.withReactions(rows.map((r) => this.toEntry(r)).reverse());
996
+ }
997
+ /** The entries with the reactions on each (oldest first), in one read. */
998
+ withReactions(entries) {
999
+ const comments = entries.filter((e) => e.kind === "comment" && !e.deleted);
1000
+ if (!comments.length)
1001
+ return entries;
1002
+ const marks = comments.map(() => "?").join(",");
1003
+ const rows = this.db.prepare(`SELECT entry_id, emoji, by, by_kind FROM task_entry_reactions WHERE entry_id IN (${marks}) ORDER BY at, rowid`)
1004
+ .all(...comments.map((e) => e.id));
1005
+ if (!rows.length)
1006
+ return entries;
1007
+ const byEntry = new Map();
1008
+ for (const r of rows) {
1009
+ const list = byEntry.get(r.entry_id) ?? [];
1010
+ let one = list.find((x) => x.emoji === r.emoji);
1011
+ if (!one) {
1012
+ one = { emoji: r.emoji, by: [] };
1013
+ list.push(one);
1014
+ }
1015
+ one.by.push({ name: r.by, kind: r.by_kind });
1016
+ byEntry.set(r.entry_id, list);
1017
+ }
1018
+ return entries.map((e) => (byEntry.has(e.id) ? { ...e, reactions: byEntry.get(e.id) } : e));
896
1019
  }
897
1020
  /** Comments and rejections by others that the assignee has not acted on yet. */
898
1021
  newComments(card) {
899
- const rows = this.db.prepare("SELECT * FROM task_entries WHERE task_id = ? AND id > ? AND kind IN ('comment', 'reject') AND author IS NOT ? ORDER BY id")
1022
+ const rows = this.db.prepare("SELECT * FROM task_entries WHERE task_id = ? AND id > ? AND kind IN ('comment', 'reject') AND author IS NOT ? AND deleted_at IS NULL ORDER BY id")
900
1023
  .all(card.uuid, card.seenEntryId, card.assignee);
901
1024
  return rows.map((r) => this.toEntry(r));
902
1025
  }
@@ -913,14 +1036,19 @@ export class TaskBoard {
913
1036
  })).reverse();
914
1037
  }
915
1038
  toEntry(r) {
1039
+ const deleted = typeof r.deleted_at === "string" ? { at: r.deleted_at, by: r.deleted_by ?? "" } : null;
916
1040
  return {
917
1041
  id: Number(r.id),
918
1042
  cardId: this.codeOf(r.task_id),
919
1043
  kind: r.kind,
920
1044
  author: r.author,
921
1045
  authorKind: r.author_kind,
922
- text: r.text,
1046
+ text: deleted ? "" : r.text,
923
1047
  at: r.at,
1048
+ ...(r.parent_id !== null && r.parent_id !== undefined ? { parentId: Number(r.parent_id) } : {}),
1049
+ ...(typeof r.edited_at === "string" && !deleted ? { editedAt: r.edited_at } : {}),
1050
+ ...(deleted ? { deleted } : {}),
1051
+ ...(typeof r.resolved_at === "string" ? { resolved: { at: r.resolved_at, by: r.resolved_by ?? "" } } : {}),
924
1052
  };
925
1053
  }
926
1054
  /**
@@ -1135,6 +1263,29 @@ export class TaskBoard {
1135
1263
  return { card, since: at ?? card.submittedAt ?? card.createdAt };
1136
1264
  }).sort((a, b) => a.since.localeCompare(b.since));
1137
1265
  }
1266
+ /**
1267
+ * What is new for `person` — a name, or a name and the person's key (the marks are kept under the key: two accounts of one name do not share
1268
+ * them) (docs/design/task-board.md, "Unread"; task-board-unread.ts): the cards someone answered, named them on or
1269
+ * handed them to confirm or answer since they last opened the card. Worked out, never stored, but for the person's floor (the
1270
+ * first time they are asked: only what comes after counts). Not a board write: no revision, no event.
1271
+ */
1272
+ unreadFor(person, gone) {
1273
+ const who = typeof person === "string" ? { name: person } : person;
1274
+ const waiting = this.waitingForPerson(gone).map(({ card }) => ({ uuid: card.uuid, code: card.code, status: card.status }));
1275
+ // What the answer is worked out from, read cheaply (UnreadCache): an unchanged board answers from what was kept.
1276
+ const newest = this.db.prepare("SELECT (SELECT COALESCE(MAX(id), 0) FROM task_entries) AS entry, (SELECT COALESCE(MAX(id), 0) FROM task_events) AS event").get();
1277
+ const state = [this.revision(), newest.entry, newest.event, this.entryWakesGen, waiting.map((w) => `${w.uuid}:${w.status}`).join(",")].join("|");
1278
+ const now = this.nowIso();
1279
+ return this.unread.get(who, state, now, () => unreadFor(this.db, who, waiting, now));
1280
+ }
1281
+ /** `person` opened the card: all of it so far is read (a mark moves only forward). */
1282
+ markRead(person, ref) {
1283
+ const card = this.getCard(ref);
1284
+ const who = typeof person === "string" ? { name: person } : person;
1285
+ markRead(this.db, who, card.uuid, this.nowIso());
1286
+ this.unread.forget(who);
1287
+ return card;
1288
+ }
1138
1289
  /** Cards by their numbers, in one read (the ones that exist; #2341 review: the cards a summary line named). */
1139
1290
  cardsByCode(codes) {
1140
1291
  const out = [];
@@ -1170,7 +1321,7 @@ export class TaskBoard {
1170
1321
  // Unseen entries of the live cards: comments and rejections by anyone but the card's assignee, after what it saw.
1171
1322
  const fresh = new Map();
1172
1323
  for (const r of this.db.prepare(`SELECT e.* FROM task_entries e JOIN tasks t ON e.task_id = t.id
1173
- WHERE t.status IN ('open', 'claimed', 'blocked', 'review') AND e.id > t.seen_entry_id AND e.kind IN ('comment', 'reject') AND e.author IS NOT t.assignee ORDER BY e.id`).all()) {
1324
+ WHERE t.status IN ('open', 'claimed', 'blocked', 'review') AND e.id > t.seen_entry_id AND e.kind IN ('comment', 'reject') AND e.deleted_at IS NULL AND e.author IS NOT t.assignee ORDER BY e.id`).all()) {
1174
1325
  const list = fresh.get(r.task_id) ?? [];
1175
1326
  list.push({ id: Number(r.id), cardId: all.get(r.task_id)?.code ?? r.task_id.slice(0, 8), kind: r.kind, author: r.author,
1176
1327
  authorKind: r.author_kind, text: r.text, at: r.at });
@@ -1436,8 +1587,11 @@ export class TaskBoard {
1436
1587
  touched = true;
1437
1588
  }
1438
1589
  }
1590
+ if ((patch.replyTo !== undefined || patch.to !== undefined) && patch.comment === undefined && !patch.attach?.length) {
1591
+ throw new TaskBoardError("invalid", "replyTo and to go with a comment", "reply_needs_comment");
1592
+ }
1439
1593
  if (patch.comment !== undefined || patch.attach?.length) {
1440
- if (this.writeComment(card, actor, patch.comment ?? "", patch.attach))
1594
+ if (this.writeComment(card, actor, patch.comment ?? "", patch.attach, false, { replyTo: patch.replyTo, to: patch.to }))
1441
1595
  touched = true;
1442
1596
  }
1443
1597
  if (!touched)
@@ -1531,6 +1685,208 @@ export class TaskBoard {
1531
1685
  return card;
1532
1686
  });
1533
1687
  }
1688
+ // ── Comment threads (docs/design/task-board.md, "Comment threads") ──
1689
+ /** One comment of a card, as stored; refused when the card has none by that number. */
1690
+ commentRow(card, id) {
1691
+ const row = this.db.prepare("SELECT * FROM task_entries WHERE id = ? AND task_id = ? AND kind = 'comment'").get(id, card.uuid);
1692
+ if (!row)
1693
+ throw new TaskBoardError("not_found", `${card.code} has no comment c${id}`, "comment_not_found", [card.code, `c${id}`]);
1694
+ return row;
1695
+ }
1696
+ /** The comment as a read gives it, with its reactions. */
1697
+ commentOf(card, id) {
1698
+ return this.withReactions([this.toEntry(this.commentRow(card, id))])[0];
1699
+ }
1700
+ /**
1701
+ * Who wrote a comment: the same kind (a person, an instance or a script) and, for a comment that kept its writer's key, the same key —
1702
+ * whatever name each uses now (a person who renamed themselves is still the author; two people with one name are not each other, and a
1703
+ * session with no key is not a keyed comment's author). Only a comment with no key (one written before keys were kept, an instance's, a
1704
+ * script's) falls back to the name, and then to its original author's kind and name alone: it cannot tell two same-named sessions apart.
1705
+ */
1706
+ wroteComment(row, actor) {
1707
+ if (row.author_kind !== actor.kind)
1708
+ return false;
1709
+ if (typeof row.author_key === "string" && row.author_key)
1710
+ return !!actor.key && row.author_key === actor.key;
1711
+ return row.author === actor.name;
1712
+ }
1713
+ /** Who a reaction is by, as stored: a person's key when the session has one, else the name — the name alone never stands in for a key. */
1714
+ reactor(actor) {
1715
+ return actor.kind === "person" && actor.key ? `key:${actor.key}` : `name:${actor.name}`;
1716
+ }
1717
+ /** The reactions `actor` made on a card's comments, as `<comment number>|<emoji>` (the dashboard marks those chips the viewer's). */
1718
+ reactedBy(ref, actor) {
1719
+ const card = this.getCard(ref);
1720
+ const rows = this.db.prepare(`SELECT r.entry_id AS id, r.emoji AS emoji FROM task_entry_reactions r JOIN task_entries e ON e.id = r.entry_id WHERE e.task_id = ? AND r.who = ? AND r.by_kind = ?`)
1721
+ .all(card.uuid, this.reactor(actor), actor.kind);
1722
+ return new Set(rows.map((r) => `${r.id}|${r.emoji}`));
1723
+ }
1724
+ /** The numbers of the comments on a card that `actor` wrote (the dashboard marks them `mine`: those are theirs to edit). */
1725
+ commentsWrittenBy(ref, actor) {
1726
+ const card = this.getCard(ref);
1727
+ const rows = this.db.prepare("SELECT * FROM task_entries WHERE task_id = ? AND kind = 'comment' AND deleted_at IS NULL").all(card.uuid);
1728
+ return new Set(rows.filter((r) => this.wroteComment(r, actor)).map((r) => Number(r.id)));
1729
+ }
1730
+ /**
1731
+ * The history's "commented" event keeps the comment's words (`data.text`); when the comment changes or goes, so does that
1732
+ * copy. An event written since the thread work names its entry. An older one (it names none) is the comment's own when it was
1733
+ * written at the same time by the same author with the same words: of those, the one closest in time to the comment — exactly
1734
+ * one, so deleting one "ok" never blanks the card's other "ok" lines.
1735
+ */
1736
+ rewriteCommentEvents(card, row, to) {
1737
+ const events = this.db.prepare("SELECT id, at, actor, actor_kind, data FROM task_events WHERE task_id = ? AND type = 'commented'").all(card.uuid);
1738
+ const update = this.db.prepare("UPDATE task_events SET data = ? WHERE id = ?");
1739
+ const wrote = Date.parse(String(row.at));
1740
+ let legacy = null;
1741
+ for (const e of events) {
1742
+ let data;
1743
+ try {
1744
+ data = JSON.parse(e.data);
1745
+ }
1746
+ catch {
1747
+ continue;
1748
+ }
1749
+ if (data.entry !== undefined) {
1750
+ if (data.entry === Number(row.id))
1751
+ update.run(JSON.stringify({ ...data, text: to }), e.id);
1752
+ continue;
1753
+ }
1754
+ if (e.actor !== row.author || e.actor_kind !== row.author_kind || data.text !== row.text)
1755
+ continue;
1756
+ const gap = Math.abs((Date.parse(e.at) || 0) - (Number.isFinite(wrote) ? wrote : 0));
1757
+ if (!legacy || gap < legacy.gap || (gap === legacy.gap && e.id < legacy.id))
1758
+ legacy = { id: e.id, data, gap };
1759
+ }
1760
+ if (legacy)
1761
+ update.run(JSON.stringify({ ...legacy.data, text: to }), legacy.id);
1762
+ }
1763
+ /**
1764
+ * The author changes a comment's words (a person or an instance alike; never someone else's). Nothing is woken for it —
1765
+ * except the instances the new words `@`-name that the old ones did not, and only those (docs/design/task-board.md, "Comment
1766
+ * threads"). Marked edited; the card's version does not move (a comment never held a version).
1767
+ */
1768
+ editComment(actor, ref, id, raw) {
1769
+ return this.tx(() => {
1770
+ const card = this.getCard(ref);
1771
+ const row = this.commentRow(card, id);
1772
+ if (typeof row.deleted_at === "string")
1773
+ throw new TaskBoardError("invalid", `comment c${id} on ${card.code} was deleted`, "comment_deleted", [`c${id}`]);
1774
+ if (!this.wroteComment(row, actor))
1775
+ throw new TaskBoardError("forbidden", `only its author can edit comment c${id} on ${card.code}`, "comment_not_yours", [`c${id}`]);
1776
+ const text = checkText("the comment", raw, CARD_LIMITS.comment);
1777
+ if (!text)
1778
+ throw new TaskBoardError("invalid", "the comment cannot be empty", "comment_empty");
1779
+ if (text === row.text)
1780
+ return { card, notes: ["no change"], said: [], entry: this.commentOf(card, id) };
1781
+ const names = [...this.routing.instances()];
1782
+ const before = new Set(parseMentions(row.text, names).names);
1783
+ const added = parseMentions(text, names).names.filter((n) => !before.has(n));
1784
+ // What the comment named stays counted: the stored `@` names (those of its words as written, for a row from before they were
1785
+ // stored) and, added, the names the new words bring — so taking an `@` out does not take its turn out of the loop guard.
1786
+ const kept = this.storedNotify(row, names);
1787
+ const notify = { ...kept, at: [...new Set([...kept.at, ...added])] };
1788
+ this.db.prepare("UPDATE task_entries SET text = ?, edited_at = ?, notify = ? WHERE id = ?").run(text, this.nowIso(), JSON.stringify(notify), id);
1789
+ this.rewriteCommentEvents(card, row, text);
1790
+ const audience = added.length ? this.routeComment(actor, card, text, false, { only: added }) : undefined;
1791
+ this.signal(actor, card, "comment_edited", { entry: id, text }, audience);
1792
+ if (audience)
1793
+ this.recordWakes(actor, card, id, audience, null, true);
1794
+ return { card, ...this.spoken(), entry: this.commentOf(card, id) };
1795
+ });
1796
+ }
1797
+ /**
1798
+ * Deletes a comment: its author, or a person (an administrator's dashboard session). The words, the reactions and the files
1799
+ * that came with it go; the entry stays as a placeholder, so the replies under it still hang from something. Wakes nobody.
1800
+ */
1801
+ deleteComment(actor, ref, id) {
1802
+ const removed = [];
1803
+ const result = this.tx(() => {
1804
+ const card = this.getCard(ref);
1805
+ const row = this.commentRow(card, id);
1806
+ if (typeof row.deleted_at === "string")
1807
+ return { card, notes: ["no change"], said: [], entry: this.commentOf(card, id) };
1808
+ if (!this.wroteComment(row, actor) && !isPerson(actor))
1809
+ throw new TaskBoardError("forbidden", `only its author or a person can delete comment c${id} on ${card.code}`, "comment_delete_forbidden", [`c${id}`]);
1810
+ this.rewriteCommentEvents(card, row, "");
1811
+ this.db.prepare("UPDATE task_entries SET text = '', deleted_at = ?, deleted_by = ? WHERE id = ?").run(this.nowIso(), actor.name, id);
1812
+ this.db.prepare("DELETE FROM task_entry_reactions WHERE entry_id = ?").run(id);
1813
+ for (const f of this.db.prepare("SELECT id FROM task_attachments WHERE entry_id = ?").all(id))
1814
+ removed.push({ uuid: card.uuid, file: f.id });
1815
+ this.db.prepare("DELETE FROM task_attachments WHERE entry_id = ?").run(id);
1816
+ this.signal(actor, card, "comment_deleted", { entry: id });
1817
+ return { card, ...this.spoken(), entry: this.commentOf(card, id) };
1818
+ });
1819
+ // The rows are gone for good; the files follow (one that cannot be removed now is swept as an orphan later).
1820
+ const store = this.fileStore;
1821
+ if (store)
1822
+ for (const f of removed) {
1823
+ try {
1824
+ store.removeFile(f.uuid, f.file);
1825
+ }
1826
+ catch { /* swept later */ }
1827
+ }
1828
+ return result;
1829
+ }
1830
+ /** Puts an emoji on a comment, or takes the actor's back (`on: false`). Anyone who may read the card may react; nobody is woken. */
1831
+ react(actor, ref, id, emoji, on) {
1832
+ return this.tx(() => {
1833
+ const card = this.getCard(ref);
1834
+ const row = this.commentRow(card, id);
1835
+ if (typeof row.deleted_at === "string")
1836
+ throw new TaskBoardError("invalid", `comment c${id} on ${card.code} was deleted`, "comment_deleted", [`c${id}`]);
1837
+ const mark = checkEmoji(emoji);
1838
+ let changed = false;
1839
+ if (on) {
1840
+ const kinds = this.db.prepare("SELECT COUNT(DISTINCT emoji) AS n, MAX(emoji = ?) AS has FROM task_entry_reactions WHERE entry_id = ?").get(mark, id);
1841
+ if (!kinds.has && kinds.n >= MAX_REACTION_KINDS)
1842
+ throw new TaskBoardError("too_long", `comment c${id} already has ${MAX_REACTION_KINDS} different reactions`, "reaction_limit", [`c${id}`, MAX_REACTION_KINDS]);
1843
+ changed = this.db.prepare("INSERT OR IGNORE INTO task_entry_reactions (entry_id, emoji, by, by_kind, who, at) VALUES (?, ?, ?, ?, ?, ?)").run(id, mark, actor.name, actor.kind, this.reactor(actor), this.nowIso()).changes > 0;
1844
+ }
1845
+ else {
1846
+ changed = this.db.prepare("DELETE FROM task_entry_reactions WHERE entry_id = ? AND emoji = ? AND who = ? AND by_kind = ?").run(id, mark, this.reactor(actor), actor.kind).changes > 0;
1847
+ }
1848
+ if (changed)
1849
+ this.signal(actor, card, "comment_reacted", { entry: id, emoji: mark, on });
1850
+ return { card, notes: changed ? [] : ["no change"], said: [], entry: this.commentOf(card, id) };
1851
+ });
1852
+ }
1853
+ /** Folds a thread away (`resolved`) or opens it again. Only a thread's first comment is resolved; anyone who may comment may. Wakes nobody. */
1854
+ resolveThread(actor, ref, id, resolved) {
1855
+ return this.tx(() => {
1856
+ const card = this.getCard(ref);
1857
+ const row = this.commentRow(card, id);
1858
+ if (typeof row.deleted_at === "string")
1859
+ throw new TaskBoardError("invalid", `comment c${id} on ${card.code} was deleted`, "comment_deleted", [`c${id}`]);
1860
+ if (row.parent_id !== null && row.parent_id !== undefined)
1861
+ throw new TaskBoardError("invalid", `c${id} is a reply: resolve the thread by its first comment`, "resolve_root_only", [`c${id}`]);
1862
+ if ((typeof row.resolved_at === "string") === resolved)
1863
+ return { card, notes: ["no change"], said: [], entry: this.commentOf(card, id) };
1864
+ if (resolved)
1865
+ this.db.prepare("UPDATE task_entries SET resolved_at = ?, resolved_by = ? WHERE id = ?").run(this.nowIso(), actor.name, id);
1866
+ else
1867
+ this.db.prepare("UPDATE task_entries SET resolved_at = NULL, resolved_by = NULL WHERE id = ?").run(id);
1868
+ this.signal(actor, card, "comment_resolved", { entry: id, resolved });
1869
+ return { card, notes: [], said: [], entry: this.commentOf(card, id) };
1870
+ });
1871
+ }
1872
+ /** A comment's stored recipients, `at` read from its words when the row has none stored (written before they were). */
1873
+ storedNotify(row, names) {
1874
+ const strs = (v) => (Array.isArray(v) ? v.filter((x) => typeof x === "string") : []);
1875
+ let n = {};
1876
+ if (typeof row.notify === "string") {
1877
+ try {
1878
+ n = JSON.parse(row.notify);
1879
+ }
1880
+ catch {
1881
+ n = {};
1882
+ }
1883
+ }
1884
+ return { to: strs(n.to), assignee: n.assignee !== false, at: Array.isArray(n.at) ? strs(n.at) : parseMentions(String(row.text ?? ""), names).names };
1885
+ }
1886
+ /** A change to a comment the page and the revision hear of, with no history line of its own (SignalType). */
1887
+ signal(actor, card, type, data, audience) {
1888
+ this.pending.push({ code: card.code, uuid: card.uuid, actor, type, data, ...(audience ? { audience } : {}) });
1889
+ }
1534
1890
  // ── Writing: the fleet's `task` tool (and the old /ui/tasks routes) ──
1535
1891
  /**
1536
1892
  * A task as the `task` tool has always opened it: a main task under no project, assigned only when asked, with no
@@ -2015,6 +2371,14 @@ export class TaskBoard {
2015
2371
  setContactGate(gate) {
2016
2372
  this.contactGate = gate;
2017
2373
  }
2374
+ /**
2375
+ * How far the board's notices got in the fleet's delivery outbox, by their keys (the outbox's `noticeProgress`): what `handedAt` reads so
2376
+ * that a hand-over whose notice is still queued, failed, unconfirmed or withdrawn is not taken as the card having reached its assignee.
2377
+ * Read at every board read, once for all its cards.
2378
+ */
2379
+ setNoticeProgress(read) {
2380
+ this.noticeProgress = read;
2381
+ }
2018
2382
  /** Whether `actor`'s words may reach `target` (a person's always may: the gate is for an agent's conversation). */
2019
2383
  mayReach(actor, target) {
2020
2384
  if (actor.kind === "person" || actor.kind === "system")
@@ -2116,6 +2480,13 @@ export class TaskBoard {
2116
2480
  this.event(actor, main, "moved", { from, to: next, auto: true });
2117
2481
  if (next === "review")
2118
2482
  this.say("review_waiting", [main.code, main.title], `${main.code} "${main.title}": every sub task is done; it is waiting for ${confirmerOf(main)}'s confirmation`);
2483
+ else if (next === "done") {
2484
+ // Nobody confirms it: it is done by itself, whatever its definition of done and result say — whoever owns it wraps it up.
2485
+ const gap = wrapUpGap(main);
2486
+ const owner = main.assignee && main.assignee !== actor.name ? main.assignee : null;
2487
+ this.say("main_done", [main.code, main.title], `${main.code} "${main.title}": every sub task is done, so it is done by itself`
2488
+ + (gap ? `, though ${gapText(gap, true)} — ${owner ? `${owner}, its owner, is told to fill that in` : "fill that in with update (check the items that are met, result: a short summary), and tell the person on the card"}` : ""));
2489
+ }
2119
2490
  else if (from === "done" || from === "review")
2120
2491
  this.say("back_to", [main.code, next], `${main.code} has unfinished sub tasks again; it is back to ${next}`);
2121
2492
  if (next === "done")
@@ -2330,7 +2701,7 @@ export class TaskBoard {
2330
2701
  */
2331
2702
  settleWakes(events) {
2332
2703
  const out = new Map();
2333
- const add = (card, instance, reason, by, text, news) => {
2704
+ const add = (card, instance, reason, by, text, news, reply, entry) => {
2334
2705
  // Never its own write — but a person's `@name` is not the instance of that name's own write.
2335
2706
  if (!instance || (instance === by.name && !(reason === "mention" && isPerson(by))))
2336
2707
  return;
@@ -2341,8 +2712,18 @@ export class TaskBoard {
2341
2712
  // A later progress replaces the earlier one whole: its words are its own, never the earlier change's.
2342
2713
  if (news && !text)
2343
2714
  delete w.texts[reason];
2344
- if (text)
2715
+ if (text) {
2345
2716
  w.texts[reason] = text;
2717
+ // The words answer a comment: the notice says which. A later comment that answers none drops the earlier one's.
2718
+ if (reply)
2719
+ (w.replies ??= {})[reason] = reply;
2720
+ else if (w.replies)
2721
+ delete w.replies[reason];
2722
+ if (entry !== undefined)
2723
+ (w.entries ??= {})[reason] = entry;
2724
+ else if (w.entries)
2725
+ delete w.entries[reason];
2726
+ }
2346
2727
  if (news)
2347
2728
  w.news = news;
2348
2729
  w.by[reason] = by.name;
@@ -2354,15 +2735,18 @@ export class TaskBoard {
2354
2735
  w.principals.push(by.name);
2355
2736
  out.set(key, w);
2356
2737
  };
2738
+ // `ready`: which card's finishing readied which (by instance and card), kept with the handoff.
2739
+ const readied = new Map();
2357
2740
  // The answer to a blocked question is the comment that came with it (#2801: a comment alone wakes nobody).
2358
2741
  const comments = new Map();
2742
+ const entryOf = (e) => (typeof e.data.entry === "number" ? e.data.entry : undefined);
2359
2743
  for (const e of events)
2360
2744
  if (e.type === "commented")
2361
- comments.set(e.uuid, String(e.data.text ?? ""));
2745
+ comments.set(e.uuid, { text: String(e.data.text ?? ""), entry: entryOf(e) });
2362
2746
  for (const e of events) {
2363
2747
  const card = e.type === "commented" && e.data.kept === true ? this.byUuid(e.uuid) : undefined;
2364
2748
  if (card)
2365
- add(card, card.assignee, "answer_kept", e.actor, String(e.data.text ?? ""));
2749
+ add(card, card.assignee, "answer_kept", e.actor, String(e.data.text ?? ""), undefined, undefined, entryOf(e));
2366
2750
  }
2367
2751
  for (const e of events) {
2368
2752
  const card = this.byUuid(e.uuid);
@@ -2381,7 +2765,8 @@ export class TaskBoard {
2381
2765
  }
2382
2766
  else if (e.type === "moved") {
2383
2767
  if (d.to === "done")
2384
- this.wakeReady(card, e.actor, add);
2768
+ this.wakeReady(card, e.actor, (c, instance, reason, by) => { if (instance)
2769
+ readied.set(`${instance}\u0000${c.uuid}`, card.uuid); add(c, instance, reason, by); });
2385
2770
  if (d.to === "cancelled") {
2386
2771
  // Taken down with its main task: why the main task was cancelled.
2387
2772
  const main = d.cascade ? events.find((x) => x.code === d.cascade && x.type === "moved" && x.data.to === "cancelled") : undefined;
@@ -2399,15 +2784,18 @@ export class TaskBoard {
2399
2784
  if (d.to === "review" && card.assignee && confirmingInstance(card) === card.assignee)
2400
2785
  add(card, card.assignee, "confirm_own", e.actor);
2401
2786
  if (d.auto) {
2402
- // #2801: one change, one instance — the dispatcher's confirmation already says what it lacks.
2403
- if (d.to === "review" && card.kind === "main" && wrapUpGap(card) && !toConfirm)
2787
+ // #2801: one change, one instance — the dispatcher's confirmation already says what it lacks. A main task that needs
2788
+ // nobody's confirmation goes straight to done when its last sub task does: its owner is the only one left to tick the
2789
+ // definition of done and sum it up (the followers hear the sub task's move, not that the whole is finished). The board's own
2790
+ // catch-up (a main task read behind its sub tasks) wakes nobody for that.
2791
+ if ((d.to === "review" ? !toConfirm : d.to === "done" && e.actor.kind !== "system") && card.kind === "main" && wrapUpGap(card))
2404
2792
  add(card, card.assignee, "wrap_up", e.actor);
2405
2793
  continue;
2406
2794
  }
2407
2795
  if (d.from === "open" && d.to === "claimed")
2408
2796
  add(card, card.assignee, "start", e.actor);
2409
2797
  else if (d.from === "blocked" && d.to === "claimed")
2410
- add(card, card.assignee, "answered", e.actor, comments.get(card.uuid));
2798
+ add(card, card.assignee, "answered", e.actor, comments.get(card.uuid)?.text, undefined, undefined, comments.get(card.uuid)?.entry);
2411
2799
  else if (d.from === "review" && (d.to === "claimed" || d.to === "open"))
2412
2800
  add(card, card.assignee, "sent_back", e.actor, d.reason);
2413
2801
  if (d.to === "blocked" && !isPerson(e.actor))
@@ -2416,28 +2804,143 @@ export class TaskBoard {
2416
2804
  }
2417
2805
  // Comments and mentions: the assignee hears a comment someone else wrote, an instance it names hears it. An answer
2418
2806
  // to a blocked question already says its words (answered, answer_kept), and a mention says it all to the assignee.
2807
+ // An edit counts as the comment it changed, for the instances its new words name (and only those: `audience.assignee` is false).
2419
2808
  for (const e of events) {
2420
- if (e.type !== "commented" || !e.audience)
2809
+ if ((e.type !== "commented" && e.type !== "comment_edited") || !e.audience)
2421
2810
  continue;
2422
2811
  const card = this.byUuid(e.uuid);
2423
2812
  if (!card)
2424
2813
  continue;
2425
2814
  const text = String(e.data.text ?? "");
2815
+ const entry = entryOf(e);
2426
2816
  for (const name of e.audience.mentions)
2427
- add(card, name, "mention", e.actor, text);
2817
+ add(card, name, "mention", e.actor, text, undefined, e.audience.reply, entry);
2428
2818
  const held = card.assignee ? out.get(`${card.assignee}\u0000${card.uuid}`) : undefined;
2429
2819
  if (e.audience.assignee && card.assignee && !e.audience.mentions.includes(card.assignee) && !held?.reasons.some((r) => r === "answered" || r === "answer_kept")) {
2430
- add(card, card.assignee, "comment", e.actor, text);
2820
+ add(card, card.assignee, "comment", e.actor, text, undefined, e.audience.reply, entry);
2431
2821
  }
2432
2822
  }
2433
2823
  this.settleProgress(events, add);
2434
2824
  const wakes = [...out.values()].map((w) => this.wakeHolds(w)).filter((w) => w !== null);
2825
+ this.settleEntryAudience(events, wakes);
2826
+ this.recordHandoffs(wakes, readied);
2435
2827
  // Said to the writer, so an agent knows the followers are told and need no message of its own.
2436
2828
  const told = wakes.filter((w) => w.reasons.includes("progress") && w.news).map((w) => `${w.instance} (${w.news.as})`);
2437
2829
  if (told.length)
2438
2830
  this.say("progress_wakes", [told.join(", ")], `how this changed the card is told to ${told.join(", ")} as a [Task board] notice: no need to message them about it`);
2439
2831
  return wakes;
2440
2832
  }
2833
+ /**
2834
+ * Keeps that a card was handed to an instance (docs/design/task-board.md, "Handoffs"): each wake of this write that tells an instance its
2835
+ * card can be started — everything it waited for is done (`ready`), or it was given to it while it could start (`assigned`) — is one
2836
+ * row of `task_handoffs`, with the card whose finishing readied it. The fleet's waker settles it when the notice goes out (`handoffHanded`
2837
+ * / `handoffDropped`) and the delivery outbox says how far it got, so the card's page can show "S-1 done → handed to dev → dev read it".
2838
+ * Not an event, not a revision of its own: the write that caused it carries it. An assignee that is no instance of the fleet is never
2839
+ * told, so nothing is kept for it. Never read by a release without the table.
2840
+ */
2841
+ recordHandoffs(wakes, readied) {
2842
+ const fleet = new Set(this.routing.instances());
2843
+ const at = this.nowIso();
2844
+ for (const w of wakes) {
2845
+ const why = w.reasons.includes("assigned") ? "assigned" : w.reasons.includes("ready") ? "ready" : null;
2846
+ if (!why || !fleet.has(w.instance))
2847
+ continue;
2848
+ const after = why === "ready" ? readied.get(`${w.instance}\u0000${w.uuid}`) ?? null : null;
2849
+ this.db.prepare("INSERT INTO task_handoffs (task_id, instance, why, after_id, at) VALUES (?, ?, ?, ?, ?)").run(w.uuid, w.instance, why, after, at);
2850
+ }
2851
+ }
2852
+ /** The newest handoffs of these cards (the caller names a main task's sub tasks too), oldest first. */
2853
+ handoffsOf(uuids, limit = 60) {
2854
+ if (!uuids.length)
2855
+ return [];
2856
+ const marks = uuids.map(() => "?").join(",");
2857
+ const rows = this.db.prepare(`SELECT * FROM task_handoffs WHERE task_id IN (${marks}) ORDER BY id DESC LIMIT ?`).all(...uuids, limit);
2858
+ return rows.reverse().flatMap((r) => {
2859
+ const card = this.codeOf(r.task_id);
2860
+ if (!card || (r.why !== "ready" && r.why !== "assigned"))
2861
+ return [];
2862
+ const skip = typeof r.skip === "string" && WAKE_SKIPS.includes(r.skip) ? r.skip : undefined;
2863
+ return [{ id: Number(r.id), card, to: r.instance, why: r.why, after: typeof r.after_id === "string" ? this.codeOf(r.after_id) ?? null : null, at: r.at,
2864
+ ...(typeof r.notice_key === "string" && r.notice_key ? { key: r.notice_key } : {}), ...(skip ? { skip } : {}) }];
2865
+ });
2866
+ }
2867
+ /**
2868
+ * The fleet's waker took the news about `uuid` for `instance` (its notice has the outbox's `key`): the handoffs still waiting to be told
2869
+ * to it are carried by it — and one a withdrawn notice carried (`replaces`) takes the new key and loses any `skip` an earlier replacement left
2870
+ * on it (`noticeState` reads `skip` first), as `wakeHanded` does for a comment. Not a board write. Returns the card numbers a page showing it reads again: the card, and its main task
2871
+ * (whose page lists the handoffs of its sub tasks).
2872
+ */
2873
+ handoffHanded(uuid, instance, key, replaces) {
2874
+ return this.settleHandoffs(uuid, instance, "notice_key = ?, skip = NULL", key, replaces);
2875
+ }
2876
+ /**
2877
+ * The news about `uuid` for `instance` was not sent (`skip` says why): the handoffs waiting to be told to it say so — and so does one a
2878
+ * withdrawn notice carried (`replaces`, its key) when this was its replacement: it shows why it was not sent (`noticeState` puts `skip`
2879
+ * before `key`), not the withdrawn notice's state.
2880
+ */
2881
+ handoffDropped(uuid, instance, skip, replaces) {
2882
+ return this.settleHandoffs(uuid, instance, "skip = ?", skip, replaces);
2883
+ }
2884
+ /** `replaces`: notices that were withdrawn and told anew (a comment they quoted was edited or deleted): what they carried now has the new key. */
2885
+ settleHandoffs(uuid, instance, set, value, replaces = []) {
2886
+ const was = replaces.length ? ` OR notice_key IN (${replaces.map(() => "?").join(",")})` : "";
2887
+ const r = this.db.prepare(`UPDATE task_handoffs SET ${set} WHERE task_id = ? AND instance = ? AND ((notice_key IS NULL AND skip IS NULL)${was})`).run(value, uuid, instance, ...replaces);
2888
+ if (!r.changes)
2889
+ return [];
2890
+ const card = this.byUuid(uuid);
2891
+ const main = card?.parent ? this.codeOf(card.parent) : null;
2892
+ return [...(card ? [card.code] : []), ...(main ? [main] : [])];
2893
+ }
2894
+ /** The moves of a main task's sub tasks, newest 80, oldest first — its page lists them with its own activity. */
2895
+ subEvents(main, limit = 80) {
2896
+ const rows = this.db.prepare(`SELECT e.id, e.at, e.actor, e.actor_kind, e.data, t.code, t.title FROM task_events e JOIN tasks t ON t.id = e.task_id
2897
+ WHERE t.parent_id = ? AND e.type = 'moved' ORDER BY e.id DESC LIMIT ?`).all(main, limit);
2898
+ return rows.reverse().flatMap((r) => {
2899
+ let d = {};
2900
+ try {
2901
+ d = JSON.parse(r.data);
2902
+ }
2903
+ catch { /* a hand-edited row reads as no data */ }
2904
+ const keep = {};
2905
+ if (typeof d.from === "string")
2906
+ keep.from = d.from;
2907
+ if (typeof d.to === "string")
2908
+ keep.to = d.to;
2909
+ if (d.auto === true)
2910
+ keep.auto = true;
2911
+ if (typeof d.reason === "string" && d.reason)
2912
+ keep.reason = d.reason;
2913
+ return [{ id: Number(r.id), at: r.at, actor: r.actor, actorKind: r.actor_kind, card: r.code, title: r.title, data: keep }];
2914
+ });
2915
+ }
2916
+ /**
2917
+ * A comment's audience (recordWakes) as it stands once the write's wakes are settled: an instance the comment was meant for
2918
+ * that no wake of this write carries — the card no longer waits on it (wakeHolds) — is marked so (`not_waiting`), so the comment's
2919
+ * writer is not told something is on its way that is not.
2920
+ */
2921
+ settleEntryAudience(events, wakes) {
2922
+ for (const e of events) {
2923
+ if ((e.type !== "commented" && e.type !== "comment_edited") || !e.audience)
2924
+ continue;
2925
+ const entry = Number(e.data.entry);
2926
+ if (!Number.isSafeInteger(entry))
2927
+ continue;
2928
+ const card = this.byUuid(e.uuid);
2929
+ const meant = new Set([...e.audience.mentions, ...(e.audience.assignee && card?.assignee ? [card.assignee] : [])]);
2930
+ if (!meant.size)
2931
+ continue;
2932
+ const list = this.wakesOf(entry);
2933
+ let changed = false;
2934
+ for (const w of list) {
2935
+ if (!meant.has(w.to) || w.key || w.skip || wakes.some((x) => x.instance === w.to && x.uuid === e.uuid))
2936
+ continue;
2937
+ w.skip = "not_waiting";
2938
+ changed = true;
2939
+ }
2940
+ if (changed)
2941
+ this.db.prepare("UPDATE task_entries SET wakes = ? WHERE id = ?").run(JSON.stringify(list), entry);
2942
+ }
2943
+ }
2441
2944
  /**
2442
2945
  * Followers: the instances that handed a card out, watch it or lead its project hear it was finished, went to
2443
2946
  * review, was sent back, was blocked or got another assignee (docs/design/task-board.md, "Following a card"). The
@@ -2498,10 +3001,11 @@ export class TaskBoard {
2498
3001
  /**
2499
3002
  * What of a wake still stands now (at the end of its write, and again when the fleet sends it): a finished card is
2500
3003
  * news only as a cancel; a card that is no longer the instance's is not; a question only while the card is blocked
2501
- * and the instance still handed it out; a wrap-up only while it waits unfinished; and an assignment only once the
2502
- * card can start (its "ready" wakes it then). What asks the instance to act holds only while it still can (#2303
2503
- * review): "ready" while the card is open with nothing left to wait for, "start" and "answered" while it is in
2504
- * progress, "sent back" while it is back with the instance. null when nothing is left.
3004
+ * and the instance still handed it out; a wrap-up only while the main task still lacks something and is in review, or
3005
+ * done with nobody to confirm it; and an assignment only once the card can start (its "ready" wakes it then). What
3006
+ * asks the instance to act holds only while it still can (#2303 review): "ready" while the card is open with nothing
3007
+ * left to wait for, "start" and "answered" while it is in progress, "sent back" while it is back with the instance.
3008
+ * null when nothing is left.
2505
3009
  */
2506
3010
  wakeHolds(wake) {
2507
3011
  const card = this.byUuid(wake.uuid);
@@ -2510,7 +3014,16 @@ export class TaskBoard {
2510
3014
  const handedOut = card.dispatcher?.kind === "instance" && card.dispatcher.name === wake.instance;
2511
3015
  const own = card.assignee === wake.instance;
2512
3016
  const waiting = this.unmetDeps(card).length > 0;
3017
+ // The words a reason quotes are the comment's as it stands now (an edit made since is what is told), and a comment that was deleted is not told.
3018
+ const quoted = (id) => {
3019
+ if (id === undefined)
3020
+ return null;
3021
+ const row = this.db.prepare("SELECT text, deleted_at FROM task_entries WHERE id = ?").get(id);
3022
+ return !row || row.deleted_at ? { text: "", gone: true } : { text: row.text, gone: false };
3023
+ };
2513
3024
  let reasons = wake.reasons.filter((r) => {
3025
+ if ((r === "comment" || r === "mention") && quoted(wake.entries?.[r])?.gone)
3026
+ return false;
2514
3027
  if (r === "cancelled")
2515
3028
  return card.status === "cancelled" && own;
2516
3029
  // A mention was asked for by name: it holds whatever state the card is in, finished too.
@@ -2519,6 +3032,11 @@ export class TaskBoard {
2519
3032
  // A follower is told how the card moved on while it still stands there (finished too), and while it still follows it.
2520
3033
  if (r === "progress")
2521
3034
  return !!wake.news && this.followersOf(card).has(wake.instance) && this.progressStands(card, wake.news);
3035
+ // A main task that finished by itself stays its owner's to wrap up while something is still missing: in review, or done
3036
+ // when nobody had to confirm it. One confirmed since (done after review) was accepted as it is: nothing left to wrap up.
3037
+ if (r === "wrap_up")
3038
+ return own && card.kind === "main" && wrapUpGap(card) !== null
3039
+ && (card.status === "review" || (card.status === "done" && !requiresReview(card)));
2522
3040
  if (isFinished(card))
2523
3041
  return false;
2524
3042
  if (r === "decide")
@@ -2534,8 +3052,6 @@ export class TaskBoard {
2534
3052
  return (card.status !== "open" || !waiting) && this.newComments(card).some((e) => e.kind === "comment");
2535
3053
  if (r === "confirm_own")
2536
3054
  return card.status === "review" && confirmingInstance(card) === wake.instance;
2537
- if (r === "wrap_up")
2538
- return card.status === "review" && wrapUpGap(card) !== null;
2539
3055
  if (r === "assigned")
2540
3056
  return !waiting;
2541
3057
  if (r === "ready")
@@ -2564,6 +3080,41 @@ export class TaskBoard {
2564
3080
  return null;
2565
3081
  const keep = (o) => Object.fromEntries(Object.entries(o).filter(([r]) => reasons.includes(r)));
2566
3082
  const held = { ...wake, title: card.title, reasons, texts: keep(wake.texts), by: keep(wake.by) };
3083
+ if (wake.replies) {
3084
+ const replies = keep(wake.replies);
3085
+ if (Object.keys(replies).length)
3086
+ held.replies = replies;
3087
+ else
3088
+ delete held.replies;
3089
+ }
3090
+ if (wake.entries) {
3091
+ const entries = keep(wake.entries);
3092
+ if (Object.keys(entries).length)
3093
+ held.entries = entries;
3094
+ else
3095
+ delete held.entries;
3096
+ for (const r of Object.keys(entries)) {
3097
+ const now = quoted(entries[r]);
3098
+ if (!now)
3099
+ continue;
3100
+ if (now.gone)
3101
+ delete held.texts[r];
3102
+ else
3103
+ held.texts[r] = now.text;
3104
+ }
3105
+ }
3106
+ // What a reply quotes of the comment it answers is that comment's words now; one that has since been deleted is not quoted.
3107
+ if (held.replies) {
3108
+ for (const r of Object.keys(held.replies)) {
3109
+ const to = held.replies[r], now = quoted(to.id);
3110
+ if (now?.gone)
3111
+ delete held.replies[r];
3112
+ else if (now && now.text !== to.text)
3113
+ held.replies[r] = { ...to, text: now.text };
3114
+ }
3115
+ if (!Object.keys(held.replies).length)
3116
+ delete held.replies;
3117
+ }
2567
3118
  if (!reasons.includes("progress"))
2568
3119
  delete held.news;
2569
3120
  if (!reasons.some((r) => WORD_REASONS.includes(r))) {
@@ -2611,7 +3162,9 @@ export class TaskBoard {
2611
3162
  const projects = this.projectsChanged;
2612
3163
  if (touched.length || projects) {
2613
3164
  const changed = [...new Set(touched.filter((e) => e.type === "moved" || e.type === "assigned").map((e) => e.uuid))];
2614
- const change = { rev: this.revision(), ids: [...new Set(touched.map((e) => e.code))], actors: [...new Set(touched.map((e) => e.actor.name))], projects, wakes, changed };
3165
+ const recalled = touched.filter((e) => (e.type === "comment_edited" || e.type === "comment_deleted") && typeof e.data.entry === "number")
3166
+ .map((e) => ({ uuid: e.uuid, entry: e.data.entry, deleted: e.type === "comment_deleted" }));
3167
+ const change = { rev: this.revision(), ids: [...new Set(touched.map((e) => e.code))], actors: [...new Set(touched.map((e) => e.actor.name))], projects, wakes, changed, ...(recalled.length ? { recalled } : {}) };
2615
3168
  for (const listener of this.listeners) {
2616
3169
  try {
2617
3170
  listener(change);
@@ -2732,17 +3285,48 @@ export class TaskBoard {
2732
3285
  * "commented" event. A write that brings files and no words leaves a line naming them (`📎 name, name`), which an
2733
3286
  * older release shows as the comment it is. False when there is nothing to write (no words, no files).
2734
3287
  */
2735
- writeComment(card, actor, raw, attach, kept = false) {
3288
+ writeComment(card, actor, raw, attach, kept = false, opts = {}) {
3289
+ // What it answers is checked first: a reply to a comment that is not there writes nothing.
3290
+ const reply = opts.replyTo !== undefined ? this.replyTarget(card, opts.replyTo) : null;
2736
3291
  const files = attach?.length ? this.stagedFiles(card, actor, attach) : [];
2737
3292
  const words = checkText("the comment", raw, CARD_LIMITS.comment);
2738
3293
  const text = words || (files.length ? checkText("the comment", `📎 ${files.map((f) => f.name).join(", ")}`, CARD_LIMITS.comment) : "");
2739
3294
  if (!text)
2740
3295
  return false;
2741
- const entryId = this.entry(card, "comment", actor, text);
3296
+ // The `@` names are stored with the comment as it was written (the loop guard reads them back, not the words, which an edit or a
3297
+ // deletion changes): so is whom it was addressed to.
3298
+ const notify = this.notifyOf(actor, reply, opts.to, parseMentions(text, [...this.routing.instances()]).names);
3299
+ const entryId = this.entry(card, "comment", actor, text, { parentId: reply?.id ?? null, notify });
2742
3300
  this.linkFiles(card, actor, entryId, files);
2743
- this.commented(actor, card, text, kept, files.length);
3301
+ this.commented(actor, card, text, kept, files.length, { entry: entryId, reply, notify });
2744
3302
  return true;
2745
3303
  }
3304
+ /** The comment a reply answers: one of this card's comments that has not been deleted. */
3305
+ replyTarget(card, id) {
3306
+ const row = this.db.prepare("SELECT * FROM task_entries WHERE id = ? AND task_id = ? AND kind = 'comment'").get(id, card.uuid);
3307
+ if (!row)
3308
+ throw new TaskBoardError("not_found", `${card.code} has no comment c${id} to reply to`, "comment_not_found", [card.code, `c${id}`]);
3309
+ const entry = this.toEntry(row);
3310
+ if (entry.deleted)
3311
+ throw new TaskBoardError("invalid", `comment c${id} on ${card.code} was deleted; reply to the comment above it`, "comment_deleted", [`c${id}`]);
3312
+ return entry;
3313
+ }
3314
+ /**
3315
+ * Whom a comment woke, or was meant to, as it is stored with it (`notify`, read back by the loop guard): `at`, the instances its
3316
+ * words `@`-named when it was written, and `to`, the recipients its writer chose (else — a reply that chose none — the author of
3317
+ * the comment it answers when that is an instance). `assignee: false` is a chosen recipient list: the card's assignee hears the
3318
+ * comment only if it is on it. They are kept apart from the words because the words change: an edit that takes an `@` out, or a
3319
+ * deletion, must not take its turn out of the agents' count. A row from before this (no `notify`, or one with no `at`) is read from
3320
+ * its words, as it always was.
3321
+ */
3322
+ notifyOf(actor, reply, to, at) {
3323
+ const chosen = to !== undefined;
3324
+ const names = [...(to ?? [])];
3325
+ if (!chosen && reply && reply.authorKind === "instance")
3326
+ names.push(reply.author);
3327
+ const direct = [...new Set(names.map((n) => n.trim()).filter(Boolean))].filter((n) => isPerson(actor) || n !== actor.name);
3328
+ return { to: direct.slice(0, MAX_RECIPIENTS), assignee: !chosen, at: [...at] };
3329
+ }
2746
3330
  /** The files `actor` staged, checked against this card's limits (nothing is moved yet). */
2747
3331
  stagedFiles(card, actor, ids) {
2748
3332
  const store = this.fileStore;
@@ -2822,18 +3406,107 @@ export class TaskBoard {
2822
3406
  return;
2823
3407
  card.seenEntryId = this.db.prepare("SELECT COALESCE(MAX(id), 0) AS m FROM task_entries WHERE task_id = ?").get(card.uuid).m;
2824
3408
  }
2825
- entry(card, kind, actor, text) {
2826
- const r = this.db.prepare("INSERT INTO task_entries (task_id, kind, author, author_kind, text, at) VALUES (?, ?, ?, ?, ?, ?)")
2827
- .run(card.uuid, kind, actor.name, actor.kind, text, this.nowIso());
3409
+ entry(card, kind, actor, text, extra = {}) {
3410
+ const r = this.db.prepare("INSERT INTO task_entries (task_id, kind, author, author_kind, text, at, parent_id, notify, author_key) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)")
3411
+ .run(card.uuid, kind, actor.name, actor.kind, text, this.nowIso(), extra.parentId ?? null, extra.notify ? JSON.stringify(extra.notify) : null, actor.kind === "person" && actor.key ? actor.key : null);
2828
3412
  return Number(r.lastInsertRowid);
2829
3413
  }
2830
3414
  /**
2831
3415
  * A comment written (its entry is already on the card): the "commented" event, and whom the comment concerns, which
2832
3416
  * settleWakes reads when the write ends. `kept` is a dispatcher's answer a busy assignee finds on the card (#2303).
2833
3417
  */
2834
- commented(actor, card, text, kept = false, files = 0) {
2835
- this.event(actor, card, "commented", { text, ...(kept ? { kept: true } : {}), ...(files ? { files } : {}) });
2836
- this.pending[this.pending.length - 1].audience = this.routeComment(actor, card, text, kept);
3418
+ commented(actor, card, text, kept = false, files = 0, more = {}) {
3419
+ this.event(actor, card, "commented", { text, ...(more.entry !== undefined ? { entry: more.entry } : {}), ...(kept ? { kept: true } : {}), ...(files ? { files } : {}) });
3420
+ const audience = this.routeComment(actor, card, text, kept, { notify: more.notify ?? null, reply: more.reply ?? null });
3421
+ this.pending[this.pending.length - 1].audience = audience;
3422
+ if (more.entry !== undefined)
3423
+ this.recordWakes(actor, card, more.entry, audience, more.notify ?? null, false);
3424
+ }
3425
+ /**
3426
+ * Keeps with a comment whom it was written for and what became of it at the board (docs/design/task-board.md, "Comment
3427
+ * status"): the instances it wakes (the card's assignee, one its writer chose, one its words name) and those it could not wake,
3428
+ * with why. `merge`: an edit adds the instances its new words name to what the comment already had. Never an event, never a
3429
+ * revision of its own: the comment's own write carries them. How far an instance got with it is read from the delivery outbox
3430
+ * when it is shown (the key the fleet's notice carries is added by `wakeHanded`).
3431
+ */
3432
+ recordWakes(author, card, entry, audience, notify, merge) {
3433
+ const at = this.nowIso();
3434
+ const chosen = new Set(notify?.to ?? []);
3435
+ const out = [];
3436
+ const add = (to, why, skip) => { if (!out.some((w) => w.to === to))
3437
+ out.push({ to, why, ...(skip ? { skip } : {}), at }); };
3438
+ // What was refused first: the audience's `assignee` is only whether the card's assignee may hear it, and it may be one of those.
3439
+ for (const r of audience.refused ?? [])
3440
+ add(r.name, r.name === card.assignee ? "assignee" : chosen.has(r.name) ? "addressed" : "mention", r.skip);
3441
+ for (const n of audience.mentions)
3442
+ add(n, chosen.has(n) ? "addressed" : "mention");
3443
+ // (the card's assignee does not hear its own comment: settleWakes leaves a writer's own words out too)
3444
+ if (audience.assignee && card.assignee && card.assignee !== author.name && !audience.mentions.includes(card.assignee))
3445
+ add(card.assignee, "assignee");
3446
+ if (!out.length)
3447
+ return;
3448
+ const had = merge ? this.wakesOf(entry) : [];
3449
+ const kept = had.filter((w) => !out.some((o) => o.to === w.to));
3450
+ this.db.prepare("UPDATE task_entries SET wakes = ? WHERE id = ?").run(JSON.stringify([...kept, ...out]), entry);
3451
+ }
3452
+ /** What a comment was written for and what became of it at the board (`recordWakes`, `wakeHanded`), as stored; none for an older comment. */
3453
+ wakesOf(entry) {
3454
+ const row = this.db.prepare("SELECT wakes FROM task_entries WHERE id = ?").get(entry);
3455
+ return parseWakes(row?.wakes);
3456
+ }
3457
+ /**
3458
+ * The comments of a card that were written for instances (`recordWakes`): by entry number, as stored. The delivery's state is
3459
+ * the fleet's to add (it knows the outbox and the instance), so what the page shows is built from this and that.
3460
+ */
3461
+ entryWakes(ref) {
3462
+ const card = this.getCard(ref);
3463
+ const out = new Map();
3464
+ for (const r of this.db.prepare("SELECT id, wakes FROM task_entries WHERE task_id = ? AND wakes IS NOT NULL ORDER BY id").all(card.uuid)) {
3465
+ const list = parseWakes(r.wakes);
3466
+ if (list.length)
3467
+ out.set(Number(r.id), list);
3468
+ }
3469
+ return out;
3470
+ }
3471
+ /**
3472
+ * The fleet's waker took the news about `uuid` for `instance` (its notice has the delivery outbox's `key`): every comment on the
3473
+ * card waiting to be told to that instance is now carried by it. Not a board write — no revision, no event, no wake; returns the
3474
+ * card numbers it touched (none when no comment was waiting), for the live page to read again.
3475
+ */
3476
+ wakeHanded(uuid, instance, key, replaces) {
3477
+ return this.settleEntryWakes(uuid, instance, (w) => { w.key = key; delete w.skip; }, replaces);
3478
+ }
3479
+ /**
3480
+ * The news about `uuid` for `instance` was not sent (`skip` says why): the comments waiting to be told to it say so — and so do the
3481
+ * ones a withdrawn notice carried (`replaces`, its key) when this was its replacement: they show why it was not sent (wakeViews puts
3482
+ * `skip` before `key`), not the withdrawn notice's state.
3483
+ */
3484
+ wakeDropped(uuid, instance, skip, replaces) {
3485
+ return this.settleEntryWakes(uuid, instance, (w) => { w.skip = skip; }, replaces);
3486
+ }
3487
+ /** `replaces`: a notice that was withdrawn and told anew — what it carried (its key) now has the new notice's. */
3488
+ settleEntryWakes(uuid, instance, set, replaces) {
3489
+ const code = this.codeOf(uuid);
3490
+ const rows = this.db.prepare("SELECT id, wakes FROM task_entries WHERE task_id = ? AND wakes IS NOT NULL").all(uuid);
3491
+ const write = this.db.prepare("UPDATE task_entries SET wakes = ? WHERE id = ?");
3492
+ let touched = false;
3493
+ for (const r of rows) {
3494
+ const list = parseWakes(r.wakes);
3495
+ let changed = false;
3496
+ for (const w of list)
3497
+ if (w.to === instance && ((!w.key && !w.skip) || (replaces !== undefined && w.key !== undefined && replaces.includes(w.key)))) {
3498
+ set(w);
3499
+ changed = true;
3500
+ }
3501
+ if (changed) {
3502
+ write.run(JSON.stringify(list), r.id);
3503
+ touched = true;
3504
+ }
3505
+ }
3506
+ // Not a board write (no revision), yet whether an instance's comment answers the person reads it: what unreadFor kept is read again.
3507
+ if (touched)
3508
+ this.entryWakesGen++;
3509
+ return touched && code ? [code] : [];
2837
3510
  }
2838
3511
  /**
2839
3512
  * Whom a comment wakes (docs/design/task-board.md, "Comments and mentions"): the card's assignee, when someone else
@@ -2843,61 +3516,106 @@ export class TaskBoard {
2843
3516
  * to the loop guard (AGENT_COMMENT_CHAIN, MAX_COMMENT_WAKES). A card that is not on the board (the `task` tool's own
2844
3517
  * task) wakes nobody by a comment, as it wakes nobody by an assignment.
2845
3518
  */
2846
- routeComment(author, card, text, kept) {
3519
+ routeComment(author, card, text, kept, opts = {}) {
2847
3520
  const none = { mentions: [], assignee: false };
2848
- if (author.kind === "system" || !this.routing.enabled() || !this.isOnBoard(card))
3521
+ if (author.kind === "system" || !this.isOnBoard(card))
2849
3522
  return none;
2850
3523
  const names = [...this.routing.instances()];
3524
+ // Whom it was meant for and could not wake, with why — kept with the comment (recordWakes), so its writer can still see it.
3525
+ const refused = new Map();
3526
+ const refuse = (name, skip) => { if (!refused.has(name))
3527
+ refused.set(name, skip); };
3528
+ if (!this.routing.enabled()) {
3529
+ // Comment wakes are switched off for the fleet: what the box said it would do (its chip, the assignee) does not happen.
3530
+ const meant = opts.only !== undefined ? [...opts.only] : [...(opts.notify?.to ?? []), ...((opts.notify == null || opts.notify.assignee) && card.assignee !== null ? [card.assignee] : [])];
3531
+ for (const n of meant)
3532
+ if (names.includes(n) && n !== author.name)
3533
+ refuse(n, "wakes_off");
3534
+ return refused.size ? { ...none, refused: [...refused].map(([name, skip]) => ({ name, skip })) } : none;
3535
+ }
2851
3536
  const parsed = parseMentions(text, names);
2852
3537
  const agent = author.kind !== "person";
3538
+ const answer = (a) => (refused.size ? { ...a, refused: [...refused].map(([name, skip]) => ({ name, skip })) } : a);
3539
+ // An edit wakes only the instances its new words name that the old ones did not (`only`); a comment its writer
3540
+ // addressed (`notify.to`) wakes those too. The card's assignee hears a comment by the old rule — unless its writer
3541
+ // chose the recipients, when it hears it only if it is among them (and then as the card's assignee, as always).
3542
+ const editing = opts.only !== undefined;
3543
+ const notify = editing ? null : opts.notify ?? null;
3544
+ const chosen = (notify?.to ?? []).filter((n) => names.includes(n));
3545
+ const unknownChosen = (notify?.to ?? []).filter((n) => !names.includes(n));
3546
+ const toAssignee = card.assignee !== null && chosen.includes(card.assignee);
3547
+ // A comment to the assignee is the old rule's comment (it is told only while it can act on it). One the writer chose it for
3548
+ // is asked for by name, as an `@` is: on a finished card, or one still waiting on what it depends on, where the old rule
3549
+ // tells nobody, it goes as a mention — what the recipient chip says is what happens.
3550
+ const asMention = toAssignee && (isFinished(card) || (card.status === "open" && this.unmetDeps(card).length > 0));
3551
+ const hearsAsAssignee = !editing && (notify === null || notify.assignee || (toAssignee && !asMention));
3552
+ const written = parsed.names.filter((n) => !editing || opts.only.includes(n));
2853
3553
  // Only an instance (or a script) is itself: a person whose name is an instance's name is someone else, and a mention
2854
3554
  // of that instance is for it (the board's names are one string, but an `@name` always means the instance).
2855
- let mentions = parsed.names.filter((n) => agent ? n !== author.name : true);
3555
+ let mentions = [...new Set([...chosen.filter((n) => n !== card.assignee || asMention), ...written])].filter((n) => (agent ? n !== author.name : true));
2856
3556
  for (const n of mentions.filter((m) => this.boardOff(m))) {
2857
3557
  this.say("mention_off", [n], `@${n} has the task board switched off, so it was not woken: it cannot read the card`);
3558
+ refuse(n, "board_off");
2858
3559
  }
2859
3560
  mentions = mentions.filter((n) => !this.boardOff(n));
2860
- let asAssignee = !kept && card.assignee !== null && card.assignee !== author.name && names.includes(card.assignee) && !this.boardOff(card.assignee) && !mentions.includes(card.assignee);
3561
+ // The card's assignee with the board off hears nothing either (said by no note: it is no mention) — but its writer should know.
3562
+ if (hearsAsAssignee && !kept && card.assignee !== null && card.assignee !== author.name && names.includes(card.assignee) && this.boardOff(card.assignee))
3563
+ refuse(card.assignee, "board_off");
3564
+ let asAssignee = hearsAsAssignee && !kept && card.assignee !== null && card.assignee !== author.name && names.includes(card.assignee) && !this.boardOff(card.assignee) && !mentions.includes(card.assignee);
2861
3565
  // An agent's words reach another instance only as its contact rules allow (M-3160 / M-3384), per recipient.
2862
3566
  // The assignee is asked whatever the board knows of it: settleWakes adds it to any comment that leaves it out.
2863
3567
  const held = agent ? mentions.filter((n) => !this.mayReach(author, n)) : [];
2864
- const assigneeHeld = agent && !kept && card.assignee !== null && card.assignee !== author.name && !this.mayReach(author, card.assignee);
3568
+ const assigneeHeld = agent && hearsAsAssignee && !kept && card.assignee !== null && card.assignee !== author.name && !this.mayReach(author, card.assignee);
2865
3569
  if (assigneeHeld) {
2866
3570
  if (!held.includes(card.assignee))
2867
3571
  held.push(card.assignee);
2868
3572
  asAssignee = false;
2869
3573
  }
2870
3574
  if (held.length) {
3575
+ for (const n of held)
3576
+ refuse(n, "contact_held");
2871
3577
  mentions = mentions.filter((n) => !held.includes(n));
2872
3578
  this.say("contact_held", [held.join(", ")], `${held.join(", ")} not woken by this comment: this conversation may not reach another instance on its own `
2873
3579
  + `(its origin is unknown or not an administrator's, or a Hub contact restriction is on). The comment is kept on the card; to reach them, use send_to_instance, which asks for the approval where one can be given`);
2874
3580
  }
2875
- if (parsed.unknown.length) {
2876
- this.say("mention_unknown", [parsed.unknown.map((w) => `@${w}`).join(", ")], `${parsed.unknown.map((w) => `@${w}`).join(", ")}: no such instance, nobody was woken for it`);
3581
+ const unknown = [...(editing ? [] : parsed.unknown.map((w) => `@${w}`)), ...unknownChosen.map((n) => `@${n}`)];
3582
+ if (unknown.length) {
3583
+ this.say("mention_unknown", [unknown.join(", ")], `${unknown.join(", ")}: no such instance, nobody was woken for it`);
3584
+ // An agent that `@`-names a person (the usual way to tell them something) is not making a mistake: the note above is its own,
3585
+ // and the comment carries no "no such instance" under it. A person's typo is the case the status line is for.
3586
+ if (!agent)
3587
+ for (const u of unknown)
3588
+ refuse(u.replace(/^@/, ""), "unknown");
2877
3589
  }
2878
3590
  const run = agent && (mentions.length || asAssignee) ? this.agentCommentRun(card, names) : 0;
2879
3591
  if (run > AGENT_COMMENT_CHAIN) {
2880
3592
  this.say("comment_chain", [card.code, run], `nobody was woken by this comment: it is turn ${run} of agents answering each other on ${card.code} (a loop guard). It is kept on the card; `
2881
3593
  + `comments wake again once a person writes on it, or when these are ${AGENT_COMMENT_WINDOW_MS / 60_000} minutes old`);
2882
- return none;
3594
+ for (const n of [...mentions, ...(asAssignee && card.assignee ? [card.assignee] : [])])
3595
+ refuse(n, "loop_guard");
3596
+ return answer(none);
2883
3597
  }
2884
3598
  // The limit is for everyone the comment wakes, counted once each: the card's assignee, when it hears the comment —
2885
3599
  // named or not, wherever its name is in the text (settleWakes adds it to a comment that does not name it), and also
2886
3600
  // when the comment is a dispatcher's answer kept for a busy assignee (its baseline `answer_kept` notice, #2303, which
2887
3601
  // no gate holds) — takes one place, and the instances named besides it share the rest in the order written (#4367
2888
3602
  // review). It is counted whenever settleWakes would add it, so the board's own wakes never pass the limit.
2889
- const assigneeWakes = card.assignee !== null && card.assignee !== author.name && (kept || !assigneeHeld);
3603
+ const assigneeWakes = card.assignee !== null && card.assignee !== author.name && (kept || (hearsAsAssignee && !assigneeHeld));
2890
3604
  const others = mentions.filter((n) => !(assigneeWakes && n === card.assignee));
2891
3605
  const room = MAX_COMMENT_WAKES - (assigneeWakes ? 1 : 0);
2892
3606
  if (agent && others.length > room) {
2893
3607
  this.say("mention_cap", [room], `only the first ${room} instances you mentioned were woken (an agent's comment wakes at most ${MAX_COMMENT_WAKES}, the card's assignee included)`);
2894
3608
  const kept = new Set(others.slice(0, room));
3609
+ for (const n of others.slice(room))
3610
+ refuse(n, "cap");
2895
3611
  mentions = mentions.filter((n) => kept.has(n) || (assigneeWakes && n === card.assignee));
2896
3612
  }
2897
- const heard = [...mentions.map((n) => `${n} (mentioned)`), ...(asAssignee ? [`${card.assignee} (assignee)`] : [])];
3613
+ const addressed = (n) => chosen.includes(n) && !written.includes(n);
3614
+ const heard = [...mentions.map((n) => `${n} (${addressed(n) ? "addressed" : "mentioned"})`), ...(asAssignee ? [`${card.assignee} (assignee)`] : [])];
2898
3615
  if (heard.length)
2899
3616
  this.say("comment_wakes", [heard.join(", ")], `this comment is told to ${heard.join(", ")} as a [Task board] notice: no need to message them about it`);
2900
- return { mentions, assignee: !kept && !assigneeHeld };
3617
+ const reply = opts.reply ? { id: opts.reply.id, author: opts.reply.author, text: [...opts.reply.text.replace(/\s+/g, " ").trim()].slice(0, 160).join("") } : undefined;
3618
+ return answer({ mentions, assignee: hearsAsAssignee && !kept && !assigneeHeld, ...(reply ? { reply } : {}) });
2901
3619
  }
2902
3620
  /**
2903
3621
  * How many turns the agents' talk on the card has had, within AGENT_COMMENT_WINDOW_MS, back to the last thing a person
@@ -2923,7 +3641,7 @@ export class TaskBoard {
2923
3641
  // nobody and leave the turns before them unread, so that the next comment reads as turn 1 (#4367 review). The window
2924
3642
  // bounds it; a person's entry ends it early.
2925
3643
  // (Read last: nothing else may run on the connection while it is read.)
2926
- const rows = this.db.prepare("SELECT kind, author, author_kind, text, at FROM task_entries WHERE task_id = ? AND kind IN ('comment', 'reject', 'approve') AND at >= ? ORDER BY id DESC")
3644
+ const rows = this.db.prepare("SELECT kind, author, author_kind, text, at, notify FROM task_entries WHERE task_id = ? AND kind IN ('comment', 'reject', 'approve') AND at >= ? ORDER BY id DESC")
2927
3645
  .iterate(card.uuid, since);
2928
3646
  const assigneeAt = (at) => {
2929
3647
  const next = handovers.find((h) => h.at > at);
@@ -2932,12 +3650,33 @@ export class TaskBoard {
2932
3650
  return typeof next.from === "string" ? next.from : null;
2933
3651
  };
2934
3652
  const assigneeHears = (by, at) => { const a = assigneeAt(at); return a !== null && a !== by && names.includes(a); };
3653
+ // A comment its writer addressed (the recipients stored with it, a reply's author among them) woke those instances without an
3654
+ // `@`: they count as the mentions do — and the assignee hears it only when the writer left that rule on (`assignee`).
3655
+ // `at`: the `@` names stored when it was written (null: a row from before they were stored — its words say). An edit or a deletion
3656
+ // changes the words, never what was stored, so neither takes a turn out of the count.
3657
+ const notified = (raw) => {
3658
+ const strs = (v) => (Array.isArray(v) ? v.filter((x) => typeof x === "string") : []);
3659
+ if (!raw)
3660
+ return { to: [], assignee: true, at: null };
3661
+ try {
3662
+ const n = JSON.parse(raw);
3663
+ return { to: strs(n.to), assignee: n.assignee !== false, at: Array.isArray(n.at) ? strs(n.at) : null };
3664
+ }
3665
+ catch {
3666
+ return { to: [], assignee: true, at: null };
3667
+ }
3668
+ };
2935
3669
  let turns = 0;
2936
3670
  let writer = null;
2937
3671
  for (const r of rows) {
2938
3672
  if (r.author_kind === "person")
2939
3673
  break;
2940
- if (r.kind !== "comment" || !(parseMentions(r.text, names).names.some((n) => n !== r.author) || assigneeHears(r.author, r.at)))
3674
+ if (r.kind !== "comment")
3675
+ continue;
3676
+ const n = notified(r.notify);
3677
+ // The assignee a writer addressed by `to` is among `to`, so it counts there; the old rule (`assignee`) counts it as it did.
3678
+ const named = n.at ?? parseMentions(r.text, names).names;
3679
+ if (!(named.some((m) => m !== r.author && names.includes(m)) || n.to.some((m) => m !== r.author && names.includes(m)) || (n.assignee && assigneeHears(r.author, r.at))))
2941
3680
  continue;
2942
3681
  if (r.author !== writer) {
2943
3682
  turns++;