@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
@@ -571,6 +571,450 @@ describe("quickjs structuredClone boundaries", () => {
571
571
  });
572
572
  });
573
573
 
574
+ // Retries: `retry()` in the stdlib, method-aware `ctx.stdlib.fetch` retries,
575
+ // and the bridge's own retries under `ctx.swarm`. The fixture fails the first
576
+ // N hits of a path whose segment reads `<status>-<N>-<tag>`, then answers 200.
577
+ // Routes with a fixed path (the MCP bridge, rooms/decode, scripts/run) carry
578
+ // the spec in the JSON body instead; their hits are keyed by the spec. A tag
579
+ // with `stall` holds the next answer for 20 s, one with `slow` for 6 s.
580
+ type RetryHit = { at: number; key: string | null };
581
+ const retryHits = new Map<string, RetryHit[]>();
582
+ const holdFor = (ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms).unref?.());
583
+ const retryServer = Bun.serve({
584
+ port: 0,
585
+ hostname: "127.0.0.1",
586
+ idleTimeout: 60,
587
+ async fetch(req) {
588
+ const path = new URL(req.url).pathname;
589
+ const body = req.method === "POST" ? await req.text() : "";
590
+ const bodySpec = /(\d{3})-(\d+)-([\w-]+)/.exec(body);
591
+ const spec = /(\d{3})-(\d+)-([^/]+)/.exec(path) ?? bodySpec;
592
+ const hitKey = spec === bodySpec && spec ? spec[0] : path;
593
+ const hits = retryHits.get(hitKey) ?? [];
594
+ hits.push({ at: Date.now(), key: req.headers.get("idempotency-key") });
595
+ retryHits.set(hitKey, hits);
596
+ if (spec && hits.length <= Number(spec[2])) {
597
+ const status = Number(spec[1]);
598
+ const headers: Record<string, string> =
599
+ status === 429 && spec[3].includes("ra") ? { "retry-after": "1" } : {};
600
+ return Response.json({ error: "transient" }, { status, headers });
601
+ }
602
+ if (spec?.[3].includes("stall")) await holdFor(20_000);
603
+ if (spec?.[3].includes("slow")) await holdFor(6_000);
604
+ return Response.json({ ok: true, key: "k", value: 1 });
605
+ },
606
+ });
607
+ afterAll(() => retryServer.stop(true));
608
+ const retryBase = `http://127.0.0.1:${retryServer.port}`;
609
+ const hitsOf = (path: string) => retryHits.get(path) ?? [];
610
+
611
+ // A raw TCP server whose first connection for each path closes before any
612
+ // answer (a network error on the client); later connections answer 200.
613
+ const dropHits = new Map<string, number>();
614
+ const dropServer = Bun.listen({
615
+ hostname: "127.0.0.1",
616
+ port: 0,
617
+ socket: {
618
+ data(socket, chunk) {
619
+ const path = /^[A-Z]+ (\S+)/.exec(chunk.toString())?.[1] ?? "";
620
+ const count = (dropHits.get(path) ?? 0) + 1;
621
+ dropHits.set(path, count);
622
+ if (count === 1) {
623
+ socket.end();
624
+ return;
625
+ }
626
+ const reply = JSON.stringify({ ok: true, key: "k", value: 1 });
627
+ socket.end(
628
+ `HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: ${reply.length}\r\nConnection: close\r\n\r\n${reply}`,
629
+ );
630
+ },
631
+ },
632
+ });
633
+ afterAll(() => dropServer.stop(true));
634
+ const dropBase = `http://127.0.0.1:${dropServer.port}`;
635
+
636
+ describe("retries match across executors", () => {
637
+ const executors: Array<[string, () => ScriptExecutor, boolean]> = [
638
+ ["native", () => new NativeScriptExecutor(), true],
639
+ ["quickjs", () => new QuickJSScriptExecutor(), false],
640
+ ];
641
+ const run = (
642
+ makeExecutor: () => ScriptExecutor,
643
+ source: string,
644
+ args: unknown = {},
645
+ mcpBaseUrl = retryBase,
646
+ ) =>
647
+ makeExecutor().run(
648
+ input({
649
+ source,
650
+ args,
651
+ configPayload: {
652
+ ...payload,
653
+ system: { ...payload.system, mcpBaseUrl: { value: mcpBaseUrl, isSecret: false } },
654
+ },
655
+ resources: { ...DEFAULT_SCRIPT_RESOURCES, memoryMb: 2048, wallClockMs: 15_000 },
656
+ }),
657
+ );
658
+
659
+ for (const [name, makeExecutor, spawns] of executors) {
660
+ const retryTest = (title: string, fn: () => Promise<void>) =>
661
+ test.skipIf(spawns && SKIP_SANDBOX_SPAWN_TESTS)(
662
+ `${title} (${name})`,
663
+ fn,
664
+ CHILD_PROCESS_TEST_BUDGET_MS,
665
+ );
666
+
667
+ retryTest("retry() handles sync and async functions", async () => {
668
+ const output = await run(
669
+ makeExecutor,
670
+ `import { retry } from "stdlib";
671
+ export default async (_args, ctx) => {
672
+ const fast = { minDelayMs: 1 };
673
+ const out = {};
674
+ let calls = 0;
675
+ out.syncReturn = [await retry(() => { calls++; return 5; }), calls];
676
+ calls = 0;
677
+ out.syncThrowThenOk = [await retry((a) => { calls++; if (a < 2) throw new Error("x"); return a; }, fast), calls];
678
+ calls = 0;
679
+ out.asyncRejectThenOk = [await retry(async (a) => { calls++; if (a < 3) throw new Error("x"); return "ok"; }, fast), calls];
680
+ calls = 0;
681
+ try {
682
+ await retry((a) => { calls++; throw new Error("fail " + a); }, { ...fast, retries: 2 });
683
+ out.exhausted = "resolved";
684
+ } catch (error) {
685
+ out.exhausted = [error.message, calls];
686
+ }
687
+ calls = 0;
688
+ try {
689
+ await ctx.stdlib.retry(() => { calls++; throw new Error("stop"); }, { ...fast, retryOn: () => false });
690
+ } catch (error) {
691
+ out.retryOnFalse = [error.message, calls];
692
+ }
693
+ calls = 0;
694
+ out.lastResult = [await retry(() => { calls++; return { success: false, status: 502 }; }, { ...fast, retries: 1 }), calls];
695
+ calls = 0;
696
+ const add = retry.wrap((a, b) => { calls++; if (calls < 2) throw new Error("x"); return a + b; }, fast);
697
+ out.wrap = [await add(2, 3), calls];
698
+ return out;
699
+ };`,
700
+ );
701
+ expect(output.error).toBeUndefined();
702
+ expect(output.result).toEqual({
703
+ syncReturn: [5, 1],
704
+ syncThrowThenOk: [2, 2],
705
+ asyncRejectThenOk: ["ok", 3],
706
+ exhausted: ["fail 3", 3],
707
+ retryOnFalse: ["stop", 1],
708
+ lastResult: [{ success: false, status: 502 }, 2],
709
+ wrap: [5, 2],
710
+ });
711
+ });
712
+
713
+ retryTest("retry() honours Retry-After on a 429", async () => {
714
+ const path = `/f/429-1-ra-${name}`;
715
+ const output = await run(
716
+ makeExecutor,
717
+ `export default async (args, ctx) => {
718
+ const res = await ctx.stdlib.retry(() => fetch(args.url), { minDelayMs: 1 });
719
+ return res.status;
720
+ };`,
721
+ { url: `${retryBase}${path}` },
722
+ );
723
+ expect(output.error).toBeUndefined();
724
+ expect(output.result).toBe(200);
725
+ const hits = hitsOf(path);
726
+ expect(hits.length).toBe(2);
727
+ expect(hits[1].at - hits[0].at).toBeGreaterThanOrEqual(900);
728
+ });
729
+
730
+ retryTest("stdlib.fetch retries by method and idempotency key", async () => {
731
+ const paths = {
732
+ postNoKey: `/f/502-5-postnokey-${name}`,
733
+ postKey: `/f/502-2-postkey-${name}`,
734
+ get: `/f/502-1-get-${name}`,
735
+ off: `/f/502-5-off-${name}`,
736
+ legacy: `/f/502-5-legacy-${name}`,
737
+ };
738
+ const urls = Object.fromEntries(
739
+ Object.entries(paths).map(([key, path]) => [key, `${retryBase}${path}`]),
740
+ );
741
+ const output = await run(
742
+ makeExecutor,
743
+ `export default async (args, ctx) => {
744
+ const f = ctx.stdlib.fetch;
745
+ return {
746
+ postNoKey: (await f(args.postNoKey, { method: "POST", body: "x", retry: { minDelayMs: 1 } })).status,
747
+ postKey: (await f(args.postKey, { method: "POST", body: "x", retry: { minDelayMs: 1, idempotencyKey: true } })).status,
748
+ get: (await f(args.get, { retry: { minDelayMs: 100 } })).status,
749
+ off: (await f(args.off, { retry: false })).status,
750
+ legacy: (await f(args.legacy, { retries: 2 })).status,
751
+ };
752
+ };`,
753
+ urls,
754
+ );
755
+ expect(output.error).toBeUndefined();
756
+ expect(output.result).toEqual({
757
+ postNoKey: 502,
758
+ postKey: 200,
759
+ get: 200,
760
+ off: 502,
761
+ legacy: 502,
762
+ });
763
+ expect(hitsOf(paths.postNoKey).length).toBe(1);
764
+ const keyed = hitsOf(paths.postKey);
765
+ expect(keyed.length).toBe(3);
766
+ expect(keyed[0].key).toMatch(/^[0-9a-f-]{36}$/);
767
+ expect(new Set(keyed.map((hit) => hit.key)).size).toBe(1);
768
+ const get = hitsOf(paths.get);
769
+ expect(get.length).toBe(2);
770
+ // Equal jitter: the first wait is at least half of minDelayMs.
771
+ expect(get[1].at - get[0].at).toBeGreaterThanOrEqual(45);
772
+ expect(hitsOf(paths.off).length).toBe(1);
773
+ expect(hitsOf(paths.legacy).length).toBe(2);
774
+ });
775
+
776
+ // An abort during the backoff wait rejects at once with the signal's reason
777
+ // and starts no further attempt. quickjs has no AbortController, so the
778
+ // script falls back to a plain signal object there.
779
+ retryTest("an abort ends the retry wait at once", async () => {
780
+ const path = `/f/503-5-abort-${name}`;
781
+ const output = await run(
782
+ makeExecutor,
783
+ `export default async (args, ctx) => {
784
+ const controller = () => {
785
+ if (typeof AbortController === "function") return new AbortController();
786
+ const listeners = new Set();
787
+ const signal = {
788
+ aborted: false,
789
+ reason: undefined,
790
+ addEventListener: (_type, fn) => listeners.add(fn),
791
+ removeEventListener: (_type, fn) => listeners.delete(fn),
792
+ };
793
+ return { signal, abort(reason) { signal.aborted = true; signal.reason = reason; for (const fn of [...listeners]) fn(); } };
794
+ };
795
+ const timed = async (start) => {
796
+ const c = controller();
797
+ setTimeout(() => c.abort(new Error("stop")), 100);
798
+ const started = Date.now();
799
+ try {
800
+ await start(c.signal);
801
+ return { error: null, ms: Date.now() - started };
802
+ } catch (error) {
803
+ return { error: error.message, ms: Date.now() - started };
804
+ }
805
+ };
806
+ const slow = { retries: 1, minDelayMs: 2000, maxDelayMs: 2000 };
807
+ let calls = 0;
808
+ const fetchAbort = await timed((signal) => ctx.stdlib.fetch(args.url, { signal, retry: slow }));
809
+ const retryAbort = await timed((signal) => ctx.stdlib.retry(() => { calls++; throw new Error("x"); }, { ...slow, signal }));
810
+ const retryCalls = calls;
811
+ calls = 0;
812
+ const early = controller();
813
+ early.abort(new Error("early"));
814
+ let preAborted;
815
+ try {
816
+ await ctx.stdlib.retry(() => { calls++; return 1; }, { signal: early.signal });
817
+ } catch (error) {
818
+ preAborted = [error.message, calls];
819
+ }
820
+ return { fetchAbort, retryAbort, retryCalls, preAborted };
821
+ };`,
822
+ { url: `${retryBase}${path}` },
823
+ );
824
+ expect(output.error).toBeUndefined();
825
+ const result = output.result as {
826
+ fetchAbort: { error: string | null; ms: number };
827
+ retryAbort: { error: string | null; ms: number };
828
+ retryCalls: number;
829
+ preAborted: unknown;
830
+ };
831
+ // The first wait is at least 1000 ms, so anything under that is the abort.
832
+ expect(result.fetchAbort.error).toBe("stop");
833
+ expect(result.fetchAbort.ms).toBeLessThan(900);
834
+ expect(hitsOf(path).length).toBe(1);
835
+ expect(result.retryAbort.error).toBe("stop");
836
+ expect(result.retryAbort.ms).toBeLessThan(900);
837
+ expect(result.retryCalls).toBe(1);
838
+ expect(result.preAborted).toEqual(["early", 0]);
839
+ });
840
+
841
+ retryTest("ctx.swarm retries 429 always and 5xx only when a repeat is safe", async () => {
842
+ const keys = {
843
+ write429: `429-1-w429-${name}`,
844
+ read502: `502-1-r502-${name}`,
845
+ write502: `502-1-w502-${name}`,
846
+ trigger502: `502-1-trig-${name}`,
847
+ };
848
+ const output = await run(
849
+ makeExecutor,
850
+ `export default async (args, ctx) => {
851
+ const pick = (r) => [r.success, r.status];
852
+ return {
853
+ write429: pick(await ctx.swarm.kv_set({ key: args.write429, value: 1 })),
854
+ read502: pick(await ctx.swarm.kv_get({ key: args.read502 })),
855
+ write502: pick(await ctx.swarm.kv_set({ key: args.write502, value: 1 })),
856
+ trigger502: pick(await ctx.swarm.workflow_trigger({ id: args.trigger502, idempotencyKey: "same-key" })),
857
+ };
858
+ };`,
859
+ keys,
860
+ );
861
+ expect(output.error).toBeUndefined();
862
+ expect(output.result).toEqual({
863
+ write429: [true, 200],
864
+ read502: [true, 200],
865
+ write502: [false, 502],
866
+ trigger502: [true, 200],
867
+ });
868
+ expect(hitsOf(`/api/kv/${keys.write429}`).length).toBe(2);
869
+ expect(hitsOf(`/api/kv/${keys.read502}`).length).toBe(2);
870
+ expect(hitsOf(`/api/kv/${keys.write502}`).length).toBe(1);
871
+ const trigger = hitsOf(`/api/workflows/${keys.trigger502}/trigger`);
872
+ expect(trigger.map((hit) => hit.key)).toEqual(["same-key", "same-key"]);
873
+ });
874
+
875
+ retryTest("ctx.swarm retries a 502 on reads sent by POST", async () => {
876
+ const keys = {
877
+ appQuery: `502-1-appq-${name}`,
878
+ userResolve: `502-1-user-${name}`,
879
+ roomDecode: `502-1-room-${name}`,
880
+ scriptRun: `502-1-srun-${name}`,
881
+ };
882
+ const output = await run(
883
+ makeExecutor,
884
+ `export default async (args, ctx) => {
885
+ const out = {
886
+ appQuery: (await ctx.swarm.app_query({ appId: args.appQuery, sql: "select 1" })).success,
887
+ userResolve: (await ctx.swarm.user_resolve({ query: args.userResolve })).success,
888
+ roomDecode: (await ctx.swarm.room.decode({ token: args.roomDecode })).ok,
889
+ };
890
+ try {
891
+ await ctx.swarm.script_run({ name: args.scriptRun, idempotencyKey: "same-key", args: {} });
892
+ out.scriptRun = "resolved";
893
+ } catch (error) {
894
+ out.scriptRun = error.message.includes("502");
895
+ }
896
+ return out;
897
+ };`,
898
+ keys,
899
+ );
900
+ expect(output.error).toBeUndefined();
901
+ expect(output.result).toEqual({
902
+ appQuery: true,
903
+ userResolve: true,
904
+ roomDecode: true,
905
+ scriptRun: true,
906
+ });
907
+ expect(hitsOf(keys.appQuery).length).toBe(2);
908
+ expect(hitsOf(keys.userResolve).length).toBe(2);
909
+ expect(hitsOf(keys.roomDecode).length).toBe(2);
910
+ // script_run's idempotencyKey does not dedupe the run, so a 502 never repeats it.
911
+ expect(hitsOf(keys.scriptRun).length).toBe(1);
912
+ });
913
+
914
+ retryTest("ctx.swarm retries a network error on a read, never on a write", async () => {
915
+ const keys = { read: `drop-read-${name}`, write: `drop-write-${name}` };
916
+ const output = await run(
917
+ makeExecutor,
918
+ `export default async (args, ctx) => {
919
+ const read = await ctx.swarm.kv_get({ key: args.read });
920
+ let write;
921
+ try {
922
+ await ctx.swarm.kv_set({ key: args.write, value: 1 });
923
+ write = "resolved";
924
+ } catch {
925
+ write = "threw";
926
+ }
927
+ return { read: [read.success, read.status], write };
928
+ };`,
929
+ keys,
930
+ dropBase,
931
+ );
932
+ expect(output.error).toBeUndefined();
933
+ expect(output.result).toEqual({ read: [true, 200], write: "threw" });
934
+ expect(dropHits.get(`/api/kv/${keys.read}`)).toBe(2);
935
+ expect(dropHits.get(`/api/kv/${keys.write}`)).toBe(1);
936
+ });
937
+
938
+ retryTest("ctx.swarm cuts a stalled read retry off at the retry budget", async () => {
939
+ const keys = { read: `502-1-stall-${name}`, room: `502-1-stallroom-${name}` };
940
+ const output = await run(
941
+ makeExecutor,
942
+ `export default async (args, ctx) => {
943
+ let started = Date.now();
944
+ const read = await ctx.swarm.kv_get({ key: args.read });
945
+ const readMs = Date.now() - started;
946
+ started = Date.now();
947
+ let room;
948
+ try {
949
+ await ctx.swarm.room.decode({ token: args.room });
950
+ room = "resolved";
951
+ } catch (error) {
952
+ room = error.message;
953
+ }
954
+ return { read: [read.success, read.status], readMs, room, roomMs: Date.now() - started };
955
+ };`,
956
+ keys,
957
+ );
958
+ expect(output.error).toBeUndefined();
959
+ const result = output.result as Record<string, unknown>;
960
+ expect(result.read).toEqual([false, 502]);
961
+ expect(result.readMs).toBeLessThan(6_000);
962
+ expect(result.room).toContain("failed with 502");
963
+ expect(result.room).toContain("retry budget");
964
+ expect(result.roomMs).toBeLessThan(6_000);
965
+ expect(hitsOf(`/api/kv/${keys.read}`).length).toBe(2);
966
+ expect(hitsOf(keys.room).length).toBe(2);
967
+ });
968
+
969
+ retryTest("ctx.swarm never cuts off a write retried after a 429", async () => {
970
+ const key = `429-1-slow-${name}`;
971
+ const output = await run(
972
+ makeExecutor,
973
+ `export default async (args, ctx) => {
974
+ const started = Date.now();
975
+ const write = await ctx.swarm.kv_set({ key: args.key, value: 1 });
976
+ return { write: [write.success, write.status], writeMs: Date.now() - started };
977
+ };`,
978
+ { key },
979
+ );
980
+ expect(output.error).toBeUndefined();
981
+ const result = output.result as Record<string, unknown>;
982
+ // The 429 means the write never ran, so its retry is the real run and
983
+ // may take longer than the retry budget.
984
+ expect(result.write).toEqual([true, 200]);
985
+ expect(result.writeMs).toBeGreaterThanOrEqual(5_900);
986
+ expect(hitsOf(`/api/kv/${key}`).length).toBe(2);
987
+ });
988
+
989
+ // A keyed write is repeat-safe, but it is still a write: its retry may start
990
+ // a run, so the read retry budget must not cut it off and report a failure.
991
+ retryTest("ctx.swarm never cuts off a keyed write's retry", async () => {
992
+ const keys = { after429: `429-1-slow-${name}-k429`, after502: `502-1-slow-${name}-k502` };
993
+ const output = await run(
994
+ makeExecutor,
995
+ `export default async (args, ctx) => {
996
+ const timed = async (id) => {
997
+ const started = Date.now();
998
+ const r = await ctx.swarm.workflow_trigger({ id, idempotencyKey: "same-key" });
999
+ return { result: [r.success, r.status], ms: Date.now() - started };
1000
+ };
1001
+ const [after429, after502] = await Promise.all([timed(args.after429), timed(args.after502)]);
1002
+ return { after429, after502 };
1003
+ };`,
1004
+ keys,
1005
+ );
1006
+ expect(output.error).toBeUndefined();
1007
+ const result = output.result as Record<string, { result: unknown; ms: number }>;
1008
+ for (const [label, id] of Object.entries(keys)) {
1009
+ expect(result[label].result).toEqual([true, 200]);
1010
+ expect(result[label].ms).toBeGreaterThanOrEqual(5_900);
1011
+ const hits = hitsOf(`/api/workflows/${id}/trigger`);
1012
+ expect(hits.map((hit) => hit.key)).toEqual(["same-key", "same-key"]);
1013
+ }
1014
+ });
1015
+ }
1016
+ });
1017
+
574
1018
  describe("native-only executor behavior", () => {
575
1019
  test.skipIf(SKIP_SANDBOX_SPAWN_TESTS)("timeout maps to timeout", async () => {
576
1020
  const output = await new NativeScriptExecutor().run(
@@ -7,6 +7,7 @@ import { closeDb, createAgent, getDbClient, initDb, upsertSwarmConfig } from "..
7
7
  import { getScript, listScripts } from "../be/scripts/db";
8
8
  import { setScriptEmbeddingProviderForTests } from "../be/scripts/embeddings";
9
9
  import { configSecretName, registerStoredSecret } from "../be/secret-registry";
10
+ import { mintScriptRunToken } from "../be/users";
10
11
  import { handleCore } from "../http/core";
11
12
  import { handleScripts } from "../http/scripts";
12
13
  import { getPathSegments, parseQueryParams } from "../http/utils";
@@ -696,6 +697,60 @@ describe("/api/scripts HTTP", () => {
696
697
  expect(result).toBeDefined();
697
698
  expect(result?.argsJsonSchema).not.toBeNull();
698
699
  });
700
+
701
+ skip(
702
+ "a nested run takes its step and parent run from the token only",
703
+ async () => {
704
+ const forged = {
705
+ "X-Source-Step-Id": "forged-step",
706
+ "X-Source-Script-Run-Id": "forged-run",
707
+ };
708
+ const body = (marker: string) =>
709
+ JSON.stringify({
710
+ source: `export default async () => "${marker}";`,
711
+ intent: "provenance",
712
+ sourceStepId: "forged-step",
713
+ parentScriptRunId: "forged-run",
714
+ sourceScriptRunId: "forged-run",
715
+ });
716
+ const row = async (marker: string) =>
717
+ await getDbClient().get<{ sourceStepId: string | null; parentScriptRunId: string | null }>(
718
+ "SELECT sourceStepId, parentScriptRunId FROM script_runs WHERE source LIKE ?",
719
+ [`%${marker}%`],
720
+ );
721
+
722
+ // The caller's per-run token carries the step and its run id.
723
+ const token = await mintScriptRunToken(workerId, 60_000, {
724
+ sourceStepId: "step-from-token",
725
+ sourceScriptRunId: "run-from-token",
726
+ });
727
+ const nested = await dispatch("/api/scripts/run", {
728
+ method: "POST",
729
+ agentId: workerId,
730
+ headers: { Authorization: `Bearer ${token.plaintext}`, ...forged },
731
+ body: body("nested-provenance"),
732
+ });
733
+ expect(nested.status).toBe(200);
734
+ expect(await row("nested-provenance")).toEqual({
735
+ sourceStepId: "step-from-token",
736
+ parentScriptRunId: "run-from-token",
737
+ });
738
+
739
+ // The operator key with an agent header and the same forged fields stamps nothing.
740
+ const plain = await dispatch("/api/scripts/run", {
741
+ method: "POST",
742
+ agentId: workerId,
743
+ headers: forged,
744
+ body: body("plain-provenance"),
745
+ });
746
+ expect(plain.status).toBe(200);
747
+ expect(await row("plain-provenance")).toEqual({
748
+ sourceStepId: null,
749
+ parentScriptRunId: null,
750
+ });
751
+ },
752
+ CHILD_PROCESS_TEST_BUDGET_MS,
753
+ );
699
754
  });
700
755
 
701
756
  describe("script source with an embedded secret is refused at write", () => {
@@ -26,7 +26,7 @@ describe("runtimeFetch abort handling", () => {
26
26
  await new Promise<void>((resolve) => stallReleases.push(resolve));
27
27
  }
28
28
  if (path === "/flaky" && hits[path] === 1) {
29
- return new Response("boom", { status: 500 });
29
+ return new Response("boom", { status: 502 });
30
30
  }
31
31
  return new Response("ok");
32
32
  },
@@ -108,7 +108,7 @@ describe("runtimeFetch abort handling", () => {
108
108
  expect(hits["/stall-timeout"]).toBe(2);
109
109
  });
110
110
 
111
- test("5xx responses still retry and succeed on a later attempt", async () => {
111
+ test("a 502 on a GET still retries and succeeds on a later attempt", async () => {
112
112
  const controller = new AbortController();
113
113
  const res = await runtimeFetch(`${origin}/flaky`, {
114
114
  signal: controller.signal,
@@ -1,11 +1,12 @@
1
1
  import { describe, expect, test } from "bun:test";
2
2
  import { randomBytes } from "node:crypto";
3
- import { convertGoRegex, stripKeyPrefix } from "../../scripts/gen-secret-rules";
3
+ import { anchorAlternation, convertGoRegex, stripKeyPrefix } from "../../scripts/gen-secret-rules";
4
4
  import { GITLEAKS_RULES } from "../utils/secret-rules.generated";
5
5
  import {
6
6
  clearVolatileSecretsForTesting,
7
7
  scrubSecrets,
8
8
  setGitleaksPassEnabledForTesting,
9
+ takePass2SweepCountForTesting,
9
10
  } from "../utils/secret-scrubber";
10
11
  import { buildNegatives, buildPositives } from "./fixtures/secret-corpus";
11
12
  import { randomToken } from "./synthetic-secret-helpers";
@@ -54,6 +55,54 @@ describe("convertGoRegex", () => {
54
55
  });
55
56
  });
56
57
 
58
+ describe("anchorAlternation", () => {
59
+ test("anchors a ^a|b$ alternation as a whole", () => {
60
+ expect(anchorAlternation({ source: "^true|false|null$", flags: "i" })).toEqual({
61
+ source: "^(?:true|false|null)$",
62
+ flags: "i",
63
+ });
64
+ });
65
+
66
+ test("splits only on top-level pipes, not escaped, grouped or in a class", () => {
67
+ expect(anchorAlternation({ source: String.raw`^a|[|](b|c)|d\|e$`, flags: "" }).source).toBe(
68
+ String.raw`^(?:a|[|](b|c)|d\|e)$`,
69
+ );
70
+ });
71
+
72
+ test("leaves single, grouped and uniformly anchored alternations alone", () => {
73
+ for (const source of ["^abc$", "^(?:a|b)$", "^a$|^b$", "a|b"]) {
74
+ expect(anchorAlternation({ source, flags: "" }).source).toBe(source);
75
+ }
76
+ });
77
+
78
+ test("rejects any other mix of anchored and unanchored branches", () => {
79
+ expect(() => anchorAlternation({ source: "^a|b", flags: "" })).toThrow(/mixes anchored/);
80
+ expect(() => anchorAlternation({ source: "a|^b$", flags: "" })).toThrow(/mixes anchored/);
81
+ expect(() => anchorAlternation({ source: String.raw`^a|b\$`, flags: "" })).toThrow(
82
+ /mixes anchored/,
83
+ );
84
+ });
85
+
86
+ test("every generated allowlist regex is already anchored as a whole", () => {
87
+ const sources = [
88
+ ...GITLEAKS_RULES.globalAllowlist.regexes,
89
+ ...GITLEAKS_RULES.rules.flatMap((r) => (r.allowlists ?? []).flatMap((l) => l.regexes)),
90
+ ];
91
+ expect(sources.length).toBeGreaterThan(10);
92
+ for (const re of sources) expect(anchorAlternation(re)).toEqual(re);
93
+ });
94
+
95
+ test("the global allowlist still allows the bare values true, false and null", () => {
96
+ const res = GITLEAKS_RULES.globalAllowlist.regexes.map((r) => new RegExp(r.source, r.flags));
97
+ for (const value of ["true", "FALSE", "Null"]) {
98
+ expect(res.some((re) => re.test(value))).toBe(true);
99
+ }
100
+ for (const value of ["truex", "xfalse", "nullx", "afalseb"]) {
101
+ expect(res.some((re) => re.test(value))).toBe(false);
102
+ }
103
+ });
104
+ });
105
+
57
106
  describe("generated gitleaks rules", () => {
58
107
  test("every rule compiles under Bun and has a keyword", () => {
59
108
  expect(GITLEAKS_RULES.rules.length).toBeGreaterThan(200);
@@ -149,6 +198,80 @@ describe("secret corpus", () => {
149
198
  }
150
199
  });
151
200
 
201
+ test("redacts a secret that contains true, false or null", () => {
202
+ // The global allowlist was `^true|false|null$`: it allowed any secret
203
+ // containing "false", starting with "true" or ending with "null".
204
+ const lowerAlnum = (len: number) =>
205
+ randomToken(len * 2)
206
+ .toLowerCase()
207
+ .slice(0, len);
208
+ const words = ["true", "FALsE", "nULL", "True", "false", "Null"];
209
+ const cases: { text: string; secret: string; rule: string }[] = [];
210
+ for (const word of words) {
211
+ // The vault secret starts with `hvs.`, so the word goes mid and end.
212
+ for (const at of [31, 96 - word.length]) {
213
+ const tail = randomToken(96);
214
+ const secret = ["hvs", ".", tail.slice(0, at), word, tail.slice(at + word.length)].join("");
215
+ cases.push({ text: `token ${secret} end`, secret, rule: "vault-service-token" });
216
+ }
217
+ for (const at of [0, 14, 32 - word.length]) {
218
+ const body = lowerAlnum(32);
219
+ const secret = [body.slice(0, at), word, body.slice(at + word.length)].join("");
220
+ cases.push({ text: `droneci: ${secret}`, secret, rule: "droneci-access-token" });
221
+ }
222
+ }
223
+ for (const { text, secret, rule } of cases) {
224
+ const out = scrubSecrets(text);
225
+ expect(out, `${rule} ${secret.slice(0, 8)}…`).not.toContain(secret);
226
+ expect(out).toContain(`[REDACTED:gitleaks:${rule}]`);
227
+ }
228
+ });
229
+
230
+ test("a vendor secret wins over a structural rule matching inside it", () => {
231
+ // A Heroku v2 key (`HRKU-AA` + 58 URL-safe chars) whose tail embeds
232
+ // `-sk-` + 20 alnum: pass 2's sk_key matched the tail first, and pass 5
233
+ // then missed the key, leaving its prefix in the output.
234
+ const heroku = () => ["HRKU", "-AA", randomToken(14), "-sk-", randomToken(40)].join("");
235
+ const bareSk = ["sk", randomToken(32)].join("-");
236
+ const a = heroku();
237
+ const b = heroku();
238
+ expect(a.length).toBe(65);
239
+ expect(scrubSecrets(`the response included ${a} in its body`)).toBe(
240
+ "the response included [REDACTED:gitleaks:heroku-api-key-v2] in its body",
241
+ );
242
+ // Two covered keys and an uncovered sk- key in one text keep their own labels.
243
+ expect(scrubSecrets(`${a} ${bareSk}\n${b}`)).toBe(
244
+ "[REDACTED:gitleaks:heroku-api-key-v2] [REDACTED:sk_key]\n[REDACTED:gitleaks:heroku-api-key-v2]",
245
+ );
246
+ });
247
+
248
+ test("pass 2 sweeps gitleaks once per call, however many rules hit", () => {
249
+ const heroku = () => ["HRKU", "-AA", randomToken(14), "-sk-", randomToken(40)].join("");
250
+ const a = heroku();
251
+ const b = heroku();
252
+ // Hits of several structural rules ahead of each key shift its offsets.
253
+ const text = [
254
+ ["lin", "api", randomToken(24)].join("_"),
255
+ a,
256
+ ["AKIA", "Q7RW3MZPXK5TB2NH"].join(""),
257
+ ["sk", randomToken(32)].join("-"),
258
+ b,
259
+ ["xai", randomToken(48)].join("-"),
260
+ ].join(" ");
261
+ takePass2SweepCountForTesting();
262
+ expect(scrubSecrets(text)).toBe(
263
+ [
264
+ "[REDACTED:linear_api]",
265
+ "[REDACTED:gitleaks:heroku-api-key-v2]",
266
+ "[REDACTED:aws_access_key]",
267
+ "[REDACTED:sk_key]",
268
+ "[REDACTED:gitleaks:heroku-api-key-v2]",
269
+ "[REDACTED:xai_key]",
270
+ ].join(" "),
271
+ );
272
+ expect(takePass2SweepCountForTesting()).toBe(1);
273
+ });
274
+
152
275
  test("redacts a token whose last character is a dash or equals sign", () => {
153
276
  // `\b` after a trailing `-` backtracks one character and leaves it behind.
154
277
  const tokens = [