@desplega.ai/agent-swarm 2.8.2 → 2.8.3

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 (258) hide show
  1. package/dist/acp-adapter-xq6s2z6t.js +14 -0
  2. package/dist/{actions-kxek041g.js → actions-ewz7bp4g.js} +20 -19
  3. package/dist/{amp-adapter-ce7jjke4.js → amp-adapter-f25tqhnf.js} +3 -3
  4. package/dist/{app-v6zz8yh0.js → app-mkptw0k7.js} +4 -4
  5. package/dist/{assistant-m0sw9xx2.js → assistant-c47rfe77.js} +23 -22
  6. package/dist/{boot-args-schema-66bk37wv.js → boot-args-schema-4vb0xsat.js} +1 -1
  7. package/dist/{boot-reembed-edjpwsc1.js → boot-reembed-1ghy2sab.js} +1 -1
  8. package/dist/{boot-reembed-y27n09tz.js → boot-reembed-htr73hbs.js} +1 -1
  9. package/dist/{boot-scrub-sweep-1xc35965.js → boot-scrub-sweep-yrytg42z.js} +4 -4
  10. package/dist/{boot-seeds-7hjj91qj.js → boot-seeds-n2b3dx4e.js} +4 -4
  11. package/dist/{boxd-ent8ch04.js → boxd-jmfqgkqa.js} +1 -1
  12. package/dist/{claude-adapter-stw7jdcf.js → claude-adapter-r33pqnzx.js} +8 -9
  13. package/dist/{claude-managed-adapter-jh6c523j.js → claude-managed-adapter-hddmxjyj.js} +4 -4
  14. package/dist/{claude-managed-setup-y6z2perp.js → claude-managed-setup-hfvry1bd.js} +5 -5
  15. package/dist/{claude-sdk-session-vvya8wqk.js → claude-sdk-session-0hamqzc7.js} +10 -11
  16. package/dist/{cli-v1dv1r37.js → cli-0bcgyj5b.js} +74 -3
  17. package/dist/{cli-t2tma8gb.js → cli-0vksaxvr.js} +2 -2
  18. package/dist/{cli-mrt48bx7.js → cli-15204js0.js} +1 -1
  19. package/dist/{cli-8aes17e4.js → cli-1m96dc36.js} +3 -3
  20. package/dist/{cli-2r0jcc3k.js → cli-2d0cghfn.js} +1 -1
  21. package/dist/{cli-0cq8y6m7.js → cli-4ax9mvvg.js} +4 -4
  22. package/dist/{cli-tekytdq9.js → cli-4dpkjc2e.js} +6 -6
  23. package/dist/{cli-x1wa213s.js → cli-4e1hfbpq.js} +5 -5
  24. package/dist/{cli-7349va39.js → cli-500c09j9.js} +921 -431
  25. package/dist/{cli-9mb2q6pb.js → cli-54qr8mcd.js} +2 -2
  26. package/dist/{cli-m88rpzkh.js → cli-5a7szzfh.js} +2 -2
  27. package/dist/{cli-bst1vp7e.js → cli-5y2fvw4z.js} +13 -5
  28. package/dist/{cli-vj75tyaw.js → cli-6yygkr0w.js} +7 -7
  29. package/dist/{cli-kjtwrhea.js → cli-7c5tgqhf.js} +5 -5
  30. package/dist/{cli-2gxeg5gr.js → cli-8476gtwf.js} +1 -1
  31. package/dist/{cli-zh9rsbqf.js → cli-922z7gwm.js} +3 -3
  32. package/dist/{cli-jrzkw01m.js → cli-93t5s4zq.js} +2 -2
  33. package/dist/{cli-gyt3zydq.js → cli-9zmb7ptc.js} +9 -9
  34. package/dist/{cli-dzpc6en0.js → cli-am1ptset.js} +2 -2
  35. package/dist/{cli-w401b9tq.js → cli-awwptga4.js} +1 -1
  36. package/dist/{cli-26ctbcdp.js → cli-bhsfbmk8.js} +3 -3
  37. package/dist/{cli-mxn1qvbn.js → cli-bj6qhgte.js} +14 -32
  38. package/dist/{cli-g70vxtjh.js → cli-c0xjnr8z.js} +2 -2
  39. package/dist/{cli-jdknh18m.js → cli-c3ng0mb4.js} +13 -13
  40. package/dist/{cli-f4e8r23x.js → cli-c71n3bxq.js} +11 -6
  41. package/dist/{cli-6rc5frdm.js → cli-crpf163n.js} +25 -18
  42. package/dist/{cli-1qkz151v.js → cli-dpsfwh7n.js} +13 -21
  43. package/dist/{cli-xzm9vcfg.js → cli-dtdht77h.js} +2 -2
  44. package/dist/{cli-a0z912j7.js → cli-e2w34h6z.js} +137 -62
  45. package/dist/{cli-eddnyg3t.js → cli-emekyyhr.js} +1 -1
  46. package/dist/{cli-d84byzn8.js → cli-f1kwb5fc.js} +109 -33
  47. package/dist/{cli-0jzra9ad.js → cli-gn9y6fn7.js} +2 -2
  48. package/dist/{cli-vdektqgf.js → cli-gpz1d0t2.js} +4 -4
  49. package/dist/{cli-rcecc3yq.js → cli-h9yy18gy.js} +84 -36
  50. package/dist/{cli-m5akxq8q.js → cli-j8cjdzan.js} +1 -1
  51. package/dist/{cli-m9s2qff2.js → cli-jg5txpm6.js} +187 -93
  52. package/dist/{cli-b98a65ed.js → cli-k2rw11py.js} +3 -3
  53. package/dist/{cli-3e875j5p.js → cli-k96cecs7.js} +276 -47
  54. package/dist/{cli-3vjhs18n.js → cli-kd56bmk4.js} +1 -1
  55. package/dist/{cli-3sy2xags.js → cli-kmemts3w.js} +12 -12
  56. package/dist/{cli-f6bahpn5.js → cli-knva3nmx.js} +2 -2
  57. package/dist/{cli-959kp5h2.js → cli-kw44j53p.js} +13 -13
  58. package/dist/{cli-bsywb58a.js → cli-mdpbjnzq.js} +10 -10
  59. package/dist/{cli-2kvhc7x8.js → cli-me0r8gzr.js} +35 -76
  60. package/dist/{cli-4vzgeta4.js → cli-mwwmka77.js} +14 -14
  61. package/dist/{cli-q24n86d2.js → cli-n5t077me.js} +2 -2
  62. package/dist/{cli-rvhdmjvt.js → cli-nx2n3z6p.js} +1 -1
  63. package/dist/{cli-28fq781p.js → cli-pe4d96rb.js} +1 -1
  64. package/dist/{cli-3rkdne1h.js → cli-pxwtcgcp.js} +2 -2
  65. package/dist/{cli-n6vtrcht.js → cli-qmqt520k.js} +2 -2
  66. package/dist/{cli-pchypa1s.js → cli-qps8je6j.js} +17 -2
  67. package/dist/{cli-97ae65rz.js → cli-rjvsf9qa.js} +5 -5
  68. package/dist/{cli-e1p3n5gq.js → cli-rqfvkx5t.js} +6 -6
  69. package/dist/{cli-3vmb0n58.js → cli-s7zz734a.js} +1 -1
  70. package/dist/{cli-rmzsadkf.js → cli-s8p8hhty.js} +2 -2
  71. package/dist/{cli-j24zbska.js → cli-sdvcrq5x.js} +5 -5
  72. package/dist/{cli-5y340nzn.js → cli-sg27rk2t.js} +5 -5
  73. package/dist/{cli-d6521kb5.js → cli-skmhsnqh.js} +1 -1
  74. package/dist/{cli-5mrq3ake.js → cli-t4dv07kr.js} +1 -1
  75. package/dist/{cli-z1w943va.js → cli-t5ys4ebm.js} +3 -3
  76. package/dist/{cli-f4r3g076.js → cli-tas6ckky.js} +2 -2
  77. package/dist/{cli-1pz0330a.js → cli-tf79ryyy.js} +1 -1
  78. package/dist/{cli-kc7v1nfv.js → cli-tnzebztn.js} +1 -1
  79. package/dist/{cli-pfs8adn4.js → cli-vx421edw.js} +3 -3
  80. package/dist/{cli-kchjb7qy.js → cli-x3ex5bqf.js} +1 -1
  81. package/dist/cli-yss07azk.js +142 -0
  82. package/dist/{cli-fwy8kfd6.js → cli-z8cvws4c.js} +98 -16
  83. package/dist/{cli-g5mtmf6t.js → cli-zdaypkq9.js} +146 -52
  84. package/dist/{cli-fpjmegdb.js → cli-zeaehgyd.js} +2 -2
  85. package/dist/{cli-837vfs2x.js → cli-ztq5z4e1.js} +4 -4
  86. package/dist/cli.js +20 -20
  87. package/dist/{codex-adapter-zerf5qsp.js → codex-adapter-2brxx5ta.js} +7 -8
  88. package/dist/{codex-hook-30gyhzxe.js → codex-hook-c930c3ea.js} +1 -1
  89. package/dist/{codex-login-bcda78ge.js → codex-login-cbrs1h5w.js} +1 -1
  90. package/dist/{codex-session-runner-89s304py.js → codex-session-runner-y9anfj0r.js} +8 -9
  91. package/dist/{commands-jeh1b51j.js → commands-wn9q06qr.js} +3 -3
  92. package/dist/{controller-mctfbrse.js → controller-fw608czd.js} +4 -4
  93. package/dist/{controllers-connect-nxa1ddwn.js → controllers-connect-63j5rdcm.js} +20 -20
  94. package/dist/{cursor-adapter-qj8vehv6.js → cursor-adapter-6mb9jme8.js} +2 -2
  95. package/dist/{db-2dvay0es.js → db-0m6v5tq4.js} +3 -3
  96. package/dist/{db-b36qn6k3.js → db-y4wfrzbm.js} +4 -2
  97. package/dist/{devin-adapter-xedz98zv.js → devin-adapter-r0yx3gv8.js} +1 -1
  98. package/dist/{dispatcher-gndbta01.js → dispatcher-9tq2zzdj.js} +17 -17
  99. package/dist/{docker-866qpzt9.js → docker-j75atvpt.js} +2 -2
  100. package/dist/{dsh-adapter-f75sz821.js → dsh-adapter-t09sv4tq.js} +2 -2
  101. package/dist/{e2b-jbm7mj93.js → e2b-7s9dscap.js} +2 -2
  102. package/dist/{e2b-3gpc2n3w.js → e2b-a7vzs2vj.js} +2 -2
  103. package/dist/{easter-egg-3d-533knw22.js → easter-egg-3d-fbwvmwhe.js} +1 -1
  104. package/dist/{embedding-space-4p05vb2x.js → embedding-space-wh8de1t9.js} +6 -6
  105. package/dist/{embeddings-m6768mgh.js → embeddings-3hpbdtjr.js} +1 -1
  106. package/dist/{event-bus-e66gh7cc.js → event-bus-tr6h3gv8.js} +1 -1
  107. package/dist/{execute-b3mrb1mv.js → execute-4bdf8sdy.js} +1 -1
  108. package/dist/{external-channel-gjv3jne3.js → external-channel-ts2fwqh0.js} +2 -2
  109. package/dist/fx-adapter-1rnxnf56.js +17 -0
  110. package/dist/grok-adapter-efhmf1r8.js +17 -0
  111. package/dist/handlers-anrr3py9.js +32 -0
  112. package/dist/{heartbeat-a1tv60gt.js → heartbeat-2ze5fzpc.js} +20 -20
  113. package/dist/{hook-8h5dzcgq.js → hook-ca54yd4s.js} +5 -5
  114. package/dist/{hook-cyaps9ba.js → hook-gaehe2w5.js} +7 -7
  115. package/dist/{http-t15mhbd9.js → http-jfg8t2yk.js} +3861 -1798
  116. package/dist/{index-tvfafeyy.js → index-3gv6sc4z.js} +1 -1
  117. package/dist/{index-qav6455f.js → index-3yvzbhxd.js} +97 -22
  118. package/dist/index-8w2aznds.js +33 -0
  119. package/dist/{index-w1zqf680.js → index-csgrxedz.js} +1 -1
  120. package/dist/index-qnjvr362.js +37 -0
  121. package/dist/index-yzxd3sn9.js +32 -0
  122. package/dist/{keepalive-91s7hzrb.js → keepalive-k2a3qe73.js} +4 -4
  123. package/dist/lead-zhxqbfdv.js +69 -0
  124. package/dist/{maintenance-7pjmy5xy.js → maintenance-gb5sd5nc.js} +1 -1
  125. package/dist/{node-4c5jqxr3.js → node-7qsx5kvm.js} +1 -1
  126. package/dist/{oauth-refresh-sweep-rzqfm94j.js → oauth-refresh-sweep-y7rm6bkb.js} +3 -3
  127. package/dist/{onboard-74st7pag.js → onboard-jmc5qerv.js} +3 -3
  128. package/dist/{opencode-adapter-arn7gm8q.js → opencode-adapter-7eade9ev.js} +6 -7
  129. package/dist/{otel-impl-rnzey8cb.js → otel-impl-8j1xhxqd.js} +2 -2
  130. package/dist/{pi-mono-adapter-6mkwq64n.js → pi-mono-adapter-yqmaf32x.js} +13 -13
  131. package/dist/{pricing-refresh-ha21jhk7.js → pricing-refresh-1nj722h6.js} +2 -2
  132. package/dist/{rbac-roles-wqhma4dr.js → rbac-roles-b1mtr6dr.js} +3 -3
  133. package/dist/{rbac-roles-59dxachk.js → rbac-roles-n1f3frk1.js} +2 -2
  134. package/dist/{render-v2-14kpzx12.js → render-v2-1gfpd8rj.js} +4 -4
  135. package/dist/{resume-gsa5fb5f.js → resume-w1s1eh5v.js} +7 -7
  136. package/dist/{runtime-1hv06jsn.js → runtime-84g5egsc.js} +1 -1
  137. package/dist/{session-access-skm7bnp6.js → session-access-y6z1txk4.js} +4 -4
  138. package/dist/{session-source-backfill-pbqzbncv.js → session-source-backfill-gxxwfh12.js} +3 -3
  139. package/dist/{setup-5yermsem.js → setup-r91gstyk.js} +1 -1
  140. package/dist/{virtual-modules-gazyapte.js → virtual-modules-cgnj6kme.js} +3 -3
  141. package/dist/{work-objects-xj0ck0w4.js → work-objects-qcxzg61c.js} +20 -20
  142. package/dist/worker-7j2907g6.js +69 -0
  143. package/dist/{worker-follow-up-911xc0b8.js → worker-follow-up-y2d2h7km.js} +17 -17
  144. package/dist/{x-2fyrt5pp.js → x-qhxq2ama.js} +2 -2
  145. package/openapi.json +1214 -108
  146. package/package.json +3 -3
  147. package/src/be/db/tasks/read.ts +33 -0
  148. package/src/be/db.ts +32 -7
  149. package/src/be/migrations/289_automation_savings_daily.sql +47 -0
  150. package/src/be/migrations/291_task_slack_participants.sql +4 -0
  151. package/src/be/migrations/293_savings_component_links.sql +58 -0
  152. package/src/be/migrations/296_automation_savings_daily_read_index.sql +6 -0
  153. package/src/be/model-profile-check.ts +10 -2
  154. package/src/be/savings/compute.ts +511 -16
  155. package/src/be/savings/model.ts +282 -14
  156. package/src/be/savings/read.ts +1500 -0
  157. package/src/be/savings/rollup.ts +571 -0
  158. package/src/be/scripts/run-credential.ts +15 -3
  159. package/src/be/scripts/typecheck.ts +86 -4
  160. package/src/be/seed-scripts/catalog/dreaming-learnings.ts +10 -2
  161. package/src/be/seed-scripts/catalog/dreaming-memtax-create.ts +70 -4
  162. package/src/be/swarm-config-guard.ts +8 -0
  163. package/src/be/users.ts +29 -2
  164. package/src/commands/runner.ts +159 -41
  165. package/src/extensions/contract-types.generated.ts +1 -1
  166. package/src/http/index.ts +8 -1
  167. package/src/http/poll.ts +14 -1
  168. package/src/http/requested-by.ts +97 -1
  169. package/src/http/savings.ts +676 -190
  170. package/src/http/scripts.ts +26 -15
  171. package/src/http/tasks.ts +43 -5
  172. package/src/prompts/session-templates.ts +80 -3
  173. package/src/providers/acp-targets.ts +1 -1
  174. package/src/providers/amp-adapter.ts +1 -1
  175. package/src/providers/claude-adapter.ts +0 -20
  176. package/src/providers/claude-flag-settings.ts +12 -10
  177. package/src/providers/codex-adapter.ts +9 -34
  178. package/src/providers/opencode-adapter.ts +34 -12
  179. package/src/scheduler/scheduler.ts +20 -14
  180. package/src/scripts-runtime/ctx.ts +1 -1
  181. package/src/scripts-runtime/executors/quickjs-bundle.ts +1 -0
  182. package/src/scripts-runtime/executors/quickjs-prelude.ts +162 -2
  183. package/src/scripts-runtime/executors/quickjs-runner.ts +4 -1
  184. package/src/scripts-runtime/stdlib/fetch.ts +113 -15
  185. package/src/scripts-runtime/stdlib/index.ts +3 -1
  186. package/src/scripts-runtime/stdlib/retry.ts +174 -0
  187. package/src/scripts-runtime/swarm-sdk.ts +186 -17
  188. package/src/scripts-runtime/types/stdlib.d.ts +86 -4
  189. package/src/scripts-runtime/types/swarm-extension.d.ts +26 -0
  190. package/src/scripts-runtime/types/swarm-sdk.d.ts +60 -2
  191. package/src/slack/actions.ts +1 -0
  192. package/src/slack/assistant.ts +2 -0
  193. package/src/slack/enrich.ts +144 -50
  194. package/src/slack/handlers.ts +37 -95
  195. package/src/slack/templates.ts +9 -0
  196. package/src/slack/thread-buffer.ts +45 -71
  197. package/src/slack/thread-participants.ts +187 -0
  198. package/src/tests/base-prompt.test.ts +5 -4
  199. package/src/tests/claude-adapter-binary.test.ts +7 -1
  200. package/src/tests/claude-adapter.test.ts +10 -64
  201. package/src/tests/claude-flag-settings.test.ts +15 -11
  202. package/src/tests/claude-hook-credentials.test.ts +0 -1
  203. package/src/tests/claude-sdk-lifecycle.test.ts +5 -1
  204. package/src/tests/codex-adapter.test.ts +17 -78
  205. package/src/tests/create-task-vcs-repo.test.ts +136 -0
  206. package/src/tests/db-task-read-contract.test.ts +2 -0
  207. package/src/tests/db-task-write-contract.test.ts +1 -0
  208. package/src/tests/docs-index-footprint.test.js +3 -3
  209. package/src/tests/dreaming-learnings.test.ts +104 -0
  210. package/src/tests/extensions-pre-task.test.ts +4 -2
  211. package/src/tests/fetch-resolved-env.test.ts +47 -1
  212. package/src/tests/opencode-adapter.test.ts +53 -6
  213. package/src/tests/prompt-template-session.test.ts +17 -1
  214. package/src/tests/runner-requester-profile.test.ts +139 -1
  215. package/src/tests/savings-compound.test.ts +774 -0
  216. package/src/tests/savings-compute.test.ts +7 -198
  217. package/src/tests/savings-fleet-latency.test.ts +143 -0
  218. package/src/tests/savings-fleet-read.test.ts +195 -0
  219. package/src/tests/savings-fleet-scale.test.ts +222 -0
  220. package/src/tests/savings-model.test.ts +212 -0
  221. package/src/tests/savings-read.test.ts +367 -0
  222. package/src/tests/savings-rollup.test.ts +766 -0
  223. package/src/tests/savings-scripts.test.ts +611 -0
  224. package/src/tests/script-connections.test.ts +2 -0
  225. package/src/tests/script-executor-conformance.test.ts +444 -0
  226. package/src/tests/scripts-http.test.ts +55 -0
  227. package/src/tests/scripts-runtime-fetch.test.ts +2 -2
  228. package/src/tests/secret-rules.test.ts +124 -1
  229. package/src/tests/secret-scrubber.test.ts +1 -1
  230. package/src/tests/slack-dm-implicit-mention.test.ts +20 -1
  231. package/src/tests/slack-identity-resolution.test.ts +23 -0
  232. package/src/tests/slack-inbound-files.test.ts +2 -1
  233. package/src/tests/slack-thread-participants.test.ts +429 -0
  234. package/src/tests/tool-annotations.test.ts +30 -0
  235. package/src/types.ts +31 -0
  236. package/src/utils/mcp-server-fetcher.test.ts +89 -0
  237. package/src/utils/mcp-server-fetcher.ts +13 -5
  238. package/src/utils/request-auth-context.ts +24 -0
  239. package/src/utils/secret-rules.generated.ts +1 -1
  240. package/src/utils/secret-scrubber.ts +154 -29
  241. package/src/workflows/executors/swarm-script.ts +23 -19
  242. package/templates/skills/swarm-scripts/SKILL.md +5 -4
  243. package/templates/skills/swarm-scripts/content.md +5 -4
  244. package/templates/skills/work-on-task/SKILL.md +1 -1
  245. package/templates/skills/work-on-task/content.md +1 -1
  246. package/templates/workflows/dreaming/content.md +1 -1
  247. package/dist/acp-adapter-fqzkxyra.js +0 -15
  248. package/dist/cli-4bd1rck6.js +0 -4
  249. package/dist/cli-xf3qw745.js +0 -104
  250. package/dist/fx-adapter-rpsgb1tw.js +0 -18
  251. package/dist/grok-adapter-n2m3zjg1.js +0 -18
  252. package/dist/handlers-nv8edn19.js +0 -32
  253. package/dist/index-ksmyd6kc.js +0 -37
  254. package/dist/index-rjnrje98.js +0 -32
  255. package/dist/index-tv3413wy.js +0 -33
  256. package/dist/lead-3hmddvrm.js +0 -70
  257. package/dist/worker-qgg0m2gw.js +0 -70
  258. package/src/providers/ctx-mode-env.ts +0 -10
@@ -0,0 +1,774 @@
1
+ import { afterAll, beforeAll, describe, expect, test } from "bun:test";
2
+ import { unlink } from "node:fs/promises";
3
+ import { createServer as createHttpServer, type IncomingMessage, type Server } from "node:http";
4
+ import {
5
+ closeDb,
6
+ createAgent,
7
+ createSessionCost,
8
+ createTaskExtended,
9
+ createWorkflow,
10
+ createWorkflowRun,
11
+ getDbClient,
12
+ initDb,
13
+ recordInlineScriptRun,
14
+ upsertSwarmConfig,
15
+ } from "../be/db";
16
+ import type { SavingsSql } from "../be/savings/compute";
17
+ import {
18
+ CURVE,
19
+ type CurveSet,
20
+ MODEL_VERSION,
21
+ SAVINGS_CALIBRATION_KEY,
22
+ SAVINGS_TIERS,
23
+ } from "../be/savings/model";
24
+ import {
25
+ readScriptSavings,
26
+ readWorkflowComponents,
27
+ readWorkflowSavings,
28
+ resetSavingsReadCache,
29
+ } from "../be/savings/read";
30
+ import { resetSavingsRollupForTests, runSavingsRollupTick } from "../be/savings/rollup";
31
+ import { mintScriptRunToken, resolveSessionToken } from "../be/users";
32
+ import { clearCalibrationCache, handleSavings, resetSavingsRefreshCache } from "../http/savings";
33
+ import { getPathSegments, parseQueryParams } from "../http/utils";
34
+ import { beginRequestAuthScope, setRequestAuth } from "../utils/request-auth-context";
35
+ import { listenOnFreePort } from "./test-net";
36
+
37
+ const TEST_DB_PATH = "./test-savings-compound.sqlite";
38
+ // The route reads the window ending at the real clock, so the fixture lives two days back.
39
+ const NOW = Date.now();
40
+ const DAY = new Date(NOW - 2 * 86_400_000).toISOString().slice(0, 10);
41
+ const at = (sec: number) => new Date(Date.parse(`${DAY}T10:00:00.000Z`) + sec * 1000).toISOString();
42
+
43
+ // The route's refresh path reads the DB file from a child process, so this
44
+ // file opts out of the in-memory template (as savings-rollup.test.ts does).
45
+ const testGlobals = globalThis as typeof globalThis & {
46
+ __testMigrationTemplate?: Uint8Array;
47
+ __savedCompoundTemplate?: Uint8Array;
48
+ };
49
+
50
+ const inProcessSql: SavingsSql = (sql, params) => getDbClient().query(sql, params);
51
+
52
+ async function removeDbFiles(path: string): Promise<void> {
53
+ for (const suffix of ["", "-wal", "-shm"]) {
54
+ try {
55
+ await unlink(path + suffix);
56
+ } catch (error) {
57
+ if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error;
58
+ }
59
+ }
60
+ }
61
+
62
+ async function run(
63
+ id: string,
64
+ workflowId: string,
65
+ trigger: string,
66
+ startedAt: string,
67
+ extra: { parentStepId?: string; sourceStepId?: string } = {},
68
+ ) {
69
+ await getDbClient().run(
70
+ `INSERT INTO workflow_runs (id, workflowId, triggerType, status, startedAt, parentStepId, parentStepAttempt, sourceStepId)
71
+ VALUES (?, ?, ?, 'completed', ?, ?, 0, ?)`,
72
+ [id, workflowId, trigger, startedAt, extra.parentStepId ?? null, extra.sourceStepId ?? null],
73
+ );
74
+ }
75
+
76
+ async function step(
77
+ id: string,
78
+ runId: string,
79
+ nodeId: string,
80
+ nodeType: string,
81
+ startedAt: string,
82
+ output: unknown = null,
83
+ ) {
84
+ await getDbClient().run(
85
+ `INSERT INTO workflow_run_steps (id, runId, nodeId, nodeType, status, startedAt, finishedAt, output)
86
+ VALUES (?, ?, ?, ?, 'completed', ?, ?, ?)`,
87
+ [
88
+ id,
89
+ runId,
90
+ nodeId,
91
+ nodeType,
92
+ startedAt,
93
+ new Date(Date.parse(startedAt) + 2000).toISOString(),
94
+ output === null ? null : JSON.stringify(output),
95
+ ],
96
+ );
97
+ }
98
+
99
+ /** Run `fn` with the request auth of a script run's token carrying `provenance`. */
100
+ async function asScriptRun<T>(
101
+ agentId: string,
102
+ provenance: { sourceStepId?: string | null; sourceScriptRunId?: string | null },
103
+ fn: () => Promise<T>,
104
+ ): Promise<T> {
105
+ return await Promise.resolve().then(async () => {
106
+ beginRequestAuthScope();
107
+ setRequestAuth({} as IncomingMessage, {
108
+ kind: "agent",
109
+ tokenKind: "agent",
110
+ agentId,
111
+ taskId: null,
112
+ runtimeId: null,
113
+ tokenId: "t",
114
+ expiresAt: "9999-12-31T00:00:00.000Z",
115
+ ...provenance,
116
+ });
117
+ return await fn();
118
+ });
119
+ }
120
+
121
+ describe("savings with components", () => {
122
+ let agentId: string;
123
+ let root: string;
124
+ let child: string;
125
+ let grandchild: string;
126
+ let other: string;
127
+ let leaf: string;
128
+ let server: Server;
129
+ let port: number;
130
+
131
+ async function cost(taskId: string, usd: number) {
132
+ await createSessionCost({
133
+ sessionId: crypto.randomUUID(),
134
+ taskId,
135
+ agentId,
136
+ totalCostUsd: usd,
137
+ durationMs: 60_000,
138
+ numTurns: 3,
139
+ model: "claude-opus-5-5",
140
+ });
141
+ }
142
+
143
+ async function task(createdAt: string, opts: Parameters<typeof createTaskExtended>[1]) {
144
+ const t = await createTaskExtended(`compound fixture ${createdAt}`, { agentId, ...opts });
145
+ await getDbClient().run("UPDATE agent_tasks SET createdAt=? WHERE id=?", [createdAt, t.id]);
146
+ return t.id;
147
+ }
148
+
149
+ const get = async (query: string) => {
150
+ resetSavingsRefreshCache();
151
+ const res = await fetch(`http://127.0.0.1:${port}/api/savings/jobs?${query}`);
152
+ return { status: res.status, body: (await res.json()) as Record<string, any> };
153
+ };
154
+
155
+ beforeAll(async () => {
156
+ testGlobals.__savedCompoundTemplate = testGlobals.__testMigrationTemplate;
157
+ testGlobals.__testMigrationTemplate = undefined;
158
+ await removeDbFiles(TEST_DB_PATH);
159
+ initDb(TEST_DB_PATH);
160
+ await resetSavingsRollupForTests();
161
+ agentId = (await createAgent({ name: "compound-agent", isLead: false, status: "idle" })).id;
162
+ for (const [name, source] of [
163
+ ["compound-starter", "await ctx.swarm.workflow_trigger({}); await ctx.swarm.task_send({});"],
164
+ ["compound-helper", "await a(); await b(); await c();"],
165
+ ] as const) {
166
+ await getDbClient().run(
167
+ `INSERT INTO scripts (id, name, scope, source, description, intent, signatureJson, contentHash)
168
+ VALUES (?, ?, 'global', ?, 'savings fixture', 'fixture', '{}', ?)`,
169
+ [
170
+ crypto.randomUUID(),
171
+ name,
172
+ `export default async function (args, ctx) { ${source} }`,
173
+ crypto.randomUUID(),
174
+ ],
175
+ );
176
+ }
177
+ const notify = { nodes: [{ id: "hello", type: "notify", config: {} }] };
178
+ root = (
179
+ await createWorkflow({
180
+ name: "compound-root",
181
+ definition: { nodes: [{ id: "dispatch", type: "sub-workflow", config: {} }] },
182
+ })
183
+ ).id;
184
+ const starter = {
185
+ nodes: [
186
+ { id: "start", type: "swarm-script", config: { scriptName: "compound-starter" } },
187
+ { id: "work", type: "agent-task", config: {} },
188
+ { id: "back", type: "sub-workflow", config: {} },
189
+ ],
190
+ };
191
+ child = (await createWorkflow({ name: "compound-child", definition: starter })).id;
192
+ other = (await createWorkflow({ name: "compound-other", definition: starter })).id;
193
+ grandchild = (await createWorkflow({ name: "compound-grandchild", definition: notify })).id;
194
+ leaf = (await createWorkflow({ name: "compound-leaf", definition: notify })).id;
195
+
196
+ // root -> child: four sub-workflow runs. Each child run's script step
197
+ // starts a grandchild run named in its output (unstamped, 2 s in).
198
+ for (let i = 1; i <= 4; i++) {
199
+ await run(`r${i}`, root, "manual", at(i * 60));
200
+ await step(`r${i}-dispatch`, `r${i}`, "dispatch", "sub-workflow", at(i * 60));
201
+ await run(`c${i}`, child, "manual", at(i * 60 + 1), { parentStepId: `r${i}-dispatch` });
202
+ await step(`c${i}-start`, `c${i}`, "start", "swarm-script", at(i * 60 + 1), {
203
+ result: { started: `00000000-0000-4000-8000-00000000000${i}` },
204
+ });
205
+ await run(`00000000-0000-4000-8000-00000000000${i}`, grandchild, "api", at(i * 60 + 2));
206
+ }
207
+ // A cycle: one child run starts a root run as its sub-workflow.
208
+ await step("c4-back", "c4", "back", "sub-workflow", at(4 * 60 + 1));
209
+ await run("r5", root, "manual", at(4 * 60 + 2), { parentStepId: "c4-back" });
210
+ // Stamped wins: c1's output also names this grandchild run, but its run
211
+ // token said compound-other's step started it.
212
+ await run("x1", other, "manual", at(30));
213
+ await step("x1-start", "x1", "start", "swarm-script", at(30), {});
214
+ await getDbClient().run("UPDATE workflow_run_steps SET output=? WHERE id='c1-start'", [
215
+ JSON.stringify({
216
+ result: {
217
+ started: "00000000-0000-4000-8000-000000000001",
218
+ seen: "00000000-0000-4000-8000-000000000009",
219
+ },
220
+ }),
221
+ ]);
222
+ await run("00000000-0000-4000-8000-000000000009", grandchild, "api", at(61), {
223
+ sourceStepId: "x1-start",
224
+ });
225
+ // child's agent-task node task ($0.50) with a descendant ($2), and a task
226
+ // its script step created ($1), named in the step output.
227
+ const nodeTask = await task(at(62), { source: "workflow", workflowRunId: "c1" });
228
+ await cost(nodeTask, 0.5);
229
+ const below = await task(at(63), { parentTaskId: nodeTask });
230
+ await cost(below, 2);
231
+ const fromStep = await task(at(3 * 60 + 2), {});
232
+ await cost(fromStep, 1);
233
+ await getDbClient().run("UPDATE workflow_run_steps SET output=? WHERE id='c3-start'", [
234
+ JSON.stringify({
235
+ result: { started: "00000000-0000-4000-8000-000000000003", task: fromStep },
236
+ }),
237
+ ]);
238
+ // A nested script run made under c2's step token.
239
+ await getDbClient().run(
240
+ `INSERT INTO script_runs (id, agentId, scriptName, source, args, kind, status, startedAt, finishedAt, sourceStepId)
241
+ VALUES ('nested-1', ?, 'compound-helper', '', 'null', 'inline', 'completed', ?, ?, 'c2-start')`,
242
+ [agentId, at(2 * 60 + 1), at(2 * 60 + 2)],
243
+ );
244
+ // That nested run created a task through its own token: an exact effect
245
+ // link, though compound-helper's source cannot dispatch.
246
+ await getDbClient().run("UPDATE agent_tasks SET sourceScriptRunId='nested-1' WHERE id=?", [
247
+ await task(at(2 * 60 + 2), {}),
248
+ ]);
249
+ // A leaf workflow with nothing below it.
250
+ for (let i = 1; i <= 3; i++) {
251
+ await run(`l${i}`, leaf, "manual", at(600 + i));
252
+ await step(`l${i}-hello`, `l${i}`, "hello", "notify", at(600 + i));
253
+ }
254
+
255
+ const stats = await runSavingsRollupTick(inProcessSql, { now: NOW });
256
+ expect(stats.lastError).toBeNull();
257
+
258
+ server = createHttpServer(async (req, res) => {
259
+ const handled = await handleSavings(
260
+ req,
261
+ res,
262
+ getPathSegments(req.url || ""),
263
+ parseQueryParams(req.url || ""),
264
+ );
265
+ if (!handled) {
266
+ res.writeHead(404);
267
+ res.end();
268
+ }
269
+ });
270
+ port = await listenOnFreePort(server);
271
+ });
272
+
273
+ afterAll(async () => {
274
+ server?.close();
275
+ await resetSavingsRollupForTests();
276
+ closeDb();
277
+ testGlobals.__testMigrationTemplate = testGlobals.__savedCompoundTemplate;
278
+ testGlobals.__savedCompoundTemplate = undefined;
279
+ await removeDbFiles(TEST_DB_PATH);
280
+ });
281
+
282
+ test("the rollup writes one link row per parent, child and kind", async () => {
283
+ const links = await getDbClient().query<Record<string, unknown>>(
284
+ "SELECT parentJobId, childKind, childJobId, linkKind, n, actualUsd FROM automation_savings_links WHERE day=? ORDER BY 1,2,3,4",
285
+ [DAY],
286
+ );
287
+ const named = links.map((l) => ({ ...l, actualUsd: Number(l.actualUsd) }));
288
+ expect(named).toEqual(
289
+ expect.arrayContaining([
290
+ {
291
+ parentJobId: root,
292
+ childKind: "workflow",
293
+ childJobId: child,
294
+ linkKind: "sub-workflow",
295
+ n: 4,
296
+ actualUsd: 0,
297
+ },
298
+ {
299
+ parentJobId: child,
300
+ childKind: "workflow",
301
+ childJobId: root,
302
+ linkKind: "sub-workflow",
303
+ n: 1,
304
+ actualUsd: 0,
305
+ },
306
+ {
307
+ parentJobId: child,
308
+ childKind: "workflow",
309
+ childJobId: grandchild,
310
+ linkKind: "step-workflow",
311
+ n: 4,
312
+ actualUsd: 0,
313
+ },
314
+ {
315
+ parentJobId: other,
316
+ childKind: "workflow",
317
+ childJobId: grandchild,
318
+ linkKind: "step-workflow",
319
+ n: 1,
320
+ actualUsd: 0,
321
+ },
322
+ {
323
+ parentJobId: child,
324
+ childKind: "script",
325
+ childJobId: "compound-helper",
326
+ linkKind: "step-script",
327
+ n: 1,
328
+ actualUsd: 0,
329
+ },
330
+ {
331
+ parentJobId: child,
332
+ childKind: "task",
333
+ childJobId: "",
334
+ linkKind: "step-task",
335
+ n: 1,
336
+ actualUsd: 1,
337
+ },
338
+ {
339
+ parentJobId: child,
340
+ childKind: "task",
341
+ childJobId: "",
342
+ linkKind: "descendant-task",
343
+ n: 1,
344
+ actualUsd: 2,
345
+ },
346
+ ]),
347
+ );
348
+ expect(links).toHaveLength(7);
349
+ });
350
+
351
+ test("a task stamped with its script run is that run's effect", async () => {
352
+ const bucket = await getDbClient().get<{ effectRuns: number }>(
353
+ "SELECT effectRuns FROM automation_savings_daily WHERE day=? AND jobKind='script' AND jobId='compound-helper'",
354
+ [DAY],
355
+ );
356
+ expect(bucket?.effectRuns).toBe(1);
357
+ });
358
+
359
+ test("stamped rows win over the output-id link", async () => {
360
+ const { body } = await get(`workflowId=${other}&components=true&days=7`);
361
+ expect(body.components).toEqual([
362
+ expect.objectContaining({ kind: "workflow", workflowId: grandchild, runs: 1, depth: 1 }),
363
+ ]);
364
+ });
365
+
366
+ test("the tree equals the sum of the rows it reaches", async () => {
367
+ const { status, body } = await get(`workflowId=${root}&components=true&days=7`);
368
+ expect(status).toBe(200);
369
+ const workflows = await readWorkflowSavings({ days: 7, tier: "smart", now: Date.now() });
370
+ const scripts = await readScriptSavings({ days: 7, tier: "smart", now: Date.now() });
371
+ const row = (id: string) => workflows.rows.find((r) => r.workflowId === id)!;
372
+ const helper = scripts.rows.find((r) => r.scriptName === "compound-helper")!;
373
+ // child: 4 of its 4 runs; grandchild: 4 of its 5 runs; helper: 1 of 1. The
374
+ // cycle back to the root and the child's own tasks add nothing.
375
+ const expected =
376
+ row(root).savingUsd.p50 +
377
+ row(child).savingUsd.p50 +
378
+ (row(grandchild).savingUsd.p50 * 4) / 5 +
379
+ helper.savingUsd.p50;
380
+ expect(body.withComponents.savingUsd.p50).toBeCloseTo(expected, 1);
381
+ expect(body.rows[0].savingUsd.p50).toBeCloseTo(row(root).savingUsd.p50, 2);
382
+ expect(body.components.map((c: any) => [c.kind, c.name, c.depth, c.runs])).toEqual(
383
+ expect.arrayContaining([
384
+ ["workflow", "compound-child", 1, 4],
385
+ ["workflow", "compound-grandchild", 2, 4],
386
+ ["script", "compound-helper", 2, 1],
387
+ ]),
388
+ );
389
+ expect(body.components).toHaveLength(3);
390
+ });
391
+
392
+ test("a stored deployment curve prices the components as it prices the root", async () => {
393
+ const deployed = Object.fromEntries(
394
+ SAVINGS_TIERS.map((t) => [
395
+ t,
396
+ { usd: CURVE[t].usd.map((v, i) => v * 3 + i * 0.01), hrs: CURVE[t].hrs },
397
+ ]),
398
+ ) as CurveSet;
399
+ const expectedTree = async (set?: CurveSet) => {
400
+ const now = Date.now();
401
+ const workflows = await readWorkflowSavings({ days: 7, tier: "smart", now, curve: set });
402
+ const scripts = await readScriptSavings({ days: 7, tier: "smart", now, curve: set });
403
+ const row = (id: string) => workflows.rows.find((r) => r.workflowId === id)!;
404
+ const helper = scripts.rows.find((r) => r.scriptName === "compound-helper")!;
405
+ return (
406
+ row(root).savingUsd.p50 +
407
+ row(child).savingUsd.p50 +
408
+ (row(grandchild).savingUsd.p50 * 4) / 5 +
409
+ helper.savingUsd.p50
410
+ );
411
+ };
412
+ try {
413
+ await upsertSwarmConfig({
414
+ scope: "global",
415
+ key: SAVINGS_CALIBRATION_KEY,
416
+ value: JSON.stringify({
417
+ calibratedAt: "2026-12-01",
418
+ model: "claude-opus-5-5",
419
+ curve: deployed,
420
+ }),
421
+ });
422
+ clearCalibrationCache();
423
+ resetSavingsRefreshCache();
424
+ const { body } = await get(`workflowId=${root}&components=true&days=7`);
425
+ expect(body.calibrationSource).toBe("deployment");
426
+ const shipped = await expectedTree();
427
+ const withCurve = await expectedTree(deployed);
428
+ expect(withCurve).toBeGreaterThan(shipped * 2);
429
+ expect(body.withComponents.savingUsd.p50).toBeCloseTo(withCurve, 1);
430
+ } finally {
431
+ await getDbClient().run("DELETE FROM swarm_config WHERE key = ?", [SAVINGS_CALIBRATION_KEY]);
432
+ clearCalibrationCache();
433
+ resetSavingsRefreshCache();
434
+ }
435
+ });
436
+
437
+ test("unowned tasks show on their workflow and count in its own row", async () => {
438
+ const { body } = await get(`workflowId=${child}&components=true&days=7`);
439
+ const tasks = body.components.filter((c: any) => c.kind === "task");
440
+ expect(tasks.map((t: any) => [t.linkKind, t.runs, t.actualUsd, t.inOwnRow])).toEqual(
441
+ expect.arrayContaining([
442
+ ["step-task", 1, 1, true],
443
+ ["descendant-task", 1, 2, true],
444
+ ]),
445
+ );
446
+ // $0.50 node task + $2 descendant + $1 step task, all measured on the own row.
447
+ expect(body.rows[0].measuredUsd).toBeCloseTo(3.5, 2);
448
+ });
449
+
450
+ test("a leaf workflow has no components and equals its own runs", async () => {
451
+ const { body } = await get(`workflowId=${leaf}&components=true&days=7`);
452
+ expect(body.components).toEqual([]);
453
+ expect(body.withComponents.savingUsd).toEqual(body.total.savingUsd);
454
+ });
455
+
456
+ test("lists stay own runs only", async () => {
457
+ const before = await get("kind=workflow&days=7");
458
+ await get(`workflowId=${root}&components=true&days=7`);
459
+ const after = await get("kind=workflow&days=7");
460
+ expect(after.body.total).toEqual(before.body.total);
461
+ const own = before.body.rows.reduce((s: number, r: any) => s + r.savingUsd.p50, 0);
462
+ expect(before.body.total.savingUsd.p50).toBeCloseTo(own, 1);
463
+ expect(before.body.components).toBeUndefined();
464
+ expect((await get("kind=workflow&components=true")).status).toBe(400);
465
+ expect((await get("scriptName=compound-helper&components=true")).status).toBe(400);
466
+ });
467
+
468
+ test("a burst of component reads shares one tree for a minute", async () => {
469
+ const read = async () => {
470
+ const res = await fetch(
471
+ `http://127.0.0.1:${port}/api/savings/jobs?workflowId=${leaf}&components=true&days=7`,
472
+ );
473
+ return ((await res.json()) as Record<string, any>).components as unknown[];
474
+ };
475
+ resetSavingsRefreshCache();
476
+ expect(await read()).toEqual([]);
477
+ // A link the held tree has not seen: reads inside the minute keep the held tree.
478
+ await getDbClient().run(
479
+ `INSERT INTO automation_savings_links (day, parentJobId, childKind, childJobId, linkKind, n, actualUsd, keptUsd, modelVersion, computedAt)
480
+ VALUES (?, ?, 'workflow', ?, 'step-workflow', 1, 0, 0, ?, ?)`,
481
+ [DAY, leaf, child, MODEL_VERSION, new Date().toISOString()],
482
+ );
483
+ try {
484
+ expect(await Promise.all([read(), read()])).toEqual([[], []]);
485
+ resetSavingsRefreshCache();
486
+ expect(await read()).toEqual(
487
+ expect.arrayContaining([
488
+ expect.objectContaining({ kind: "workflow", workflowId: child, depth: 1 }),
489
+ ]),
490
+ );
491
+ } finally {
492
+ await getDbClient().run("DELETE FROM automation_savings_links WHERE parentJobId=?", [leaf]);
493
+ }
494
+ });
495
+ });
496
+
497
+ describe("run provenance stamping", () => {
498
+ let agentId: string;
499
+ let workflowId: string;
500
+
501
+ beforeAll(async () => {
502
+ initDb(":memory:");
503
+ agentId = (await createAgent({ name: "stamp-agent", isLead: false, status: "idle" })).id;
504
+ workflowId = (await createWorkflow({ name: "stamp-wf", definition: { nodes: [] } })).id;
505
+ });
506
+
507
+ afterAll(() => closeDb());
508
+
509
+ test("a script run token carries its step and run back to the request", async () => {
510
+ const token = await mintScriptRunToken(agentId, 60_000, {
511
+ sourceStepId: "step-1",
512
+ sourceScriptRunId: "run-1",
513
+ });
514
+ const plain = await mintScriptRunToken(agentId, 60_000);
515
+ expect(await resolveSessionToken(token.plaintext)).toMatchObject({
516
+ kind: "agent",
517
+ sourceStepId: "step-1",
518
+ sourceScriptRunId: "run-1",
519
+ });
520
+ expect(await resolveSessionToken(plain.plaintext)).not.toHaveProperty("sourceStepId");
521
+ });
522
+
523
+ test("rows a script run creates are stamped; rows a workflow owns are not", async () => {
524
+ const ownerRun = await createWorkflowRun({ id: crypto.randomUUID(), workflowId });
525
+ const stamped = await asScriptRun(
526
+ agentId,
527
+ { sourceStepId: "step-1", sourceScriptRunId: "run-1" },
528
+ async () => {
529
+ const task = await createTaskExtended("made by a script", { agentId });
530
+ const owned = await createTaskExtended("node task", {
531
+ agentId,
532
+ workflowRunId: ownerRun.id,
533
+ });
534
+ const manual = await createWorkflowRun({ id: crypto.randomUUID(), workflowId });
535
+ const event = await createWorkflowRun({
536
+ id: crypto.randomUUID(),
537
+ workflowId,
538
+ triggerType: "event",
539
+ });
540
+ const sub = await createWorkflowRun({
541
+ id: crypto.randomUUID(),
542
+ workflowId,
543
+ parentStepId: "parent-step",
544
+ });
545
+ const nested = await recordInlineScriptRun({
546
+ id: crypto.randomUUID(),
547
+ agentId,
548
+ source: "",
549
+ args: null,
550
+ scriptName: "nested",
551
+ status: "completed",
552
+ startedAt: new Date().toISOString(),
553
+ finishedAt: new Date().toISOString(),
554
+ });
555
+ return { task, owned, manual, event, sub, nested };
556
+ },
557
+ );
558
+ const col = async (table: string, id: string, column: string) =>
559
+ (
560
+ await getDbClient().get<Record<string, unknown>>(
561
+ `SELECT ${column} v FROM ${table} WHERE id=?`,
562
+ [id],
563
+ )
564
+ )?.v;
565
+ expect(await col("agent_tasks", stamped.task.id, "sourceStepId")).toBe("step-1");
566
+ expect(await col("agent_tasks", stamped.task.id, "sourceScriptRunId")).toBe("run-1");
567
+ expect(await col("agent_tasks", stamped.owned.id, "sourceStepId")).toBeNull();
568
+ expect(await col("workflow_runs", stamped.manual.id, "sourceStepId")).toBe("step-1");
569
+ expect(await col("workflow_runs", stamped.event.id, "sourceStepId")).toBeNull();
570
+ expect(await col("workflow_runs", stamped.sub.id, "sourceStepId")).toBeNull();
571
+ expect(await col("script_runs", stamped.nested.id, "sourceStepId")).toBe("step-1");
572
+ expect(await col("script_runs", stamped.nested.id, "parentScriptRunId")).toBe("run-1");
573
+
574
+ // Outside a script run's request nothing is stamped.
575
+ const plain = await createTaskExtended("made by hand", { agentId });
576
+ expect(await col("agent_tasks", plain.id, "sourceStepId")).toBeNull();
577
+ });
578
+ });
579
+
580
+ describe("each task counts under one root", () => {
581
+ let agentId: string;
582
+ let chained: string;
583
+ let nodeOwned: string;
584
+ let crossDay: string;
585
+ const chain: string[] = [];
586
+ // Two closed days: D1 then D2.
587
+ const D1 = new Date(NOW - 3 * 86_400_000).toISOString().slice(0, 10);
588
+ const D2 = new Date(NOW - 2 * 86_400_000).toISOString().slice(0, 10);
589
+ const on = (day: string, sec: number) =>
590
+ new Date(Date.parse(`${day}T10:00:00.000Z`) + sec * 1000).toISOString();
591
+
592
+ async function task(
593
+ createdAt: string,
594
+ usd: number,
595
+ opts: { parentTaskId?: string; workflowRunId?: string; sourceStepId?: string } = {},
596
+ ) {
597
+ const t = await createTaskExtended(`root fixture ${createdAt}`, {
598
+ agentId,
599
+ ...(opts.parentTaskId ? { parentTaskId: opts.parentTaskId } : {}),
600
+ ...(opts.workflowRunId ? { source: "workflow", workflowRunId: opts.workflowRunId } : {}),
601
+ });
602
+ await getDbClient().run("UPDATE agent_tasks SET createdAt=?, sourceStepId=? WHERE id=?", [
603
+ createdAt,
604
+ opts.sourceStepId ?? null,
605
+ t.id,
606
+ ]);
607
+ await createSessionCost({
608
+ sessionId: crypto.randomUUID(),
609
+ taskId: t.id,
610
+ agentId,
611
+ totalCostUsd: usd,
612
+ durationMs: 60_000,
613
+ numTurns: 3,
614
+ model: "claude-opus-5-5",
615
+ });
616
+ return t.id;
617
+ }
618
+
619
+ const childTaskUsd = async (day: string, workflowId: string) =>
620
+ Number(
621
+ (
622
+ await getDbClient().get<{ v: number }>(
623
+ "SELECT childTaskUsd v FROM automation_savings_daily WHERE day=? AND jobKind='workflow' AND jobId=?",
624
+ [day, workflowId],
625
+ )
626
+ )?.v,
627
+ );
628
+
629
+ beforeAll(async () => {
630
+ initDb(":memory:");
631
+ await resetSavingsRollupForTests();
632
+ agentId = (await createAgent({ name: "roots-agent", isLead: false, status: "idle" })).id;
633
+ const scripted = {
634
+ nodes: [
635
+ { id: "start", type: "swarm-script", config: { scriptName: "roots-helper" } },
636
+ { id: "work", type: "agent-task", config: {} },
637
+ ],
638
+ };
639
+ chained = (await createWorkflow({ name: "roots-chained", definition: scripted })).id;
640
+ nodeOwned = (await createWorkflow({ name: "roots-node", definition: scripted })).id;
641
+ crossDay = (await createWorkflow({ name: "roots-cross-day", definition: scripted })).id;
642
+
643
+ // Step task A ($1) and step task B ($2) below it: 3, not 5.
644
+ await run("ca", chained, "manual", on(D1, 0));
645
+ await step("ca-start", "ca", "start", "swarm-script", on(D1, 0));
646
+ const a = await task(on(D1, 1), 1, { sourceStepId: "ca-start" });
647
+ await task(on(D1, 2), 2, { sourceStepId: "ca-start", parentTaskId: a });
648
+
649
+ // Node task N ($0.50, its own row) with a stamped child B ($2): 2, not 4.
650
+ await run("na", nodeOwned, "manual", on(D1, 10));
651
+ await step("na-start", "na", "start", "swarm-script", on(D1, 10));
652
+ const n = await task(on(D1, 11), 0.5, { workflowRunId: "na" });
653
+ await task(on(D1, 12), 2, { sourceStepId: "na-start", parentTaskId: n });
654
+
655
+ // Across midnight: step task A on D1 ($1), its unstamped child C on D2
656
+ // ($4, A's), and a stamped child B on D2 ($2, D2's own root).
657
+ await run("xa", crossDay, "manual", on(D1, 20));
658
+ await step("xa-start", "xa", "start", "swarm-script", on(D1, 20));
659
+ await run("xb", crossDay, "manual", on(D2, 20));
660
+ await step("xb-start", "xb", "start", "swarm-script", on(D2, 20));
661
+ const x = await task(on(D1, 21), 1, { sourceStepId: "xa-start" });
662
+ await task(on(D2, 22), 4, { parentTaskId: x });
663
+ await task(on(D2, 23), 2, { sourceStepId: "xb-start", parentTaskId: x });
664
+
665
+ // A chain of 12 workflows, each run starting the next as a sub-workflow.
666
+ for (let i = 0; i < 12; i++) {
667
+ chain.push(
668
+ (
669
+ await createWorkflow({
670
+ name: `roots-chain-${i}`,
671
+ definition: { nodes: [{ id: "next", type: "sub-workflow", config: {} }] },
672
+ })
673
+ ).id,
674
+ );
675
+ await run(`q${i}`, chain[i] as string, "manual", on(D1, 100 + i), {
676
+ ...(i > 0 ? { parentStepId: `q${i - 1}-next` } : {}),
677
+ });
678
+ await step(`q${i}-next`, `q${i}`, "next", "sub-workflow", on(D1, 100 + i));
679
+ }
680
+
681
+ for (let i = 0; i < 5; i++) {
682
+ const stats = await runSavingsRollupTick(inProcessSql, { now: NOW, budgetMs: 60_000 });
683
+ expect(stats.lastError).toBeNull();
684
+ if (stats.daysPending === 0) break;
685
+ }
686
+ });
687
+
688
+ afterAll(async () => {
689
+ await resetSavingsRollupForTests();
690
+ closeDb();
691
+ });
692
+
693
+ test("a step task below another step task counts once", async () => {
694
+ expect(await childTaskUsd(D1, chained)).toBeCloseTo(3, 6);
695
+ });
696
+
697
+ test("a stamped task below a node task counts under its own step", async () => {
698
+ expect(await childTaskUsd(D1, nodeOwned)).toBeCloseTo(2, 6);
699
+ });
700
+
701
+ test("a chain across midnight splits at the stamped task", async () => {
702
+ expect(await childTaskUsd(D1, crossDay)).toBeCloseTo(5, 6);
703
+ expect(await childTaskUsd(D2, crossDay)).toBeCloseTo(2, 6);
704
+ });
705
+
706
+ test("the kept spend moves measured spend, not the saving", async () => {
707
+ const read = async () =>
708
+ (await readWorkflowSavings({ days: 7, tier: "smart", now: NOW })).rows.find(
709
+ (r) => r.workflowId === chained,
710
+ )!;
711
+ const counted = await read();
712
+ await getDbClient().run(
713
+ "UPDATE automation_savings_daily SET childTaskUsd=0, childTaskMs=0 WHERE jobKind='workflow' AND jobId=?",
714
+ [chained],
715
+ );
716
+ // A raw UPDATE bypasses the rollup writers, so drop the cached fleet read by hand.
717
+ resetSavingsReadCache();
718
+ const without = await read();
719
+ expect(counted.measuredUsd - without.measuredUsd).toBeCloseTo(3, 6);
720
+ expect(counted.savingUsd.p50).toBeGreaterThan(0);
721
+ for (const q of ["p10", "p50", "p90"] as const) {
722
+ expect(counted.savingUsd[q]).toBeCloseTo(without.savingUsd[q], 9);
723
+ }
724
+ });
725
+
726
+ test("the component tree stops at depth 10", async () => {
727
+ const own = (await readWorkflowSavings({ days: 7, tier: "smart", now: NOW })).rows.find(
728
+ (r) => r.workflowId === chain[0],
729
+ )!;
730
+ const tree = await readWorkflowComponents({
731
+ days: 7,
732
+ tier: "smart",
733
+ now: NOW,
734
+ workflowId: chain[0] as string,
735
+ own,
736
+ });
737
+ const depthOf = new Map(tree.components.map((c) => [c.workflowId, c.depth]));
738
+ expect(Math.max(...depthOf.values())).toBe(10);
739
+ expect(depthOf.get(chain[10])).toBe(10);
740
+ expect(depthOf.has(chain[11])).toBe(false);
741
+ expect(tree.components).toHaveLength(10);
742
+ });
743
+
744
+ test("links on the window's partial first day count by the share inside it", async () => {
745
+ const own = (await readWorkflowSavings({ days: 7, tier: "smart", now: NOW })).rows.find(
746
+ (r) => r.workflowId === chain[0],
747
+ )!;
748
+ const parent = "boundary-root";
749
+ // 7 x 24h ending 06:00 starts at 06:00 on the first day: 18 of its 24 hours count.
750
+ const now = Date.parse("2030-01-08T06:00:00.000Z");
751
+ const link = (day: string, n: number) =>
752
+ getDbClient().run(
753
+ `INSERT INTO automation_savings_links (day, parentJobId, childKind, childJobId, linkKind, n, actualUsd, keptUsd, modelVersion, computedAt)
754
+ VALUES (?, ?, 'workflow', 'boundary-child', 'step-workflow', ?, 0, 0, ?, ?)`,
755
+ [day, parent, n, MODEL_VERSION, new Date().toISOString()],
756
+ );
757
+ await link("2029-12-31", 2);
758
+ await link("2030-01-01", 4);
759
+ await link("2030-01-05", 1);
760
+ try {
761
+ const tree = await readWorkflowComponents({
762
+ days: 7,
763
+ tier: "smart",
764
+ now,
765
+ workflowId: parent,
766
+ own: { ...own, workflowId: parent },
767
+ });
768
+ expect(tree.components).toHaveLength(1);
769
+ expect(tree.components[0]!.runs).toBeCloseTo(4 * 0.75 + 1, 9);
770
+ } finally {
771
+ await getDbClient().run("DELETE FROM automation_savings_links WHERE parentJobId=?", [parent]);
772
+ }
773
+ });
774
+ });