@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
@@ -27,6 +27,11 @@ import {
27
27
  type SlackMessageRecord,
28
28
  updateSlackMessageRecord,
29
29
  } from "../be/db";
30
+ import {
31
+ closeSlackTreeIfSettled,
32
+ getSlackThreadsOfTasks,
33
+ slackThreadHasOutcomeWork,
34
+ } from "../be/db/slack-trees";
30
35
  import { getTaskCitations } from "../be/task-citations";
31
36
  import { slackContextKey } from "../tasks/context-key";
32
37
  import type { AgentTask, TaskAttachment } from "../types";
@@ -35,6 +40,7 @@ import { isEnvFlagEnabled } from "../utils/env-flag";
35
40
  import { scrubSecrets } from "../utils/secret-scrubber";
36
41
  import { taskAttachmentDisplayUrl } from "../utils/task-attachment-links";
37
42
  import { renderTaskCitations, taskCitationSourceGroups } from "../utils/task-citations";
43
+ import { workflowEventBus } from "../workflows/event-bus";
38
44
  import {
39
45
  finalizeSlackMessageReaction,
40
46
  finalizeSlackSteerReactions,
@@ -1612,6 +1618,8 @@ export async function refreshResolvedDeferralCards(): Promise<void> {
1612
1618
  } else {
1613
1619
  await markSlackDeferralResolved(card.id);
1614
1620
  }
1621
+ // The rewrite changes the card, so the thread's tree re-renders next tick.
1622
+ markSlackThreadDirty(card.channelId, card.threadTs);
1615
1623
  deferralRefreshAttempts.delete(card.id);
1616
1624
  // The rewrite is the wake-up's outcome, so it settles the ask's reaction.
1617
1625
  if (!isDeferredTask(wake)) await finalizeTerminalSlackReactions([wake]);
@@ -1638,257 +1646,457 @@ export async function refreshResolvedDeferralCards(): Promise<void> {
1638
1646
  }
1639
1647
  }
1640
1648
 
1641
- export async function processSlackRenderV2(): Promise<void> {
1642
- if (!isSlackRenderV2Enabled()) return;
1643
- const activatedAt = await ensureSlackRenderV2Activation();
1644
- const delegationEnabled = isSlackDelegationEnabled();
1645
- const delegationActivatedAt = delegationEnabled ? await ensureSlackDelegationActivation() : null;
1646
- const statusTick = beginSlackStatusTick();
1649
+ type RenderPassContext = {
1650
+ activatedAt: string;
1651
+ delegationEnabled: boolean;
1652
+ delegationActivatedAt: string | null;
1653
+ statusTick: ReturnType<typeof beginSlackStatusTick>;
1654
+ };
1647
1655
 
1648
- for (const task of await getSlackTasksMissingTree()) {
1649
- if (!isSlackRenderV2Enabled()) return;
1650
- if (!task.slackChannelId || !task.slackThreadTs) continue;
1656
+ /**
1657
+ * One tree's render pass: outcome, child and conclusion cards, the tree
1658
+ * itself, the session status, then the close check. "stop" means render v2
1659
+ * was switched off mid-pass; "skipped" that the pass bailed out early (an
1660
+ * error, or a pending tree that could not be recovered).
1661
+ */
1662
+ async function renderStoredTree(
1663
+ storedTree: SlackMessageRecord,
1664
+ { activatedAt, delegationEnabled, delegationActivatedAt, statusTick }: RenderPassContext,
1665
+ ): Promise<"stop" | "skipped" | "open" | "closed"> {
1666
+ if (!isSlackRenderV2Enabled()) return "stop";
1667
+ let tree = storedTree;
1668
+ const initialTasks = await getSlackTasksInThread(tree.channelId, tree.threadTs);
1669
+ if (isPendingSlackMessage(tree)) {
1651
1670
  try {
1652
- await ensureSlackThreadTree([task.id], statusTick.budget);
1671
+ const recovered = await ensureSlackThreadTree(
1672
+ initialTasks.map((task) => task.id),
1673
+ statusTick.budget,
1674
+ );
1675
+ if (!recovered) return "skipped";
1676
+ tree = recovered;
1653
1677
  } catch (error) {
1654
- console.error(`[Slack] Failed to create v2 tree for task ${task.id}:`, error);
1678
+ console.error(`[Slack] Failed to recover pending v2 tree ${tree.id}:`, error);
1679
+ return "skipped";
1655
1680
  }
1656
1681
  }
1657
-
1658
- for (const storedTree of await getSlackTreeMessages()) {
1659
- if (!isSlackRenderV2Enabled()) return;
1660
- let tree = storedTree;
1661
- const initialTasks = await getSlackTasksInThread(tree.channelId, tree.threadTs);
1662
- if (isPendingSlackMessage(tree)) {
1663
- try {
1664
- const recovered = await ensureSlackThreadTree(
1665
- initialTasks.map((task) => task.id),
1666
- statusTick.budget,
1667
- );
1668
- if (!recovered) continue;
1669
- tree = recovered;
1670
- } catch (error) {
1671
- console.error(`[Slack] Failed to recover pending v2 tree ${tree.id}:`, error);
1672
- continue;
1673
- }
1674
- }
1675
- const app = getSlackApp();
1676
- if (app && !tree.permalink) {
1677
- try {
1678
- tree = await ensureTreePermalink(app.client, tree);
1679
- } catch (error) {
1680
- if (isSlackMessageNotFound(error)) {
1681
- try {
1682
- await replaceMissingTree(tree, statusTick.budget);
1683
- } catch (replacementError) {
1684
- console.error(
1685
- `[Slack] Failed to replace missing v2 tree ${tree.id}:`,
1686
- replacementError,
1687
- );
1688
- }
1689
- continue;
1690
- }
1691
- console.error(`[Slack] Failed to resolve v2 tree permalink ${tree.id}:`, error);
1692
- continue;
1693
- }
1694
- }
1695
- let tasks = await getSlackTasksInThread(tree.channelId, tree.threadTs);
1696
- let needsOutcome = false;
1697
- for (const task of tasks) {
1698
- const card = await getSlackOutcomeMessage(task.id);
1699
- if (card && isSettledSlackMessage(card)) continue;
1700
- // In-progress asks are eligible only for the timeout backstop. They do
1701
- // not represent immediately active outcome work, so avoid waking an old
1702
- // tree solely to verify its permalink on every render tick.
1703
- const isDirectCandidate =
1704
- (await taskNeedsDirectOutcome(task, activatedAt)) &&
1705
- isOutcomeStatus(task.status) &&
1706
- !(await isAnsweredByDeferralCard(task, tasks));
1707
- const isChildCandidate =
1708
- delegationEnabled &&
1709
- delegationActivatedAt !== null &&
1710
- isChildCardCandidate(task, delegationActivatedAt) &&
1711
- !task.slackReplySent;
1712
- if (isDirectCandidate || isChildCandidate) {
1713
- needsOutcome = true;
1714
- break;
1715
- }
1716
- }
1717
- if (needsOutcome && app) {
1718
- try {
1719
- await resolvePermalink(app.client, tree.channelId, tree.ts);
1720
- } catch (error) {
1721
- if (!isSlackMessageNotFound(error)) {
1722
- console.error(`[Slack] Failed to verify v2 tree ${tree.id}:`, error);
1723
- continue;
1724
- }
1682
+ const app = getSlackApp();
1683
+ if (app && !tree.permalink) {
1684
+ try {
1685
+ tree = await ensureTreePermalink(app.client, tree);
1686
+ } catch (error) {
1687
+ if (isSlackMessageNotFound(error)) {
1725
1688
  try {
1726
- const replacement = await replaceMissingTree(tree, statusTick.budget);
1727
- if (!replacement) continue;
1728
- tree = replacement;
1729
- tasks = await getSlackTasksInThread(tree.channelId, tree.threadTs);
1689
+ await replaceMissingTree(tree, statusTick.budget);
1730
1690
  } catch (replacementError) {
1731
1691
  console.error(`[Slack] Failed to replace missing v2 tree ${tree.id}:`, replacementError);
1732
- continue;
1733
1692
  }
1693
+ return "skipped";
1734
1694
  }
1695
+ console.error(`[Slack] Failed to resolve v2 tree permalink ${tree.id}:`, error);
1696
+ return "skipped";
1735
1697
  }
1736
- const settleSec = Number(process.env.SLACK_CONCLUSION_SETTLE_SEC) || 10;
1737
- const timeoutMin = Number(process.env.SLACK_CONCLUSION_TIMEOUT_MIN) || 240;
1738
- const closuresByAskId = new Map<string, AgentTask[]>();
1739
- const ownerAskId = new Map<string, string>();
1740
- if (delegationEnabled) {
1741
- for (const ask of tasks.filter((candidate) => candidate.source === "slack")) {
1742
- const closure = buildAskClosure(ask, tasks);
1743
- closuresByAskId.set(ask.id, closure);
1744
- for (const member of closure) {
1745
- if (!ownerAskId.has(member.id)) ownerAskId.set(member.id, ask.id);
1746
- }
1698
+ }
1699
+ let tasks = await getSlackTasksInThread(tree.channelId, tree.threadTs);
1700
+ let needsOutcome = false;
1701
+ for (const task of tasks) {
1702
+ const card = await getSlackOutcomeMessage(task.id);
1703
+ if (card && isSettledSlackMessage(card)) continue;
1704
+ // In-progress asks are eligible only for the timeout backstop. They do
1705
+ // not represent immediately active outcome work, so avoid waking an old
1706
+ // tree solely to verify its permalink on every render tick.
1707
+ const isDirectCandidate =
1708
+ (await taskNeedsDirectOutcome(task, activatedAt)) &&
1709
+ isOutcomeStatus(task.status) &&
1710
+ !(await isAnsweredByDeferralCard(task, tasks));
1711
+ const isChildCandidate =
1712
+ delegationEnabled &&
1713
+ delegationActivatedAt !== null &&
1714
+ isChildCardCandidate(task, delegationActivatedAt) &&
1715
+ !task.slackReplySent;
1716
+ if (isDirectCandidate || isChildCandidate) {
1717
+ needsOutcome = true;
1718
+ break;
1719
+ }
1720
+ }
1721
+ if (needsOutcome && app) {
1722
+ try {
1723
+ await resolvePermalink(app.client, tree.channelId, tree.ts);
1724
+ } catch (error) {
1725
+ if (!isSlackMessageNotFound(error)) {
1726
+ console.error(`[Slack] Failed to verify v2 tree ${tree.id}:`, error);
1727
+ return "skipped";
1728
+ }
1729
+ try {
1730
+ const replacement = await replaceMissingTree(tree, statusTick.budget);
1731
+ if (!replacement) return "skipped";
1732
+ tree = replacement;
1733
+ tasks = await getSlackTasksInThread(tree.channelId, tree.threadTs);
1734
+ } catch (replacementError) {
1735
+ console.error(`[Slack] Failed to replace missing v2 tree ${tree.id}:`, replacementError);
1736
+ return "skipped";
1747
1737
  }
1748
1738
  }
1749
- const childCardCounts = new Map<string, number>();
1750
- async function childCardCountFor(askId: string): Promise<number> {
1751
- const cached = childCardCounts.get(askId);
1752
- if (cached !== undefined) return cached;
1753
- const closure = closuresByAskId.get(askId) ?? [];
1754
- let count = 0;
1739
+ }
1740
+ const settleSec = Number(process.env.SLACK_CONCLUSION_SETTLE_SEC) || 10;
1741
+ const timeoutMin = Number(process.env.SLACK_CONCLUSION_TIMEOUT_MIN) || 240;
1742
+ const closuresByAskId = new Map<string, AgentTask[]>();
1743
+ const ownerAskId = new Map<string, string>();
1744
+ if (delegationEnabled) {
1745
+ for (const ask of tasks.filter((candidate) => candidate.source === "slack")) {
1746
+ const closure = buildAskClosure(ask, tasks);
1747
+ closuresByAskId.set(ask.id, closure);
1755
1748
  for (const member of closure) {
1756
- if (await getSlackOutcomeMessage(member.id)) count++;
1749
+ if (!ownerAskId.has(member.id)) ownerAskId.set(member.id, ask.id);
1757
1750
  }
1758
- childCardCounts.set(askId, count);
1759
- return count;
1760
1751
  }
1752
+ }
1753
+ const childCardCounts = new Map<string, number>();
1754
+ async function childCardCountFor(askId: string): Promise<number> {
1755
+ const cached = childCardCounts.get(askId);
1756
+ if (cached !== undefined) return cached;
1757
+ const closure = closuresByAskId.get(askId) ?? [];
1758
+ let count = 0;
1759
+ for (const member of closure) {
1760
+ if (await getSlackOutcomeMessage(member.id)) count++;
1761
+ }
1762
+ childCardCounts.set(askId, count);
1763
+ return count;
1764
+ }
1761
1765
 
1762
- let outcomeCreated = false;
1763
- // Child cards post before ask conclusions, in two passes over the same
1764
- // tick. Tasks are walked in creation order, so an ask is otherwise
1765
- // visited before the delegated children it owns; if their conclusion
1766
- // ran first, a closure that goes fully terminal within one tick would
1767
- // compute conclusionResultsLines() against children that have no card
1768
- // yet, permanently fall back to digest text, and never self-correct —
1769
- // the conclusion card is immutable once finalized.
1770
- let childCardsThisTick = 0;
1771
- for (const task of tasks) {
1772
- if (!isSlackRenderV2Enabled()) return;
1773
- if (task.source === "slack") continue;
1774
- const card = await getSlackOutcomeMessage(task.id);
1775
- if (card && isSettledSlackMessage(card)) continue;
1776
- if (!delegationEnabled || delegationActivatedAt === null) continue;
1777
- if (!isChildCardCandidate(task, delegationActivatedAt) || task.slackReplySent) continue;
1778
- const askId = ownerAskId.get(task.id);
1779
- const ownerAsk = askId ? tasks.find((candidate) => candidate.id === askId) : undefined;
1780
- if (!ownerAsk || ownerAsk.createdAt < delegationActivatedAt) continue;
1781
- if (childCardsThisTick >= CHILD_CARDS_PER_TICK) continue;
1782
- if (askId && (await childCardCountFor(askId)) >= CHILD_CARDS_PER_ASK) continue;
1766
+ let outcomeCreated = false;
1767
+ // Child cards post before ask conclusions, in two passes over the same
1768
+ // tick. Tasks are walked in creation order, so an ask is otherwise
1769
+ // visited before the delegated children it owns; if their conclusion
1770
+ // ran first, a closure that goes fully terminal within one tick would
1771
+ // compute conclusionResultsLines() against children that have no card
1772
+ // yet, permanently fall back to digest text, and never self-correct —
1773
+ // the conclusion card is immutable once finalized.
1774
+ let childCardsThisTick = 0;
1775
+ for (const task of tasks) {
1776
+ if (!isSlackRenderV2Enabled()) return "stop";
1777
+ if (task.source === "slack") continue;
1778
+ const card = await getSlackOutcomeMessage(task.id);
1779
+ if (card && isSettledSlackMessage(card)) continue;
1780
+ if (!delegationEnabled || delegationActivatedAt === null) continue;
1781
+ if (!isChildCardCandidate(task, delegationActivatedAt) || task.slackReplySent) continue;
1782
+ const askId = ownerAskId.get(task.id);
1783
+ const ownerAsk = askId ? tasks.find((candidate) => candidate.id === askId) : undefined;
1784
+ if (!ownerAsk || ownerAsk.createdAt < delegationActivatedAt) continue;
1785
+ if (childCardsThisTick >= CHILD_CARDS_PER_TICK) continue;
1786
+ if (askId && (await childCardCountFor(askId)) >= CHILD_CARDS_PER_ASK) continue;
1787
+ if (!(await checkOutcomeDeliveryGate(task, card, statusTick.budget))) continue;
1788
+ try {
1789
+ const outcome = await streamOutcomeCard(task, tree, {
1790
+ buildContent: childOutcomeContent,
1791
+ statusBudget: statusTick.budget,
1792
+ });
1793
+ if (outcome) {
1794
+ noteOutcomeDeliverySuccess(task.id);
1795
+ childCardsThisTick++;
1796
+ if (askId) childCardCounts.set(askId, (childCardCounts.get(askId) ?? 0) + 1);
1797
+ await recordSlackDelivery(task, outcome, "child_outcome");
1798
+ }
1799
+ outcomeCreated ||= !!outcome;
1800
+ } catch (error) {
1801
+ await noteOutcomeDeliveryFailure(task, tree, error, statusTick.budget);
1802
+ }
1803
+ }
1804
+
1805
+ for (const task of tasks) {
1806
+ if (!isSlackRenderV2Enabled()) return "stop";
1807
+ if (!(await taskNeedsDirectOutcome(task, activatedAt))) continue;
1808
+ const card = await getSlackOutcomeMessage(task.id);
1809
+ if (card && isSettledSlackMessage(card)) continue;
1810
+ if (await isAnsweredByDeferralCard(task, tasks)) continue;
1811
+ const deferByClosure =
1812
+ task.source === "slack" &&
1813
+ delegationEnabled &&
1814
+ delegationActivatedAt !== null &&
1815
+ task.createdAt >= delegationActivatedAt;
1816
+
1817
+ if (!deferByClosure) {
1783
1818
  if (!(await checkOutcomeDeliveryGate(task, card, statusTick.budget))) continue;
1784
1819
  try {
1785
- const outcome = await streamOutcomeCard(task, tree, {
1786
- buildContent: childOutcomeContent,
1787
- statusBudget: statusTick.budget,
1788
- });
1820
+ const outcome = await streamOutcomeCard(task, tree, { statusBudget: statusTick.budget });
1789
1821
  if (outcome) {
1790
1822
  noteOutcomeDeliverySuccess(task.id);
1791
- childCardsThisTick++;
1792
- if (askId) childCardCounts.set(askId, (childCardCounts.get(askId) ?? 0) + 1);
1793
- await recordSlackDelivery(task, outcome, "child_outcome");
1823
+ await finalizeTerminalSlackReactions([task]);
1794
1824
  }
1795
1825
  outcomeCreated ||= !!outcome;
1796
1826
  } catch (error) {
1797
1827
  await noteOutcomeDeliveryFailure(task, tree, error, statusTick.budget);
1798
1828
  }
1829
+ continue;
1799
1830
  }
1800
1831
 
1801
- for (const task of tasks) {
1802
- if (!isSlackRenderV2Enabled()) return;
1803
- if (!(await taskNeedsDirectOutcome(task, activatedAt))) continue;
1804
- const card = await getSlackOutcomeMessage(task.id);
1805
- if (card && isSettledSlackMessage(card)) continue;
1806
- if (await isAnsweredByDeferralCard(task, tasks)) continue;
1807
- const deferByClosure =
1808
- task.source === "slack" &&
1809
- delegationEnabled &&
1810
- delegationActivatedAt !== null &&
1811
- task.createdAt >= delegationActivatedAt;
1812
-
1813
- if (!deferByClosure) {
1814
- if (!(await checkOutcomeDeliveryGate(task, card, statusTick.budget))) continue;
1815
- try {
1816
- const outcome = await streamOutcomeCard(task, tree, { statusBudget: statusTick.budget });
1817
- if (outcome) {
1818
- noteOutcomeDeliverySuccess(task.id);
1819
- await finalizeTerminalSlackReactions([task]);
1820
- }
1821
- outcomeCreated ||= !!outcome;
1822
- } catch (error) {
1823
- await noteOutcomeDeliveryFailure(task, tree, error, statusTick.budget);
1824
- }
1825
- continue;
1826
- }
1827
-
1828
- const closure = closuresByAskId.get(task.id) ?? buildAskClosure(task, tasks);
1829
- // A conclusion is immutable, so wait until every eligible terminal
1830
- // child has its card. The per-tick cap may leave overflow children
1831
- // uncarded even though the closure itself is otherwise settled.
1832
- let childCardPending = false;
1833
- const existingChildCards = await childCardCountFor(task.id);
1834
- for (const member of closure) {
1835
- if (!isChildCardCandidate(member, delegationActivatedAt!) || member.slackReplySent)
1836
- continue;
1837
- // Once the per-ask cap is reached, remaining terminal children are
1838
- // represented in the conclusion digest rather than blocking it.
1839
- if (existingChildCards >= CHILD_CARDS_PER_ASK) break;
1840
- const memberCard = await getSlackOutcomeMessage(member.id);
1841
- if (!memberCard || !isSettledSlackMessage(memberCard)) {
1842
- childCardPending = true;
1843
- break;
1844
- }
1832
+ const closure = closuresByAskId.get(task.id) ?? buildAskClosure(task, tasks);
1833
+ // A conclusion is immutable, so wait until every eligible terminal
1834
+ // child has its card. The per-tick cap may leave overflow children
1835
+ // uncarded even though the closure itself is otherwise settled.
1836
+ let childCardPending = false;
1837
+ const existingChildCards = await childCardCountFor(task.id);
1838
+ for (const member of closure) {
1839
+ if (!isChildCardCandidate(member, delegationActivatedAt!) || member.slackReplySent) continue;
1840
+ // Once the per-ask cap is reached, remaining terminal children are
1841
+ // represented in the conclusion digest rather than blocking it.
1842
+ if (existingChildCards >= CHILD_CARDS_PER_ASK) break;
1843
+ const memberCard = await getSlackOutcomeMessage(member.id);
1844
+ if (!memberCard || !isSettledSlackMessage(memberCard)) {
1845
+ childCardPending = true;
1846
+ break;
1845
1847
  }
1846
- if (childCardPending) continue;
1847
- const state = closureState(task, closure, new Date(), settleSec, timeoutMin);
1848
- if (state === "open") continue;
1849
- if (!(await checkOutcomeDeliveryGate(task, card, statusTick.budget))) continue;
1850
- try {
1851
- const outcome = await streamOutcomeCard(task, tree, {
1852
- buildContent: (_t, slackReplySent) =>
1853
- askConclusionContent(task, closure, state, slackReplySent),
1854
- conclusionKind: state === "timedOut" ? "timeout" : "complete",
1855
- statusBudget: statusTick.budget,
1856
- });
1857
- if (outcome) {
1858
- noteOutcomeDeliverySuccess(task.id);
1859
- const app = getSlackApp();
1860
- if (app && task.slackChannelId && task.slackTriggerMessageTs) {
1861
- const reaction = conclusionReactionChoice(state, task, closure);
1862
- await finalizeSlackMessageReaction(
1863
- app.client,
1864
- task.slackChannelId,
1865
- task.slackTriggerMessageTs,
1866
- reaction.name,
1867
- reaction.event,
1868
- );
1869
- await finalizeSlackSteerReactions([task], () => reaction);
1870
- }
1871
- await recordSlackDelivery(
1872
- task,
1873
- outcome,
1874
- state === "timedOut" ? "conclusion_timeout" : "conclusion",
1848
+ }
1849
+ if (childCardPending) continue;
1850
+ const state = closureState(task, closure, new Date(), settleSec, timeoutMin);
1851
+ if (state === "open") continue;
1852
+ if (!(await checkOutcomeDeliveryGate(task, card, statusTick.budget))) continue;
1853
+ try {
1854
+ const outcome = await streamOutcomeCard(task, tree, {
1855
+ buildContent: (_t, slackReplySent) =>
1856
+ askConclusionContent(task, closure, state, slackReplySent),
1857
+ conclusionKind: state === "timedOut" ? "timeout" : "complete",
1858
+ statusBudget: statusTick.budget,
1859
+ });
1860
+ if (outcome) {
1861
+ noteOutcomeDeliverySuccess(task.id);
1862
+ const app = getSlackApp();
1863
+ if (app && task.slackChannelId && task.slackTriggerMessageTs) {
1864
+ const reaction = conclusionReactionChoice(state, task, closure);
1865
+ await finalizeSlackMessageReaction(
1866
+ app.client,
1867
+ task.slackChannelId,
1868
+ task.slackTriggerMessageTs,
1869
+ reaction.name,
1870
+ reaction.event,
1875
1871
  );
1872
+ await finalizeSlackSteerReactions([task], () => reaction);
1876
1873
  }
1877
- outcomeCreated ||= !!outcome;
1878
- } catch (error) {
1879
- await noteOutcomeDeliveryFailure(task, tree, error, statusTick.budget);
1874
+ await recordSlackDelivery(
1875
+ task,
1876
+ outcome,
1877
+ state === "timedOut" ? "conclusion_timeout" : "conclusion",
1878
+ );
1880
1879
  }
1880
+ outcomeCreated ||= !!outcome;
1881
+ } catch (error) {
1882
+ await noteOutcomeDeliveryFailure(task, tree, error, statusTick.budget);
1883
+ }
1884
+ }
1885
+ try {
1886
+ await updateThreadTree(tree, outcomeCreated, statusTick.budget);
1887
+ } catch (error) {
1888
+ console.error(`[Slack] Failed to update v2 tree ${tree.id}:`, error);
1889
+ }
1890
+ await statusTick.reconcile(tree.channelId, tree.threadTs);
1891
+ try {
1892
+ // Drop the tree from later sweeps once its thread has no work left.
1893
+ // Any later task or outcome write in the thread reopens it.
1894
+ if (await closeSlackTreeIfSettled(tree.id)) return "closed";
1895
+ } catch (error) {
1896
+ console.error(`[Slack] Failed to close settled v2 tree ${tree.id}:`, error);
1897
+ }
1898
+ return "open";
1899
+ }
1900
+
1901
+ /** Task events that can change what a thread's tree or cards should show. */
1902
+ const SLACK_RENDER_TASK_EVENTS = [
1903
+ "task.created",
1904
+ "task.completed",
1905
+ "task.failed",
1906
+ "task.cancelled",
1907
+ "task.skipped",
1908
+ "task.superseded",
1909
+ "task.progress",
1910
+ ] as const;
1911
+
1912
+ /** Coalesces a burst of task events into one render of the threads they touch. */
1913
+ const DIRTY_FLUSH_DEBOUNCE_MS = 500;
1914
+ /** Re-check cadence for a thread that still owes an outcome card (settle wait, backoff). */
1915
+ const DIRTY_REVISIT_MS = 3_000;
1916
+
1917
+ type SlackThreadAddress = { channelId: string; threadTs: string };
1918
+
1919
+ const dirtyTaskIds = new Set<string>();
1920
+ const dirtyThreads = new Map<string, SlackThreadAddress>();
1921
+ let renderInFlight: Promise<void> | null = null;
1922
+ let renderEventsSubscribed = false;
1923
+ let dirtyFlushTimer: ReturnType<typeof setTimeout> | null = null;
1924
+ let dirtyFlushAt = 0;
1925
+
1926
+ /** Let pending I/O (the Slack socket) run between synchronous SQLite phases. */
1927
+ function yieldToEventLoop(): Promise<void> {
1928
+ return new Promise((resolve) => setImmediate(resolve));
1929
+ }
1930
+
1931
+ /**
1932
+ * Arm the dirty-thread flush to run in `delayMs`, unless one is already armed
1933
+ * to run sooner. Only armed while task events are subscribed (watcher running).
1934
+ */
1935
+ function scheduleDirtyFlush(delayMs: number): void {
1936
+ if (!renderEventsSubscribed) return;
1937
+ const at = Date.now() + delayMs;
1938
+ if (dirtyFlushTimer && dirtyFlushAt <= at) return;
1939
+ if (dirtyFlushTimer) clearTimeout(dirtyFlushTimer);
1940
+ dirtyFlushAt = at;
1941
+ dirtyFlushTimer = setTimeout(() => {
1942
+ dirtyFlushTimer = null;
1943
+ void flushSlackRenderV2DirtyThreads().catch((error) => {
1944
+ console.error("[Slack] Event-driven v2 render failed:", error);
1945
+ });
1946
+ }, delayMs);
1947
+ }
1948
+
1949
+ /** Queue one thread for the event-driven render. */
1950
+ export function markSlackThreadDirty(
1951
+ channelId: string,
1952
+ threadTs: string,
1953
+ delayMs = DIRTY_FLUSH_DEBOUNCE_MS,
1954
+ ): void {
1955
+ dirtyThreads.set(`${channelId}\u0000${threadTs}`, { channelId, threadTs });
1956
+ scheduleDirtyFlush(delayMs);
1957
+ }
1958
+
1959
+ function onSlackRenderTaskEvent(data: unknown): void {
1960
+ const taskId = (data as { taskId?: unknown } | null)?.taskId;
1961
+ if (typeof taskId !== "string") return;
1962
+ dirtyTaskIds.add(taskId);
1963
+ scheduleDirtyFlush(DIRTY_FLUSH_DEBOUNCE_MS);
1964
+ }
1965
+
1966
+ /**
1967
+ * Render a thread shortly after a task event touches it, instead of waiting
1968
+ * for the watcher's full reconcile. Started and stopped with the watcher.
1969
+ */
1970
+ export function startSlackRenderV2Events(): void {
1971
+ if (renderEventsSubscribed) return;
1972
+ for (const event of SLACK_RENDER_TASK_EVENTS) workflowEventBus.on(event, onSlackRenderTaskEvent);
1973
+ renderEventsSubscribed = true;
1974
+ }
1975
+
1976
+ export function stopSlackRenderV2Events(): void {
1977
+ if (!renderEventsSubscribed) return;
1978
+ for (const event of SLACK_RENDER_TASK_EVENTS) workflowEventBus.off(event, onSlackRenderTaskEvent);
1979
+ renderEventsSubscribed = false;
1980
+ if (dirtyFlushTimer) clearTimeout(dirtyFlushTimer);
1981
+ dirtyFlushTimer = null;
1982
+ }
1983
+
1984
+ /**
1985
+ * Run `work` unless a render pass is already running. An overlapping call
1986
+ * waits for the running pass and does not start its own, so two passes never
1987
+ * interleave their Slack writes.
1988
+ */
1989
+ function runExclusive(work: () => Promise<void>): Promise<void> {
1990
+ if (renderInFlight) return renderInFlight;
1991
+ const run = (async () => {
1992
+ try {
1993
+ await work();
1994
+ } finally {
1995
+ renderInFlight = null;
1881
1996
  }
1997
+ })();
1998
+ renderInFlight = run;
1999
+ return run;
2000
+ }
2001
+
2002
+ async function beginRenderPass(): Promise<RenderPassContext> {
2003
+ const activatedAt = await ensureSlackRenderV2Activation();
2004
+ const delegationEnabled = isSlackDelegationEnabled();
2005
+ const delegationActivatedAt = delegationEnabled ? await ensureSlackDelegationActivation() : null;
2006
+ return {
2007
+ activatedAt,
2008
+ delegationEnabled,
2009
+ delegationActivatedAt,
2010
+ statusTick: beginSlackStatusTick(),
2011
+ };
2012
+ }
2013
+
2014
+ /**
2015
+ * Event-driven render: only the threads that task events, deferral rewrites
2016
+ * or unfinished outcome work marked. Waits for a running pass instead of
2017
+ * overlapping it, then runs if anything is still queued.
2018
+ */
2019
+ export async function flushSlackRenderV2DirtyThreads(): Promise<void> {
2020
+ if (!isSlackRenderV2Enabled() || !getSlackApp()) return;
2021
+ if (renderInFlight) {
2022
+ await renderInFlight;
2023
+ if (dirtyTaskIds.size === 0 && dirtyThreads.size === 0) return;
2024
+ }
2025
+ await runExclusive(renderDirtyThreads);
2026
+ }
2027
+
2028
+ /**
2029
+ * Full reconcile, run on every watcher tick (the safety net behind the
2030
+ * event-driven render): every recent tree-less Slack task, every open tree,
2031
+ * every deferral card, then the session-status sweep.
2032
+ */
2033
+ export function processSlackRenderV2(): Promise<void> {
2034
+ if (!isSlackRenderV2Enabled()) return Promise.resolve();
2035
+ return runExclusive(reconcileAllThreads);
2036
+ }
2037
+
2038
+ async function reconcileAllThreads(): Promise<void> {
2039
+ // The full pass covers everything queued so far.
2040
+ dirtyTaskIds.clear();
2041
+ dirtyThreads.clear();
2042
+ const context = await beginRenderPass();
2043
+
2044
+ for (const task of await getSlackTasksMissingTree()) {
2045
+ if (!isSlackRenderV2Enabled()) return;
2046
+ if (!task.slackChannelId || !task.slackThreadTs) continue;
1882
2047
  try {
1883
- await updateThreadTree(tree, outcomeCreated, statusTick.budget);
2048
+ await ensureSlackThreadTree([task.id], context.statusTick.budget);
1884
2049
  } catch (error) {
1885
- console.error(`[Slack] Failed to update v2 tree ${tree.id}:`, error);
2050
+ console.error(`[Slack] Failed to create v2 tree for task ${task.id}:`, error);
1886
2051
  }
1887
- await statusTick.reconcile(tree.channelId, tree.threadTs);
2052
+ }
2053
+ await yieldToEventLoop();
2054
+
2055
+ for (const storedTree of await getSlackTreeMessages()) {
2056
+ if ((await renderStoredTree(storedTree, context)) === "stop") return;
2057
+ await yieldToEventLoop();
1888
2058
  }
1889
2059
 
1890
2060
  await refreshResolvedDeferralCards();
1891
- await statusTick.finish();
2061
+ await yieldToEventLoop();
2062
+ await context.statusTick.finish();
2063
+ }
2064
+
2065
+ async function renderDirtyThreads(): Promise<void> {
2066
+ const taskIds = [...dirtyTaskIds];
2067
+ dirtyTaskIds.clear();
2068
+ const threads = new Map(dirtyThreads);
2069
+ dirtyThreads.clear();
2070
+ const touched = await getSlackThreadsOfTasks(taskIds);
2071
+ for (const thread of touched.threads) {
2072
+ threads.set(`${thread.channelId}\u0000${thread.threadTs}`, thread);
2073
+ }
2074
+ if (threads.size === 0 && !touched.wakeTouched) return;
2075
+ const context = await beginRenderPass();
2076
+
2077
+ for (const thread of threads.values()) {
2078
+ if (!isSlackRenderV2Enabled()) return;
2079
+ for (const task of await getSlackTasksMissingTree({ thread })) {
2080
+ try {
2081
+ await ensureSlackThreadTree([task.id], context.statusTick.budget);
2082
+ } catch (error) {
2083
+ console.error(`[Slack] Failed to create v2 tree for task ${task.id}:`, error);
2084
+ }
2085
+ }
2086
+ for (const storedTree of await getSlackTreeMessages({ thread })) {
2087
+ const result = await renderStoredTree(storedTree, context);
2088
+ if (result === "stop") return;
2089
+ // Time-based waits (conclusion settle, delivery backoff) emit no event:
2090
+ // keep the thread queued while it still owes an outcome card.
2091
+ if (result !== "closed" && (await slackThreadHasOutcomeWork(thread))) {
2092
+ markSlackThreadDirty(thread.channelId, thread.threadTs, DIRTY_REVISIT_MS);
2093
+ }
2094
+ }
2095
+ await yieldToEventLoop();
2096
+ }
2097
+
2098
+ // A settled wake-up can resolve a ⏳ card in a thread it does not belong to.
2099
+ if (touched.wakeTouched) await refreshResolvedDeferralCards();
1892
2100
  }
1893
2101
 
1894
2102
  export function _resetSlackRenderV2ForTests(): void {
@@ -1901,6 +2109,10 @@ export function _resetSlackRenderV2ForTests(): void {
1901
2109
  cachedTeamId = undefined;
1902
2110
  outcomeDeliveryNextAttemptAt.clear();
1903
2111
  outcomeReservedWithoutAttempt.clear();
2112
+ dirtyTaskIds.clear();
2113
+ dirtyThreads.clear();
2114
+ renderInFlight = null;
2115
+ stopSlackRenderV2Events();
1904
2116
  _resetSlackSessionStatusForTests();
1905
2117
  }
1906
2118