@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
@@ -0,0 +1,146 @@
1
+ import { getDbClient } from "../db";
2
+
3
+ /**
4
+ * True when the tree sweep has render work for `tree` (aliases `tree` and
5
+ * `state` must be in scope). Shared by the sweep (getSlackTreeMessages) and by
6
+ * closeSlackTreeIfSettled, so a closed tree is exactly one the sweep would
7
+ * skip. Migration 278 backfills closed_at with the same predicate; keep the
8
+ * two in step.
9
+ */
10
+ export const SLACK_TREE_NEEDS_RENDER_SQL = `(
11
+ (tree.ts LIKE 'pending:%' AND tree.created_at >= state.activated_at)
12
+ OR EXISTS (
13
+ SELECT 1 FROM agent_tasks task
14
+ WHERE task.slackChannelId = tree.channel_id
15
+ AND task.slackThreadTs = tree.thread_ts
16
+ AND task.source = 'slack'
17
+ AND task.createdAt >= state.activated_at
18
+ AND task.status IN ('completed', 'failed', 'cancelled')
19
+ AND NOT EXISTS (
20
+ SELECT 1 FROM slack_messages outcome
21
+ WHERE outcome.kind = 'outcome'
22
+ AND outcome.task_id = task.id
23
+ AND (outcome.finalized_at IS NOT NULL OR outcome.delivery_abandoned_at IS NOT NULL)
24
+ )
25
+ )
26
+ OR
27
+ EXISTS (
28
+ SELECT 1 FROM agent_tasks task
29
+ WHERE task.slackChannelId = tree.channel_id
30
+ AND task.slackThreadTs = tree.thread_ts
31
+ AND task.createdAt >= state.activated_at
32
+ AND task.status NOT IN ('completed', 'failed', 'cancelled', 'superseded', 'skipped')
33
+ )
34
+ OR EXISTS (
35
+ SELECT 1 FROM agent_tasks task
36
+ WHERE task.slackChannelId = tree.channel_id
37
+ AND task.slackThreadTs = tree.thread_ts
38
+ AND task.createdAt >= state.activated_at
39
+ AND task.lastUpdatedAt > tree.updated_at
40
+ )
41
+ OR EXISTS (
42
+ SELECT 1 FROM slack_messages outcome
43
+ JOIN agent_tasks task ON task.id = outcome.task_id
44
+ WHERE outcome.kind = 'outcome'
45
+ AND outcome.channel_id = tree.channel_id
46
+ AND outcome.thread_ts = tree.thread_ts
47
+ AND task.createdAt >= state.activated_at
48
+ AND (
49
+ (outcome.finalized_at IS NULL AND outcome.delivery_abandoned_at IS NULL)
50
+ OR outcome.updated_at > tree.updated_at
51
+ )
52
+ )
53
+ )`;
54
+
55
+ /**
56
+ * Close a tree once the sweep has nothing left to do for it: every task in
57
+ * the thread is terminal, every outcome card is finalized or abandoned, and no
58
+ * task or card changed after the tree. One statement, so a write that lands
59
+ * before it is seen by the predicate; a write after it reopens the tree
60
+ * through migration 278's triggers. Returns true when the tree was closed.
61
+ */
62
+ export async function closeSlackTreeIfSettled(id: string): Promise<boolean> {
63
+ const result = await getDbClient().run(
64
+ `UPDATE slack_messages AS tree SET closed_at = ?
65
+ WHERE tree.id = ?
66
+ AND tree.kind = 'tree'
67
+ AND tree.closed_at IS NULL
68
+ AND tree.ts NOT LIKE 'pending:%'
69
+ AND EXISTS (
70
+ SELECT 1 FROM slack_render_v2_state state
71
+ WHERE state.id = 1 AND NOT ${SLACK_TREE_NEEDS_RENDER_SQL}
72
+ )`,
73
+ [new Date().toISOString(), id],
74
+ );
75
+ return result.changes > 0;
76
+ }
77
+
78
+ const THREAD_LOOKUP_CHUNK = 500;
79
+
80
+ /**
81
+ * The Slack threads the given tasks belong to, for the event-driven render.
82
+ * `wakeTouched` is true when any of them is a deferral wake-up, whose
83
+ * settling can resolve a ⏳ card in another thread.
84
+ */
85
+ export async function getSlackThreadsOfTasks(taskIds: string[]): Promise<{
86
+ threads: { channelId: string; threadTs: string }[];
87
+ wakeTouched: boolean;
88
+ }> {
89
+ const threads = new Map<string, { channelId: string; threadTs: string }>();
90
+ let wakeTouched = false;
91
+ for (let i = 0; i < taskIds.length; i += THREAD_LOOKUP_CHUNK) {
92
+ const chunk = taskIds.slice(i, i + THREAD_LOOKUP_CHUNK);
93
+ const rows = await getDbClient().query<{
94
+ slackChannelId: string | null;
95
+ slackThreadTs: string | null;
96
+ taskType: string | null;
97
+ }>(
98
+ `SELECT slackChannelId, slackThreadTs, taskType FROM agent_tasks
99
+ WHERE id IN (${chunk.map(() => "?").join(",")})`,
100
+ chunk,
101
+ );
102
+ for (const row of rows) {
103
+ if (row.taskType === "deferred") wakeTouched = true;
104
+ if (!row.slackChannelId || !row.slackThreadTs) continue;
105
+ threads.set(`${row.slackChannelId}\u0000${row.slackThreadTs}`, {
106
+ channelId: row.slackChannelId,
107
+ threadTs: row.slackThreadTs,
108
+ });
109
+ }
110
+ }
111
+ return { threads: [...threads.values()], wakeTouched };
112
+ }
113
+
114
+ /**
115
+ * True while the thread still owes an outcome card: a terminal Slack task
116
+ * whose card is not finalized or abandoned, or a card still in flight. These
117
+ * wait on time (conclusion settle, delivery backoff), not on a task event.
118
+ */
119
+ export async function slackThreadHasOutcomeWork(thread: {
120
+ channelId: string;
121
+ threadTs: string;
122
+ }): Promise<boolean> {
123
+ const row = await getDbClient().get<{ pending: number }>(
124
+ `SELECT EXISTS (
125
+ SELECT 1 FROM agent_tasks task, slack_render_v2_state state
126
+ WHERE state.id = 1
127
+ AND task.slackChannelId = ? AND task.slackThreadTs = ?
128
+ AND task.source = 'slack'
129
+ AND task.createdAt >= state.activated_at
130
+ AND task.status IN ('completed', 'failed', 'cancelled')
131
+ AND NOT EXISTS (
132
+ SELECT 1 FROM slack_messages outcome
133
+ WHERE outcome.kind = 'outcome'
134
+ AND outcome.task_id = task.id
135
+ AND (outcome.finalized_at IS NOT NULL OR outcome.delivery_abandoned_at IS NOT NULL)
136
+ )
137
+ ) OR EXISTS (
138
+ SELECT 1 FROM slack_messages outcome
139
+ WHERE outcome.kind = 'outcome'
140
+ AND outcome.channel_id = ? AND outcome.thread_ts = ?
141
+ AND outcome.finalized_at IS NULL AND outcome.delivery_abandoned_at IS NULL
142
+ ) AS pending`,
143
+ [thread.channelId, thread.threadTs, thread.channelId, thread.threadTs],
144
+ );
145
+ return !!row?.pending;
146
+ }
@@ -1607,13 +1607,50 @@ export async function getInProgressSlackTasks(): Promise<AgentTask[]> {
1607
1607
  return rows.map(rowToAgentTask);
1608
1608
  }
1609
1609
 
1610
- export async function getSlackTasksMissingTree(): Promise<AgentTask[]> {
1610
+ /** How far back the missing-tree sweep looks for Slack tasks without a tree. */
1611
+ const SLACK_MISSING_TREE_WINDOW_MS = 24 * 60 * 60 * 1000;
1612
+
1613
+ /**
1614
+ * Slack tasks (created since render-v2 activation) whose thread has no tree
1615
+ * row yet.
1616
+ *
1617
+ * The full sweep reads only tasks updated in the last 24 h. The bound is on
1618
+ * lastUpdatedAt, not createdAt: a task that waits in backlog/unassigned for
1619
+ * days gets a fresh lastUpdatedAt when it leaves that status, so it re-enters
1620
+ * the window exactly when it starts to need a tree. idx_agent_tasks_slack_last_updated
1621
+ * makes the bound a range seek and also serves the ORDER BY. INDEXED BY:
1622
+ * without ANALYZE statistics the planner otherwise picks a wider index.
1623
+ *
1624
+ * `thread` scopes the query to one thread (event-driven render). It seeks the
1625
+ * thread through idx_agent_tasks_slack_thread_cover and has no time window,
1626
+ * so an old task in that thread is never skipped.
1627
+ */
1628
+ export async function getSlackTasksMissingTree(
1629
+ options: { now?: Date; thread?: { channelId: string; threadTs: string } } = {},
1630
+ ): Promise<AgentTask[]> {
1631
+ const thread = options.thread;
1632
+ const since = new Date(
1633
+ (options.now ?? new Date()).getTime() - SLACK_MISSING_TREE_WINDOW_MS,
1634
+ ).toISOString();
1635
+ const scope = thread
1636
+ ? {
1637
+ index: "idx_agent_tasks_slack_thread_cover",
1638
+ sql: "AND task.slackChannelId = ? AND task.slackThreadTs = ?",
1639
+ params: [thread.channelId, thread.threadTs],
1640
+ }
1641
+ : {
1642
+ index: "idx_agent_tasks_slack_last_updated",
1643
+ sql: "AND task.lastUpdatedAt >= ?",
1644
+ params: [since],
1645
+ };
1611
1646
  const rows = await getDbClient().query<AgentTaskRow>(
1612
- `SELECT task.* FROM agent_tasks task
1613
- JOIN slack_render_v2_state state ON state.id = 1
1614
- WHERE task.source = 'slack'
1647
+ `SELECT task.* FROM slack_render_v2_state state
1648
+ CROSS JOIN agent_tasks task INDEXED BY ${scope.index}
1649
+ WHERE state.id = 1
1650
+ AND task.source = 'slack'
1615
1651
  AND task.slackChannelId IS NOT NULL
1616
1652
  AND task.slackThreadTs IS NOT NULL
1653
+ ${scope.sql}
1617
1654
  AND task.createdAt >= state.activated_at
1618
1655
  AND task.status NOT IN ('backlog', 'unassigned', 'superseded')
1619
1656
  AND NOT EXISTS (
@@ -1631,6 +1668,7 @@ export async function getSlackTasksMissingTree(): Promise<AgentTask[]> {
1631
1668
  )
1632
1669
  ORDER BY task.lastUpdatedAt DESC
1633
1670
  LIMIT 200`,
1671
+ scope.params,
1634
1672
  );
1635
1673
  return rows.map(rowToAgentTask);
1636
1674
  }
@@ -1740,14 +1778,28 @@ export async function findExistingLinearTrackerContextWork(
1740
1778
  return null;
1741
1779
  }
1742
1780
 
1743
- export async function getLatestTaskByContextKey(contextKey: string): Promise<AgentTask | null> {
1781
+ /**
1782
+ * Latest task on a contextKey. `requestedByUserId` keeps only that user's
1783
+ * tasks; `notRequestedByUserId` keeps only tasks of anyone else, including
1784
+ * tasks with no requester.
1785
+ */
1786
+ export async function getLatestTaskByContextKey(
1787
+ contextKey: string,
1788
+ options: { requestedByUserId?: string; notRequestedByUserId?: string } = {},
1789
+ ): Promise<AgentTask | null> {
1744
1790
  if (!contextKey) return null;
1745
1791
  const row = await getDbClient().get<AgentTaskRow>(
1746
1792
  `SELECT * FROM agent_tasks
1747
1793
  WHERE contextKey = ?
1794
+ ${options.requestedByUserId !== undefined ? "AND requestedByUserId = ?" : ""}
1795
+ ${options.notRequestedByUserId !== undefined ? "AND requestedByUserId IS NOT ?" : ""}
1748
1796
  ORDER BY createdAt DESC
1749
1797
  LIMIT 1`,
1750
- [contextKey],
1798
+ [
1799
+ contextKey,
1800
+ ...(options.requestedByUserId !== undefined ? [options.requestedByUserId] : []),
1801
+ ...(options.notRequestedByUserId !== undefined ? [options.notRequestedByUserId] : []),
1802
+ ],
1751
1803
  );
1752
1804
  return row ? rowToAgentTask(row) : null;
1753
1805
  }
@@ -1889,19 +1941,62 @@ export async function getAgentWorkingOnContextKey(
1889
1941
  return null;
1890
1942
  }
1891
1943
 
1944
+ /**
1945
+ * Latest task whose contextKey starts with `prefix` (a half-open key range, so
1946
+ * the contextKey index serves it). The Chat SDK keys a Slack or Discord task by
1947
+ * `<channel>:<thread>`, while a slash command only knows the channel: the
1948
+ * prefix finds the tasks of every thread in it. `activeOnly` narrows to
1949
+ * `in_progress` and `pending`; `source` narrows as in the exact-key twins;
1950
+ * `requestedByUserId` keeps only that user's tasks.
1951
+ */
1952
+ export async function getLatestTaskByContextKeyPrefix(
1953
+ prefix: string,
1954
+ options: { activeOnly?: boolean; source?: string; requestedByUserId?: string } = {},
1955
+ ): Promise<AgentTask | null> {
1956
+ if (!prefix) return null;
1957
+ const upper = prefix.slice(0, -1) + String.fromCharCode(prefix.charCodeAt(prefix.length - 1) + 1);
1958
+ const source = options.source ?? null;
1959
+ const row = await getDbClient().get<AgentTaskRow>(
1960
+ `SELECT * FROM agent_tasks
1961
+ WHERE contextKey >= ? AND contextKey < ?
1962
+ AND ${contextKeySourceSql()}
1963
+ ${options.activeOnly ? "AND status IN ('in_progress', 'pending')" : ""}
1964
+ ${options.requestedByUserId !== undefined ? "AND requestedByUserId = ?" : ""}
1965
+ ORDER BY createdAt DESC, rowid DESC
1966
+ LIMIT 1`,
1967
+ [
1968
+ prefix,
1969
+ upper,
1970
+ source,
1971
+ source,
1972
+ source,
1973
+ ...(options.requestedByUserId !== undefined ? [options.requestedByUserId] : []),
1974
+ ],
1975
+ );
1976
+ return row ? rowToAgentTask(row) : null;
1977
+ }
1978
+
1892
1979
  /** Latest `in_progress` or `pending` task on a contextKey (dependency chaining). */
1893
1980
  export async function getLatestActiveTaskByContextKey(
1894
1981
  contextKey: string,
1895
1982
  source?: string,
1983
+ requestedByUserId?: string,
1896
1984
  ): Promise<AgentTask | null> {
1897
1985
  const row = await getDbClient().get<AgentTaskRow>(
1898
1986
  `SELECT * FROM agent_tasks
1899
1987
  WHERE contextKey = ?
1900
1988
  AND ${contextKeySourceSql()}
1901
1989
  AND status IN ('in_progress', 'pending')
1990
+ ${requestedByUserId !== undefined ? "AND requestedByUserId = ?" : ""}
1902
1991
  ORDER BY createdAt DESC, rowid DESC
1903
1992
  LIMIT 1`,
1904
- [contextKey, source ?? null, source ?? null, source ?? null],
1993
+ [
1994
+ contextKey,
1995
+ source ?? null,
1996
+ source ?? null,
1997
+ source ?? null,
1998
+ ...(requestedByUserId !== undefined ? [requestedByUserId] : []),
1999
+ ],
1905
2000
  );
1906
2001
 
1907
2002
  return row ? rowToAgentTask(row) : null;
@@ -1,6 +1,7 @@
1
1
  import type { Database } from "bun:sqlite";
2
2
  import { AsyncLocalStorage } from "node:async_hooks";
3
3
  import { scrubSecrets } from "../utils/secret-scrubber";
4
+ import { currentLoopPath, recordStatement } from "./event-loop-lag";
4
5
 
5
6
  /**
6
7
  * Async database seam.
@@ -216,14 +217,19 @@ const SLOW_STATEMENT_SQL_MAX_CHARS = 200;
216
217
 
217
218
  /** Params are never logged: they can carry secrets and user content. */
218
219
  function warnIfSlowStatement(sql: string, durationMs: number): void {
220
+ recordStatement(sql, durationMs);
219
221
  if (durationMs < SLOW_STATEMENT_WARN_MS) return;
220
- const flat = sql.replace(/\s+/g, " ").trim();
222
+ // Scrub the complete SQL before truncation, so a secret that straddles the
223
+ // cut cannot leave a partial token, then scrub the complete line at egress.
224
+ const flat = scrubSecrets(sql.replace(/\s+/g, " ").trim());
221
225
  const shown =
222
226
  flat.length > SLOW_STATEMENT_SQL_MAX_CHARS
223
227
  ? `${flat.slice(0, SLOW_STATEMENT_SQL_MAX_CHARS)}…`
224
228
  : flat;
225
229
  console.warn(
226
- `[db-client] slow sync statement blocked the event loop for ${Math.round(durationMs)}ms: ${scrubSecrets(shown)}`,
230
+ scrubSecrets(
231
+ `[db-client] slow sync statement blocked the event loop for ${Math.round(durationMs)}ms path=${currentLoopPath()}: ${shown}`,
232
+ ),
227
233
  );
228
234
  }
229
235
 
package/src/be/db.ts CHANGED
@@ -217,6 +217,7 @@ import {
217
217
  threadRootsSql,
218
218
  } from "./db/session-tree";
219
219
  import { searchSkillRowsRanked } from "./db/skill-search";
220
+ import { SLACK_TREE_NEEDS_RENDER_SQL } from "./db/slack-trees";
220
221
  import { classifyTaskHumanFree, reclassifyTaskHumanFree } from "./db/tasks/human-free";
221
222
  import {
222
223
  type AgentTaskRow,
@@ -367,6 +368,7 @@ export {
367
368
  getLatestLeadTaskInThread,
368
369
  getLatestScriptRunStepTaskByContextKey,
369
370
  getLatestTaskByContextKey,
371
+ getLatestTaskByContextKeyPrefix,
370
372
  getMostRecentTaskInThread,
371
373
  getPendingChatRelayTasks,
372
374
  getPendingSlackRelayTasks,
@@ -596,6 +598,8 @@ export interface SlackMessageRecord {
596
598
  deliveryAbandonedAt?: string;
597
599
  /** Last Slack verdict for the card, "<code>: <messages>", 500 chars max. */
598
600
  deliveryLastError?: string;
601
+ /** Tree rows only: set once the thread has no render work left. */
602
+ closedAt?: string;
599
603
  createdAt: string;
600
604
  updatedAt: string;
601
605
  }
@@ -628,6 +632,7 @@ type SlackMessageRow = {
628
632
  delivery_attempts: number;
629
633
  delivery_abandoned_at: string | null;
630
634
  delivery_last_error: string | null;
635
+ closed_at: string | null;
631
636
  created_at: string;
632
637
  updated_at: string;
633
638
  };
@@ -650,6 +655,7 @@ function rowToSlackMessage(row: SlackMessageRow): SlackMessageRecord {
650
655
  deliveryAttempts: row.delivery_attempts,
651
656
  deliveryAbandonedAt: row.delivery_abandoned_at ?? undefined,
652
657
  deliveryLastError: row.delivery_last_error ?? undefined,
658
+ closedAt: row.closed_at ?? undefined,
653
659
  createdAt: row.created_at,
654
660
  updatedAt: row.updated_at,
655
661
  };
@@ -872,15 +878,20 @@ export async function getSlackOutcomeMessage(taskId: string): Promise<SlackMessa
872
878
  *
873
879
  * CROSS JOIN and `+wake.taskType` pin the join order to the small chain. Without
874
880
  * them the planner drives the outer join from every terminal task (~1s at 150k tasks).
881
+ * The anchor drives from the partial index idx_agent_tasks_deferred (tasks
882
+ * that ever deferred), not from every outcome card: `deferral_resolved_at IS
883
+ * NULL` stays true forever on cards of tasks that never deferred.
884
+ * `+child.taskType` does the same for the NOT EXISTS: without it the planner
885
+ * walks every deferred-type task through idx_agent_tasks_list_filter per row.
875
886
  */
876
887
  export async function getResolvableDeferralOutcomes(
877
888
  limit = 50,
878
889
  ): Promise<{ card: SlackMessageRecord; deferredTaskId: string; wakeTaskId: string }[]> {
879
890
  const rows = await getDbClient().query<SlackMessageRow & { wake_task_id: string }>(
880
891
  `WITH RECURSIVE chain(card_id, task_id) AS (
881
- SELECT card.id, deferred.id FROM slack_messages card
882
- JOIN agent_tasks deferred ON deferred.id = card.task_id
883
- WHERE card.kind = 'outcome' AND deferred.deferredAt IS NOT NULL
892
+ SELECT card.id, deferred.id FROM agent_tasks deferred
893
+ CROSS JOIN slack_messages card ON card.task_id = deferred.id AND card.kind = 'outcome'
894
+ WHERE deferred.deferredAt IS NOT NULL
884
895
  AND card.deferral_resolved_at IS NULL AND card.finalized_at IS NOT NULL
885
896
  AND card.ts NOT LIKE 'pending:%'
886
897
  UNION
@@ -898,7 +909,7 @@ export async function getResolvableDeferralOutcomes(
898
909
  AND card.ts NOT LIKE 'pending:%'
899
910
  AND NOT EXISTS (
900
911
  SELECT 1 FROM agent_tasks child
901
- WHERE child.parentTaskId = wake.id AND child.taskType = 'deferred'
912
+ WHERE child.parentTaskId = wake.id AND +child.taskType = 'deferred'
902
913
  )
903
914
  AND (wake.deferredAt IS NULL OR wake.finishedAt > card.updated_at)
904
915
  AND wake.status IN ('completed', 'failed', 'cancelled', 'skipped')
@@ -968,57 +979,26 @@ export async function abandonSlackOutcomeDelivery(
968
979
  return row ? rowToSlackMessage(row) : null;
969
980
  }
970
981
 
971
- export async function getSlackTreeMessages(): Promise<SlackMessageRecord[]> {
982
+ /**
983
+ * Trees with pending render work. Reads only open trees (closed_at IS NULL,
984
+ * idx_slack_messages_open_trees): a settled thread is closed after its render
985
+ * pass and reopened by migration 278's triggers on any task or outcome write
986
+ * in the thread. `thread` scopes the sweep to one thread (event-driven render).
987
+ */
988
+ export async function getSlackTreeMessages(
989
+ options: { thread?: { channelId: string; threadTs: string } } = {},
990
+ ): Promise<SlackMessageRecord[]> {
991
+ const thread = options.thread;
972
992
  const rows = await getDbClient().query<SlackMessageRow>(
973
993
  `SELECT tree.*
974
994
  FROM slack_messages tree
975
995
  JOIN slack_render_v2_state state ON state.id = 1
976
996
  WHERE tree.kind = 'tree'
977
- AND (
978
- (tree.ts LIKE 'pending:%' AND tree.created_at >= state.activated_at)
979
- OR EXISTS (
980
- SELECT 1 FROM agent_tasks task
981
- WHERE task.slackChannelId = tree.channel_id
982
- AND task.slackThreadTs = tree.thread_ts
983
- AND task.source = 'slack'
984
- AND task.createdAt >= state.activated_at
985
- AND task.status IN ('completed', 'failed', 'cancelled')
986
- AND NOT EXISTS (
987
- SELECT 1 FROM slack_messages outcome
988
- WHERE outcome.kind = 'outcome'
989
- AND outcome.task_id = task.id
990
- AND (outcome.finalized_at IS NOT NULL OR outcome.delivery_abandoned_at IS NOT NULL)
991
- )
992
- )
993
- OR
994
- EXISTS (
995
- SELECT 1 FROM agent_tasks task
996
- WHERE task.slackChannelId = tree.channel_id
997
- AND task.slackThreadTs = tree.thread_ts
998
- AND task.createdAt >= state.activated_at
999
- AND task.status NOT IN ('completed', 'failed', 'cancelled', 'superseded', 'skipped')
1000
- )
1001
- OR EXISTS (
1002
- SELECT 1 FROM agent_tasks task
1003
- WHERE task.slackChannelId = tree.channel_id
1004
- AND task.slackThreadTs = tree.thread_ts
1005
- AND task.createdAt >= state.activated_at
1006
- AND task.lastUpdatedAt > tree.updated_at
1007
- )
1008
- OR EXISTS (
1009
- SELECT 1 FROM slack_messages outcome
1010
- JOIN agent_tasks task ON task.id = outcome.task_id
1011
- WHERE outcome.kind = 'outcome'
1012
- AND outcome.channel_id = tree.channel_id
1013
- AND outcome.thread_ts = tree.thread_ts
1014
- AND task.createdAt >= state.activated_at
1015
- AND (
1016
- (outcome.finalized_at IS NULL AND outcome.delivery_abandoned_at IS NULL)
1017
- OR outcome.updated_at > tree.updated_at
1018
- )
1019
- )
1020
- )
997
+ AND tree.closed_at IS NULL
998
+ ${thread ? "AND tree.channel_id = ? AND tree.thread_ts = ?" : ""}
999
+ AND ${SLACK_TREE_NEEDS_RENDER_SQL}
1021
1000
  ORDER BY tree.created_at ASC`,
1001
+ thread ? [thread.channelId, thread.threadTs] : [],
1022
1002
  );
1023
1003
  return rows.map(rowToSlackMessage);
1024
1004
  }
@@ -2621,32 +2601,44 @@ export async function createTaskExtended(
2621
2601
  // Webhook handlers locate active work via `findTaskByVcs(repo, number, provider)`,
2622
2602
  // so a resume / follow-up child MUST carry the full VCS identity or
2623
2603
  // subsequent review/update events get dropped.
2624
- if (parent.vcsProvider && !options.vcsProvider) {
2625
- options.vcsProvider = parent.vcsProvider;
2626
- }
2627
- if (parent.vcsRepo && !options.vcsRepo) {
2628
- options.vcsRepo = parent.vcsRepo;
2629
- }
2630
- if (parent.vcsNumber != null && options.vcsNumber == null) {
2631
- options.vcsNumber = parent.vcsNumber;
2632
- }
2633
- if (parent.vcsEventType && !options.vcsEventType) {
2634
- options.vcsEventType = parent.vcsEventType;
2635
- }
2636
- if (parent.vcsCommentId != null && options.vcsCommentId == null) {
2637
- options.vcsCommentId = parent.vcsCommentId;
2638
- }
2639
- if (parent.vcsAuthor && !options.vcsAuthor) {
2640
- options.vcsAuthor = parent.vcsAuthor;
2641
- }
2642
- if (parent.vcsUrl && !options.vcsUrl) {
2643
- options.vcsUrl = parent.vcsUrl;
2644
- }
2645
- if (parent.vcsInstallationId != null && options.vcsInstallationId == null) {
2646
- options.vcsInstallationId = parent.vcsInstallationId;
2647
- }
2648
- if (parent.vcsNodeId && !options.vcsNodeId) {
2649
- options.vcsNodeId = parent.vcsNodeId;
2604
+ //
2605
+ // Inherited as an atomic unit, like Slack context above: a child that
2606
+ // names its own vcsRepo different from the parent's (e.g. `send-task
2607
+ // vcsRepo=...`) inherits NONE of the parent's vcs* fields. Otherwise it
2608
+ // would pair its repo with the parent's number/URL, so PR reconciliation
2609
+ // attaches the parent's PR as the child's deliverable and
2610
+ // `findTaskByVcs` matches an unrelated PR with the same number.
2611
+ const inheritParentVcs =
2612
+ !options.vcsRepo ||
2613
+ (!!parent.vcsRepo && options.vcsRepo.toLowerCase() === parent.vcsRepo.toLowerCase());
2614
+ if (inheritParentVcs) {
2615
+ if (parent.vcsProvider && !options.vcsProvider) {
2616
+ options.vcsProvider = parent.vcsProvider;
2617
+ }
2618
+ if (parent.vcsRepo && !options.vcsRepo) {
2619
+ options.vcsRepo = parent.vcsRepo;
2620
+ }
2621
+ if (parent.vcsNumber != null && options.vcsNumber == null) {
2622
+ options.vcsNumber = parent.vcsNumber;
2623
+ }
2624
+ if (parent.vcsEventType && !options.vcsEventType) {
2625
+ options.vcsEventType = parent.vcsEventType;
2626
+ }
2627
+ if (parent.vcsCommentId != null && options.vcsCommentId == null) {
2628
+ options.vcsCommentId = parent.vcsCommentId;
2629
+ }
2630
+ if (parent.vcsAuthor && !options.vcsAuthor) {
2631
+ options.vcsAuthor = parent.vcsAuthor;
2632
+ }
2633
+ if (parent.vcsUrl && !options.vcsUrl) {
2634
+ options.vcsUrl = parent.vcsUrl;
2635
+ }
2636
+ if (parent.vcsInstallationId != null && options.vcsInstallationId == null) {
2637
+ options.vcsInstallationId = parent.vcsInstallationId;
2638
+ }
2639
+ if (parent.vcsNodeId && !options.vcsNodeId) {
2640
+ options.vcsNodeId = parent.vcsNodeId;
2641
+ }
2650
2642
  }
2651
2643
 
2652
2644
  // Execution context (per-task overrides)
@@ -13895,16 +13887,35 @@ export async function sweepExpiredKv(namespace: string, now = Date.now()): Promi
13895
13887
  /** Delete expired entries across a namespace family (`prefix` and
13896
13888
  * `prefix:*`). Used by per-agent internal stores whose inactive owners may
13897
13889
  * never return to trigger a namespace-local sweep. */
13898
- export async function sweepExpiredKvPrefix(prefix: string, now = Date.now()): Promise<number> {
13890
+ export async function sweepExpiredKvPrefix(
13891
+ prefix: string,
13892
+ now = Date.now(),
13893
+ /** Rows per DELETE, capped at 50 for multi-MB values. Yields between batches. */
13894
+ batchSize = 50,
13895
+ ): Promise<number> {
13896
+ batchSize = Math.max(1, Math.min(batchSize, 50));
13899
13897
  const escaped = prefix.replace(/[\\%_]/g, "\\$&");
13900
- const result = await getDbClient().run(
13901
- `DELETE FROM kv_entries
13902
- WHERE (namespace = ? OR namespace LIKE ? ESCAPE '\\')
13903
- AND expires_at IS NOT NULL
13904
- AND expires_at <= ?`,
13905
- [prefix, `${escaped}:%`, now],
13906
- );
13907
- return result.changes;
13898
+ // Batched, with a macrotask yield between batches: one DELETE of every
13899
+ // expired multi-MB overflow row blocked the event loop for seconds and
13900
+ // starved the Slack socket ping. `now` is fixed for the whole sweep, so the
13901
+ // batches delete the same row set as one statement. kv_entries is WITHOUT
13902
+ // ROWID, so a batch selects the (namespace, key) primary key.
13903
+ let removed = 0;
13904
+ for (;;) {
13905
+ const result = await getDbClient().run(
13906
+ `DELETE FROM kv_entries
13907
+ WHERE (namespace, key) IN (
13908
+ SELECT namespace, key FROM kv_entries
13909
+ WHERE (namespace = ? OR namespace LIKE ? ESCAPE '\\')
13910
+ AND expires_at IS NOT NULL
13911
+ AND expires_at <= ?
13912
+ LIMIT ?)`,
13913
+ [prefix, `${escaped}:%`, now, batchSize],
13914
+ );
13915
+ removed += result.changes;
13916
+ if (result.changes < batchSize) return removed;
13917
+ await new Promise<void>((resolve) => setImmediate(resolve));
13918
+ }
13908
13919
  }
13909
13920
 
13910
13921
  /**