@desplega.ai/agent-swarm 2.7.10 → 2.8.1

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 (296) hide show
  1. package/dist/acp-adapter-pdy3qsvg.js +15 -0
  2. package/dist/{actions-b8aqhrsg.js → actions-pwjpn0j6.js} +19 -20
  3. package/dist/{amp-adapter-4c165vgn.js → amp-adapter-cq9jgj6x.js} +2 -3
  4. package/dist/{app-m9khefrh.js → app-cnfffgwg.js} +3 -3
  5. package/dist/{assistant-rh4v3ntz.js → assistant-kpn317y1.js} +21 -22
  6. package/dist/{boot-args-schema-hwkc8bzv.js → boot-args-schema-pbbnhmc3.js} +1 -1
  7. package/dist/{boot-reembed-fdyk55h4.js → boot-reembed-9m0ysxma.js} +1 -1
  8. package/dist/{boot-reembed-5y6yw9sj.js → boot-reembed-majbn53m.js} +1 -1
  9. package/dist/{boot-scrub-sweep-r5r8kqsn.js → boot-scrub-sweep-app8g8ym.js} +3 -3
  10. package/dist/{boot-seeds-8f9zt5cm.js → boot-seeds-pbtmvcjm.js} +4 -5
  11. package/dist/{claude-adapter-s5df247c.js → claude-adapter-wn1g3qp5.js} +7 -8
  12. package/dist/{claude-managed-adapter-h74d06yz.js → claude-managed-adapter-jh6c523j.js} +3 -3
  13. package/dist/{claude-managed-setup-9gsmwzyx.js → claude-managed-setup-pd47nzch.js} +6 -6
  14. package/dist/{claude-sdk-session-dq1j4nz9.js → claude-sdk-session-3a2a6589.js} +9066 -8818
  15. package/dist/{cli-n5yexkdg.js → cli-0b4zam62.js} +1 -0
  16. package/dist/{cli-5wfz00be.js → cli-0jzra9ad.js} +2 -2
  17. package/dist/{cli-zjphdj1a.js → cli-0ntbxyaa.js} +40 -18
  18. package/dist/{cli-yz7v0sh4.js → cli-1xh9a7hn.js} +4 -6
  19. package/dist/{cli-eqtfgfr6.js → cli-2gxeg5gr.js} +1 -1
  20. package/dist/{cli-hfkwwy1h.js → cli-2zp0et3v.js} +21 -2
  21. package/dist/{cli-6m6b4bep.js → cli-3rkdne1h.js} +2 -2
  22. package/dist/{cli-mr97t7cc.js → cli-4r05hnqa.js} +263 -14
  23. package/dist/{cli-jc1g9ndz.js → cli-5j88qqa8.js} +10 -5
  24. package/dist/{cli-xfjrc279.js → cli-5mrq3ake.js} +48 -14
  25. package/dist/{cli-an1knn2k.js → cli-6mma83xa.js} +5 -5
  26. package/dist/{cli-tph5wt3y.js → cli-6wj7p986.js} +1 -1
  27. package/dist/{cli-t73cas91.js → cli-7349va39.js} +8100 -7620
  28. package/dist/{cli-5xcb8gxq.js → cli-7b8sbmag.js} +8 -8
  29. package/dist/{cli-3xj33nrx.js → cli-7cp6aa1q.js} +10 -3
  30. package/dist/{cli-mp9aa8g5.js → cli-7p1kvkck.js} +6 -6
  31. package/dist/{cli-j7d73g1y.js → cli-7w69ne2f.js} +3035 -354
  32. package/dist/{cli-cr14kftt.js → cli-89cqnasv.js} +3 -3
  33. package/dist/{cli-w3bk0dgv.js → cli-8aes17e4.js} +2 -2
  34. package/dist/{cli-7wz05bx3.js → cli-93k32c37.js} +468 -745
  35. package/dist/{cli-eqk5p56g.js → cli-9vhebtjz.js} +9 -9
  36. package/dist/{cli-td33w98c.js → cli-9wngrawf.js} +10 -10
  37. package/dist/cli-a3b239vq.js +242 -0
  38. package/dist/{cli-kx4c8j05.js → cli-b085njxz.js} +63 -19
  39. package/dist/{cli-8ewkreqd.js → cli-b5rs97a6.js} +7 -9
  40. package/dist/{cli-bxz823sz.js → cli-b8e9nb04.js} +1 -1
  41. package/dist/{cli-nj3x45rw.js → cli-bb431xey.js} +52 -43
  42. package/dist/{cli-36wdfzgn.js → cli-bsywb58a.js} +8 -8
  43. package/dist/{cli-18qt3few.js → cli-cyhbbd1z.js} +1 -1
  44. package/dist/{cli-eb2azq8n.js → cli-d3p5vwbk.js} +9 -9
  45. package/dist/{cli-2tsfpc70.js → cli-dy32zecz.js} +1 -1
  46. package/dist/{cli-rjyghzg4.js → cli-g70vxtjh.js} +2 -2
  47. package/dist/{cli-55bkx8hh.js → cli-gax7fk3t.js} +1 -1
  48. package/dist/{cli-jg24scat.js → cli-jcpr5smb.js} +3 -3
  49. package/dist/{cli-n07eecjs.js → cli-jywyhqws.js} +3 -3
  50. package/dist/{cli-38yww4e9.js → cli-k0615eh8.js} +8 -8
  51. package/dist/{cli-3xddv0rk.js → cli-k26bkr9t.js} +5 -7
  52. package/dist/{cli-xd5ebp64.js → cli-k93bq1wq.js} +3 -3
  53. package/dist/{cli-f2zenhja.js → cli-kc7v1nfv.js} +1 -1
  54. package/dist/{cli-x9exydey.js → cli-m4dqmnbp.js} +1 -1
  55. package/dist/{cli-gpwhbgx0.js → cli-m9s2qff2.js} +57 -25
  56. package/dist/{cli-ybjdc978.js → cli-mrt48bx7.js} +7 -4
  57. package/dist/{cli-ttbqe3q4.js → cli-p1w18yhx.js} +1 -1
  58. package/dist/{cli-h49ejvmc.js → cli-pcad4cb1.js} +1 -1
  59. package/dist/{cli-tmft5dz2.js → cli-qmqk2yc2.js} +1 -1
  60. package/dist/{cli-g1px1g2e.js → cli-re4raaj0.js} +1 -1
  61. package/dist/{cli-xbtq4d6s.js → cli-sn7rtnj4.js} +12 -8
  62. package/dist/{cli-n9abj89w.js → cli-syybb0p1.js} +8 -8
  63. package/dist/{cli-v2fwbnsk.js → cli-tacge1w0.js} +6 -6
  64. package/dist/{cli-pyrxt9gw.js → cli-tk7cjj8h.js} +1 -1
  65. package/dist/{cli-xvymtmv4.js → cli-tqegb8eq.js} +3 -3
  66. package/dist/{cli-kf3pxxdg.js → cli-v1dv1r37.js} +1 -1
  67. package/dist/{cli-z9cs5m0w.js → cli-vbh10fqa.js} +12 -12
  68. package/dist/{cli-3xcwp3z8.js → cli-vj75tyaw.js} +3 -3
  69. package/dist/{cli-xncjscpm.js → cli-vqptjbr7.js} +50 -24
  70. package/dist/{cli-q581b386.js → cli-wk18cm92.js} +5 -5
  71. package/dist/{cli-4vwxp550.js → cli-x1wa213s.js} +1 -1
  72. package/dist/{cli-n9ftpys4.js → cli-x6t50dmw.js} +7 -7
  73. package/dist/{cli-jrp1dt73.js → cli-xzm9vcfg.js} +1 -1
  74. package/dist/{cli-16phend6.js → cli-yn2bbre9.js} +1 -1
  75. package/dist/{cli-rt0ag4x1.js → cli-yncmerje.js} +5 -5
  76. package/dist/{cli-0m7rtm11.js → cli-zcsw143p.js} +1 -1
  77. package/dist/cli.js +18 -18
  78. package/dist/{codex-adapter-yr60sme6.js → codex-adapter-nha71q3n.js} +5 -6
  79. package/dist/{codex-hook-fac6175r.js → codex-hook-h3vk6xzr.js} +1 -1
  80. package/dist/{codex-session-runner-pch8x584.js → codex-session-runner-ak9x1k1h.js} +5 -6
  81. package/dist/{commands-phjfbkv0.js → commands-f587qpq8.js} +3 -3
  82. package/dist/{controller-jkx994pz.js → controller-hxx8wwy1.js} +2 -2
  83. package/dist/{controllers-connect-c4448kwa.js → controllers-connect-k5sg9m9h.js} +20 -21
  84. package/dist/{cursor-adapter-ndebqnm8.js → cursor-adapter-n5nc3mfe.js} +1 -2
  85. package/dist/{db-ef32tbfc.js → db-amm8w15a.js} +10 -2
  86. package/dist/{db-ez6egt6v.js → db-nzf8zb5z.js} +3 -3
  87. package/dist/{devin-adapter-z46ep5ph.js → devin-adapter-xedz98zv.js} +1 -1
  88. package/dist/{dispatcher-g3tt9hs9.js → dispatcher-89zrts8f.js} +18 -19
  89. package/dist/{dsh-adapter-tcyn3099.js → dsh-adapter-nrhbrjz8.js} +1 -2
  90. package/dist/{easter-egg-3d-e36hk5td.js → easter-egg-3d-533knw22.js} +1 -1
  91. package/dist/{embedding-space-4kyh5qqj.js → embedding-space-ezwenjmj.js} +6 -6
  92. package/dist/{embeddings-6a8v4a6t.js → embeddings-np74ht6g.js} +1 -1
  93. package/dist/{execute-3cbg0twf.js → execute-b3mrb1mv.js} +1 -1
  94. package/dist/{external-channel-se646snz.js → external-channel-z46yx9d7.js} +2 -2
  95. package/dist/{fx-adapter-yw795hqq.js → fx-adapter-3q12snn6.js} +7 -8
  96. package/dist/{grok-adapter-ttmcss2j.js → grok-adapter-ahb1w033.js} +7 -8
  97. package/dist/handlers-vbww69re.js +32 -0
  98. package/dist/heartbeat-dt9qw9c8.js +43 -0
  99. package/dist/{hook-hq93y5ej.js → hook-8k6fbz9b.js} +5 -5
  100. package/dist/{hook-g3nhexsy.js → hook-jgcgygex.js} +6 -6
  101. package/dist/{http-5a9p4h6y.js → http-haw4r8ne.js} +284 -142
  102. package/dist/{index-0eny15vj.js → index-2skqtd76.js} +2 -2
  103. package/dist/{index-6haqt3v5.js → index-4a0670yh.js} +8917 -8476
  104. package/dist/index-4xwaf5th.js +32 -0
  105. package/dist/{index-3c5pxbge.js → index-5gk12my8.js} +1 -1
  106. package/dist/{index-w7em4ktq.js → index-d6wkh8ar.js} +2 -2
  107. package/dist/index-f0hcrs8e.js +33 -0
  108. package/dist/{index-rvccek1w.js → index-gjwaqaq8.js} +5 -5
  109. package/dist/{index-e5pfbsys.js → index-hjhfk3ra.js} +3 -3
  110. package/dist/{index-1qw6f2dc.js → index-khe3gp0k.js} +4 -4
  111. package/dist/index-s4ewdma4.js +37 -0
  112. package/dist/{index-hgn3c961.js → index-tez78qj3.js} +979 -36
  113. package/dist/{index-s72rqgsx.js → index-tvfafeyy.js} +1 -1
  114. package/dist/{keepalive-1j4n4dmk.js → keepalive-xn6s7rmg.js} +3 -3
  115. package/dist/lead-6ygbfhbh.js +70 -0
  116. package/dist/{maintenance-dmghacy5.js → maintenance-vdts800b.js} +1 -1
  117. package/dist/{node-je82wjet.js → node-4c5jqxr3.js} +1 -1
  118. package/dist/{oauth-refresh-sweep-yy06c03c.js → oauth-refresh-sweep-094c8wfk.js} +2 -2
  119. package/dist/{onboard-52f9t5dm.js → onboard-v99eh56m.js} +3 -3
  120. package/dist/{opencode-adapter-krnh9jkn.js → opencode-adapter-dsagkhtw.js} +5 -6
  121. package/dist/{otel-impl-xjqz6wjj.js → otel-impl-q7yr9yp0.js} +1 -1
  122. package/dist/{pi-mono-adapter-dbxyp0qv.js → pi-mono-adapter-546cd1cc.js} +9 -9
  123. package/dist/{pricing-refresh-ctdr74pd.js → pricing-refresh-7dh2yase.js} +2 -3
  124. package/dist/{rbac-roles-ehv8s10n.js → rbac-roles-mdmc96p4.js} +3 -3
  125. package/dist/{rbac-roles-q0gr8eyj.js → rbac-roles-npbmdh77.js} +4 -6
  126. package/dist/{registry-hpjfmcfz.js → registry-32b1mft6.js} +1 -1
  127. package/dist/{render-v2-5b6chvcq.js → render-v2-twhhwmms.js} +3 -3
  128. package/dist/{resume-5a5d2845.js → resume-5gsrjd5e.js} +6 -6
  129. package/dist/{runtime-khxszyfp.js → runtime-1hv06jsn.js} +1 -1
  130. package/dist/{session-access-gj0bjhqg.js → session-access-m191x30x.js} +4 -4
  131. package/dist/{session-source-backfill-2sy0krfk.js → session-source-backfill-nt923ask.js} +2 -2
  132. package/dist/{setup-7ssfakk1.js → setup-wv467afy.js} +1 -1
  133. package/dist/{virtual-modules-pjj0knwf.js → virtual-modules-gazyapte.js} +3 -3
  134. package/dist/{work-objects-bf3syvhq.js → work-objects-8zkrpy13.js} +21 -22
  135. package/dist/{worker-follow-up-38xevga6.js → worker-follow-up-cecqszem.js} +18 -19
  136. package/dist/worker-mz5z7kj0.js +70 -0
  137. package/openapi.json +334 -7
  138. package/package.json +5 -5
  139. package/src/apps/definition.ts +11 -0
  140. package/src/apps/store.ts +28 -8
  141. package/src/be/db/model-profiles.ts +147 -38
  142. package/src/be/db/tasks/read.ts +5 -1
  143. package/src/be/db/workflow-run-definitions.ts +117 -0
  144. package/src/be/db.ts +24 -3
  145. package/src/be/memory/constants.ts +14 -1
  146. package/src/be/memory/key-paths.ts +8 -0
  147. package/src/be/memory/providers/sqlite-store.ts +160 -10
  148. package/src/be/memory/task-learning.ts +79 -14
  149. package/src/be/memory/types.ts +24 -1
  150. package/src/be/migrations/279_backfill_learning_expiry.sql +15 -0
  151. package/src/be/migrations/281_model_profiles_pr2.sql +28 -0
  152. package/src/be/migrations/283_workflow_run_definitions.sql +14 -0
  153. package/src/be/model-profile-check.ts +284 -0
  154. package/src/be/model-tier-resolution.ts +112 -12
  155. package/src/be/multi-runtime.ts +27 -0
  156. package/src/be/runtime-pools/routing.ts +52 -4
  157. package/src/be/scripts/typecheck.ts +1 -0
  158. package/src/be/seed-scripts/catalog/dreaming-learnings.ts +552 -0
  159. package/src/be/seed-scripts/catalog/dreaming-memtax-create.ts +389 -14
  160. package/src/be/seed-scripts/catalog/dreaming-memtax.ts +6 -3
  161. package/src/be/seed-scripts/index.ts +9 -0
  162. package/src/be/steering.ts +8 -2
  163. package/src/commands/onboard/agent-fs-version.ts +1 -1
  164. package/src/commands/runner.ts +32 -1
  165. package/src/fs/provider.ts +17 -3
  166. package/src/heartbeat/heartbeat.ts +12 -1
  167. package/src/heartbeat/index.ts +1 -0
  168. package/src/http/agents.ts +56 -4
  169. package/src/http/apps.ts +3 -1
  170. package/src/http/config.ts +2 -6
  171. package/src/http/index.ts +2 -3
  172. package/src/http/model-profiles.ts +58 -10
  173. package/src/http/poll.ts +36 -3
  174. package/src/http/schedules.ts +42 -3
  175. package/src/http/tasks.ts +37 -12
  176. package/src/http/workflows.ts +15 -2
  177. package/src/prompts/session-templates.ts +1 -1
  178. package/src/providers/acp-targets.ts +11 -6
  179. package/src/providers/amp-adapter.ts +1 -1
  180. package/src/providers/claude-sdk-session.ts +132 -23
  181. package/src/providers/codex-skill-resolver.ts +10 -4
  182. package/src/providers/cursor-adapter.ts +1 -1
  183. package/src/providers/devin-skill-resolver.ts +5 -5
  184. package/src/providers/dsh-adapter.ts +1 -1
  185. package/src/scheduler/schedule-task.ts +1 -0
  186. package/src/scripts-runtime/eval-harness.ts +14 -1
  187. package/src/scripts-runtime/executors/types.ts +3 -0
  188. package/src/scripts-runtime/sdk-allowlist.ts +1 -0
  189. package/src/scripts-runtime/swarm-sdk.ts +18 -1
  190. package/src/scripts-runtime/types/stdlib.d.ts +1 -0
  191. package/src/scripts-runtime/types/swarm-sdk.d.ts +1 -0
  192. package/src/server.ts +2 -0
  193. package/src/slack/app.ts +93 -0
  194. package/src/slack/inbound-dispatch.ts +18 -1
  195. package/src/slack/workspace-guard.ts +345 -0
  196. package/src/tasks/task-terminal-effects.ts +4 -0
  197. package/src/tasks/worker-follow-up.ts +102 -2
  198. package/src/tests/acp-adapter.test.ts +82 -0
  199. package/src/tests/apps-icon.test.ts +120 -0
  200. package/src/tests/chained-task-follow-up.test.ts +248 -0
  201. package/src/tests/check-pr-body.test.ts +40 -0
  202. package/src/tests/claude-sdk-lifecycle.test.ts +216 -1
  203. package/src/tests/claude-sdk-process.fixture.ts +57 -0
  204. package/src/tests/codex-skill-resolver.test.ts +31 -0
  205. package/src/tests/credentials-allowlist.test.ts +470 -0
  206. package/src/tests/db-task-read-contract.test.ts +5 -0
  207. package/src/tests/db-task-write-contract.test.ts +5 -0
  208. package/src/tests/deferred-wake-follow-up.test.ts +47 -0
  209. package/src/tests/docs-index-footprint.test.js +3 -3
  210. package/src/tests/dreaming-learnings.test.ts +1395 -0
  211. package/src/tests/dsh-adapter.test.ts +1 -1
  212. package/src/tests/explicit-model-validation.test.ts +2 -0
  213. package/src/tests/fs-provider.test.ts +42 -0
  214. package/src/tests/heartbeat.test.ts +28 -1
  215. package/src/tests/human-free-reclassify.test.ts +5 -1
  216. package/src/tests/list-endpoint-slimming.test.ts +17 -0
  217. package/src/tests/mcp-tools.test.ts +1 -1
  218. package/src/tests/migration-283-workflow-run-definitions.test.ts +69 -0
  219. package/src/tests/model-profile-check.test.ts +387 -0
  220. package/src/tests/model-profiles-api.test.ts +528 -1
  221. package/src/tests/profile-claim.test.ts +415 -3
  222. package/src/tests/profile-tier-alias.test.ts +382 -0
  223. package/src/tests/schedule-profile.test.ts +359 -0
  224. package/src/tests/script-connections.test.ts +6 -0
  225. package/src/tests/script-native-unawaited-drain.test.ts +167 -0
  226. package/src/tests/script-per-script-executor.test.ts +1 -0
  227. package/src/tests/scripts-sdk-bridge-tool-failure.test.ts +141 -0
  228. package/src/tests/seed-scripts.test.ts +2 -2
  229. package/src/tests/slack-inbound-receipts.test.ts +22 -2
  230. package/src/tests/slack-socket-ack.test.ts +16 -1
  231. package/src/tests/slack-workspace-guard.test.ts +905 -0
  232. package/src/tests/steering-core.test.ts +40 -0
  233. package/src/tests/store-progress-learning.test.ts +605 -20
  234. package/src/tests/tool-annotations.test.ts +1 -1
  235. package/src/tests/workflow-convergence.test.ts +46 -40
  236. package/src/tests/workflow-definition-pinning-recovery.test.ts +552 -0
  237. package/src/tests/workflow-definition-pinning.test.ts +645 -0
  238. package/src/tests/workflow-executors.test.ts +16 -7
  239. package/src/tests/workflow-foreach.test.ts +43 -20
  240. package/src/tests/workflow-notify-slack-ready.test.ts +161 -0
  241. package/src/tests/workflow-profile.test.ts +328 -0
  242. package/src/tools/app-upsert.ts +1 -1
  243. package/src/tools/memory-edit.ts +2 -1
  244. package/src/tools/model-profiles/check-model-profile.ts +63 -0
  245. package/src/tools/schedules/create-schedule.ts +45 -4
  246. package/src/tools/schedules/patch-schedule.ts +50 -4
  247. package/src/tools/schedules/update-schedule.ts +50 -4
  248. package/src/tools/script-run.ts +1 -1
  249. package/src/tools/send-task.ts +17 -2
  250. package/src/tools/store-progress.ts +15 -3
  251. package/src/tools/task-action.ts +9 -1
  252. package/src/tools/templates.ts +13 -0
  253. package/src/tools/tool-config.ts +2 -1
  254. package/src/tools/utils.ts +61 -4
  255. package/src/tools/workflows/create-workflow.ts +1 -1
  256. package/src/tools/workflows/retry-workflow-run.ts +1 -1
  257. package/src/tools/workflows/update-workflow.ts +10 -1
  258. package/src/types.ts +56 -1
  259. package/src/utils/credentials.ts +89 -12
  260. package/src/workflows/engine.ts +10 -1
  261. package/src/workflows/executors/agent-task.ts +21 -2
  262. package/src/workflows/executors/foreach.ts +4 -1
  263. package/src/workflows/executors/notify.ts +62 -6
  264. package/src/workflows/executors/sub-workflow.ts +1 -1
  265. package/src/workflows/executors/swarm-script.ts +4 -1
  266. package/src/workflows/foreach-driver.ts +8 -5
  267. package/src/workflows/limits.ts +2 -1
  268. package/src/workflows/model-validation.ts +27 -2
  269. package/src/workflows/patch-definition.ts +3 -1
  270. package/src/workflows/recovery.ts +6 -6
  271. package/src/workflows/resume.ts +9 -9
  272. package/src/workflows/retry-poller.ts +2 -2
  273. package/templates/skills/apps/SKILL.md +2 -0
  274. package/templates/skills/apps/content.md +2 -0
  275. package/templates/skills/code-quality/content.md +12 -0
  276. package/templates/skills/memory/content.md +8 -0
  277. package/templates/skills/scheduling/config.json +1 -1
  278. package/templates/skills/scheduling/content.md +2 -2
  279. package/templates/skills/swarm-docs/content.md +4 -0
  280. package/templates/skills/swarm-extensions/content.md +1 -1
  281. package/templates/skills/swarm-scripts/SKILL.md +2 -2
  282. package/templates/skills/swarm-scripts/content.md +2 -2
  283. package/templates/skills/work-on-task/SKILL.md +2 -0
  284. package/templates/skills/work-on-task/content.md +2 -0
  285. package/templates/workflows/dreaming/content.md +174 -7
  286. package/dist/acp-adapter-srfhs1s9.js +0 -16
  287. package/dist/cli-bzvs88tv.js +0 -339
  288. package/dist/cli-cyn9v8zr.js +0 -748
  289. package/dist/cli-ed6yqpf1.js +0 -779
  290. package/dist/handlers-17wha3ze.js +0 -33
  291. package/dist/heartbeat-gwewgdms.js +0 -42
  292. package/dist/index-8arwq8mw.js +0 -34
  293. package/dist/index-tpw054az.js +0 -38
  294. package/dist/index-waq75j2j.js +0 -31
  295. package/dist/lead-re73kdgc.js +0 -72
  296. package/dist/worker-r8mz7a65.js +0 -72
@@ -8,10 +8,18 @@ import {
8
8
  getDb,
9
9
  getTaskById,
10
10
  initDb,
11
+ isSqliteVecAvailable,
11
12
  startTask,
12
13
  } from "../be/db";
14
+ import { getDbClient } from "../be/db/runtime";
15
+ import { serializeEmbedding } from "../be/embedding";
13
16
  import { getEmbeddingProvider, getMemoryStore } from "../be/memory";
14
- import { EMBEDDING_DIMENSIONS } from "../be/memory/constants";
17
+ import {
18
+ EMBEDDING_DIMENSIONS,
19
+ EXHAUSTIVE_SEARCH_MAX_ROWS,
20
+ LEARNING_TTL_DAYS,
21
+ TTL_DEFAULTS,
22
+ } from "../be/memory/constants";
15
23
  import { registerStoreProgressTool } from "../tools/store-progress";
16
24
 
17
25
  interface ToolResult {
@@ -75,10 +83,24 @@ function learningRows(taskId: string): MemoryRow[] {
75
83
 
76
84
  function learningData(result: ToolResult) {
77
85
  return result.structuredContent?.learning as
78
- | { status: string; key?: string; memoryId?: string; similarity?: number; error?: string }
86
+ | {
87
+ status: string;
88
+ key?: string;
89
+ memoryId?: string;
90
+ similarity?: number;
91
+ error?: string;
92
+ noiseFloor?: string;
93
+ }
79
94
  | undefined;
80
95
  }
81
96
 
97
+ /** A line-2 rule that lifts a short test title over the noise floor. */
98
+ const RULE = "\nWhen this lesson applies, do what it says; the evidence would follow this line.";
99
+
100
+ function lesson(title: string) {
101
+ return `${title}${RULE}`;
102
+ }
103
+
82
104
  function message(result: ToolResult) {
83
105
  return String(result.structuredContent?.message);
84
106
  }
@@ -133,11 +155,14 @@ describe("store-progress learning", () => {
133
155
 
134
156
  test("string form falls back to the repo name, then to general", async () => {
135
157
  const withRepo = await task("desplega-ai/agent-swarm");
136
- await call({ taskId: withRepo.id, learning: "Run lint before tsc" });
158
+ await call({ taskId: withRepo.id, learning: lesson("Run lint before tsc") });
137
159
  expect(learningRows(withRepo.id)[0]?.key).toBe("/learnings/agent-swarm/run-lint-before-tsc");
138
160
 
139
161
  const withoutRepo = await task();
140
- const result = await call({ taskId: withoutRepo.id, learning: { text: "Prefer scripts" } });
162
+ const result = await call({
163
+ taskId: withoutRepo.id,
164
+ learning: { text: lesson("Prefer scripts") },
165
+ });
141
166
  expect(learningData(result)).toMatchObject({ status: "stored", workstream: "general" });
142
167
  expect(learningRows(withoutRepo.id)[0]?.key).toBe("/learnings/general/prefer-scripts");
143
168
  });
@@ -145,8 +170,11 @@ describe("store-progress learning", () => {
145
170
  test("a taken key gets a short suffix instead of failing", async () => {
146
171
  const first = await task();
147
172
  const second = await task();
148
- await call({ taskId: first.id, learning: "Same title\nfirst body" });
149
- const result = await call({ taskId: second.id, learning: "Same title\nsecond body" });
173
+ await call({ taskId: first.id, learning: lesson("Same title") });
174
+ const result = await call({
175
+ taskId: second.id,
176
+ learning: `${lesson("Same title")} Second body.`,
177
+ });
150
178
 
151
179
  expect(learningData(result)?.status).toBe("stored");
152
180
  expect(learningRows(first.id)[0]?.key).toBe("/learnings/general/same-title");
@@ -157,8 +185,8 @@ describe("store-progress learning", () => {
157
185
 
158
186
  test("an exact replay on the same task is skipped", async () => {
159
187
  const t = await task();
160
- await call({ taskId: t.id, learning: "Replay me" });
161
- const replay = await call({ taskId: t.id, progress: "again", learning: "Replay me" });
188
+ await call({ taskId: t.id, learning: lesson("Replay me") });
189
+ const replay = await call({ taskId: t.id, progress: "again", learning: lesson("Replay me") });
162
190
 
163
191
  expect(learningData(replay)).toMatchObject({
164
192
  status: "replayed",
@@ -169,7 +197,7 @@ describe("store-progress learning", () => {
169
197
 
170
198
  test("overlapping calls with the same learning store it once", async () => {
171
199
  const t = await task();
172
- const learning = "Concurrent replay\nKeep exactly one copy of this lesson.";
200
+ const learning = lesson("Concurrent replay");
173
201
  const results = await Promise.all([
174
202
  call({ taskId: t.id, learning }),
175
203
  call({ taskId: t.id, learning }),
@@ -191,7 +219,7 @@ describe("store-progress learning", () => {
191
219
  const result = await call({
192
220
  taskId: t.id,
193
221
  learning: {
194
- text: `${token}\nKeep credentials out of memory.`,
222
+ text: `${token}${RULE}`,
195
223
  workstream: token,
196
224
  tags: [token],
197
225
  },
@@ -208,7 +236,7 @@ describe("store-progress learning", () => {
208
236
 
209
237
  test("a replay of a secret-bearing learning is still detected", async () => {
210
238
  const t = await task();
211
- const learning = `Redact diagnostic tokens\nExample token: ${token}`;
239
+ const learning = `${lesson("Redact diagnostic tokens")} Example token: ${token}`;
212
240
  await call({ taskId: t.id, learning });
213
241
  const replay = await call({ taskId: t.id, learning });
214
242
 
@@ -227,7 +255,7 @@ describe("store-progress learning", () => {
227
255
  progress: "progress survives",
228
256
  status: "completed",
229
257
  output: "done",
230
- learning: "This write fails",
258
+ learning: lesson("This write fails"),
231
259
  });
232
260
  expect(result.isError).toBeFalsy();
233
261
  expect(learningData(result)).toMatchObject({ status: "failed" });
@@ -259,13 +287,66 @@ describe("store-progress learning", () => {
259
287
  expect(learningRows(t.id)).toHaveLength(0);
260
288
  });
261
289
 
290
+ test("a learning under the noise floor is rejected with a steer, progress kept", async () => {
291
+ const t = await task();
292
+ const result = await call({
293
+ taskId: t.id,
294
+ progress: "PR opened",
295
+ learning: "PR opened, CI green",
296
+ });
297
+
298
+ expect(result.isError).toBeFalsy();
299
+ expect(learningData(result)).toMatchObject({ status: "failed", noiseFloor: "too-short" });
300
+ expect(message(result)).toContain("Learning not stored: learning is under 80 characters");
301
+ expect(String(result.structuredContent?.nudge)).toContain('the rule as "When X, do Y"');
302
+ expect((await getTaskById(t.id))?.progress).toBe("PR opened");
303
+ expect(learningRows(t.id)).toHaveLength(0);
304
+ });
305
+
306
+ test("a learning that restates the same call's progress or output is rejected", async () => {
307
+ const t = await task();
308
+ const echoed = lesson("Fixed the flaky push hook");
309
+ const fromProgress = await call({
310
+ taskId: t.id,
311
+ progress: `Done. ${echoed.toUpperCase()} Next: review.`,
312
+ learning: echoed,
313
+ });
314
+ expect(learningData(fromProgress)).toMatchObject({
315
+ status: "failed",
316
+ noiseFloor: "repeats-progress",
317
+ });
318
+ expect(learningData(fromProgress)?.error).toContain("this call's progress");
319
+ expect(String(fromProgress.structuredContent?.nudge)).toContain("restates this call's");
320
+
321
+ const fromOutput = await call({
322
+ taskId: t.id,
323
+ status: "completed",
324
+ output: `Shipped.\n${echoed}`,
325
+ learning: echoed,
326
+ });
327
+ expect(learningData(fromOutput)).toMatchObject({ noiseFloor: "repeats-progress" });
328
+ expect(learningData(fromOutput)?.error).toContain("this call's output");
329
+ expect((await getTaskById(t.id))?.status).toBe("completed");
330
+ expect(learningRows(t.id)).toHaveLength(0);
331
+ });
332
+
333
+ test("a learning that contains the progress line and adds a rule is stored", async () => {
334
+ const t = await task();
335
+ const result = await call({
336
+ taskId: t.id,
337
+ progress: "Fixed the flaky push hook",
338
+ learning: lesson("Fixed the flaky push hook"),
339
+ });
340
+ expect(learningData(result)?.status).toBe("stored");
341
+ });
342
+
262
343
  test("a learning on the completing call is stored", async () => {
263
344
  const t = await task();
264
345
  const result = await call({
265
346
  taskId: t.id,
266
347
  status: "completed",
267
348
  output: "done",
268
- learning: "Ship on the completing call",
349
+ learning: lesson("Ship on the completing call"),
269
350
  });
270
351
  expect(learningData(result)?.status).toBe("stored");
271
352
  expect((await getTaskById(t.id))?.status).toBe("completed");
@@ -319,8 +400,8 @@ describe("store-progress learning near-duplicate guard", () => {
319
400
  afterAll(() => embedSpy.mockRestore());
320
401
 
321
402
  test("a near duplicate in another workstream is not stored and rates the existing row", async () => {
322
- const existing = await seed("Upsert scripts from file bytes\nPOST the raw file.", vector(10));
323
- const text = "Byte-exact script upsert from a local file\nPOST it to the API.";
403
+ const existing = await seed(lesson("Upsert scripts from file bytes"), vector(10));
404
+ const text = lesson("Byte-exact script upsert from a local file");
324
405
  vectors.set(text, vector(10, 0.9));
325
406
  const t = await task();
326
407
  const result = await call({ taskId: t.id, learning: { text, workstream: "other" } });
@@ -343,9 +424,227 @@ describe("store-progress learning near-duplicate guard", () => {
343
424
  expect(ratings).toEqual([{ source: "learning-duplicate", signal: 1, taskId: t.id }]);
344
425
  });
345
426
 
427
+ /** A curated swarm memory under `key`, with its embedding written now. */
428
+ async function seedLongterm(key: string, embedding: Float32Array) {
429
+ const memory = await getMemoryStore().store({
430
+ agentId,
431
+ scope: "swarm",
432
+ source: "manual",
433
+ name: key,
434
+ content: `Curated knowledge at ${key}`,
435
+ key,
436
+ });
437
+ await getMemoryStore().updateEmbedding(memory.id, embedding, "test-embedding");
438
+ return memory;
439
+ }
440
+
441
+ for (const [label, key, axis] of [
442
+ ["facts", "/longterm/facts/github/enqueue-unstable-pr-merge-queue", 50],
443
+ ["entities", "/longterm/entities/people/someone", 60],
444
+ ["workstreams", "/longterm/workstreams/active/some-workstream", 70],
445
+ ] as const) {
446
+ test(`a near duplicate of a /longterm/${label} memory is not stored`, async () => {
447
+ const existing = await seedLongterm(key, vector(axis));
448
+ const text = lesson(`Merge queue rule ${label}`);
449
+ vectors.set(text, vector(axis, 0.86));
450
+ const t = await task();
451
+ const result = await call({ taskId: t.id, learning: text });
452
+
453
+ expect(learningData(result)).toMatchObject({
454
+ status: "duplicate",
455
+ memoryId: existing.id,
456
+ key,
457
+ });
458
+ expect(learningData(result)?.similarity).toBeCloseTo(0.86, 2);
459
+ expect(learningRows(t.id)).toHaveLength(0);
460
+ const ratings = getDb()
461
+ .query<{ source: string }, [string]>("SELECT source FROM memory_rating WHERE memoryId = ?")
462
+ .all(existing.id);
463
+ expect(ratings).toEqual([{ source: "learning-duplicate" }]);
464
+ });
465
+ }
466
+
467
+ test("a /longterm duplicate is found behind more than 4096 closer rows outside the prefixes", async () => {
468
+ const existing = await seedLongterm("/longterm/facts/dedup/behind-the-cap", vector(200));
469
+ const text = lesson("Behind the KNN cap");
470
+ const query = vector(200, 0.86);
471
+ vectors.set(text, query);
472
+
473
+ // Each noise row is query + a private axis: cosine 0.98 to the query, so
474
+ // all of them outrank the 0.86 /longterm row in the vector index.
475
+ const store = getMemoryStore();
476
+ for (let i = 0; i < 4100; i++) {
477
+ const noise = new Float32Array(EMBEDDING_DIMENSIONS);
478
+ for (let d = 0; d < noise.length; d++) noise[d] = 0.98 * query[d]!;
479
+ noise[300 + (i % 200)] = Math.sqrt(1 - 0.98 ** 2);
480
+ const memory = await store.store({
481
+ agentId,
482
+ scope: "swarm",
483
+ source: "manual",
484
+ name: `noise ${i}`,
485
+ content: `unrelated ${i}`,
486
+ key: `/notes/noise/n-${i}`,
487
+ });
488
+ await store.updateEmbedding(memory.id, noise, "test-embedding");
489
+ }
490
+
491
+ const t = await task();
492
+ const result = await call({ taskId: t.id, learning: text });
493
+ expect(learningData(result)).toMatchObject({ status: "duplicate", memoryId: existing.id });
494
+ expect(learningData(result)?.similarity).toBeCloseTo(0.86, 2);
495
+ expect(learningRows(t.id)).toHaveLength(0);
496
+ }, 120_000);
497
+
498
+ /** `count` newer swarm rows under /longterm/, inserted in one transaction (the store path takes minutes). */
499
+ function insertNewerLongtermNoise(count: number, tag: string): string[] {
500
+ const noise = new Float32Array(EMBEDDING_DIMENSIONS);
501
+ noise[400] = 1;
502
+ const noiseBlob = serializeEmbedding(noise);
503
+ const now = new Date().toISOString();
504
+ const ids = Array.from({ length: count }, () => crypto.randomUUID());
505
+ const insert = getDb().prepare(
506
+ `INSERT INTO agent_memory (id, agentId, scope, key, name, content, embedding, embeddingModel, source, createdAt, updatedAt, accessedAt)
507
+ VALUES (?, ?, 'swarm', ?, ?, ?, ?, 'test-embedding', 'manual', ?, ?, ?)`,
508
+ );
509
+ getDb()
510
+ .transaction(() => {
511
+ ids.forEach((id, i) => {
512
+ const key = `/longterm/facts/${tag}/n-${i}`;
513
+ insert.run(id, agentId, key, key, `${tag} ${i}`, noiseBlob, now, now, now);
514
+ });
515
+ })
516
+ .immediate();
517
+ return ids;
518
+ }
519
+
520
+ /** Rows the /longterm/ dedup scan counts toward its cap. */
521
+ function eligibleLongtermRows(): number {
522
+ return getDb()
523
+ .query<{ n: number }, []>(
524
+ `SELECT COUNT(*) AS n FROM agent_memory
525
+ WHERE key LIKE '/longterm/%' AND scope = 'swarm' AND embedding IS NOT NULL
526
+ AND (expiresAt IS NULL OR expiresAt > datetime('now'))`,
527
+ )
528
+ .get()!.n;
529
+ }
530
+
531
+ /** Make `ids` the oldest eligible rows: older `updatedAt` than every noise row. */
532
+ function makeOldest(ids: string[]) {
533
+ getDb().run(
534
+ `UPDATE agent_memory SET updatedAt = '2020-01-01T00:00:00.000Z' WHERE id IN (${ids.map(() => "?").join(", ")})`,
535
+ ids,
536
+ );
537
+ }
538
+
539
+ /** Take `ids` out of later scans. */
540
+ function expire(ids: string[]) {
541
+ getDb().run(
542
+ `UPDATE agent_memory SET expiresAt = '2000-01-01T00:00:00.000Z' WHERE id IN (${ids.map(() => "?").join(", ")})`,
543
+ ids,
544
+ );
545
+ }
546
+
547
+ /**
548
+ * The oldest /longterm twin is found while the prefix holds exactly
549
+ * EXHAUSTIVE_SEARCH_MAX_ROWS eligible rows, and missed (with `capped=true`)
550
+ * once one newer row pushes it past the cap. `sqlPath` asserts which scorer ran.
551
+ */
552
+ async function expectCapBoundary(axis: number, sqlPath: boolean) {
553
+ const twin = await seedLongterm(`/longterm/facts/dedup/cap-boundary-${axis}`, vector(axis));
554
+ makeOldest([twin.id]);
555
+ const noiseIds = insertNewerLongtermNoise(
556
+ EXHAUSTIVE_SEARCH_MAX_ROWS - eligibleLongtermRows(),
557
+ `cap-noise-${axis}`,
558
+ );
559
+ expect(eligibleLongtermRows()).toBe(EXHAUSTIVE_SEARCH_MAX_ROWS);
560
+ const querySpy = spyOn(getDbClient(), "query");
561
+ const logSpy = spyOn(console, "log");
562
+ try {
563
+ const within = lesson(`Within the cap ${axis}`);
564
+ vectors.set(within, vector(axis, 0.9));
565
+ const t1 = await task();
566
+ const found = await call({ taskId: t1.id, learning: within });
567
+ expect(learningData(found)).toMatchObject({ status: "duplicate", memoryId: twin.id });
568
+ expect(learningData(found)?.similarity).toBeCloseTo(0.9, 2);
569
+ expect(learningRows(t1.id)).toHaveLength(0);
570
+
571
+ const scans = querySpy.mock.calls
572
+ .map(([sql], i) => ({ sql, result: querySpy.mock.results[i] }))
573
+ .filter(({ sql }) => sql.includes("vec_distance_cosine(embedding"));
574
+ expect(scans).toHaveLength(sqlPath ? 2 : 0);
575
+ for (const { sql, result: returned } of scans) {
576
+ // SQLite ranks inside the query: each prefix scan hands back at most one row.
577
+ expect(sql).toContain("ORDER BY updatedAt DESC, id");
578
+ expect(((await returned?.value) as unknown[]).length).toBeLessThanOrEqual(1);
579
+ }
580
+
581
+ // One newer row pushes the twin to 10,001st: the documented miss.
582
+ noiseIds.push(...insertNewerLongtermNoise(1, `cap-overflow-${axis}`));
583
+ makeOldest([twin.id]);
584
+ logSpy.mockClear();
585
+ const past = lesson(`Past the cap ${axis}`);
586
+ vectors.set(past, vector(axis, 0.9));
587
+ const t2 = await task();
588
+ const missed = await call({ taskId: t2.id, learning: past });
589
+ expect(learningData(missed)?.status).toBe("stored");
590
+ expect(learningRows(t2.id)).toHaveLength(1);
591
+ const capLogs = logSpy.mock.calls
592
+ .map((args) => String(args[0]))
593
+ .filter(
594
+ (line) => line.includes("retrieval_path=exhaustive") && line.includes("capped=true"),
595
+ );
596
+ expect(capLogs).toHaveLength(1);
597
+ expect(capLogs[0]).toContain(`scanned=${EXHAUSTIVE_SEARCH_MAX_ROWS}`);
598
+ } finally {
599
+ querySpy.mockRestore();
600
+ logSpy.mockRestore();
601
+ expire([twin.id, ...noiseIds]);
602
+ }
603
+ }
604
+
605
+ test("with sqlite-vec, a /longterm twin is found within the 10,000-row cap and missed past it", async () => {
606
+ expect(isSqliteVecAvailable()).toBe(true);
607
+ await expectCapBoundary(210, true);
608
+ }, 120_000);
609
+
610
+ /** Run `fn` with MEMORY_MIN_SIMILARITY set to `value`, then restore it. */
611
+ async function withRetrievalFloor<T>(value: string, fn: () => Promise<T>): Promise<T> {
612
+ const original = process.env.MEMORY_MIN_SIMILARITY;
613
+ process.env.MEMORY_MIN_SIMILARITY = value;
614
+ try {
615
+ return await fn();
616
+ } finally {
617
+ if (original === undefined) delete process.env.MEMORY_MIN_SIMILARITY;
618
+ else process.env.MEMORY_MIN_SIMILARITY = original;
619
+ }
620
+ }
621
+
622
+ test("a retrieval floor above the dedup threshold still catches a /longterm duplicate", async () => {
623
+ const existing = await seedLongterm("/longterm/facts/dedup/strict-floor", vector(80));
624
+ const text = lesson("Strict retrieval floor");
625
+ vectors.set(text, vector(80, 0.86));
626
+ const t = await task();
627
+ const result = await withRetrievalFloor("0.9", () => call({ taskId: t.id, learning: text }));
628
+
629
+ expect(learningData(result)).toMatchObject({ status: "duplicate", memoryId: existing.id });
630
+ expect(learningData(result)?.similarity).toBeCloseTo(0.86, 2);
631
+ expect(learningRows(t.id)).toHaveLength(0);
632
+ });
633
+
634
+ test("a retrieval floor below the dedup threshold does not lower it", async () => {
635
+ await seedLongterm("/longterm/facts/dedup/loose-floor", vector(90));
636
+ const text = lesson("Loose retrieval floor");
637
+ vectors.set(text, vector(90, 0.7));
638
+ const t = await task();
639
+ const result = await withRetrievalFloor("0.5", () => call({ taskId: t.id, learning: text }));
640
+
641
+ expect(learningData(result)?.status).toBe("stored");
642
+ expect(learningRows(t.id)).toHaveLength(1);
643
+ });
644
+
346
645
  test("a related learning below the threshold is stored", async () => {
347
- await seed("Retry flaky pushes once\nThe pre-push hook is slow.", vector(20));
348
- const text = "Pre-push hooks take five minutes\nLet them finish.";
646
+ await seed(lesson("Retry flaky pushes once"), vector(20));
647
+ const text = lesson("Pre-push hooks take five minutes");
349
648
  vectors.set(text, vector(20, 0.7));
350
649
  const t = await task();
351
650
  const result = await call({ taskId: t.id, learning: text });
@@ -355,8 +654,8 @@ describe("store-progress learning near-duplicate guard", () => {
355
654
  });
356
655
 
357
656
  test("a failed search falls through to the normal insert", async () => {
358
- await seed("Kebab keys only\nSlugs are lowercase.", vector(30));
359
- const text = "Keys are kebab case\nSlugs stay lowercase.";
657
+ await seed(lesson("Kebab keys only"), vector(30));
658
+ const text = lesson("Keys are kebab case");
360
659
  vectors.set(text, vector(30, 0.95));
361
660
  const searchSpy = spyOn(getMemoryStore(), "search").mockRejectedValue(new Error("vec down"));
362
661
  try {
@@ -371,11 +670,297 @@ describe("store-progress learning near-duplicate guard", () => {
371
670
  });
372
671
 
373
672
  test("an exact replay on the same task is replayed, not a duplicate", async () => {
374
- const text = "Replay before similarity\nThe same task retrying is not a duplicate.";
673
+ const text = lesson("Replay before similarity");
375
674
  const seeded = await seed(text, vector(40));
376
675
  const replay = await call({ taskId: seeded.task.id, learning: { text, workstream: "seeded" } });
377
676
 
378
677
  expect(learningData(replay)).toMatchObject({ status: "replayed", memoryId: seeded.memoryId });
379
678
  expect(learningRows(seeded.task.id)).toHaveLength(1);
380
679
  });
680
+
681
+ describe("without sqlite-vec", () => {
682
+ const originalVecPath = process.env.SQLITE_VEC_EXTENSION_PATH;
683
+
684
+ /** A fresh in-memory DB, opened with `vecPath` as the sqlite-vec extension path. */
685
+ async function reopenDb(vecPath: string | undefined) {
686
+ closeDb();
687
+ if (vecPath === undefined) delete process.env.SQLITE_VEC_EXTENSION_PATH;
688
+ else process.env.SQLITE_VEC_EXTENSION_PATH = vecPath;
689
+ initDb(":memory:");
690
+ // The memory store singleton built memory_fts on the first DB only (same
691
+ // DDL as SqliteMemoryStore.ensureFtsTable).
692
+ getDb().run(
693
+ "CREATE VIRTUAL TABLE IF NOT EXISTS memory_fts USING fts5(memory_id UNINDEXED, name, content, tokenize='porter unicode61')",
694
+ );
695
+ await createAgent({ id: agentId, name: "Learner", isLead: false, status: "idle" });
696
+ }
697
+
698
+ beforeAll(async () => {
699
+ await reopenDb("/nonexistent/vec.so");
700
+ expect(isSqliteVecAvailable()).toBe(false);
701
+ });
702
+ afterAll(() => reopenDb(originalVecPath));
703
+
704
+ test("a near duplicate is still caught, not stored", async () => {
705
+ const existing = await seed(lesson("Pin the worktree path"), vector(220));
706
+ const text = lesson("Worktrees live under the retention root");
707
+ vectors.set(text, vector(220, 0.9));
708
+ const t = await task();
709
+ const result = await call({ taskId: t.id, learning: { text, workstream: "other" } });
710
+
711
+ expect(learningData(result)).toMatchObject({
712
+ status: "duplicate",
713
+ memoryId: existing.memoryId,
714
+ });
715
+ expect(learningData(result)?.similarity).toBeCloseTo(0.9, 2);
716
+ expect(learningRows(t.id)).toHaveLength(0);
717
+ });
718
+
719
+ test("a /longterm twin is found within the 10,000-row cap and missed past it", async () => {
720
+ await expectCapBoundary(230, false);
721
+ }, 120_000);
722
+ });
723
+ });
724
+
725
+ describe("store-progress learning expiry", () => {
726
+ const DAY_MS = 86_400_000;
727
+
728
+ function expiryRow(id: string) {
729
+ return getDb()
730
+ .query<{ createdAt: string; expiresAt: string | null }, [string]>(
731
+ "SELECT createdAt, expiresAt FROM agent_memory WHERE id = ?",
732
+ )
733
+ .get(id);
734
+ }
735
+
736
+ test(`a new learning expires ${LEARNING_TTL_DAYS} days after it is created`, async () => {
737
+ const t = await task();
738
+ const result = await call({
739
+ taskId: t.id,
740
+ learning: lesson("Learnings age out"),
741
+ });
742
+ const row = expiryRow(learningData(result)!.memoryId!)!;
743
+
744
+ expect(row.expiresAt).toMatch(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/);
745
+ const days = (Date.parse(row.expiresAt!) - Date.parse(row.createdAt)) / DAY_MS;
746
+ expect(days).toBeGreaterThan(LEARNING_TTL_DAYS - 0.001);
747
+ expect(days).toBeLessThan(LEARNING_TTL_DAYS + 0.001);
748
+ });
749
+
750
+ test("a /longterm memory and a non-learning manual memory never expire", async () => {
751
+ const store = getMemoryStore();
752
+ const base = { agentId, scope: "swarm" as const, source: "manual" as const, content: "x" };
753
+ const longterm = await store.store({
754
+ ...base,
755
+ name: "curated",
756
+ key: "/longterm/facts/expiry/curated",
757
+ });
758
+ const manual = await store.store({ ...base, name: "plain manual" });
759
+ const nearMiss = await store.store({ ...base, name: "near miss", key: "/learnings-x/y" });
760
+
761
+ for (const memory of [longterm, manual, nearMiss]) {
762
+ expect(memory.expiresAt).toBeNull();
763
+ expect(expiryRow(memory.id)?.expiresAt).toBeNull();
764
+ }
765
+ });
766
+
767
+ test("an in-place edit keeps a learning's expiry; a move into /longterm clears it", async () => {
768
+ const t = await task();
769
+ const result = await call({
770
+ taskId: t.id,
771
+ learning: lesson("Edit keeps expiry"),
772
+ });
773
+ const id = learningData(result)!.memoryId!;
774
+ const before = expiryRow(id)!.expiresAt;
775
+ expect(before).not.toBeNull();
776
+
777
+ const store = getMemoryStore();
778
+ await store.edit({
779
+ id,
780
+ mode: "exact",
781
+ oldString: "do what it says",
782
+ newString: "still do what it says",
783
+ intent: "test edit",
784
+ });
785
+ expect(expiryRow(id)?.expiresAt).toBe(before);
786
+
787
+ await store.edit({
788
+ id,
789
+ mode: "exact",
790
+ newKey: "/longterm/facts/expiry/promoted",
791
+ intent: "promote",
792
+ });
793
+ expect(expiryRow(id)?.expiresAt).toBeNull();
794
+ });
795
+
796
+ function expectLearningTtl(expiresAt: string | null | undefined, from: number) {
797
+ expect(expiresAt).not.toBeNull();
798
+ const days = (Date.parse(expiresAt!) - from) / DAY_MS;
799
+ expect(days).toBeGreaterThan(LEARNING_TTL_DAYS - 0.01);
800
+ expect(days).toBeLessThan(LEARNING_TTL_DAYS + 0.01);
801
+ }
802
+
803
+ test("a move into /learnings starts the learning TTL on every chunk; a move out ends it", async () => {
804
+ const store = getMemoryStore();
805
+ const base = { agentId, scope: "swarm" as const, source: "manual" as const, name: "doc" };
806
+ const chunks = [
807
+ await store.store({
808
+ ...base,
809
+ content: "c0",
810
+ key: "/notes/expiry/doc",
811
+ chunkIndex: 0,
812
+ totalChunks: 2,
813
+ }),
814
+ await store.store({
815
+ ...base,
816
+ content: "c1",
817
+ key: "/notes/expiry/doc",
818
+ chunkIndex: 1,
819
+ totalChunks: 2,
820
+ }),
821
+ ];
822
+ for (const chunk of chunks) expect(expiryRow(chunk.id)?.expiresAt).toBeNull();
823
+
824
+ const movedAt = Date.now();
825
+ const moved = await store.edit({
826
+ id: chunks[1]!.id,
827
+ mode: "exact",
828
+ newKey: "/learnings/expiry/doc",
829
+ intent: "demote to a learning",
830
+ });
831
+ expectLearningTtl(moved.memory.expiresAt, movedAt);
832
+ for (const chunk of chunks) expect(expiryRow(chunk.id)?.expiresAt).toBe(moved.memory.expiresAt);
833
+
834
+ const back = await store.edit({
835
+ id: chunks[0]!.id,
836
+ mode: "exact",
837
+ newKey: "/notes/expiry/doc-kept",
838
+ intent: "keep it after all",
839
+ });
840
+ expect(back.memory.expiresAt).toBeNull();
841
+ for (const chunk of chunks) expect(expiryRow(chunk.id)?.expiresAt).toBeNull();
842
+ });
843
+
844
+ test("a learning moved out of /learnings past its deadline survives the purge", async () => {
845
+ const t = await task();
846
+ const result = await call({ taskId: t.id, learning: lesson("Moved out") });
847
+ const id = learningData(result)!.memoryId!;
848
+ getDb().run("UPDATE agent_memory SET expiresAt = '2000-01-01T00:00:00.000Z' WHERE id = ?", [
849
+ id,
850
+ ]);
851
+
852
+ const store = getMemoryStore();
853
+ await store.edit({ id, mode: "exact", newKey: "/notes/expiry/kept", intent: "keep" });
854
+ await store.purgeExpired();
855
+ expect(expiryRow(id)).toMatchObject({ expiresAt: null });
856
+ });
857
+
858
+ test("a move out of /learnings takes the source's own TTL; a move within keeps the deadline", async () => {
859
+ const store = getMemoryStore();
860
+ const completion = await store.store({
861
+ agentId,
862
+ scope: "swarm",
863
+ source: "task_completion",
864
+ name: "tc",
865
+ content: "tc",
866
+ key: "/learnings/expiry/tc",
867
+ });
868
+ const deadline = expiryRow(completion.id)!.expiresAt;
869
+
870
+ const renamed = await store.edit({
871
+ id: completion.id,
872
+ mode: "exact",
873
+ newKey: "/learnings/expiry/tc-renamed",
874
+ intent: "rename",
875
+ });
876
+ expect(renamed.memory.expiresAt).toBe(deadline);
877
+ expect(expiryRow(completion.id)?.expiresAt).toBe(deadline);
878
+
879
+ const movedAt = Date.now();
880
+ await store.edit({
881
+ id: completion.id,
882
+ mode: "exact",
883
+ newKey: "/notes/expiry/tc",
884
+ intent: "out",
885
+ });
886
+ const days = (Date.parse(expiryRow(completion.id)!.expiresAt!) - movedAt) / DAY_MS;
887
+ expect(days).toBeGreaterThan(TTL_DEFAULTS.task_completion! - 0.01);
888
+ expect(days).toBeLessThan(TTL_DEFAULTS.task_completion! + 0.01);
889
+ });
890
+
891
+ test("an expired learning is left out of search and removed by the purge", async () => {
892
+ const t = await task();
893
+ const result = await call({ taskId: t.id, learning: lesson("Expired learning") });
894
+ const id = learningData(result)!.memoryId!;
895
+ const embedding = new Float32Array(EMBEDDING_DIMENSIONS);
896
+ embedding[90] = 1;
897
+ const store = getMemoryStore();
898
+ await store.updateEmbedding(id, embedding, "test-embedding");
899
+ const search = () =>
900
+ store.search(embedding, agentId, { scope: "swarm", keyPrefix: "/learnings/", limit: 50 });
901
+ expect((await search()).map((hit) => hit.id)).toContain(id);
902
+
903
+ getDb().run("UPDATE agent_memory SET expiresAt = '2000-01-01T00:00:00.000Z' WHERE id = ?", [
904
+ id,
905
+ ]);
906
+ expect((await search()).map((hit) => hit.id)).not.toContain(id);
907
+ expect(await store.purgeExpired()).toBeGreaterThanOrEqual(1);
908
+ expect(expiryRow(id)).toBeNull();
909
+ });
910
+ });
911
+
912
+ describe("279_backfill_learning_expiry", () => {
913
+ test("sets createdAt + 30 days on learnings without an expiry and touches nothing else", async () => {
914
+ const store = getMemoryStore();
915
+ const base = { agentId, scope: "swarm" as const, source: "manual" as const, content: "y" };
916
+ const legacy = await store.store({
917
+ ...base,
918
+ name: "legacy",
919
+ key: "/learnings/backfill/legacy",
920
+ });
921
+ const preset = await store.store({
922
+ ...base,
923
+ name: "preset",
924
+ key: "/learnings/backfill/preset",
925
+ });
926
+ const longterm = await store.store({ ...base, name: "lt", key: "/longterm/facts/backfill/lt" });
927
+ const manual = await store.store({ ...base, name: "manual" });
928
+ const nearMiss = await store.store({ ...base, name: "near", key: "/learnings-x/backfill" });
929
+ const completion = await store.store({ ...base, name: "tc", source: "task_completion" });
930
+
931
+ const db = getDb();
932
+ const createdAt = "2026-10-26T09:15:00.123Z";
933
+ db.run("UPDATE agent_memory SET expiresAt = NULL, createdAt = ? WHERE id = ?", [
934
+ createdAt,
935
+ legacy.id,
936
+ ]);
937
+ db.run("UPDATE agent_memory SET expiresAt = '2099-01-01T00:00:00.000Z' WHERE id = ?", [
938
+ preset.id,
939
+ ]);
940
+ const before = new Map(
941
+ [longterm, manual, nearMiss, completion].map((m) => [
942
+ m.id,
943
+ db
944
+ .query<{ expiresAt: string | null }, [string]>(
945
+ "SELECT expiresAt FROM agent_memory WHERE id = ?",
946
+ )
947
+ .get(m.id)?.expiresAt,
948
+ ]),
949
+ );
950
+
951
+ const sql = await Bun.file(
952
+ new URL("../be/migrations/279_backfill_learning_expiry.sql", import.meta.url),
953
+ ).text();
954
+ db.run(sql);
955
+
956
+ const expiry = (id: string) =>
957
+ db
958
+ .query<{ expiresAt: string | null }, [string]>(
959
+ "SELECT expiresAt FROM agent_memory WHERE id = ?",
960
+ )
961
+ .get(id)?.expiresAt;
962
+ expect(expiry(legacy.id)).toBe("2026-11-25T09:15:00.123Z");
963
+ expect(expiry(preset.id)).toBe("2099-01-01T00:00:00.000Z");
964
+ for (const [id, value] of before) expect(expiry(id)).toBe(value);
965
+ });
381
966
  });