@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,766 @@
1
+ import { afterAll, beforeAll, describe, expect, test } from "bun:test";
2
+ import { unlink } from "node:fs/promises";
3
+ import { createServer as createHttpServer, type Server } from "node:http";
4
+ import {
5
+ closeDb,
6
+ createAgent,
7
+ createSessionCost,
8
+ createTaskExtended,
9
+ createWorkflow,
10
+ createWorkflowRun,
11
+ getDbClient,
12
+ getWorkflow,
13
+ initDb,
14
+ upsertSwarmConfig,
15
+ } from "../be/db";
16
+ import { computeWorkflowWindow, type SavingsSql } from "../be/savings/compute";
17
+ import {
18
+ CURVE,
19
+ MODEL_VERSION,
20
+ priceWorkflow,
21
+ SAVINGS_CALIBRATION_KEY,
22
+ SAVINGS_TIERS,
23
+ } from "../be/savings/model";
24
+ import { readWorkflowSavings, resetSavingsReadCache } from "../be/savings/read";
25
+ import {
26
+ daysToCompute,
27
+ getSavingsRollupStats,
28
+ ROLLUP_DAYS,
29
+ refreshWorkflowToday,
30
+ resetSavingsRollupForTests,
31
+ runSavingsRollupTick,
32
+ stopSavingsRollup,
33
+ utcDay,
34
+ workflowDaysToCompute,
35
+ } from "../be/savings/rollup";
36
+ import { getDbQueryConcurrencyCap } from "../http/db-query-shared";
37
+ import {
38
+ clearCalibrationCache,
39
+ handleSavings,
40
+ resetSavingsRefreshCache,
41
+ savingsRequestSql,
42
+ } from "../http/savings";
43
+ import { getPathSegments, parseQueryParams } from "../http/utils";
44
+ import { listenOnFreePort } from "./test-net";
45
+
46
+ const TEST_DB_PATH = "./test-savings-rollup.sqlite";
47
+ const NOW = Date.parse("2026-10-31T12:00:00.000Z");
48
+ const HOUR = 3_600_000;
49
+ const WEEK = ["25", "26", "27", "28", "29", "30", "31"].map((d) => `2026-10-${d}`);
50
+ const DEFINITION = { nodes: [{ id: "hello", type: "notify", config: {} }] };
51
+
52
+ // The route's refresh path reads the DB file from a child process (the
53
+ // bounded executor), so this file opts out of the in-memory template.
54
+ const testGlobals = globalThis as typeof globalThis & {
55
+ __testMigrationTemplate?: Uint8Array;
56
+ __savedRollupTemplate?: Uint8Array;
57
+ };
58
+
59
+ const inProcessSql: SavingsSql = (sql, params) => getDbClient().query(sql, params);
60
+
61
+ async function removeDbFiles(path: string): Promise<void> {
62
+ for (const suffix of ["", "-wal", "-shm"]) {
63
+ try {
64
+ await unlink(path + suffix);
65
+ } catch (error) {
66
+ if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error;
67
+ }
68
+ }
69
+ }
70
+
71
+ /** `count` runs of one workflow on `day`, one a minute from 00:00. */
72
+ async function bulkRuns(workflowId: string, trigger: string, day: string, count: number) {
73
+ await getDbClient().run(
74
+ `INSERT INTO workflow_runs (id, workflowId, triggerType, status, startedAt)
75
+ WITH RECURSIVE seq(i) AS (SELECT 0 UNION ALL SELECT i + 1 FROM seq WHERE i < ? - 1)
76
+ SELECT ? || '-' || ? || '-' || i, ?, ?, 'completed',
77
+ strftime('%Y-%m-%dT%H:%M:%fZ', ?, '+' || i || ' minutes') FROM seq`,
78
+ [count, workflowId, day, workflowId, trigger, `${day}T00:00:00.000Z`],
79
+ );
80
+ // One notify step (1 op) per run.
81
+ await getDbClient().run(
82
+ `INSERT INTO workflow_run_steps (id, runId, nodeId, nodeType, status, startedAt, finishedAt)
83
+ SELECT id || '-s', id, 'hello', 'notify', 'completed', startedAt, startedAt
84
+ FROM workflow_runs WHERE workflowId=? AND startedAt>=? AND startedAt<?`,
85
+ [workflowId, `${day}T00:00:00.000Z`, `${day}T23:59:59.999Z`],
86
+ );
87
+ }
88
+
89
+ /** One run with one notify step, started at `startedAt`. */
90
+ async function runAt(workflowId: string, startedAt: string): Promise<string> {
91
+ const id = `${workflowId}-${startedAt}`;
92
+ await getDbClient().run(
93
+ "INSERT INTO workflow_runs (id, workflowId, triggerType, status, startedAt) VALUES (?, ?, 'manual', 'completed', ?)",
94
+ [id, workflowId, startedAt],
95
+ );
96
+ await getDbClient().run(
97
+ "INSERT INTO workflow_run_steps (id, runId, nodeId, nodeType, status, startedAt, finishedAt) VALUES (?, ?, 'hello', 'notify', 'completed', ?, ?)",
98
+ [`${id}-s`, id, startedAt, startedAt],
99
+ );
100
+ return id;
101
+ }
102
+
103
+ describe("savings rollup", () => {
104
+ let agentId: string;
105
+ let capLive: string;
106
+ let capRetired: string;
107
+ let router: string;
108
+ let oncall: string;
109
+ let server: Server;
110
+ let port: number;
111
+
112
+ async function effectTask(runId: string, usd: number) {
113
+ const task = await createTaskExtended(`rollup fixture ${runId}`, {
114
+ agentId,
115
+ source: "workflow",
116
+ workflowRunId: runId,
117
+ });
118
+ await createSessionCost({
119
+ sessionId: crypto.randomUUID(),
120
+ taskId: task.id,
121
+ agentId,
122
+ totalCostUsd: usd,
123
+ durationMs: 60_000,
124
+ numTurns: 3,
125
+ model: "claude-opus-5-5",
126
+ });
127
+ }
128
+
129
+ beforeAll(async () => {
130
+ testGlobals.__savedRollupTemplate = testGlobals.__testMigrationTemplate;
131
+ testGlobals.__testMigrationTemplate = undefined;
132
+ await removeDbFiles(TEST_DB_PATH);
133
+ initDb(TEST_DB_PATH);
134
+ await resetSavingsRollupForTests();
135
+ agentId = (await createAgent({ name: "rollup-agent", isLead: false, status: "idle" })).id;
136
+ capLive = (await createWorkflow({ name: "cap-poll", definition: DEFINITION })).id;
137
+ capRetired = (
138
+ await createWorkflow({ name: "cap-poll-retired-2026-10-01", definition: DEFINITION })
139
+ ).id;
140
+ router = (await createWorkflow({ name: "event-router", definition: DEFINITION })).id;
141
+ oncall = (await createWorkflow({ name: "event-oncall", definition: DEFINITION })).id;
142
+ await createWorkflow({ name: "rollup-idle", definition: DEFINITION });
143
+
144
+ for (const day of WEEK) {
145
+ // 30 schedule runs a day on both versions: 420 in the week against a cap of 168.
146
+ await bulkRuns(capLive, "schedule", day, 30);
147
+ await bulkRuns(capRetired, "schedule", day, 30);
148
+ // Two of the live version's runs a day created an agent task ($0.50 each).
149
+ await effectTask(`${capLive}-${day}-0`, 0.5);
150
+ await effectTask(`${capLive}-${day}-1`, 0.5);
151
+ // 300 event runs a day; 2,100 in the week is above 240 a day.
152
+ await bulkRuns(router, "event", day, 300);
153
+ // 50 event runs a day: busy, but below the router threshold.
154
+ await bulkRuns(oncall, "event", day, 50);
155
+ }
156
+ // One router run had an effect.
157
+ await effectTask(`${router}-${WEEK[3]}-7`, 0);
158
+
159
+ server = createHttpServer(async (req, res) => {
160
+ const handled = await handleSavings(
161
+ req,
162
+ res,
163
+ getPathSegments(req.url || ""),
164
+ parseQueryParams(req.url || ""),
165
+ );
166
+ if (!handled) {
167
+ res.writeHead(404);
168
+ res.end();
169
+ }
170
+ });
171
+ port = await listenOnFreePort(server);
172
+ });
173
+
174
+ afterAll(async () => {
175
+ server?.close();
176
+ await resetSavingsRollupForTests();
177
+ closeDb();
178
+ testGlobals.__testMigrationTemplate = testGlobals.__savedRollupTemplate;
179
+ testGlobals.__savedRollupTemplate = undefined;
180
+ await removeDbFiles(TEST_DB_PATH);
181
+ });
182
+
183
+ test("before the first tick no window is complete", async () => {
184
+ const read = await readWorkflowSavings({ days: 7, tier: "smart", now: NOW });
185
+ expect(read).toMatchObject({ complete: false, computedAt: null, rows: [], total: null });
186
+ });
187
+
188
+ test("the first tick backfills every day; an hour later only days that are not final are due", async () => {
189
+ const stats = await runSavingsRollupTick(inProcessSql, { now: NOW });
190
+ expect(stats.lastError).toBeNull();
191
+ expect(stats.daysPending).toBe(0);
192
+ const marked = await getDbClient().get<{ n: number }>(
193
+ "SELECT count(*) n FROM automation_savings_days WHERE jobKind='workflow' AND modelVersion=?",
194
+ [MODEL_VERSION],
195
+ );
196
+ expect(marked?.n).toBe(ROLLUP_DAYS);
197
+ // Just computed: nothing is due until the next hourly tick.
198
+ expect(await workflowDaysToCompute(NOW)).toEqual([]);
199
+ // Today and yesterday were computed less than a day after they ended.
200
+ expect(await workflowDaysToCompute(NOW + HOUR)).toEqual(["2026-10-31", "2026-10-30"]);
201
+ const buckets = await getDbClient().get<{ n: number }>(
202
+ "SELECT count(*) n FROM automation_savings_daily",
203
+ );
204
+ // Four workflows ran on each of the 7 days; the idle one has no bucket.
205
+ expect(buckets?.n).toBe(4 * 7);
206
+ });
207
+
208
+ test("a day computed under an older model version is recomputed", async () => {
209
+ await getDbClient().run(
210
+ "UPDATE automation_savings_days SET modelVersion=? WHERE day='2026-10-20'",
211
+ [MODEL_VERSION - 1],
212
+ );
213
+ expect(await workflowDaysToCompute(NOW)).toContain("2026-10-20");
214
+ await runSavingsRollupTick(inProcessSql, { now: NOW });
215
+ expect(await workflowDaysToCompute(NOW)).not.toContain("2026-10-20");
216
+ });
217
+
218
+ test("concurrent callers share one tick; stop aborts it", async () => {
219
+ await getDbClient().run("DELETE FROM automation_savings_days WHERE day<'2026-10-01'");
220
+ const slowSql: SavingsSql = async (sql, params) => {
221
+ await Bun.sleep(5);
222
+ return inProcessSql(sql, params);
223
+ };
224
+ const a = runSavingsRollupTick(slowSql, { now: NOW });
225
+ const b = runSavingsRollupTick(slowSql, { now: NOW });
226
+ expect(a).toBe(b);
227
+ await Bun.sleep(30);
228
+ await stopSavingsRollup();
229
+ const stats = await a;
230
+ expect(stats.daysPending).toBeGreaterThan(0);
231
+ expect(getSavingsRollupStats().lastError).toBeNull();
232
+ // A full tick catches up.
233
+ expect((await runSavingsRollupTick(inProcessSql, { now: NOW })).daysPending).toBe(0);
234
+ });
235
+
236
+ test("the cap is shared across buckets and versions: the window cap, not 24 per bucket", async () => {
237
+ const read = await readWorkflowSavings({ days: 7, tier: "smart", now: NOW });
238
+ expect(read.complete).toBe(true);
239
+ const live = read.rows.find((r) => r.workflowId === capLive);
240
+ const retired = read.rows.find((r) => r.workflowId === capRetired);
241
+ // max(min(420 schedule runs, 24 x 7), 14 effect runs) = 168, all on the live version.
242
+ expect(live?.substitutedRuns).toBe(168);
243
+ expect(retired?.substitutedRuns).toBe(0);
244
+ expect(live?.capApplied).toBe(true);
245
+ // One version alone gets the same window cap.
246
+ const one = await readWorkflowSavings({
247
+ days: 7,
248
+ tier: "smart",
249
+ now: NOW,
250
+ workflowId: capLive,
251
+ });
252
+ expect(one.rows).toHaveLength(1);
253
+ expect(one.rows[0]?.substitutedRuns).toBe(168);
254
+ });
255
+
256
+ test("the enabled-only rule flips only the router-shaped workflow", async () => {
257
+ const read = await readWorkflowSavings({ days: 7, tier: "smart", now: NOW });
258
+ expect(read.rows.filter((r) => r.enabledOnlyRule).map((r) => r.workflowId)).toEqual([router]);
259
+ const r = read.rows.find((x) => x.workflowId === router);
260
+ expect(r).toMatchObject({ runs: 2100, substitutedRuns: 1, enabledOnlyRuns: 2099 });
261
+ const o = read.rows.find((x) => x.workflowId === oncall);
262
+ expect(o).toMatchObject({ enabledOnlyRule: false, runs: 350, substitutedRuns: 350 });
263
+ // The total uses the fleet band and sums the rows' p50.
264
+ const p50 = read.rows.reduce((s, x) => s + x.savingUsd.p50, 0);
265
+ expect(read.total?.savingUsd.p50).toBeCloseTo(p50, 6);
266
+ });
267
+
268
+ test("daily points add up to the window saving and actual cost", async () => {
269
+ const read = await readWorkflowSavings({
270
+ days: 30,
271
+ tier: "smart",
272
+ now: NOW,
273
+ workflowId: capLive,
274
+ });
275
+ const row = read.rows[0];
276
+ expect(row && row.actualUsd > 0).toBe(true);
277
+ // The rolling window touches 31 UTC days; the first starts at noon.
278
+ expect(read.points).toHaveLength(31);
279
+ expect(read.points[0]?.day).toBe("2026-10-01");
280
+ const saving = read.points.reduce((s, p) => s + p.savingUsd, 0);
281
+ const actual = read.points.reduce((s, p) => s + p.actualUsd, 0);
282
+ expect(saving).toBeCloseTo(row?.savingUsd.p50 ?? Number.NaN, 6);
283
+ expect(actual).toBeCloseTo(row?.actualUsd ?? Number.NaN, 6);
284
+ const measured = read.points.reduce((s, p) => s + p.measuredUsd, 0);
285
+ expect(measured).toBeCloseTo(row?.measuredUsd ?? Number.NaN, 6);
286
+ const estimated = read.points.reduce((s, p) => s + p.estimatedLlmUsd, 0);
287
+ expect(estimated).toBeCloseTo(row?.estimatedLlmUsd ?? Number.NaN, 6);
288
+ // 14 effect tasks at $0.50 each, unscaled.
289
+ expect(row?.measuredUsd).toBeCloseTo(7, 6);
290
+ expect(read.points.filter((p) => p.savingUsd > 0).map((p) => p.day)).toEqual(WEEK);
291
+ });
292
+
293
+ describe("rolling window", () => {
294
+ let rolling: string;
295
+ // 02:00 cuts the first day of the fixture week: 180 of the router's 300 runs that day are inside.
296
+ const NOW2 = Date.parse("2026-11-01T02:00:00.000Z");
297
+
298
+ /** The rollup read of one workflow equals the live computation over the same window. */
299
+ async function reconcile(workflowId: string, days: number, now: number) {
300
+ const read = await readWorkflowSavings({ days, tier: "smart", now, workflowId });
301
+ const live = await computeWorkflowWindow(
302
+ { id: workflowId, definition: (await getWorkflow(workflowId))?.definition },
303
+ { start: read.window.start, end: read.window.end },
304
+ inProcessSql,
305
+ );
306
+ if (live.status !== "ok") throw new Error("the live computation refused");
307
+ const priced = priceWorkflow(live.facts, { tier: "smart", days, band: "job" });
308
+ const row = read.rows[0];
309
+ expect(read.complete).toBe(true);
310
+ expect(read.boundaryEstimated).toBe(false);
311
+ expect(read.rows).toHaveLength(1);
312
+ expect(row?.runs).toBe(live.facts.runs);
313
+ expect(row?.substitutedRuns).toBe(priced.substitutedRuns);
314
+ expect(row?.enabledOnlyRule).toBe(priced.enabledOnlyRule);
315
+ for (const k of ["measuredUsd", "estimatedLlmUsd", "actualUsd", "actualHours"] as const) {
316
+ expect(row?.[k]).toBeCloseTo(priced[k], 9);
317
+ }
318
+ for (const q of ["p10", "p50", "p90"] as const) {
319
+ expect(row?.savingUsd[q]).toBeCloseTo(priced.savingUsd[q], 9);
320
+ expect(row?.hoursSaved[q]).toBeCloseTo(priced.hoursSaved[q], 9);
321
+ }
322
+ expect(read.total?.savingUsd.p50).toBeCloseTo(priced.savingUsd.p50, 9);
323
+ return read;
324
+ }
325
+
326
+ beforeAll(async () => {
327
+ rolling = (await createWorkflow({ name: "rolling-window", definition: DEFINITION })).id;
328
+ // A 7-day window ending at noon starts at noon: 11:00 that day is outside, 13:00 inside.
329
+ await runAt(rolling, "2026-10-24T11:00:00.000Z");
330
+ const inside = await runAt(rolling, "2026-10-24T13:00:00.000Z");
331
+ await runAt(rolling, "2026-10-28T10:00:00.000Z");
332
+ await runAt(rolling, "2026-10-31T11:00:00.000Z");
333
+ await effectTask(inside, 0.25);
334
+ await getDbClient().run(
335
+ "DELETE FROM automation_savings_days WHERE day IN ('2026-10-24', '2026-10-28', '2026-10-31')",
336
+ );
337
+ await runSavingsRollupTick(inProcessSql, { now: NOW });
338
+ });
339
+
340
+ test("a window starting at noon keeps the runs of its first half day", async () => {
341
+ const read = await reconcile(rolling, 7, NOW);
342
+ expect(read.window.start).toBe("2026-10-24T12:00:00.000Z");
343
+ expect(read.rows[0]?.runs).toBe(3);
344
+ expect(read.rows[0]?.measuredUsd).toBeCloseTo(0.25, 9);
345
+ expect(read.points.map((p) => p.day)).toEqual(["2026-10-24", ...WEEK]);
346
+ });
347
+
348
+ test("a boundary inside a busy day matches the live computation", async () => {
349
+ await runSavingsRollupTick(inProcessSql, { now: NOW2 });
350
+ const router7 = await reconcile(router, 7, NOW2);
351
+ expect(router7.rows[0]).toMatchObject({ runs: 180 + 300 * 6, enabledOnlyRule: true });
352
+ // All 50 of the first day's runs fall before 02:00.
353
+ expect((await reconcile(oncall, 7, NOW2)).rows[0]?.runs).toBe(50 * 6);
354
+ expect((await reconcile(rolling, 30, NOW2)).rows[0]?.runs).toBe(4);
355
+ });
356
+
357
+ test("a first day that cannot be scanned is scaled to the window and flagged", async () => {
358
+ resetSavingsReadCache();
359
+ const busy: SavingsSql = async () => {
360
+ throw new Error("database is busy");
361
+ };
362
+ const read = await readWorkflowSavings({
363
+ days: 7,
364
+ tier: "smart",
365
+ now: NOW2,
366
+ workflowId: router,
367
+ sql: busy,
368
+ });
369
+ expect(read.boundaryEstimated).toBe(true);
370
+ // 22 of the first day's 24 hours are inside the window: 275 of its 300 runs.
371
+ expect(read.rows[0]?.runs).toBe(275 + 300 * 6);
372
+ // The failed scan is not kept: the next read in the same minute scans again.
373
+ const again = await readWorkflowSavings({
374
+ days: 7,
375
+ tier: "smart",
376
+ now: NOW2,
377
+ workflowId: router,
378
+ });
379
+ expect(again.boundaryEstimated).toBe(false);
380
+ expect(again.rows[0]?.runs).toBe(180 + 300 * 6);
381
+ resetSavingsReadCache();
382
+ });
383
+
384
+ describe("first-day scans through the bounded executor, above its concurrency cap", () => {
385
+ const read = (sql: SavingsSql, workflowId?: string) => {
386
+ resetSavingsReadCache();
387
+ return readWorkflowSavings({ days: 7, tier: "smart", now: NOW2, workflowId, sql });
388
+ };
389
+ let fanout: string;
390
+
391
+ beforeAll(async () => {
392
+ // Four versions of one job, each with two runs before the window's 02:00 start and one after.
393
+ const names = ["fanout", ...["09", "08", "07"].map((m) => `fanout-retired-2026-${m}-01`)];
394
+ for (const name of names) {
395
+ const id = (await createWorkflow({ name, definition: DEFINITION })).id;
396
+ if (name === "fanout") fanout = id;
397
+ for (const t of ["00:30", "01:30", "13:00"]) await runAt(id, `2026-10-25T${t}:00.000Z`);
398
+ }
399
+ await getDbClient().run("DELETE FROM automation_savings_days WHERE day='2026-10-25'");
400
+ await runSavingsRollupTick(inProcessSql, { now: NOW2 });
401
+ });
402
+
403
+ test("a fleet read scans every first day exactly", async () => {
404
+ const firstDay = await getDbClient().get<{ n: number }>(
405
+ "SELECT count(DISTINCT jobId) n FROM automation_savings_daily WHERE day='2026-10-25' AND runs>0",
406
+ );
407
+ // Control: more first-day workflows than the cap, so parallel scans would be refused.
408
+ expect(Number(firstDay?.n)).toBeGreaterThan(getDbQueryConcurrencyCap());
409
+ const bounded = await read(savingsRequestSql);
410
+ expect(bounded.boundaryEstimated).toBe(false);
411
+ expect(bounded.rows).toEqual((await read(inProcessSql)).rows);
412
+ // A time-scaled estimate would keep 28 of the 30 runs of cap-poll's first day; all fall before 02:00.
413
+ expect(bounded.rows.find((r) => r.workflowId === capLive)?.runs).toBe(30 * 6);
414
+ resetSavingsReadCache();
415
+ });
416
+
417
+ test("a detail read scans every version of its job exactly", async () => {
418
+ const bounded = await read(savingsRequestSql, fanout);
419
+ expect(bounded.boundaryEstimated).toBe(false);
420
+ // Only the 13:00 run is inside; an estimate would keep 3 x 22/24, so 3.
421
+ expect(bounded.rows).toHaveLength(1);
422
+ expect(bounded.rows[0]?.runs).toBe(1);
423
+ expect(bounded.rows).toEqual((await read(inProcessSql, fanout)).rows);
424
+ resetSavingsReadCache();
425
+ });
426
+
427
+ test("fleet reads keep only the runs from a mid-hour or midnight window start", async () => {
428
+ const MINUTE = 60_000;
429
+ // fanout ran at 00:30, 01:30 and 13:00 on the first day.
430
+ const runsAt = async (now: number, workflowId?: string, sql = inProcessSql) =>
431
+ (await readWorkflowSavings({ days: 7, tier: "smart", now, workflowId, sql })).rows.find(
432
+ (r) => r.workflowId === (workflowId ?? fanout),
433
+ )?.runs;
434
+ resetSavingsReadCache();
435
+ // Mid-hour: a 01:10 start keeps 01:30 and 13:00.
436
+ expect(await runsAt(NOW2 - 50 * MINUTE)).toBe(2);
437
+ // The same hour's cached slice starts at 01:00; a 01:45 start drops 01:30.
438
+ expect(await runsAt(NOW2 - 15 * MINUTE)).toBe(1);
439
+ expect(await runsAt(NOW2 - 15 * MINUTE, fanout)).toBe(1);
440
+ // Midnight: a 00:45 start (slice floored to the day start) drops 00:30.
441
+ expect(await runsAt(NOW2 - 75 * MINUTE)).toBe(2);
442
+ // Control: a window starting at midnight keeps the whole first day.
443
+ expect(await runsAt(NOW2 - 2 * HOUR)).toBe(3);
444
+
445
+ // A failed scan scales the first day by the share of it from the window start, not the hour.
446
+ const failing: SavingsSql = async () => {
447
+ throw new Error("database is busy");
448
+ };
449
+ resetSavingsReadCache();
450
+ const fleet = await readWorkflowSavings({
451
+ days: 7,
452
+ tier: "smart",
453
+ now: NOW2 - 15 * MINUTE,
454
+ sql: failing,
455
+ });
456
+ expect(fleet.boundaryEstimated).toBe(true);
457
+ // 300 x 22.25/24 rounds to 278; from 01:00 it would be 288.
458
+ expect(fleet.rows.find((r) => r.workflowId === router)?.runs).toBe(278 + 300 * 6);
459
+ resetSavingsReadCache();
460
+ });
461
+
462
+ test("fleet list reads across the minutes of an hour scan each first-day workflow once", async () => {
463
+ resetSavingsReadCache();
464
+ const MINUTE = 60_000;
465
+ const scanned: string[] = [];
466
+ const counting: SavingsSql = (sql, params) => {
467
+ // Every first-day scan opens with this count.
468
+ if (sql.startsWith("SELECT count(*) n FROM workflow_runs WHERE workflowId=?")) {
469
+ scanned.push(String(params?.[0]));
470
+ }
471
+ return inProcessSql(sql, params);
472
+ };
473
+ const list = (now: number) =>
474
+ readWorkflowSavings({ days: 7, tier: "smart", now, sql: counting });
475
+ const firstDayIds = (
476
+ await getDbClient().query<{ jobId: string }>(
477
+ "SELECT DISTINCT jobId FROM automation_savings_daily WHERE day='2026-10-25' AND runs>0",
478
+ )
479
+ ).map((r) => r.jobId);
480
+
481
+ // Control: the first read scans every first-day workflow, once.
482
+ const first = await list(NOW2 + MINUTE);
483
+ expect(first.boundaryEstimated).toBe(false);
484
+ expect([...scanned].sort()).toEqual([...firstDayIds].sort());
485
+ const later = [];
486
+ for (const m of [2, 17, 59]) later.push({ m, read: await list(NOW2 + m * MINUTE) });
487
+ expect(scanned).toHaveLength(firstDayIds.length);
488
+ // Within the hour every list read reuses the slice from 02:00 and keeps
489
+ // only the runs from its own start: router matches its exact detail read.
490
+ for (const { m, read } of later) {
491
+ const detail = await readWorkflowSavings({
492
+ days: 7,
493
+ tier: "smart",
494
+ now: NOW2 + m * MINUTE,
495
+ workflowId: router,
496
+ });
497
+ expect(read.rows.find((r) => r.workflowId === router)?.runs).toBe(detail.rows[0]?.runs);
498
+ }
499
+ // Control: router runs every few minutes, so the later starts drop some of them.
500
+ expect(later[2]?.read.rows.find((r) => r.workflowId === router)?.runs).toBeLessThan(
501
+ first.rows.find((r) => r.workflowId === router)?.runs ?? 0,
502
+ );
503
+ // The next hour's window scans again.
504
+ await list(NOW2 + HOUR + MINUTE);
505
+ expect(scanned).toHaveLength(2 * firstDayIds.length);
506
+ resetSavingsReadCache();
507
+ });
508
+ });
509
+ });
510
+
511
+ test("catch-up ticks backfill older days when today and yesterday take the whole budget", async () => {
512
+ await getDbClient().run(
513
+ "DELETE FROM automation_savings_days WHERE day IN ('2026-10-20', '2026-10-21', '2026-10-22')",
514
+ );
515
+ await getDbClient().run(
516
+ "UPDATE automation_savings_days SET computedAt=? WHERE day IN ('2026-10-30', '2026-10-31')",
517
+ [new Date(NOW - 2 * HOUR).toISOString()],
518
+ );
519
+ const due = await workflowDaysToCompute(NOW);
520
+ expect(due.slice(0, 5)).toEqual([
521
+ "2026-10-31",
522
+ "2026-10-30",
523
+ "2026-10-22",
524
+ "2026-10-21",
525
+ "2026-10-20",
526
+ ]);
527
+ // Every scan takes a few ms against a 1 ms budget: one day per tick, a
528
+ // minute apart like catch-up ticks. The script days are due too.
529
+ const slowSql: SavingsSql = async (sql, params) => {
530
+ await Bun.sleep(2);
531
+ return inProcessSql(sql, params);
532
+ };
533
+ const ticks = due.length + (await daysToCompute("script", NOW)).length;
534
+ for (let i = 0; i < ticks; i++) {
535
+ const stats = await runSavingsRollupTick(slowSql, {
536
+ now: NOW + i * 60_000,
537
+ budgetMs: 1,
538
+ });
539
+ expect(stats.lastError).toBeNull();
540
+ }
541
+ expect(await workflowDaysToCompute(NOW + ticks * 60_000)).toEqual([]);
542
+ expect(await daysToCompute("script", NOW + ticks * 60_000)).toEqual([]);
543
+ });
544
+
545
+ describe("routes", () => {
546
+ const get = async (path: string) => {
547
+ const res = await fetch(`http://127.0.0.1:${port}${path}`);
548
+ return { status: res.status, body: (await res.json().catch(() => null)) as never };
549
+ };
550
+
551
+ test("a window the rollup has not computed is not valid, never $0", async () => {
552
+ // The fixed-clock ticks above do not cover the real current week.
553
+ const { status, body } = await get(`/api/savings/jobs?workflowId=${capLive}&days=7`);
554
+ expect(status).toBe(200);
555
+ expect(body).toMatchObject({ valid: false, reason: "not-computed", rows: [], total: null });
556
+ });
557
+
558
+ test("a fresh run shows on the detail route without waiting for the hourly tick", async () => {
559
+ await runSavingsRollupTick(inProcessSql);
560
+ const wf = (await createWorkflow({ name: "rollup-fresh", definition: DEFINITION })).id;
561
+ let { body } = await get(`/api/savings/jobs?workflowId=${wf}&days=7`);
562
+ expect(body).toMatchObject({ valid: false, reason: "no-runs", rows: [] });
563
+
564
+ await createWorkflowRun({ id: crypto.randomUUID(), workflowId: wf, triggerType: "manual" });
565
+ ({ body } = await get(`/api/savings/jobs?workflowId=${wf}&days=7&tier=ultra`));
566
+ const b = body as {
567
+ valid: boolean;
568
+ tier: string;
569
+ rows: { runs: number; savingUsd: { p10: number; p50: number; p90: number } }[];
570
+ total: { savingUsd: { p50: number } };
571
+ };
572
+ expect(b.valid).toBe(true);
573
+ expect(b.tier).toBe("ultra");
574
+ expect(b.rows).toHaveLength(1);
575
+ expect(b.rows[0]?.runs).toBe(1);
576
+ const band = b.rows[0]?.savingUsd;
577
+ expect(band && band.p10 < band.p50 && band.p50 < band.p90).toBe(true);
578
+ expect(b.total.savingUsd.p50).toBe(band?.p50 as number);
579
+
580
+ const daily = (await get(`/api/savings/daily?workflowId=${wf}&days=7&tier=ultra`)).body as {
581
+ valid: boolean;
582
+ points: { day: string; savingUsd: number }[];
583
+ };
584
+ expect(daily.valid).toBe(true);
585
+ // Seven rolling days touch eight UTC days.
586
+ expect(daily.points).toHaveLength(8);
587
+ // Rounded to the cent so the points add up to the header amount exactly.
588
+ expect(Math.round(daily.points.reduce((s, p) => s + p.savingUsd, 0) * 100)).toBe(
589
+ Math.round((band?.p50 as number) * 100),
590
+ );
591
+
592
+ // The list reads the hourly buckets: the next hourly tick adds the workflow.
593
+ await getDbClient().run("UPDATE automation_savings_days SET computedAt=? WHERE day=?", [
594
+ new Date(Date.now() - HOUR).toISOString(),
595
+ utcDay(Date.now()),
596
+ ]);
597
+ await runSavingsRollupTick(inProcessSql);
598
+ const list = (await get("/api/savings/jobs?kind=workflow&days=7")).body as {
599
+ valid: boolean;
600
+ rows: { workflowId: string }[];
601
+ };
602
+ expect(list.valid).toBe(true);
603
+ expect(list.rows.map((r) => r.workflowId)).toContain(wf);
604
+ });
605
+
606
+ test("reads share one refresh, and a scanned day is held for a minute", async () => {
607
+ await runSavingsRollupTick(inProcessSql);
608
+ const wf = (await createWorkflow({ name: "rollup-burst", definition: DEFINITION })).id;
609
+ const runs = async () =>
610
+ (
611
+ (await get(`/api/savings/jobs?workflowId=${wf}&days=7`)).body as {
612
+ rows: { runs: number }[];
613
+ }
614
+ ).rows[0]?.runs ?? 0;
615
+ // No newer run: the refresh scans nothing and is not held.
616
+ expect(await runs()).toBe(0);
617
+ await createWorkflowRun({ id: crypto.randomUUID(), workflowId: wf, triggerType: "manual" });
618
+ // A burst shares the one refresh in flight.
619
+ expect(await Promise.all(Array.from({ length: 5 }, runs))).toEqual([1, 1, 1, 1, 1]);
620
+ // Within the hold, a newer run waits instead of rescanning the day.
621
+ await createWorkflowRun({ id: crypto.randomUUID(), workflowId: wf, triggerType: "manual" });
622
+ expect(await runs()).toBe(1);
623
+ resetSavingsRefreshCache();
624
+ expect(await runs()).toBe(2);
625
+ });
626
+
627
+ test("a stored deployment curve prices the rollup routes and is named as the source", async () => {
628
+ await runSavingsRollupTick(inProcessSql);
629
+ const wf = (await createWorkflow({ name: "rollup-calibrated", definition: DEFINITION })).id;
630
+ await createWorkflowRun({ id: crypto.randomUUID(), workflowId: wf, triggerType: "manual" });
631
+ type Read = {
632
+ calibrationSource: string;
633
+ calibratedAt: string;
634
+ rows: { agentOnlyUsd: { p50: number }; savingUsd: { p50: number } }[];
635
+ };
636
+ const detail = async () =>
637
+ (await get(`/api/savings/jobs?workflowId=${wf}&days=7&tier=smart`)).body as Read;
638
+ const store = async (value: string) => {
639
+ await upsertSwarmConfig({ scope: "global", key: SAVINGS_CALIBRATION_KEY, value });
640
+ clearCalibrationCache();
641
+ };
642
+ const doubled = JSON.stringify({
643
+ calibratedAt: "2026-12-01",
644
+ model: "claude-opus-5-5",
645
+ curve: Object.fromEntries(
646
+ SAVINGS_TIERS.map((t) => [t, { usd: CURVE[t].usd.map((v) => v * 2), hrs: CURVE[t].hrs }]),
647
+ ),
648
+ });
649
+ try {
650
+ clearCalibrationCache();
651
+ const shipped = await detail();
652
+ expect(shipped.calibrationSource).toBe("shipped");
653
+ await store(doubled);
654
+ const deployed = await detail();
655
+ expect(deployed).toMatchObject({
656
+ calibrationSource: "deployment",
657
+ calibratedAt: "2026-12-01",
658
+ });
659
+ expect(deployed.rows[0]?.agentOnlyUsd.p50).toBeGreaterThan(
660
+ (shipped.rows[0]?.agentOnlyUsd.p50 as number) * 1.2,
661
+ );
662
+ // The daily points use the same curve, so they still add up to the row.
663
+ const daily = (await get(`/api/savings/daily?workflowId=${wf}&days=7&tier=smart`)).body as {
664
+ calibrationSource: string;
665
+ points: { savingUsd: number }[];
666
+ };
667
+ expect(daily.calibrationSource).toBe("deployment");
668
+ const cents = daily.points.reduce((sum, p) => sum + Math.round(p.savingUsd * 100), 0);
669
+ expect(cents).toBe(Math.round((deployed.rows[0]?.savingUsd.p50 ?? Number.NaN) * 100));
670
+ const list = (await get("/api/savings/jobs?kind=workflow&days=7")).body as Read;
671
+ expect(list.calibrationSource).toBe("deployment");
672
+ // A malformed row falls back to the shipped curve.
673
+ await store("{not json");
674
+ expect(await detail()).toMatchObject({
675
+ calibrationSource: "shipped",
676
+ calibratedAt: "2026-11-05",
677
+ });
678
+ } finally {
679
+ await getDbClient().run("DELETE FROM swarm_config WHERE key = ?", [
680
+ SAVINGS_CALIBRATION_KEY,
681
+ ]);
682
+ clearCalibrationCache();
683
+ }
684
+ });
685
+
686
+ test("bad input is rejected", async () => {
687
+ expect((await get("/api/savings/jobs")).status).toBe(400);
688
+ expect((await get("/api/savings/jobs?workflowId=nope")).status).toBe(404);
689
+ expect((await get("/api/savings/daily?workflowId=nope")).status).toBe(404);
690
+ expect((await get("/api/savings/daily?workflowId=a&scriptName=b")).status).toBe(400);
691
+ expect((await get(`/api/savings/jobs?workflowId=${capLive}&tier=huge`)).status).toBe(400);
692
+ expect((await get("/api/savings/jobs?kind=workflow&days=12")).status).toBe(400);
693
+ });
694
+ });
695
+ describe("rollup and refresh writes interleaved", () => {
696
+ let wf: string;
697
+ const today = () => utcDay(Date.now());
698
+ /** An hour later: today is due on the next tick. */
699
+ const ageToday = () =>
700
+ getDbClient().run("UPDATE automation_savings_days SET computedAt=? WHERE day=?", [
701
+ new Date(Date.now() - HOUR).toISOString(),
702
+ today(),
703
+ ]);
704
+ const bucketRuns = async () =>
705
+ Number(
706
+ (
707
+ await getDbClient().get<{ runs: number }>(
708
+ "SELECT runs FROM automation_savings_daily WHERE day=? AND jobKind='workflow' AND jobId=?",
709
+ [today(), wf],
710
+ )
711
+ )?.runs ?? 0,
712
+ );
713
+ const workflowRow = async () => {
714
+ const row = await getWorkflow(wf);
715
+ if (!row) throw new Error("workflow missing");
716
+ return row;
717
+ };
718
+ /** Runs `during` once: after the rollup's scan of `wf` ends, before the day is written. */
719
+ const afterScanOf = (during: () => Promise<void>): SavingsSql => {
720
+ let fired = false;
721
+ return async (sql, params) => {
722
+ const rows = await inProcessSql(sql, params);
723
+ if (!fired && sql.includes("WITH e AS") && params[0] === wf) {
724
+ fired = true;
725
+ await during();
726
+ }
727
+ return rows;
728
+ };
729
+ };
730
+ const newRun = async () => {
731
+ await Bun.sleep(2);
732
+ await createWorkflowRun({ id: crypto.randomUUID(), workflowId: wf, triggerType: "manual" });
733
+ await Bun.sleep(2);
734
+ };
735
+
736
+ beforeAll(async () => {
737
+ wf = (await createWorkflow({ name: "rollup-interleave", definition: DEFINITION })).id;
738
+ await createWorkflowRun({ id: crypto.randomUUID(), workflowId: wf, triggerType: "manual" });
739
+ });
740
+
741
+ test("a run that starts during the rollup's scan is found by the next refresh", async () => {
742
+ await ageToday();
743
+ await runSavingsRollupTick(afterScanOf(newRun));
744
+ expect(await bucketRuns()).toBe(1);
745
+ expect(await refreshWorkflowToday(await workflowRow(), inProcessSql, Date.now())).toBe(
746
+ "computed",
747
+ );
748
+ expect(await bucketRuns()).toBe(2);
749
+ });
750
+
751
+ test("a refresh during the rollup's scan keeps its newer bucket", async () => {
752
+ await ageToday();
753
+ const row = await workflowRow();
754
+ let refreshed: string | null = null;
755
+ await runSavingsRollupTick(
756
+ afterScanOf(async () => {
757
+ await newRun();
758
+ refreshed = await refreshWorkflowToday(row, inProcessSql, Date.now());
759
+ }),
760
+ );
761
+ expect(refreshed).toBe("computed");
762
+ // The rollup scanned before the third run; its later write keeps the refresh's bucket.
763
+ expect(await bucketRuns()).toBe(3);
764
+ });
765
+ });
766
+ });