@desplega.ai/agent-swarm 2.7.9 → 2.7.10

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 (212) hide show
  1. package/dist/{acp-adapter-dn4gdsgr.js → acp-adapter-srfhs1s9.js} +5 -5
  2. package/dist/{actions-g563mbn2.js → actions-b8aqhrsg.js} +19 -18
  3. package/dist/{amp-adapter-q61w05eb.js → amp-adapter-4c165vgn.js} +1 -1
  4. package/dist/app-m9khefrh.js +20 -0
  5. package/dist/{assistant-p477rjwj.js → assistant-rh4v3ntz.js} +21 -20
  6. package/dist/{boot-args-schema-h4qj462e.js → boot-args-schema-hwkc8bzv.js} +1 -1
  7. package/dist/{boot-reembed-n1ehfbsw.js → boot-reembed-5y6yw9sj.js} +1 -1
  8. package/dist/{boot-reembed-qw4mc0pt.js → boot-reembed-fdyk55h4.js} +1 -1
  9. package/dist/{boot-scrub-sweep-9w9jp4sm.js → boot-scrub-sweep-r5r8kqsn.js} +3 -3
  10. package/dist/{boot-seeds-qdaf3sdy.js → boot-seeds-8f9zt5cm.js} +5 -5
  11. package/dist/{claude-adapter-348p5hx9.js → claude-adapter-s5df247c.js} +5 -5
  12. package/dist/{claude-managed-setup-7787fxtp.js → claude-managed-setup-9gsmwzyx.js} +1 -1
  13. package/dist/{claude-sdk-session-hbszbt8a.js → claude-sdk-session-dq1j4nz9.js} +5 -5
  14. package/dist/{cli-btf6fw39.js → cli-0m7rtm11.js} +1 -1
  15. package/dist/{cli-cseh6f8w.js → cli-16phend6.js} +1 -1
  16. package/dist/{cli-ms5m5r1y.js → cli-18qt3few.js} +1 -1
  17. package/dist/{cli-sgs5k6yd.js → cli-2tsfpc70.js} +1 -1
  18. package/dist/{cli-rwymrnaz.js → cli-36wdfzgn.js} +8 -8
  19. package/dist/{cli-qzt90yze.js → cli-38yww4e9.js} +8 -8
  20. package/dist/{cli-2a8py3sx.js → cli-3xddv0rk.js} +4 -4
  21. package/dist/{cli-p0m0p34z.js → cli-4vwxp550.js} +2 -2
  22. package/dist/{cli-bc779n4v.js → cli-55bkx8hh.js} +1 -1
  23. package/dist/{cli-21159vea.js → cli-5wfz00be.js} +2 -2
  24. package/dist/{cli-9aezs55w.js → cli-5xcb8gxq.js} +4 -4
  25. package/dist/{cli-12xyjhws.js → cli-6m6b4bep.js} +2 -2
  26. package/dist/{cli-fayav105.js → cli-7wz05bx3.js} +292 -83
  27. package/dist/{cli-y8nbefpb.js → cli-8ewkreqd.js} +9 -5
  28. package/dist/{cli-0whpms1z.js → cli-an1knn2k.js} +4 -4
  29. package/dist/{cli-qmd3mse0.js → cli-bxz823sz.js} +1 -1
  30. package/dist/{cli-a0657jmf.js → cli-bzvs88tv.js} +1 -1
  31. package/dist/{cli-agyaeef4.js → cli-cr14kftt.js} +2 -2
  32. package/dist/{cli-715t1gx6.js → cli-eb2azq8n.js} +3 -3
  33. package/dist/{cli-530hkwdy.js → cli-ed6yqpf1.js} +2 -2
  34. package/dist/{cli-k70e3x9e.js → cli-eqk5p56g.js} +3 -3
  35. package/dist/{cli-4t0fmf3z.js → cli-g1px1g2e.js} +1 -1
  36. package/dist/{cli-09kmfkmq.js → cli-h49ejvmc.js} +1 -1
  37. package/dist/{cli-cvs2r2vq.js → cli-hfkwwy1h.js} +39 -5
  38. package/dist/{cli-neyag5p6.js → cli-j7d73g1y.js} +371 -116
  39. package/dist/{cli-p17970qv.js → cli-jg24scat.js} +2 -2
  40. package/dist/{cli-varqt4d1.js → cli-kx4c8j05.js} +16 -13
  41. package/dist/{cli-jfx48xrj.js → cli-mp9aa8g5.js} +1 -1
  42. package/dist/{cli-605nn699.js → cli-mr97t7cc.js} +644 -225
  43. package/dist/{cli-v3cf1ts9.js → cli-n07eecjs.js} +3 -3
  44. package/dist/{cli-y5rbvxhc.js → cli-n515ex5z.js} +14 -14
  45. package/dist/{cli-3tqcamp6.js → cli-n9abj89w.js} +13 -12
  46. package/dist/{cli-ypff1qwp.js → cli-n9ftpys4.js} +7 -7
  47. package/dist/{cli-xk879m3k.js → cli-nj3x45rw.js} +27 -27
  48. package/dist/{cli-9r5gtwjr.js → cli-pyrxt9gw.js} +196 -1
  49. package/dist/{cli-mnrkgg60.js → cli-q581b386.js} +2 -2
  50. package/dist/{cli-hwprv9e4.js → cli-rjyghzg4.js} +2 -2
  51. package/dist/{cli-650zv9q9.js → cli-rt0ag4x1.js} +3 -3
  52. package/dist/{cli-vxh6acp7.js → cli-td33w98c.js} +2 -2
  53. package/dist/{cli-tqq0hspb.js → cli-tmft5dz2.js} +1 -1
  54. package/dist/{cli-q26b9wre.js → cli-tph5wt3y.js} +4 -4
  55. package/dist/{cli-qkdmz8c8.js → cli-ttbqe3q4.js} +1 -1
  56. package/dist/{cli-zgv8gxgs.js → cli-v2fwbnsk.js} +6 -6
  57. package/dist/{cli-b932gexn.js → cli-w3bk0dgv.js} +1 -1
  58. package/dist/{cli-serm8zrx.js → cli-x9exydey.js} +1 -1
  59. package/dist/{cli-hae9j8sv.js → cli-xbtq4d6s.js} +3 -3
  60. package/dist/{cli-587857ys.js → cli-xd5ebp64.js} +3 -3
  61. package/dist/{cli-ejkvvqbe.js → cli-xncjscpm.js} +10 -10
  62. package/dist/{cli-gce09r66.js → cli-xvymtmv4.js} +2 -2
  63. package/dist/{cli-btc9cb4c.js → cli-yz7v0sh4.js} +2 -2
  64. package/dist/{cli-sya22y84.js → cli-z9cs5m0w.js} +3 -3
  65. package/dist/{cli-2ccpqyyf.js → cli-zjphdj1a.js} +71 -10
  66. package/dist/cli.js +15 -15
  67. package/dist/{codex-adapter-ysq6bzha.js → codex-adapter-yr60sme6.js} +3 -3
  68. package/dist/{codex-session-runner-qakzfx93.js → codex-session-runner-pch8x584.js} +3 -3
  69. package/dist/{commands-rs7hkv9r.js → commands-phjfbkv0.js} +3 -3
  70. package/dist/{controller-r5x9bg6e.js → controller-jkx994pz.js} +2 -2
  71. package/dist/{controllers-connect-498hrxvk.js → controllers-connect-c4448kwa.js} +20 -19
  72. package/dist/{cursor-adapter-d46qszer.js → cursor-adapter-ndebqnm8.js} +1 -1
  73. package/dist/{db-pm96nhdb.js → db-ef32tbfc.js} +4 -2
  74. package/dist/{db-s13dqhr6.js → db-ez6egt6v.js} +3 -3
  75. package/dist/{dispatcher-j3h81t7m.js → dispatcher-g3tt9hs9.js} +18 -17
  76. package/dist/{dsh-adapter-rw0d5rc4.js → dsh-adapter-tcyn3099.js} +1 -1
  77. package/dist/{easter-egg-3d-qtgfxgze.js → easter-egg-3d-e36hk5td.js} +1 -1
  78. package/dist/{embedding-space-xh8p4q4x.js → embedding-space-4kyh5qqj.js} +6 -6
  79. package/dist/{embeddings-wp745m91.js → embeddings-6a8v4a6t.js} +1 -1
  80. package/dist/{execute-2fzb9z74.js → execute-3cbg0twf.js} +1 -1
  81. package/dist/{external-channel-ys21h3sy.js → external-channel-se646snz.js} +2 -2
  82. package/dist/{fx-adapter-vz0b9z3g.js → fx-adapter-yw795hqq.js} +6 -6
  83. package/dist/{google-generative-ai-ytpgncx9.js → google-generative-ai-h7s3e9kk.js} +1 -1
  84. package/dist/{google-vertex-tqhze5j7.js → google-vertex-fhxaafzw.js} +1 -1
  85. package/dist/{grok-adapter-spea7zkj.js → grok-adapter-ttmcss2j.js} +6 -6
  86. package/dist/handlers-17wha3ze.js +33 -0
  87. package/dist/{heartbeat-8phn1kdq.js → heartbeat-gwewgdms.js} +21 -20
  88. package/dist/{hook-amcj4s10.js → hook-g3nhexsy.js} +5 -5
  89. package/dist/{hook-bc6n49qn.js → hook-hq93y5ej.js} +4 -4
  90. package/dist/{http-7374brv5.js → http-5a9p4h6y.js} +210 -69
  91. package/dist/{index-pxn30mse.js → index-0eny15vj.js} +8 -8
  92. package/dist/{index-5a9jtqde.js → index-0rvk3vd4.js} +46 -46
  93. package/dist/{index-fvzke5kx.js → index-1qw6f2dc.js} +10 -10
  94. package/dist/{index-p4hjwbvw.js → index-3c5pxbge.js} +1 -1
  95. package/dist/{index-q5cmtbz5.js → index-6haqt3v5.js} +12296 -11042
  96. package/dist/index-8arwq8mw.js +34 -0
  97. package/dist/{index-h7f61sy9.js → index-e5pfbsys.js} +3 -3
  98. package/dist/{index-c9y31ytf.js → index-hgn3c961.js} +12 -11
  99. package/dist/{index-hsad2t3r.js → index-m5gx1xd6.js} +38 -38
  100. package/dist/{index-5fx3b3kw.js → index-rvccek1w.js} +9 -9
  101. package/dist/{index-w4m9z29z.js → index-s72rqgsx.js} +1 -1
  102. package/dist/index-tpw054az.js +38 -0
  103. package/dist/{index-514d9pf6.js → index-w7em4ktq.js} +8 -8
  104. package/dist/index-waq75j2j.js +31 -0
  105. package/dist/{keepalive-wy29kbrg.js → keepalive-1j4n4dmk.js} +3 -3
  106. package/dist/lead-re73kdgc.js +72 -0
  107. package/dist/{maintenance-h2ds9w6c.js → maintenance-dmghacy5.js} +1 -1
  108. package/dist/{oauth-refresh-sweep-q7mtbyp3.js → oauth-refresh-sweep-yy06c03c.js} +2 -2
  109. package/dist/{onboard-vw8r2fdw.js → onboard-52f9t5dm.js} +3 -3
  110. package/dist/{opencode-adapter-mtb0953j.js → opencode-adapter-krnh9jkn.js} +4 -4
  111. package/dist/{otel-impl-j42czw3r.js → otel-impl-xjqz6wjj.js} +1 -1
  112. package/dist/{pi-mono-adapter-zk8pg9jr.js → pi-mono-adapter-dbxyp0qv.js} +6 -6
  113. package/dist/{pricing-refresh-x7nhv23d.js → pricing-refresh-ctdr74pd.js} +3 -3
  114. package/dist/{rbac-roles-bzvee6cf.js → rbac-roles-ehv8s10n.js} +3 -3
  115. package/dist/{rbac-roles-9044425x.js → rbac-roles-q0gr8eyj.js} +2 -2
  116. package/dist/{render-v2-t7bn4skz.js → render-v2-5b6chvcq.js} +9 -4
  117. package/dist/{resume-x94gemep.js → resume-5a5d2845.js} +6 -6
  118. package/dist/{runtime-breq6fmv.js → runtime-khxszyfp.js} +1 -1
  119. package/dist/{session-access-q7dmqjvt.js → session-access-gj0bjhqg.js} +4 -4
  120. package/dist/{session-source-backfill-440ysamr.js → session-source-backfill-2sy0krfk.js} +2 -2
  121. package/dist/{setup-07n4727s.js → setup-7ssfakk1.js} +1 -1
  122. package/dist/{virtual-modules-z5h6mcyf.js → virtual-modules-pjj0knwf.js} +3 -3
  123. package/dist/{work-objects-pnq5y534.js → work-objects-bf3syvhq.js} +22 -21
  124. package/dist/{worker-follow-up-7z1gfkr8.js → worker-follow-up-38xevga6.js} +18 -17
  125. package/dist/worker-r8mz7a65.js +72 -0
  126. package/openapi.json +1 -1
  127. package/package.json +3 -3
  128. package/src/apps/catalog.generated.json +55 -0
  129. package/src/apps/page-validator.ts +19 -0
  130. package/src/assets/key.ts +77 -4
  131. package/src/be/db/session-labels.ts +57 -0
  132. package/src/be/db/session-tree.ts +51 -7
  133. package/src/be/db/slack-trees.ts +146 -0
  134. package/src/be/db/tasks/read.ts +102 -7
  135. package/src/be/db-client.ts +8 -2
  136. package/src/be/db.ts +95 -84
  137. package/src/be/event-loop-lag.ts +146 -0
  138. package/src/be/mcp-overflow-sweep.ts +2 -1
  139. package/src/be/memory/providers/sqlite-store.ts +39 -8
  140. package/src/be/migrations/278_slack_render_v2_reconcile.sql +108 -0
  141. package/src/be/swarm-config-guard.ts +2 -0
  142. package/src/commands/context-preamble.ts +258 -0
  143. package/src/commands/onboard/agent-fs-version.ts +1 -1
  144. package/src/extensions/catalog.generated.json +3 -3
  145. package/src/heartbeat/heartbeat.ts +5 -4
  146. package/src/http/core.ts +9 -3
  147. package/src/http/index.ts +10 -6
  148. package/src/http/memory.ts +9 -4
  149. package/src/http/sessions.ts +16 -3
  150. package/src/http/utils.ts +18 -0
  151. package/src/http/webhooks.ts +48 -0
  152. package/src/integrations/chat-sdk/commands.ts +167 -31
  153. package/src/integrations/chat-sdk/inbound.ts +10 -8
  154. package/src/integrations/chat-sdk/message-text.ts +117 -0
  155. package/src/providers/amp-adapter.ts +1 -1
  156. package/src/providers/cursor-adapter.ts +1 -1
  157. package/src/providers/dsh-adapter.ts +1 -1
  158. package/src/scheduler/scheduler.ts +4 -1
  159. package/src/scripts-runtime/executors/quickjs-runner.ts +2 -0
  160. package/src/scripts-runtime/executors/quickjs-structured-clone.ts +180 -0
  161. package/src/scripts-runtime/quickjs-compat.ts +0 -1
  162. package/src/slack/app.ts +332 -10
  163. package/src/slack/handlers.ts +9 -2
  164. package/src/slack/index.ts +7 -1
  165. package/src/slack/lifecycle-lock.ts +29 -0
  166. package/src/slack/render-v2.ts +424 -212
  167. package/src/slack/socket-fence.ts +64 -0
  168. package/src/slack/watcher.ts +42 -8
  169. package/src/tests/apps-schema-form.test.ts +151 -0
  170. package/src/tests/chat-sdk-commands.test.ts +359 -2
  171. package/src/tests/chat-sdk-inbound.test.ts +20 -0
  172. package/src/tests/chat-sdk-slack.test.ts +189 -1
  173. package/src/tests/db-client-busy-retry.test.ts +69 -18
  174. package/src/tests/db-client.test.ts +26 -1
  175. package/src/tests/db-task-read-contract.test.ts +2 -0
  176. package/src/tests/db-task-write-contract.test.ts +1 -0
  177. package/src/tests/dsh-adapter.test.ts +1 -1
  178. package/src/tests/event-loop-lag.test.ts +184 -0
  179. package/src/tests/extensions-example-comms-adherence-gate.test.ts +115 -0
  180. package/src/tests/github-webhook-early-ack.test.ts +144 -0
  181. package/src/tests/http-api-integration.test.ts +2 -0
  182. package/src/tests/http-log-scrubbing.test.ts +68 -2
  183. package/src/tests/kv-storage.test.ts +92 -1
  184. package/src/tests/memory-key-paths.test.ts +57 -0
  185. package/src/tests/memory-retrieval-purge.test.ts +19 -0
  186. package/src/tests/quickjs-compat.test.ts +1 -1
  187. package/src/tests/runner-context-preamble.test.ts +552 -0
  188. package/src/tests/script-connections.test.ts +3 -0
  189. package/src/tests/script-executor-conformance.test.ts +188 -0
  190. package/src/tests/sessions-tree.test.ts +133 -2
  191. package/src/tests/slack-app-icon.test.ts +4 -0
  192. package/src/tests/slack-dm-implicit-mention.test.ts +236 -0
  193. package/src/tests/slack-file-tools-attachments.test.ts +1 -0
  194. package/src/tests/slack-read-boundaries.test.ts +4 -3
  195. package/src/tests/slack-render-v2-query-plans.test.ts +262 -3
  196. package/src/tests/slack-render-v2-reconcile.test.ts +201 -0
  197. package/src/tests/slack-socket-watchdog.test.ts +748 -0
  198. package/src/tests/vcs-identity-inheritance.test.ts +85 -0
  199. package/src/tools/utils.ts +16 -7
  200. package/templates/extensions/comms-adherence-gate/README.md +25 -0
  201. package/templates/extensions/comms-adherence-gate/hooks.ts +100 -11
  202. package/templates/extensions/comms-adherence-gate/manifest.json +1 -1
  203. package/templates/skills/apps/SKILL.md +7 -0
  204. package/templates/skills/apps/content.md +7 -0
  205. package/dist/app-a66ssc4k.js +0 -17
  206. package/dist/handlers-crckt5dq.js +0 -32
  207. package/dist/index-4x08sjtk.js +0 -30
  208. package/dist/index-8ybffts4.js +0 -37
  209. package/dist/index-nfy4kkg5.js +0 -33
  210. package/dist/lead-zdqxsvjn.js +0 -71
  211. package/dist/worker-y62rvvq3.js +0 -71
  212. package/dist/{cli-gxy8y1dt.js → cli-8bpgbr8k.js} +3 -3
@@ -1,6 +1,8 @@
1
1
  import { Database } from "bun:sqlite";
2
2
  import { afterEach, beforeEach, describe, expect, spyOn, test } from "bun:test";
3
+ import { join } from "node:path";
3
4
  import {
5
+ claimTask,
4
6
  closeDb,
5
7
  createAgent,
6
8
  createTaskExtended,
@@ -9,8 +11,11 @@ import {
9
11
  getResolvableDeferralOutcomes,
10
12
  getSlackTreeMessages,
11
13
  initDb,
14
+ moveTaskFromBacklog,
12
15
  recordSlackMessage,
16
+ updateSlackMessageRecord,
13
17
  } from "../be/db";
18
+ import { closeSlackTreeIfSettled } from "../be/db/slack-trees";
14
19
  import { getSlackTasksMissingTree } from "../be/db/tasks/read";
15
20
  import { completeTask, startTask } from "../be/db/tasks/write";
16
21
 
@@ -123,14 +128,101 @@ describe("slack render-v2 watcher queries", () => {
123
128
  /SEARCH wake USING INDEX idx_agent_tasks_parentTaskId(_source|_id)? \(parentTaskId=\?\)/,
124
129
  );
125
130
  expect(detail).not.toContain("idx_agent_tasks_taskType");
131
+ // The NOT EXISTS seeks the wake's children, not every deferred-type task.
132
+ expect(detail).toMatch(/SEARCH child USING (COVERING )?INDEX idx_agent_tasks_parentTaskId/);
133
+ expect(detail).not.toContain("idx_agent_tasks_list_filter");
134
+ // The anchor reads only tasks that ever deferred, then seeks their card.
135
+ expect(detail).toContain("SCAN deferred USING INDEX idx_agent_tasks_deferred");
136
+ expect(detail).toContain("SEARCH card USING INDEX idx_slack_messages_outcome_task (task_id=?)");
137
+ expect(detail).not.toMatch(/SCAN card\b/);
126
138
  expect(detail).not.toContain("idx_agent_tasks_status_last_updated");
127
139
  });
128
140
 
129
- test("missing-tree scan reads only Slack tasks", async () => {
141
+ test("missing-tree scan reads only recently updated Slack tasks", async () => {
130
142
  const sql = await capturedSql(() => getSlackTasksMissingTree());
131
143
  const detail = plan(sql);
132
- expect(detail).toContain("SCAN task USING INDEX idx_agent_tasks_slack_last_updated");
133
- expect(detail).not.toContain("idx_agent_tasks_last_updated");
144
+ expect(detail).toContain(
145
+ "SEARCH task USING INDEX idx_agent_tasks_slack_last_updated (lastUpdatedAt>?)",
146
+ );
147
+ // The index order serves the ORDER BY too.
148
+ expect(detail).not.toContain("USE TEMP B-TREE");
149
+ expect(detail).not.toContain("idx_agent_tasks_last_updated ");
150
+ });
151
+
152
+ test("thread-scoped missing-tree query seeks the thread", async () => {
153
+ const sql = await capturedSql(() =>
154
+ getSlackTasksMissingTree({ thread: { channelId: "C_X", threadTs: "X.0" } }),
155
+ );
156
+ const detail = plan(sql, ["C_X", "X.0"]);
157
+ expect(detail).toContain(
158
+ "SEARCH task USING INDEX idx_agent_tasks_slack_thread_cover (slackChannelId=? AND slackThreadTs=?",
159
+ );
160
+ expect(detail).not.toContain("idx_agent_tasks_slack_last_updated");
161
+ });
162
+
163
+ test("missing-tree scan is bounded to the last 24 hours of updates", async () => {
164
+ const lead = await createAgent({ name: "Window Lead", isLead: true, status: "idle" });
165
+ const make = async (label: string, ageMs: number) => {
166
+ const task = await createTaskExtended(`ask ${label}`, {
167
+ agentId: lead.id,
168
+ source: "slack",
169
+ slackChannelId: `C_${label}`,
170
+ slackThreadTs: `${label}.0`,
171
+ });
172
+ const at = new Date(Date.now() - ageMs).toISOString();
173
+ getDb().run("UPDATE agent_tasks SET createdAt = ?, lastUpdatedAt = ? WHERE id = ?", [
174
+ at,
175
+ at,
176
+ task.id,
177
+ ]);
178
+ return task;
179
+ };
180
+ const recent = await make("RECENT", 60 * 60 * 1000);
181
+ const old = await make("OLD", 25 * 60 * 60 * 1000);
182
+
183
+ const ids = (await getSlackTasksMissingTree()).map((task) => task.id);
184
+ expect(ids).toContain(recent.id);
185
+ expect(ids).not.toContain(old.id);
186
+
187
+ // The window is relative to `now`: two days later neither is in it.
188
+ const later = new Date(Date.now() + 2 * 24 * 60 * 60 * 1000);
189
+ expect(await getSlackTasksMissingTree({ now: later })).toEqual([]);
190
+
191
+ // Thread scope narrows to one thread and has no window.
192
+ const scoped = await getSlackTasksMissingTree({
193
+ thread: { channelId: "C_RECENT", threadTs: "RECENT.0" },
194
+ });
195
+ expect(scoped.map((task) => task.id)).toEqual([recent.id]);
196
+ const oldScoped = await getSlackTasksMissingTree({
197
+ thread: { channelId: "C_OLD", threadTs: "OLD.0" },
198
+ });
199
+ expect(oldScoped.map((task) => task.id)).toEqual([old.id]);
200
+ });
201
+
202
+ test("a Slack task assigned after 24 h in backlog still gets a tree", async () => {
203
+ const lead = await createAgent({ name: "Backlog Lead", isLead: true, status: "idle" });
204
+ const task = await createTaskExtended("ask BACKLOG", {
205
+ source: "slack",
206
+ slackChannelId: "C_BACKLOG",
207
+ slackThreadTs: "BACKLOG.0",
208
+ });
209
+ const threeDaysAgo = new Date(Date.now() - 3 * 24 * 60 * 60 * 1000).toISOString();
210
+ getDb().run(
211
+ "UPDATE agent_tasks SET status = 'backlog', agentId = NULL, createdAt = ?, lastUpdatedAt = ? WHERE id = ?",
212
+ [threeDaysAgo, threeDaysAgo, task.id],
213
+ );
214
+ // In backlog: no tree yet, by design.
215
+ expect((await getSlackTasksMissingTree()).map((t) => t.id)).not.toContain(task.id);
216
+
217
+ // Released and claimed: the status change bumps lastUpdatedAt.
218
+ expect(await moveTaskFromBacklog(task.id)).not.toBeNull();
219
+ expect(await claimTask(task.id, lead.id)).not.toBeNull();
220
+
221
+ expect((await getSlackTasksMissingTree()).map((t) => t.id)).toContain(task.id);
222
+ const scoped = await getSlackTasksMissingTree({
223
+ thread: { channelId: "C_BACKLOG", threadTs: "BACKLOG.0" },
224
+ });
225
+ expect(scoped.map((t) => t.id)).toEqual([task.id]);
134
226
  });
135
227
 
136
228
  test("deferral resolution returns the latest terminal wake of each open chain", async () => {
@@ -168,3 +260,170 @@ describe("slack render-v2 watcher queries", () => {
168
260
  );
169
261
  });
170
262
  });
263
+
264
+ async function settledThread(label: string, leadId: string) {
265
+ const channelId = `C_${label}`;
266
+ const threadTs = `${label}.0`;
267
+ const ask = await createTaskExtended(`ask ${label}`, {
268
+ agentId: leadId,
269
+ source: "slack",
270
+ slackChannelId: channelId,
271
+ slackThreadTs: threadTs,
272
+ });
273
+ await startTask(ask.id);
274
+ await completeTask(ask.id, "done");
275
+ const card = await recordSlackMessage({
276
+ contextKey: `slack:${channelId}:${threadTs}`,
277
+ channelId,
278
+ threadTs,
279
+ ts: `${label}.2`,
280
+ kind: "outcome",
281
+ taskId: ask.id,
282
+ finalized: true,
283
+ });
284
+ await Bun.sleep(2);
285
+ const tree = await recordSlackMessage({
286
+ contextKey: `slack:${channelId}:${threadTs}`,
287
+ channelId,
288
+ threadTs,
289
+ ts: `${label}.1`,
290
+ kind: "tree",
291
+ });
292
+ return { ask, card, tree, channelId, threadTs };
293
+ }
294
+
295
+ function closedAt(id: string): string | null {
296
+ return (
297
+ getDb()
298
+ .query<{ closed_at: string | null }, [string]>(
299
+ "SELECT closed_at FROM slack_messages WHERE id = ?",
300
+ )
301
+ .get(id)?.closed_at ?? null
302
+ );
303
+ }
304
+
305
+ /** Tree ids in the sweep's candidate set (idx_slack_messages_open_trees). */
306
+ function openTreeIds(): string[] {
307
+ return getDb()
308
+ .query<{ id: string }, []>(
309
+ "SELECT id FROM slack_messages WHERE kind = 'tree' AND closed_at IS NULL",
310
+ )
311
+ .all()
312
+ .map((row) => row.id);
313
+ }
314
+
315
+ describe("slack render-v2 tree closed_at", () => {
316
+ let leadId: string;
317
+
318
+ beforeEach(async () => {
319
+ initDb(":memory:");
320
+ getDb().run(
321
+ "INSERT OR IGNORE INTO slack_render_v2_state (id, activated_at) VALUES (1, '2000-01-01T00:00:00.000Z')",
322
+ );
323
+ leadId = (await createAgent({ name: "Close Lead", isLead: true, status: "idle" })).id;
324
+ });
325
+
326
+ afterEach(() => {
327
+ closeDb();
328
+ });
329
+
330
+ test("the sweep reads only open trees through the partial index", async () => {
331
+ const sql = await capturedSql(() => getSlackTreeMessages());
332
+ expect(plan(sql)).toContain("SCAN tree USING INDEX idx_slack_messages_open_trees");
333
+ });
334
+
335
+ test("a settled thread closes and drops out of the sweep", async () => {
336
+ const { tree } = await settledThread("SETTLED", leadId);
337
+ // Before close: the tree is open, so the sweep's partial index still
338
+ // visits it. The sweep returns nothing only because the needs-render
339
+ // predicate finds no work in a settled thread.
340
+ expect(openTreeIds()).toContain(tree.id);
341
+ expect(await getSlackTreeMessages()).toEqual([]);
342
+ expect(await closeSlackTreeIfSettled(tree.id)).toBe(true);
343
+ // After close: the tree leaves the open-tree index the sweep scans.
344
+ expect(closedAt(tree.id)).not.toBeNull();
345
+ expect(openTreeIds()).not.toContain(tree.id);
346
+ expect(await getSlackTreeMessages()).toEqual([]);
347
+ // Closing twice is a no-op.
348
+ expect(await closeSlackTreeIfSettled(tree.id)).toBe(false);
349
+ });
350
+
351
+ test("a thread with a running task does not close", async () => {
352
+ const { tree, channelId, threadTs } = await settledThread("RUNNING", leadId);
353
+ const follow = await createTaskExtended("follow-up", {
354
+ agentId: leadId,
355
+ source: "slack",
356
+ slackChannelId: channelId,
357
+ slackThreadTs: threadTs,
358
+ });
359
+ await startTask(follow.id);
360
+ expect(await closeSlackTreeIfSettled(tree.id)).toBe(false);
361
+ expect(closedAt(tree.id)).toBeNull();
362
+ expect((await getSlackTreeMessages()).map((row) => row.id)).toEqual([tree.id]);
363
+ });
364
+
365
+ test("a new task in a closed thread reopens it", async () => {
366
+ const { tree, channelId, threadTs } = await settledThread("REOPEN", leadId);
367
+ expect(await closeSlackTreeIfSettled(tree.id)).toBe(true);
368
+
369
+ await createTaskExtended("new ask in the same thread", {
370
+ agentId: leadId,
371
+ source: "slack",
372
+ slackChannelId: channelId,
373
+ slackThreadTs: threadTs,
374
+ });
375
+ expect(closedAt(tree.id)).toBeNull();
376
+ expect((await getSlackTreeMessages()).map((row) => row.id)).toEqual([tree.id]);
377
+ expect(
378
+ (await getSlackTreeMessages({ thread: { channelId, threadTs } })).map((row) => row.id),
379
+ ).toEqual([tree.id]);
380
+ });
381
+
382
+ test("a status change in a closed thread reopens it", async () => {
383
+ const { ask, tree } = await settledThread("STATUS", leadId);
384
+ expect(await closeSlackTreeIfSettled(tree.id)).toBe(true);
385
+ getDb().run("UPDATE agent_tasks SET status = 'failed' WHERE id = ?", [ask.id]);
386
+ expect(closedAt(tree.id)).toBeNull();
387
+ });
388
+
389
+ test("an outcome card write in a closed thread reopens it", async () => {
390
+ const { card, tree } = await settledThread("CARD", leadId);
391
+ expect(await closeSlackTreeIfSettled(tree.id)).toBe(true);
392
+ await Bun.sleep(2);
393
+ await updateSlackMessageRecord(card.id, { touchUpdatedAt: true });
394
+ expect(closedAt(tree.id)).toBeNull();
395
+ // The touched card is newer than the tree, so the sweep picks it up again.
396
+ expect((await getSlackTreeMessages()).map((row) => row.id)).toEqual([tree.id]);
397
+ });
398
+
399
+ test("a task write in another thread leaves a closed tree closed", async () => {
400
+ const { tree } = await settledThread("QUIET", leadId);
401
+ expect(await closeSlackTreeIfSettled(tree.id)).toBe(true);
402
+ await settledThread("OTHER", leadId);
403
+ expect(closedAt(tree.id)).not.toBeNull();
404
+ });
405
+
406
+ test("migration 278 backfill closes settled trees and keeps open ones open", async () => {
407
+ const settled = await settledThread("BF_SETTLED", leadId);
408
+ const open = await settledThread("BF_OPEN", leadId);
409
+ const running = await createTaskExtended("running", {
410
+ agentId: leadId,
411
+ source: "slack",
412
+ slackChannelId: open.channelId,
413
+ slackThreadTs: open.threadTs,
414
+ });
415
+ await startTask(running.id);
416
+
417
+ const migration = await Bun.file(
418
+ join(import.meta.dir, "../be/migrations/278_slack_render_v2_reconcile.sql"),
419
+ ).text();
420
+ const backfill = migration.slice(
421
+ migration.indexOf("UPDATE slack_messages AS tree"),
422
+ migration.indexOf(";", migration.indexOf("UPDATE slack_messages AS tree")),
423
+ );
424
+ getDb().run(backfill);
425
+
426
+ expect(closedAt(settled.tree.id)).not.toBeNull();
427
+ expect(closedAt(open.tree.id)).toBeNull();
428
+ });
429
+ });
@@ -0,0 +1,201 @@
1
+ import { afterEach, beforeEach, describe, expect, mock, spyOn, test } from "bun:test";
2
+ import {
3
+ closeDb,
4
+ createAgent,
5
+ createTaskExtended,
6
+ getDb,
7
+ getDbClient,
8
+ getSlackTreeMessageByThread,
9
+ initDb,
10
+ } from "../be/db";
11
+ import { startTask } from "../be/db/tasks/write";
12
+ import { workflowEventBus } from "../workflows/event-bus";
13
+
14
+ let messageCounter = 0;
15
+ const mockApiCall = async (method: string, payload: Record<string, unknown> = {}) => {
16
+ messageCounter++;
17
+ return {
18
+ ok: true,
19
+ ts: `${messageCounter}.000100`,
20
+ channel: payload.channel,
21
+ permalink: `https://slack.example/p${messageCounter}`,
22
+ messages: [],
23
+ method,
24
+ };
25
+ };
26
+
27
+ mock.module("../slack/app", () => ({
28
+ getSlackApp: () => ({
29
+ client: {
30
+ apiCall: mockApiCall,
31
+ chat: {
32
+ postMessage: (payload: Record<string, unknown>) => mockApiCall("chat.postMessage", payload),
33
+ },
34
+ reactions: {
35
+ add: (payload: Record<string, unknown>) => mockApiCall("reactions.add", payload),
36
+ remove: (payload: Record<string, unknown>) => mockApiCall("reactions.remove", payload),
37
+ },
38
+ },
39
+ }),
40
+ }));
41
+
42
+ const {
43
+ _resetSlackRenderV2ForTests,
44
+ flushSlackRenderV2DirtyThreads,
45
+ processSlackRenderV2,
46
+ startSlackRenderV2Events,
47
+ } = await import("../slack/render-v2");
48
+ const { DEFAULT_SLACK_TASK_WATCHER_INTERVAL_MS, slackTaskWatcherIntervalMs } = await import(
49
+ "../slack/watcher"
50
+ );
51
+
52
+ type Captured = { sql: string; params: unknown[] };
53
+
54
+ function captureQueries(): { seen: Captured[]; restore: () => void } {
55
+ const client = getDbClient();
56
+ const seen: Captured[] = [];
57
+ const original = client.query.bind(client);
58
+ const spy = spyOn(client, "query").mockImplementation(((sql: string, params?: unknown[]) => {
59
+ seen.push({ sql, params: params ?? [] });
60
+ return original(sql, params);
61
+ }) as typeof client.query);
62
+ return { seen, restore: () => spy.mockRestore() };
63
+ }
64
+
65
+ const isTreeSweep = (q: Captured) => q.sql.includes("SELECT tree.*");
66
+
67
+ let leadId: string;
68
+
69
+ async function runningThread(label: string) {
70
+ const channelId = `C_${label}`;
71
+ const threadTs = `${label}.0`;
72
+ const task = await createTaskExtended(`ask ${label}`, {
73
+ agentId: leadId,
74
+ source: "slack",
75
+ slackChannelId: channelId,
76
+ slackThreadTs: threadTs,
77
+ });
78
+ await startTask(task.id);
79
+ return { task, channelId, threadTs };
80
+ }
81
+
82
+ beforeEach(async () => {
83
+ initDb(":memory:");
84
+ getDb().run(
85
+ "INSERT OR IGNORE INTO slack_render_v2_state (id, activated_at) VALUES (1, '2000-01-01T00:00:00.000Z')",
86
+ );
87
+ process.env.SLACK_RENDER_V2 = "true";
88
+ process.env.SLACK_RENDER_V2_DELEGATION = "false";
89
+ _resetSlackRenderV2ForTests();
90
+ leadId = (await createAgent({ name: "Reconcile Lead", isLead: true, status: "idle" })).id;
91
+ });
92
+
93
+ afterEach(() => {
94
+ _resetSlackRenderV2ForTests();
95
+ closeDb();
96
+ });
97
+
98
+ describe("slack render-v2 reconcile scheduling", () => {
99
+ test("two overlapping reconcile passes run the sweep once", async () => {
100
+ await runningThread("OVERLAP");
101
+ const { seen, restore } = captureQueries();
102
+ try {
103
+ await Promise.all([processSlackRenderV2(), processSlackRenderV2()]);
104
+ } finally {
105
+ restore();
106
+ }
107
+ expect(seen.filter(isTreeSweep)).toHaveLength(1);
108
+ });
109
+
110
+ test("a task event renders only that task's thread", async () => {
111
+ const a = await runningThread("EVENT_A");
112
+ const b = await runningThread("EVENT_B");
113
+ await processSlackRenderV2();
114
+ expect(await getSlackTreeMessageByThread(a.channelId, a.threadTs)).not.toBeNull();
115
+ expect(await getSlackTreeMessageByThread(b.channelId, b.threadTs)).not.toBeNull();
116
+
117
+ startSlackRenderV2Events();
118
+ const { seen, restore } = captureQueries();
119
+ try {
120
+ workflowEventBus.emit("task.progress", { taskId: a.task.id, progress: "working" });
121
+ // The debounced flush runs on its own, without a watcher tick.
122
+ const deadline = Date.now() + 3_000;
123
+ while (!seen.some(isTreeSweep) && Date.now() < deadline) await Bun.sleep(20);
124
+ await flushSlackRenderV2DirtyThreads();
125
+ } finally {
126
+ restore();
127
+ }
128
+ const sweeps = seen.filter(isTreeSweep);
129
+ expect(sweeps).toHaveLength(1);
130
+ expect(sweeps[0]!.params).toEqual([a.channelId, a.threadTs]);
131
+ });
132
+
133
+ test("a flush with nothing queued reads no thread", async () => {
134
+ await runningThread("IDLE");
135
+ await processSlackRenderV2();
136
+ const { seen, restore } = captureQueries();
137
+ try {
138
+ await flushSlackRenderV2DirtyThreads();
139
+ } finally {
140
+ restore();
141
+ }
142
+ expect(seen.filter(isTreeSweep)).toHaveLength(0);
143
+ });
144
+
145
+ test("events for tasks outside Slack threads render nothing", async () => {
146
+ await runningThread("OUTSIDE");
147
+ await processSlackRenderV2();
148
+ const plain = await createTaskExtended("not a Slack task", { agentId: leadId });
149
+ startSlackRenderV2Events();
150
+ const { seen, restore } = captureQueries();
151
+ try {
152
+ workflowEventBus.emit("task.completed", { taskId: plain.id });
153
+ await flushSlackRenderV2DirtyThreads();
154
+ } finally {
155
+ restore();
156
+ }
157
+ expect(seen.filter(isTreeSweep)).toHaveLength(0);
158
+ });
159
+
160
+ test("the full reconcile yields to the event loop between trees", async () => {
161
+ const labels = ["YIELD_A", "YIELD_B", "YIELD_C"];
162
+ for (const label of labels) await runningThread(label);
163
+ await processSlackRenderV2();
164
+ // Count event-loop turns during the pass. A setTimeout(0) probe is clamped
165
+ // to ~1 ms and races a fast pass on CI, so tick with setImmediate instead.
166
+ let turns = 0;
167
+ let ticking = true;
168
+ const tick = () => {
169
+ if (!ticking) return;
170
+ turns++;
171
+ setImmediate(tick);
172
+ };
173
+ setImmediate(tick);
174
+ try {
175
+ await processSlackRenderV2();
176
+ } finally {
177
+ ticking = false;
178
+ }
179
+ expect(turns).toBeGreaterThanOrEqual(labels.length);
180
+ });
181
+ });
182
+
183
+ describe("slack task watcher interval", () => {
184
+ const previous = process.env.SLACK_TASK_WATCHER_INTERVAL_MS;
185
+ afterEach(() => {
186
+ if (previous === undefined) delete process.env.SLACK_TASK_WATCHER_INTERVAL_MS;
187
+ else process.env.SLACK_TASK_WATCHER_INTERVAL_MS = previous;
188
+ });
189
+
190
+ test("defaults to 10 s and honours a positive integer override", () => {
191
+ delete process.env.SLACK_TASK_WATCHER_INTERVAL_MS;
192
+ expect(DEFAULT_SLACK_TASK_WATCHER_INTERVAL_MS).toBe(10_000);
193
+ expect(slackTaskWatcherIntervalMs()).toBe(10_000);
194
+ process.env.SLACK_TASK_WATCHER_INTERVAL_MS = "5000";
195
+ expect(slackTaskWatcherIntervalMs()).toBe(5_000);
196
+ for (const bad of ["0", "-1", "abc", "1.5", ""]) {
197
+ process.env.SLACK_TASK_WATCHER_INTERVAL_MS = bad;
198
+ expect(slackTaskWatcherIntervalMs()).toBe(10_000);
199
+ }
200
+ });
201
+ });