@desplega.ai/agent-swarm 1.160.0 → 1.162.0

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 (398) hide show
  1. package/README.md +4 -3
  2. package/dist/{acp-adapter-2mjwcsfh.js → acp-adapter-74m73ae9.js} +163 -49
  3. package/dist/{actions-e43rxskr.js → actions-4sr14gnt.js} +42 -38
  4. package/dist/{anthropic-messages-5qx80j9k.js → anthropic-messages-8xxrzky9.js} +22 -26
  5. package/dist/{app-mc7xfagn.js → app-pt68fbwp.js} +17 -14
  6. package/dist/{artifact-3v5t9jtg.js → artifact-fey7dvj9.js} +3 -2
  7. package/dist/{assistant-sedkzv3b.js → assistant-cv3jytks.js} +43 -39
  8. package/dist/{azure-openai-responses-nfb21z9a.js → azure-openai-responses-f5cqsyj8.js} +15 -10
  9. package/dist/{boot-reembed-m3656j2n.js → boot-reembed-4ht4gqth.js} +17 -14
  10. package/dist/{boot-reembed-cqz9swn5.js → boot-reembed-nxpcvpj9.js} +16 -13
  11. package/dist/{boot-scrub-logs-xbxf5d7w.js → boot-scrub-logs-k93kyw8k.js} +13 -10
  12. package/dist/boot-seeds-1skcrs0e.js +32 -0
  13. package/dist/{claude-adapter-dc6289mc.js → claude-adapter-r5g0tzge.js} +39 -30
  14. package/dist/{claude-managed-adapter-naaw51me.js → claude-managed-adapter-yxkfxg8j.js} +6 -5
  15. package/dist/{claude-managed-setup-eacvchx0.js → claude-managed-setup-pkyrgshb.js} +27 -27
  16. package/dist/{claude-sdk-session-bqp2xvym.js → claude-sdk-session-jxyxnrwd.js} +8041 -7910
  17. package/dist/{cli-4derpgyk.js → cli-2hhfhfq5.js} +6 -1
  18. package/dist/{cli-rykfmgwg.js → cli-2x0e561b.js} +1 -1
  19. package/dist/{cli-tzx2ke1v.js → cli-2zy95vhm.js} +137 -64
  20. package/dist/{cli-0x01kwrd.js → cli-4cwxn7gp.js} +47 -186
  21. package/dist/{cli-xjcywfsf.js → cli-4dcpaefp.js} +12 -11
  22. package/dist/{cli-v7fn5gms.js → cli-4x0csdjq.js} +164 -76
  23. package/dist/{cli-12tszpk9.js → cli-5bcd7sfy.js} +91 -29
  24. package/dist/{cli-jz4w45qt.js → cli-5k6k8ta3.js} +190 -50
  25. package/dist/{cli-tpq83z89.js → cli-5xhpb3kv.js} +20 -19
  26. package/dist/{cli-r1mxd1xh.js → cli-7af8yhav.js} +6 -179
  27. package/dist/{cli-jajnsm8q.js → cli-7tre70zp.js} +18160 -31345
  28. package/dist/{cli-447dt1h3.js → cli-8ev9xqnx.js} +218 -25
  29. package/dist/cli-bsky8g7w.js +449 -0
  30. package/dist/{cli-0z2v4nhw.js → cli-cat6h73s.js} +1 -1
  31. package/dist/{cli-25fcq4b4.js → cli-cebmgwsc.js} +15 -11
  32. package/dist/{cli-shkxm1vn.js → cli-cvatsam7.js} +189 -13
  33. package/dist/{cli-2658f6at.js → cli-cvk6yzw5.js} +6 -8
  34. package/dist/cli-dbmwby6a.js +9 -0
  35. package/dist/{cli-ptr8h7kp.js → cli-eg0b3p0k.js} +5 -218
  36. package/dist/cli-f9w1semm.js +413 -0
  37. package/dist/{cli-523679eh.js → cli-g739zqzt.js} +6 -5
  38. package/dist/{cli-dv6cdjs2.js → cli-gd4favx9.js} +28 -7
  39. package/dist/{cli-c8a36vcc.js → cli-gpqpmns7.js} +2 -2
  40. package/dist/{cli-5nbmpy8w.js → cli-hb5c2x5y.js} +1 -1
  41. package/dist/{cli-741yb0xx.js → cli-hmsw1gpy.js} +55 -169
  42. package/dist/{cli-qydf22qq.js → cli-jf7wmv1r.js} +2562 -735
  43. package/dist/{cli-mfe5btp9.js → cli-jxs2ygaw.js} +317 -121
  44. package/dist/{cli-kmcpfwn2.js → cli-jyy6pm2f.js} +19 -3
  45. package/dist/cli-kdkwd3yr.js +615 -0
  46. package/dist/{cli-6cs6wzxt.js → cli-kh04eqwe.js} +2 -2
  47. package/dist/{cli-9hsgwz4w.js → cli-kp42yek0.js} +1309 -391
  48. package/dist/cli-ma3zvh39.js +10404 -0
  49. package/dist/{cli-ybgv4kw2.js → cli-mbssg1xv.js} +9 -2
  50. package/dist/{cli-jsp14b6c.js → cli-mzfth0bp.js} +38 -1
  51. package/dist/{cli-r2ap2czm.js → cli-nexqx4ve.js} +6 -0
  52. package/dist/{cli-f8gy6r2r.js → cli-nq7yqw7b.js} +19 -8
  53. package/dist/{cli-10nhj6xq.js → cli-nt8hecg9.js} +34 -33
  54. package/dist/cli-p0r8sxj5.js +303 -0
  55. package/dist/{cli-58e8yr0d.js → cli-pkd6s2wy.js} +4 -2
  56. package/dist/{cli-a8dvhzrt.js → cli-q24re23n.js} +7 -5
  57. package/dist/cli-qjjvzwzd.js +222 -0
  58. package/dist/cli-qrgt5bqf.js +189 -0
  59. package/dist/{cli-et8m9xsv.js → cli-rfjw9jw2.js} +22 -10
  60. package/dist/{cli-7e398j1h.js → cli-rj0gqwwp.js} +3 -3
  61. package/dist/{cli-btfv8y88.js → cli-rnyzn44p.js} +2 -2
  62. package/dist/{cli-d5czme6m.js → cli-s3hwpt9v.js} +4754 -4945
  63. package/dist/{cli-0jwe9034.js → cli-sptrj5f5.js} +3 -3
  64. package/dist/{cli-0q3avq3s.js → cli-sqvfa090.js} +19 -11
  65. package/dist/{cli-azhgzetg.js → cli-swfmp1fx.js} +27 -27
  66. package/dist/{cli-jyk0ynw2.js → cli-t845n9xk.js} +23 -10
  67. package/dist/{cli-zpep9q5e.js → cli-tcen9p5w.js} +20 -15
  68. package/dist/{cli-74h9hscv.js → cli-tre4bdgq.js} +1 -1
  69. package/dist/{cli-pm1rst0h.js → cli-twrh04ap.js} +30 -15
  70. package/dist/{cli-phsaj4xq.js → cli-v0pvvhfq.js} +1 -1
  71. package/dist/{cli-ydmcgve1.js → cli-vc9bp061.js} +5 -5
  72. package/dist/{cli-g2whhdrf.js → cli-vxe6qa4h.js} +1 -1
  73. package/dist/{cli-vctdqs5h.js → cli-vy3ed88x.js} +15 -2
  74. package/dist/{cli-br0qdrnp.js → cli-vyqs9ya8.js} +18 -18
  75. package/dist/{cli-cpvsaqsw.js → cli-w0bwte75.js} +8 -5
  76. package/dist/cli-wbvnn6tk.js +861 -0
  77. package/dist/{cli-r94z9p1z.js → cli-wgbezhw2.js} +3 -0
  78. package/dist/{cli-evvtk35y.js → cli-wjgs5wxe.js} +7 -7
  79. package/dist/cli-wxkkd0e0.js +33 -0
  80. package/dist/{cli-0wgxmwf6.js → cli-xk79303e.js} +20 -7
  81. package/dist/{cli-ktmyrtpn.js → cli-xqpk3rp7.js} +33 -10
  82. package/dist/{cli-ygwm91nt.js → cli-yy6dew39.js} +1 -1
  83. package/dist/cli-zp38xvtm.js +9487 -0
  84. package/dist/{cli-tfky2838.js → cli-zvhd3f64.js} +4 -4
  85. package/dist/{cli-jayjpjmb.js → cli-zxqx25nz.js} +66 -23
  86. package/dist/cli.js +40 -32
  87. package/dist/{cloudflare-workers-ai-system-one-k6fbxw9d.js → cloudflare-workers-ai-system-one-k8ddqjkq.js} +8 -6
  88. package/dist/{codex-adapter-nmxcatww.js → codex-adapter-esvmnhn7.js} +24 -23
  89. package/dist/{codex-hook-20me6byw.js → codex-hook-m73jmqgx.js} +19 -3
  90. package/dist/{codex-login-w6fz4xbz.js → codex-login-cf7mzsgg.js} +2 -2
  91. package/dist/{codex-session-runner-90aa80ev.js → codex-session-runner-ban9excr.js} +24 -23
  92. package/dist/{commands-8wcq1kn7.js → commands-75413p2n.js} +13 -10
  93. package/dist/{db-j40kc4se.js → db-7f5pecwg.js} +17 -10
  94. package/dist/{dispatcher-4zqy768d.js → dispatcher-fh9at8nz.js} +41 -37
  95. package/dist/dsh-adapter-wpze65d4.js +24 -0
  96. package/dist/{e2b-ez07znam.js → e2b-gjgdjp91.js} +12 -9
  97. package/dist/easter-egg-3d-3w5c2n4c.js +1057 -0
  98. package/dist/{execute-6e7qeyk4.js → execute-f50wg9nh.js} +203 -49
  99. package/dist/{google-generative-ai-k6n5nbpp.js → google-generative-ai-jxxpnegy.js} +2 -2
  100. package/dist/{google-vertex-44xxtcvp.js → google-vertex-x7q1angm.js} +5 -5
  101. package/dist/{handlers-kjdce1w5.js → handlers-w13787bb.js} +44 -40
  102. package/dist/{hook-r2t4bqfg.js → hook-46g1jrvx.js} +34 -20
  103. package/dist/{hook-czx13n12.js → hook-4tpts2ry.js} +25 -21
  104. package/dist/{http-3bbb19be.js → http-19pzbfrt.js} +1440 -283
  105. package/dist/{index-668me3f0.js → index-8fd4dm4h.js} +42 -38
  106. package/dist/{index-fg0dsp6c.js → index-dqmp15bq.js} +41 -37
  107. package/dist/{index-kkv84jq9.js → index-qb4q1y3e.js} +41 -37
  108. package/dist/index-s75wc4wd.js +33 -0
  109. package/dist/{index-zg7vp46x.js → index-scptvdxg.js} +64 -38
  110. package/dist/{keepalive-yra8dy57.js → keepalive-xa5ts9cd.js} +15 -12
  111. package/dist/{lead-va0pad2c.js → lead-qp4xkvjq.js} +59 -54
  112. package/dist/{maintenance-hqewtmyg.js → maintenance-rm5885hm.js} +17 -14
  113. package/dist/{mistral-conversations-pc3ntnxt.js → mistral-conversations-rw7fbt22.js} +4 -4
  114. package/dist/{node-a5e00qhp.js → node-8zkdq42h.js} +834 -833
  115. package/dist/node-f0ykebbv.js +2107 -0
  116. package/dist/node-wyamey5r.js +19 -0
  117. package/dist/{oauth-refresh-sweep-7rdt1m9n.js → oauth-refresh-sweep-1csdfebf.js} +14 -11
  118. package/dist/{onboard-j6ms6d0x.js → onboard-r6b78cs4.js} +10 -10
  119. package/dist/{openai-codex-responses-bbancrr0.js → openai-codex-responses-efvrgrq3.js} +4 -4
  120. package/dist/{openai-completions-jpaj5g2b.js → openai-completions-bbbrrz4z.js} +12 -8
  121. package/dist/{openai-responses-200k1wx4.js → openai-responses-9jjyrcm1.js} +15 -10
  122. package/dist/{opencode-adapter-89rabkw2.js → opencode-adapter-kb3g6pkf.js} +12 -9
  123. package/dist/{otel-impl-a792rjz0.js → otel-impl-0y9knpky.js} +6 -6
  124. package/dist/{pi-mono-adapter-g7qzvr3v.js → pi-mono-adapter-z6s1bme2.js} +128 -37
  125. package/dist/{pricing-refresh-wx0tp7cb.js → pricing-refresh-mth26tgp.js} +15 -12
  126. package/dist/{rbac-roles-8tzawacv.js → rbac-roles-kwntb23q.js} +17 -12
  127. package/dist/rbac-roles-vpk4ebm8.js +45 -0
  128. package/dist/{registry-v5wytg0s.js → registry-km6t1jd2.js} +1 -1
  129. package/dist/{render-v2-mm7zswb8.js → render-v2-hcm7h00y.js} +17 -14
  130. package/dist/{runtime-zyssgse0.js → runtime-vfjsfsc5.js} +5 -4
  131. package/dist/{setup-8y70ys6t.js → setup-hbyzd65h.js} +2 -2
  132. package/dist/{virtual-modules-6nmk7h3n.js → virtual-modules-9bv7ry91.js} +9 -7
  133. package/dist/{work-objects-fg6xkb0n.js → work-objects-m09sxnhe.js} +44 -40
  134. package/dist/{worker-wmwhxsph.js → worker-0h35rvk4.js} +59 -54
  135. package/dist/{x-n3e0v3xa.js → x-f1gt1pz3.js} +2 -2
  136. package/openapi.json +699 -26
  137. package/package.json +19 -11
  138. package/src/azure-devops/api.ts +121 -0
  139. package/src/azure-devops/auth.ts +78 -0
  140. package/src/azure-devops/handlers.ts +413 -0
  141. package/src/azure-devops/index.ts +27 -0
  142. package/src/azure-devops/templates.ts +108 -0
  143. package/src/azure-devops/types.ts +90 -0
  144. package/src/be/api-drain.ts +184 -0
  145. package/src/be/db/tasks/read.ts +32 -7
  146. package/src/be/db/tasks/write.ts +21 -4
  147. package/src/be/db-client.ts +11 -2
  148. package/src/be/db-retention.ts +95 -32
  149. package/src/be/db.ts +44 -19
  150. package/src/be/memory/constants.ts +16 -0
  151. package/src/be/memory/graph-expansion.ts +8 -1
  152. package/src/be/memory/index-content.ts +20 -1
  153. package/src/be/memory/key-guard.ts +93 -0
  154. package/src/be/memory/key-paths.ts +103 -0
  155. package/src/be/memory/link-resolver.ts +29 -3
  156. package/src/be/memory/providers/sqlite-store.ts +152 -45
  157. package/src/be/memory/raters/llm-summarizer.ts +10 -4
  158. package/src/be/memory/raters/llm.ts +15 -5
  159. package/src/be/memory/raters/store.ts +6 -3
  160. package/src/be/memory/raters/types.ts +11 -0
  161. package/src/be/memory/reranker.ts +38 -7
  162. package/src/be/memory/types.ts +12 -1
  163. package/src/be/migrations/190_memory_rating_model.sql +7 -0
  164. package/src/be/migrations/191_context_versions_previous_index.sql +8 -0
  165. package/src/be/migrations/192_favorites_agent_fs_path.sql +36 -0
  166. package/src/be/onboarding.ts +7 -1
  167. package/src/be/pricing-normalize.ts +4 -2
  168. package/src/be/scripts/typecheck.ts +4 -3
  169. package/src/be/seed-pricing.ts +16 -0
  170. package/src/be/seed-prompt-templates.ts +1 -0
  171. package/src/be/swarm-config-guard.ts +46 -17
  172. package/src/be/task-citations.ts +11 -5
  173. package/src/be/users.ts +3 -0
  174. package/src/cli.tsx +3 -2
  175. package/src/comb/agent-fs.ts +39 -0
  176. package/src/comb/config.ts +37 -0
  177. package/src/comb/markers.ts +37 -0
  178. package/src/comb/review-batch.ts +486 -0
  179. package/src/comb/templates.ts +88 -0
  180. package/src/commands/claude-managed-setup.ts +33 -31
  181. package/src/commands/context-preamble.ts +4 -1
  182. package/src/commands/hook.ts +2 -1
  183. package/src/commands/provider-credentials.ts +28 -15
  184. package/src/commands/runner.ts +458 -110
  185. package/src/commands/templates.ts +10 -0
  186. package/src/e2b/env.ts +2 -0
  187. package/src/extensions/catalog.generated.json +17 -0
  188. package/src/extensions/contract-types.generated.ts +1 -1
  189. package/src/fs/agent-fs-provider.ts +106 -2
  190. package/src/github/handlers.ts +10 -74
  191. package/src/github/reactions.ts +119 -138
  192. package/src/github/task-reactions.ts +34 -11
  193. package/src/heartbeat/heartbeat.ts +4 -0
  194. package/src/hooks/codex-hook.ts +25 -1
  195. package/src/hooks/hook.ts +14 -1
  196. package/src/hooks/pr-body-guard.ts +983 -0
  197. package/src/http/agents.ts +1 -1
  198. package/src/http/all-routes.ts +1 -0
  199. package/src/http/assets.ts +5 -17
  200. package/src/http/comb.ts +131 -0
  201. package/src/http/core.ts +14 -1
  202. package/src/http/extensions.ts +51 -27
  203. package/src/http/fs.ts +9 -17
  204. package/src/http/index.ts +27 -9
  205. package/src/http/mcp-user.ts +8 -13
  206. package/src/http/mcp.ts +19 -12
  207. package/src/http/memory.ts +80 -14
  208. package/src/http/onboarding.ts +21 -2
  209. package/src/http/poll.ts +30 -3
  210. package/src/http/realtime.ts +62 -0
  211. package/src/http/request-principal.ts +22 -0
  212. package/src/http/session-data.ts +6 -4
  213. package/src/http/stats.ts +1 -0
  214. package/src/http/status.ts +34 -2
  215. package/src/http/tasks.ts +17 -3
  216. package/src/http/users.ts +1 -1
  217. package/src/http/webhooks.ts +120 -2
  218. package/src/kv-reserved-namespaces.ts +10 -5
  219. package/src/providers/claude-adapter.ts +84 -16
  220. package/src/providers/claude-managed-adapter.ts +29 -2
  221. package/src/providers/codex-adapter.ts +1 -1
  222. package/src/providers/codex-skill-resolver.ts +6 -0
  223. package/src/providers/dsh-adapter.ts +204 -7
  224. package/src/providers/opencode-adapter.ts +24 -3
  225. package/src/providers/pi-mono-adapter.ts +154 -5
  226. package/src/providers/pi-mono-extension.ts +1 -1
  227. package/src/providers/pricing-sources.md +5 -1
  228. package/src/providers/reasoning-effort.ts +10 -2
  229. package/src/providers/types.ts +1 -1
  230. package/src/rbac/legacy-policy.ts +3 -0
  231. package/src/rbac/permissions.ts +14 -0
  232. package/src/realtime/auth.ts +63 -1
  233. package/src/realtime/tickets.ts +52 -0
  234. package/src/realtime/transport.ts +51 -22
  235. package/src/scripts-runtime/types/stdlib.d.ts +13 -5
  236. package/src/scripts-runtime/types/swarm-extension.d.ts +7 -3
  237. package/src/scripts-runtime/types/swarm-sdk.d.ts +13 -5
  238. package/src/tasks/context-key.ts +38 -1
  239. package/src/telemetry-context.ts +175 -0
  240. package/src/telemetry-contract/EVENTS.md +81 -0
  241. package/src/telemetry-contract/SOURCE.json +9 -0
  242. package/src/telemetry-contract/catalog.json +1335 -0
  243. package/src/telemetry-contract/index.ts +60 -0
  244. package/src/telemetry-contract/types.gen.ts +1971 -0
  245. package/src/telemetry-identity.ts +129 -0
  246. package/src/telemetry-snapshot.ts +211 -0
  247. package/src/telemetry-trigger.ts +125 -0
  248. package/src/telemetry-types.typetest.ts +40 -0
  249. package/src/telemetry.ts +271 -67
  250. package/src/tests/api-drain-e2e.test.ts +249 -0
  251. package/src/tests/api-drain-worker-e2e.test.ts +216 -0
  252. package/src/tests/api-drain.test.ts +351 -0
  253. package/src/tests/azure-devops-auth.test.ts +100 -0
  254. package/src/tests/azure-devops-handlers.test.ts +324 -0
  255. package/src/tests/azure-devops-webhook-malformed.test.ts +96 -0
  256. package/src/tests/claude-default-route.test.ts +260 -0
  257. package/src/tests/claude-managed-adapter.test.ts +47 -0
  258. package/src/tests/claude-managed-setup.test.ts +48 -0
  259. package/src/tests/claude-prompt-body-once.test.ts +117 -0
  260. package/src/tests/claude-routes-e2e.test.ts +316 -0
  261. package/src/tests/comb-config-guard.test.ts +38 -0
  262. package/src/tests/comb-links.test.ts +162 -0
  263. package/src/tests/comb-markers.test.ts +68 -0
  264. package/src/tests/comb-review-batch.test.ts +770 -0
  265. package/src/tests/comb-status.test.ts +152 -0
  266. package/src/tests/context-versions-retention.test.ts +314 -0
  267. package/src/tests/core-auth.test.ts +7 -0
  268. package/src/tests/db-retention.test.ts +14 -14
  269. package/src/tests/db-task-read-contract.test.ts +3 -0
  270. package/src/tests/db-task-write-contract.test.ts +3 -0
  271. package/src/tests/docs-index-footprint.test.js +3 -3
  272. package/src/tests/dsh-adapter.test.ts +134 -2
  273. package/src/tests/dsh-usage.test.ts +153 -0
  274. package/src/tests/extensions-catalog.test.ts +1 -0
  275. package/src/tests/extensions-example-deploy-awareness.test.ts +301 -0
  276. package/src/tests/extensions-http.test.ts +137 -10
  277. package/src/tests/extensions-mcp-tools.test.ts +28 -0
  278. package/src/tests/favorites-agent-fs-path.test.ts +226 -0
  279. package/src/tests/fetch-resolved-env.test.ts +24 -0
  280. package/src/tests/fixtures/azure-devops/pull-request-commented.json +129 -0
  281. package/src/tests/fixtures/azure-devops/pull-request-created.json +88 -0
  282. package/src/tests/fixtures/fake-claude-routes.ts +229 -0
  283. package/src/tests/github-handlers-reactions.test.ts +486 -0
  284. package/src/tests/github-reactions.test.ts +280 -0
  285. package/src/tests/harness-cli-version.test.ts +62 -0
  286. package/src/tests/http-api-integration.test.ts +21 -0
  287. package/src/tests/http-task-write-ownership.test.ts +24 -1
  288. package/src/tests/internal-ai/complete-structured.test.ts +94 -0
  289. package/src/tests/internal-ai/credentials.test.ts +22 -0
  290. package/src/tests/internal-ai/models.test.ts +36 -2
  291. package/src/tests/internal-ai/schema-parity.test.ts +25 -1
  292. package/src/tests/internal-ai/summarize-session.test.ts +23 -7
  293. package/src/tests/mcp-user-route.test.ts +133 -0
  294. package/src/tests/memory-key-paths.test.ts +1055 -0
  295. package/src/tests/memory-link-resolver.test.ts +34 -0
  296. package/src/tests/memory-rate-endpoint.test.ts +66 -0
  297. package/src/tests/memory-rater-llm-summarizer.test.ts +2 -1
  298. package/src/tests/memory-rater-llm.test.ts +73 -0
  299. package/src/tests/memory-rater-store.test.ts +31 -0
  300. package/src/tests/memory-reranker.test.ts +40 -0
  301. package/src/tests/onboarding.test.ts +108 -0
  302. package/src/tests/opencode-adapter.test.ts +57 -0
  303. package/src/tests/opencode-plugin.test.ts +4 -0
  304. package/src/tests/pi-codemode.test.ts +82 -4
  305. package/src/tests/pi-mono-adapter.test.ts +265 -2
  306. package/src/tests/pr-body-leaks.test.ts +789 -0
  307. package/src/tests/preload.ts +14 -0
  308. package/src/tests/provider-registration.test.ts +0 -2
  309. package/src/tests/providers/pi-cost.test.ts +190 -4
  310. package/src/tests/rbac-engine.test.ts +25 -1
  311. package/src/tests/realtime-room-auth.test.ts +104 -1
  312. package/src/tests/realtime-tickets.test.ts +74 -0
  313. package/src/tests/realtime-transport.test.ts +131 -4
  314. package/src/tests/runner-api-drain.test.ts +301 -0
  315. package/src/tests/runner-fallback-output.test.ts +61 -0
  316. package/src/tests/runner-fenced-json-output.test.ts +178 -0
  317. package/src/tests/runner-slot-reconcile.test.ts +199 -0
  318. package/src/tests/script-connections.test.ts +6 -0
  319. package/src/tests/send-task-requested-by.test.ts +133 -15
  320. package/src/tests/session-costs-recompute-all-providers.test.ts +23 -0
  321. package/src/tests/task-lifecycle-telemetry.test.ts +8 -3
  322. package/src/tests/task-reactions.test.ts +29 -6
  323. package/src/tests/telemetry-context.test.ts +314 -0
  324. package/src/tests/telemetry-init.test.ts +51 -19
  325. package/src/tests/telemetry-snapshot.test.ts +229 -0
  326. package/src/tests/telemetry-trigger.test.ts +200 -0
  327. package/src/tests/template-registry-helpers.ts +1 -0
  328. package/src/tests/vcs-azure-devops.test.ts +73 -0
  329. package/src/tests/webhooks-task-blocked.test.ts +23 -0
  330. package/src/tests/workflow-agent-task-retry.test.ts +363 -0
  331. package/src/tests/workflow-definition-telemetry.test.ts +4 -4
  332. package/src/tests/workflow-llm.test.ts +14 -0
  333. package/src/tools/context-diff.ts +20 -0
  334. package/src/tools/extension-install.ts +27 -16
  335. package/src/tools/memory-edit.ts +47 -3
  336. package/src/tools/memory-search.ts +13 -1
  337. package/src/tools/memory-store.ts +55 -3
  338. package/src/tools/poll-task.ts +20 -1
  339. package/src/tools/send-task.ts +9 -1
  340. package/src/tools/task-action.ts +11 -0
  341. package/src/types.ts +45 -8
  342. package/src/utils/api-drain.ts +24 -0
  343. package/src/utils/constants.ts +57 -16
  344. package/src/utils/credentials.test.ts +31 -1
  345. package/src/utils/credentials.ts +20 -9
  346. package/src/utils/dsh-usage.ts +53 -0
  347. package/src/utils/harness-cli-version.ts +6 -4
  348. package/src/utils/internal-ai/complete-structured.ts +26 -3
  349. package/src/utils/internal-ai/credentials.ts +23 -9
  350. package/src/utils/internal-ai/index.ts +8 -1
  351. package/src/utils/internal-ai/models.ts +34 -8
  352. package/src/utils/internal-ai/summarize-session.ts +22 -8
  353. package/src/utils/pr-body-leaks.ts +172 -0
  354. package/src/utils/secret-scrubber.ts +8 -0
  355. package/src/utils/task-attachment-links.ts +14 -8
  356. package/src/vcs/azure-devops.ts +80 -0
  357. package/src/vcs/index.ts +5 -1
  358. package/src/vcs/types.ts +2 -2
  359. package/src/workflows/recovery.ts +26 -1
  360. package/src/workflows/resume.ts +31 -4
  361. package/src/workflows/task-step-routing.ts +75 -2
  362. package/templates/community/open-prompt-showreel/PLAYBOOK.md +336 -0
  363. package/templates/community/open-prompt-showreel/README.md +33 -0
  364. package/templates/community/open-prompt-showreel/example/tla-races/facts.ts +145 -0
  365. package/templates/community/open-prompt-showreel/example/tla-races/facts.v3.json +140 -0
  366. package/templates/community/open-prompt-showreel/example/tla-races/music.mist-city.json +8 -0
  367. package/templates/community/open-prompt-showreel/example/tla-races/reel.html +805 -0
  368. package/templates/community/open-prompt-showreel/example/tla-races/smoke.sh +48 -0
  369. package/templates/community/open-prompt-showreel/lead-prompt.md +89 -0
  370. package/templates/community/open-prompt-showreel/setup.sh +167 -0
  371. package/templates/community/open-prompt-showreel/skills/motion-design-replication/SKILL.md +85 -0
  372. package/templates/community/open-prompt-showreel/skills/motion-design-video-analysis/SKILL.md +115 -0
  373. package/templates/community/open-prompt-showreel/skills/open-prompt-showreel/SKILL.md +147 -0
  374. package/templates/community/open-prompt-showreel/skills/video-generation/SKILL.md +195 -0
  375. package/templates/community/open-prompt-showreel/tools/fetch-music.sh +65 -0
  376. package/templates/community/open-prompt-showreel/tools/music-analyze.py +69 -0
  377. package/templates/community/open-prompt-showreel/tools/music-current.sh +34 -0
  378. package/templates/community/open-prompt-showreel/tools/music-cut.sh +36 -0
  379. package/templates/community/open-prompt-showreel/tools/music-refine.py +39 -0
  380. package/templates/community/open-prompt-showreel/tools/render.mjs +157 -0
  381. package/templates/community/open-prompt-showreel/tools/sheet.sh +44 -0
  382. package/templates/community/open-prompt-showreel/tools/web-compress.sh +17 -0
  383. package/templates/community/open-prompt-showreel/tools/x-reencode.sh +21 -0
  384. package/templates/extensions/README.md +1 -0
  385. package/templates/extensions/deploy-awareness/README.md +28 -0
  386. package/templates/extensions/deploy-awareness/hooks.ts +152 -0
  387. package/templates/extensions/deploy-awareness/manifest.json +8 -0
  388. package/templates/skills/memory/config.json +2 -2
  389. package/templates/skills/memory/content.md +59 -5
  390. package/templates/skills/swarm-extensions/config.json +1 -1
  391. package/templates/skills/swarm-extensions/content.md +28 -5
  392. package/tsconfig.json +3 -0
  393. package/dist/boot-seeds-gsetbs5y.js +0 -28
  394. package/dist/cli-j490egb5.js +0 -5632
  395. package/dist/cli-tjf4cn8z.js +0 -9119
  396. package/dist/cli-tmqt7dpj.js +0 -572
  397. package/dist/dsh-adapter-mpnzgztj.js +0 -19
  398. package/dist/index-7aj368tw.js +0 -30
@@ -20,33 +20,63 @@ const YIELD_MS = 25;
20
20
  * This is deliberately a closed list. Neither table nor column names may come
21
21
  * from operator configuration: a retention policy must never target a table
22
22
  * that code review has not explicitly approved as safe to delete from.
23
+ *
24
+ * Two policies exist:
25
+ * - `age`: the env value is a number of days; rows whose `timeColumn` is older
26
+ * than that horizon are deleted.
27
+ * - `keepLatest`: the env value is a count; within each `partitionBy` group,
28
+ * only the newest `rankBy` rows are kept. The newest row of a group is
29
+ * never deleted, because the smallest accepted count is 1.
23
30
  */
24
31
  export const DB_RETENTION_TABLES = [
25
32
  {
26
33
  table: "session_logs",
34
+ policy: "age",
27
35
  timeColumn: "createdAt",
28
36
  envKey: "SESSION_LOG_RETENTION_DAYS",
29
37
  metricsKey: "sessionLogs",
30
38
  },
31
39
  {
32
40
  table: "agent_log",
41
+ policy: "age",
33
42
  timeColumn: "createdAt",
34
43
  envKey: "AGENT_LOG_RETENTION_DAYS",
35
44
  metricsKey: "agentLog",
36
45
  },
37
46
  {
38
47
  table: "events",
48
+ policy: "age",
39
49
  timeColumn: "createdAt",
40
50
  envKey: "EVENTS_RETENTION_DAYS",
41
51
  metricsKey: "events",
42
52
  },
43
- ] as const satisfies ReadonlyArray<{
44
- table: string;
45
- timeColumn: string;
46
- envKey: string;
47
- metricsKey: string;
48
- initialBatchSize?: number;
49
- }>;
53
+ {
54
+ // Every profile self-edit stores a full copy of the field, so a large,
55
+ // frequently edited field grows this table without bound. Ranking runs on
56
+ // the covering idx_cv_agent_field index, so neither the COUNT nor the
57
+ // candidate scan reads `content`. Rows are large (a version can be
58
+ // hundreds of KB), so batches start and stay small.
59
+ table: "context_versions",
60
+ policy: "keepLatest",
61
+ partitionBy: "agentId, field",
62
+ rankBy: "version",
63
+ envKey: "CONTEXT_VERSIONS_KEEP_LATEST",
64
+ metricsKey: "contextVersions",
65
+ initialBatchSize: 50,
66
+ maxBatchSize: 100,
67
+ },
68
+ ] as const satisfies ReadonlyArray<
69
+ {
70
+ table: string;
71
+ envKey: string;
72
+ metricsKey: string;
73
+ initialBatchSize?: number;
74
+ maxBatchSize?: number;
75
+ } & (
76
+ | { policy: "age"; timeColumn: string }
77
+ | { policy: "keepLatest"; partitionBy: string; rankBy: string }
78
+ )
79
+ >;
50
80
 
51
81
  type RetentionTable = (typeof DB_RETENTION_TABLES)[number];
52
82
  type RetentionMetricsKey = RetentionTable["metricsKey"];
@@ -261,27 +291,65 @@ function yieldTick(): Promise<void> {
261
291
  return new Promise((resolve) => setTimeout(resolve, YIELD_MS));
262
292
  }
263
293
 
264
- function retentionDays(table: RetentionTable): number | null {
294
+ /** Days for an `age` table, kept-version count for a `keepLatest` table; null when disabled. */
295
+ function retentionValue(table: RetentionTable): number | null {
265
296
  return readPositiveIntEnv(table.envKey);
266
297
  }
267
298
 
299
+ function initialBatchSize(table: RetentionTable): number {
300
+ return "initialBatchSize" in table ? table.initialBatchSize : DEFAULT_BATCH_SIZE;
301
+ }
302
+
303
+ function maxBatchSize(table: RetentionTable): number {
304
+ return "maxBatchSize" in table ? table.maxBatchSize : MAX_BATCH_SIZE;
305
+ }
306
+
307
+ /** The backlog COUNT and the batched DELETE for one table under its policy. */
308
+ type SweepStatements = {
309
+ backlogSql: string;
310
+ /** Takes `params` followed by the batch LIMIT. */
311
+ deleteSql: string;
312
+ params: Array<string | number>;
313
+ };
314
+
315
+ export function sweepStatements(table: RetentionTable, value: number, now: Date): SweepStatements {
316
+ if (table.policy === "keepLatest") {
317
+ // ROW_NUMBER over the (partition, rank DESC) index: rank 1 is the newest
318
+ // row of its group. The DELETE removes the deepest history first, so an
319
+ // interrupted sweep leaves each group's surviving versions contiguous.
320
+ const ranked = `SELECT rowid AS rid, ROW_NUMBER() OVER (PARTITION BY ${table.partitionBy} ORDER BY ${table.rankBy} DESC) AS rn FROM ${table.table}`;
321
+ return {
322
+ backlogSql: `SELECT COUNT(*) AS n FROM (${ranked}) WHERE rn > ?`,
323
+ deleteSql: `DELETE FROM ${table.table} WHERE rowid IN (
324
+ SELECT rid FROM (${ranked}) WHERE rn > ? ORDER BY rn DESC LIMIT ?
325
+ )`,
326
+ params: [value],
327
+ };
328
+ }
329
+ const cutoff = new Date(now.getTime() - value * DAY_MS).toISOString();
330
+ return {
331
+ backlogSql: `SELECT COUNT(*) AS n FROM ${table.table} WHERE ${table.timeColumn} < ?`,
332
+ deleteSql: `DELETE FROM ${table.table} WHERE rowid IN (
333
+ SELECT rowid FROM ${table.table} WHERE ${table.timeColumn} < ? ORDER BY ${table.timeColumn} LIMIT ?
334
+ )`,
335
+ params: [cutoff],
336
+ };
337
+ }
338
+
268
339
  function dryRunEnabled(env: NodeJS.ProcessEnv = process.env): boolean {
269
340
  const raw = env.DB_RETENTION_DRY_RUN;
270
341
  if (raw === undefined || raw.trim() === "") return false;
271
342
  return isEnvFlagEnabled("DB_RETENTION_DRY_RUN", true, env);
272
343
  }
273
344
 
274
- async function indexedBacklogCount(table: RetentionTable, cutoff: string): Promise<number> {
275
- const row = await getDbClient().get<{ n: number }>(
276
- `SELECT COUNT(*) AS n FROM ${table.table} WHERE ${table.timeColumn} < ?`,
277
- [cutoff],
278
- );
345
+ async function indexedBacklogCount(statements: SweepStatements): Promise<number> {
346
+ const row = await getDbClient().get<{ n: number }>(statements.backlogSql, statements.params);
279
347
  return row?.n ?? 0;
280
348
  }
281
349
 
282
350
  async function sweepTable(
283
351
  table: RetentionTable,
284
- cutoff: string,
352
+ statements: SweepStatements,
285
353
  dryRun: boolean,
286
354
  deadline: number,
287
355
  signal: AbortSignal,
@@ -290,33 +358,29 @@ async function sweepTable(
290
358
  const client = getDbClient();
291
359
 
292
360
  if (dryRun) {
293
- const backlogRemaining = await indexedBacklogCount(table, cutoff);
361
+ const backlogRemaining = await indexedBacklogCount(statements);
294
362
  return {
295
363
  rowsDeleted: 0,
296
364
  batches: 0,
297
365
  backlogRemaining,
298
366
  drained: backlogRemaining === 0,
299
367
  slowestStatementMs: 0,
300
- batchSize: batchSizeByTable[table.metricsKey] ?? DEFAULT_BATCH_SIZE,
368
+ batchSize: batchSizeByTable[table.metricsKey] ?? initialBatchSize(table),
301
369
  };
302
370
  }
303
371
 
304
372
  let rowsDeleted = 0;
305
373
  let batches = 0;
306
374
  let slowestStatementMs = 0;
307
- let size = batchSizeByTable[table.metricsKey] ?? DEFAULT_BATCH_SIZE;
375
+ let size = batchSizeByTable[table.metricsKey] ?? initialBatchSize(table);
376
+ const ceiling = maxBatchSize(table);
308
377
 
309
378
  try {
310
379
  while (!signal.aborted && Date.now() < deadline) {
311
380
  const limitUsed = size;
312
381
  // Never wrap multiple batches in a transaction: one autocommit DELETE per
313
382
  // batch, so the write lock and any event-loop stall end with each statement.
314
- const result = await client.runTimed(
315
- `DELETE FROM ${table.table} WHERE rowid IN (
316
- SELECT rowid FROM ${table.table} WHERE ${table.timeColumn} < ? ORDER BY ${table.timeColumn} LIMIT ?
317
- )`,
318
- [cutoff, limitUsed],
319
- );
383
+ const result = await client.runTimed(statements.deleteSql, [...statements.params, limitUsed]);
320
384
  // Execution time only. Wall time around the call also covers waiting for
321
385
  // the client's FIFO lock and its BUSY backoff sleeps, neither of which
322
386
  // this statement spent in the driver: charging those to the stall metric
@@ -331,7 +395,7 @@ async function sweepTable(
331
395
  if (elapsed > maxStatementMs) {
332
396
  size = Math.max(MIN_BATCH_SIZE, Math.floor(size / 2));
333
397
  } else if (elapsed < maxStatementMs / 5) {
334
- size = Math.min(MAX_BATCH_SIZE, size * 2);
398
+ size = Math.min(ceiling, size * 2);
335
399
  }
336
400
 
337
401
  // A DELETE that changed fewer rows than the LIMIT it used means the
@@ -351,7 +415,7 @@ async function sweepTable(
351
415
  // backlogRemaining > 0 drops the table from `undrained`, leaves catch-up
352
416
  // unarmed, and publishes that contradiction on /api/metrics until the next
353
417
  // hourly tick.
354
- const backlogRemaining = await indexedBacklogCount(table, cutoff);
418
+ const backlogRemaining = await indexedBacklogCount(statements);
355
419
  return {
356
420
  rowsDeleted,
357
421
  batches,
@@ -409,7 +473,7 @@ export function runDbRetentionTick(options: DbRetentionTickOptions = {}): Promis
409
473
  const sweepAllTables = async (rawTickSpan: SwarmSpan): Promise<void> => {
410
474
  const tickSpan = bestEffortSpan(rawTickSpan);
411
475
  const tickDeadline = tickStartedAt + budget;
412
- const enabled = DB_RETENTION_TABLES.filter((table) => retentionDays(table) !== null);
476
+ const enabled = DB_RETENTION_TABLES.filter((table) => retentionValue(table) !== null);
413
477
  if (enabled.length === 0) {
414
478
  lastSweepOrder = [];
415
479
  tickSpan.setAttributes({
@@ -431,18 +495,17 @@ export function runDbRetentionTick(options: DbRetentionTickOptions = {}): Promis
431
495
  const undrained = new Set<RetentionMetricsKey>();
432
496
 
433
497
  const sweepOne = async (table: RetentionTable, tableDeadline: number): Promise<void> => {
434
- const days = retentionDays(table);
435
- if (days === null) return;
498
+ const value = retentionValue(table);
499
+ if (value === null) return;
436
500
  const startedAt = Date.now();
437
501
  const previous = retentionStats[table.metricsKey];
438
502
  const tableSpan = bestEffortStartSpan("db.retention.table", {
439
503
  "agentswarm.retention.table": table.table,
440
504
  });
441
505
  try {
442
- const cutoff = new Date(cutoffBase.getTime() - days * DAY_MS).toISOString();
443
506
  const result = await sweepTable(
444
507
  table,
445
- cutoff,
508
+ sweepStatements(table, value, cutoffBase),
446
509
  dryRun,
447
510
  tableDeadline,
448
511
  abortController.signal,
@@ -529,7 +592,7 @@ export function runDbRetentionTick(options: DbRetentionTickOptions = {}): Promis
529
592
  partial?.progress.batchSize ??
530
593
  previous?.batchSize ??
531
594
  batchSizeByTable[table.metricsKey] ??
532
- DEFAULT_BATCH_SIZE;
595
+ initialBatchSize(table);
533
596
  // Committed rows advance the running total and justify the vacuum,
534
597
  // exactly as they would have on the success path.
535
598
  const cumulative = (cumulativeRowsDeleted[table.metricsKey] ?? 0) + rowsDeleted;
@@ -670,7 +733,7 @@ export function _getLastSweepOrderForTests(): RetentionMetricsKey[] {
670
733
  export async function startDbRetention(intervalMs = RETENTION_INTERVAL_MS): Promise<void> {
671
734
  if (retentionTimer) return;
672
735
  const configured = DB_RETENTION_TABLES.map(
673
- (table) => `${table.table}=${retentionDays(table) ?? "disabled"}`,
736
+ (table) => `${table.table}=${retentionValue(table) ?? "disabled"}`,
674
737
  ).join(", ");
675
738
  console.log(`[db-retention] starting (${configured}, dryRun=${dryRunEnabled()})`);
676
739
  retentionTimer = scheduleContextFree(() =>
package/src/be/db.ts CHANGED
@@ -10,6 +10,12 @@ import {
10
10
  import { realtimeBus } from "../realtime/bus";
11
11
  import { slackChannelFromContextKey } from "../tasks/slack-routing";
12
12
  import { _resolveIntegrationType, emitIntegrationConnected, telemetry } from "../telemetry";
13
+ import { scheduleOrgDomainRecompute } from "../telemetry-identity";
14
+ import {
15
+ emitTaskTelemetry,
16
+ type TaskTelemetryEvent,
17
+ type TaskTelemetryInput,
18
+ } from "../telemetry-trigger";
13
19
  import type {
14
20
  ActiveSession,
15
21
  Agent,
@@ -281,6 +287,7 @@ export {
281
287
  getTasksCount,
282
288
  hasNonTerminalRerouteDecisionChild,
283
289
  hasNonTerminalResumeChild,
290
+ isLinearTrackerContextKey,
284
291
  markFinalizedSlackRelaysDelivered,
285
292
  markSlackRelayAttempted,
286
293
  markSlackRelayDelivered,
@@ -303,6 +310,7 @@ export {
303
310
  getRecentlyCancelledTasksForAgent,
304
311
  overwriteTerminalTaskResultText,
305
312
  pauseTask,
313
+ recordTaskProviderIfUnset,
306
314
  resetOrphanedInProgressTasksForAgent,
307
315
  resumeTask,
308
316
  settleSupersededTaskDependents,
@@ -330,7 +338,6 @@ configureTaskReadDependencies({
330
338
  previewText: (text, maxChars) => previewText(text, maxChars),
331
339
  });
332
340
 
333
- type TaskTelemetryProps = Parameters<typeof telemetry.taskEvent>[1];
334
341
  type TaskTelemetryContext = {
335
342
  provider?: ProviderName;
336
343
  harnessVariant?: string;
@@ -346,23 +353,27 @@ function assetKeyPrefixPattern(input: string): string {
346
353
  return literalPrefixPattern(normalizeAssetKey(input));
347
354
  }
348
355
 
349
- function emitTaskLifecycleTelemetryAfterCommit(
350
- event: string,
351
- props: TaskTelemetryProps,
356
+ function emitTaskLifecycleTelemetryAfterCommit<S extends TaskTelemetryEvent>(
357
+ event: S,
358
+ props: TaskTelemetryInput<S>,
352
359
  verify?: (task: AgentTask | null) => boolean,
360
+ actorUserId?: string | null,
353
361
  ): void {
354
362
  // afterCommit (not queueMicrotask): under an async client transaction,
355
363
  // microtasks drain before COMMIT, so the verify read could observe
356
364
  // uncommitted state. afterCommit runs strictly post-COMMIT/ROLLBACK.
357
365
  getDbClient().afterCommit(() => {
366
+ // `trigger_surface` is resolved (one read up the parent chain) and
367
+ // `source` renamed to `task_source` inside emitTaskTelemetry, so every
368
+ // lifecycle event of a task reports the same root surface.
358
369
  if (!verify) {
359
- telemetry.taskEvent(event, props);
370
+ void emitTaskTelemetry(event, props, actorUserId);
360
371
  return;
361
372
  }
362
- getTaskById(props.taskId)
373
+ getTaskById((props as { taskId: string }).taskId)
363
374
  .then((task) => {
364
375
  if (!verify(task)) return;
365
- telemetry.taskEvent(event, props);
376
+ return emitTaskTelemetry(event, props, actorUserId);
366
377
  })
367
378
  .catch((err) =>
368
379
  console.error(
@@ -975,7 +986,7 @@ export async function setSlackMessageTracking(
975
986
  export async function updateTaskVcs(
976
987
  taskId: string,
977
988
  vcs: {
978
- vcsProvider: "github" | "gitlab";
989
+ vcsProvider: "github" | "gitlab" | "azure-devops";
979
990
  vcsRepo: string;
980
991
  vcsNumber: number;
981
992
  vcsUrl: string;
@@ -2895,6 +2906,8 @@ export async function createTaskExtended(
2895
2906
  priority: row.priority,
2896
2907
  },
2897
2908
  (task) => task !== null,
2909
+ // The human who asked (a pseudonymous user_ref), null for system tasks.
2910
+ row.requestedByUserId,
2898
2911
  );
2899
2912
 
2900
2913
  getDbClient().afterCommit(() => {
@@ -7351,12 +7364,17 @@ export async function createWorkflow(
7351
7364
  if (!row) throw new Error("Failed to create workflow");
7352
7365
  const workflow = rowToWorkflow(row);
7353
7366
  // afterCommit: a caller's transaction that rolls back must not report the workflow.
7367
+ const requestUserId = getCurrentRequestUserId();
7354
7368
  getDbClient().afterCommit(() =>
7355
- telemetry.workflow("created", {
7356
- workflowId: workflow.id,
7357
- nodeCount: workflow.definition.nodes.length,
7358
- ...(source ? { source } : {}),
7359
- }),
7369
+ telemetry.workflow(
7370
+ "created",
7371
+ {
7372
+ workflowId: workflow.id,
7373
+ nodeCount: workflow.definition.nodes.length,
7374
+ ...(source ? { via: source } : {}),
7375
+ },
7376
+ { userId: requestUserId ?? null },
7377
+ ),
7360
7378
  );
7361
7379
  return workflow;
7362
7380
  }
@@ -7577,11 +7595,13 @@ async function deleteWorkflowRows(id: string, source?: "api" | "mcp"): Promise<b
7577
7595
  const deleted = result.changes > 0;
7578
7596
  if (deleted) {
7579
7597
  // afterCommit: a caller's transaction that rolls back must not report the delete.
7598
+ const requestUserId = getCurrentRequestUserId();
7580
7599
  getDbClient().afterCommit(() =>
7581
- telemetry.workflow("deleted", {
7582
- workflowId: id,
7583
- ...(source ? { source } : {}),
7584
- }),
7600
+ telemetry.workflow(
7601
+ "deleted",
7602
+ { workflowId: id, ...(source ? { via: source } : {}) },
7603
+ { userId: requestUserId ?? null },
7604
+ ),
7585
7605
  );
7586
7606
  }
7587
7607
  return deleted;
@@ -7668,6 +7688,7 @@ export async function getWorkflowRun(id: string): Promise<WorkflowRun | null> {
7668
7688
 
7669
7689
  function emitWorkflowTerminalTelemetry(run: WorkflowRun): void {
7670
7690
  if (run.status !== "completed" && run.status !== "failed") return;
7691
+ const status = run.status;
7671
7692
 
7672
7693
  // afterCommit (not queueMicrotask): under an async client transaction,
7673
7694
  // microtasks drain before COMMIT, so the verify read below could observe
@@ -7677,9 +7698,9 @@ function emitWorkflowTerminalTelemetry(run: WorkflowRun): void {
7677
7698
  // crashing the process as an unhandled rejection.
7678
7699
  getDbClient().afterCommit(async () => {
7679
7700
  const latest = await getWorkflowRun(run.id);
7680
- if (!latest || latest.status !== run.status) return;
7701
+ if (!latest || latest.status !== status) return;
7681
7702
  const steps = await getWorkflowRunStepsByRunId(run.id);
7682
- telemetry.workflow(run.status, {
7703
+ telemetry.workflow(status, {
7683
7704
  workflowId: run.workflowId,
7684
7705
  durationMs: run.startedAt ? Date.now() - new Date(run.startedAt).getTime() : undefined,
7685
7706
  stepsCompleted: steps.filter((step) => step.status === "completed").length,
@@ -12045,6 +12066,8 @@ export async function createUser(data: {
12045
12066
  ],
12046
12067
  );
12047
12068
  if (!row) throw new Error("Failed to create user");
12069
+ // The org's email domain may come from this user (debounced, post-commit).
12070
+ getDbClient().afterCommit(scheduleOrgDomainRecompute);
12048
12071
  return rowToUser(row);
12049
12072
  }
12050
12073
 
@@ -12117,6 +12140,7 @@ export async function updateUser(
12117
12140
  `UPDATE users SET ${sets.join(", ")} WHERE id = ? RETURNING *`,
12118
12141
  params,
12119
12142
  );
12143
+ if (row) getDbClient().afterCommit(scheduleOrgDomainRecompute);
12120
12144
  return row ? rowToUser(row) : null;
12121
12145
  }
12122
12146
 
@@ -12226,6 +12250,7 @@ export async function deleteUser(id: string, replacementUserId?: string): Promis
12226
12250
  await reclassifyTaskHumanFree(reclassifySeedIds);
12227
12251
 
12228
12252
  const result = await tx.run("DELETE FROM users WHERE id = ?", [id]);
12253
+ if (result.changes > 0) getDbClient().afterCommit(scheduleOrgDomainRecompute);
12229
12254
  return result.changes > 0;
12230
12255
  });
12231
12256
  }
@@ -51,6 +51,22 @@ export const SOURCE_QUALITY_MULTIPLIER: Record<AgentMemorySource, number> = {
51
51
  session_summary: 0.5,
52
52
  };
53
53
 
54
+ // Path-weight multiplier for reranking, keyed by logical memory path (the
55
+ // `key` column; see key-paths.ts). The longest matching root wins. A key under
56
+ // no listed root (auto keys, file paths, anything outside /longterm) is inbox
57
+ // material and weighs 1.0.
58
+ export const PATH_WEIGHT: Readonly<Record<string, number>> = {
59
+ "/longterm/company-story": 1.4,
60
+ "/longterm/entities": 1.3,
61
+ "/longterm/facts": 1.2,
62
+ "/longterm/decisions": 1.1,
63
+ "/longterm/timeline": 0.8,
64
+ };
65
+
66
+ // A decision tagged `superseded` ranks low but stays findable.
67
+ export const DECISIONS_ROOT = "/longterm/decisions";
68
+ export const SUPERSEDED_DECISION_WEIGHT = 0.3;
69
+
54
70
  // Minimum raw cosine similarity to keep a candidate. Below this, the result is noise.
55
71
  export function minSimilarity(): number {
56
72
  return numEnv("MEMORY_MIN_SIMILARITY", 0.1);
@@ -34,6 +34,8 @@ export interface GraphExpansionOptions {
34
34
  scope?: "agent" | "swarm" | "all";
35
35
  /** Source filter the search ran with — expansion must not add off-filter rows. */
36
36
  source?: AgentMemorySource;
37
+ /** Key prefix the search ran with — expansion must not add off-prefix rows. */
38
+ keyPrefix?: string;
37
39
  isLead?: boolean;
38
40
  }
39
41
 
@@ -75,7 +77,7 @@ export async function expandCandidatesWithGraph(
75
77
  options: GraphExpansionOptions = {},
76
78
  ): Promise<MemoryCandidate[]> {
77
79
  if (!isGraphExpansionEnabled()) return candidates;
78
- const { cap = 5, damping = 0.7, scope = "all", source, isLead = false } = options;
80
+ const { cap = 5, damping = 0.7, scope = "all", source, keyPrefix, isLead = false } = options;
79
81
  if (candidates.length === 0 || cap <= 0) return candidates;
80
82
 
81
83
  const parentById = new Map(candidates.map((c) => [c.id, c]));
@@ -95,6 +97,11 @@ export async function expandCandidatesWithGraph(
95
97
  conditions.push("m.source = ?");
96
98
  params.push(source);
97
99
  }
100
+ if (keyPrefix) {
101
+ // Literal prefix, not GLOB/LIKE: mirrors SqliteMemoryStore.addKeyPrefixCondition.
102
+ conditions.push("substr(m.key, 1, length(?)) = ?");
103
+ params.push(keyPrefix, keyPrefix);
104
+ }
98
105
 
99
106
  let rows: NeighborRow[];
100
107
  try {
@@ -7,6 +7,7 @@
7
7
  */
8
8
  import { chunkContent } from "@/be/chunking";
9
9
  import { getEmbeddingProvider, getMemoryStore } from "@/be/memory";
10
+ import { assertKeyWritable, type MemoryKeyWriter } from "@/be/memory/key-guard";
10
11
  import { refreshLinks, storeLinks } from "@/be/memory/link-resolver";
11
12
  import type { AgentMemoryScope, AgentMemorySource } from "@/types";
12
13
  import { scrubSecrets } from "@/utils/secret-scrubber";
@@ -24,6 +25,18 @@ export interface IndexMemoryContentParams {
24
25
  contextKey?: string | null;
25
26
  /** Audit-trail reason. Defaults to "index memory content". */
26
27
  intent?: string;
28
+ /**
29
+ * Logical path stored in the `key` column on every chunk (for example
30
+ * `/longterm/facts/swarm-runtime/x`). Defaults to `sourcePath`, then the auto key.
31
+ */
32
+ key?: string | null;
33
+ /**
34
+ * Who is writing. The key that lands on the rows (`key`, else `sourcePath`)
35
+ * is checked against it before anything is stored: a lead-only `/longterm`
36
+ * root is refused unless the writer holds `memory.write.consolidated`. Left
37
+ * out, the writer has no authority. Throws `MemoryKeyError`.
38
+ */
39
+ writer?: MemoryKeyWriter;
27
40
  }
28
41
 
29
42
  export interface IndexMemoryContentResult {
@@ -40,6 +53,12 @@ export async function indexMemoryContent(
40
53
  ): Promise<IndexMemoryContentResult> {
41
54
  const { agentId, content, name, scope, source, sourceTaskId, sourcePath, tags } = params;
42
55
 
56
+ // The key every chunk will carry. Gate it here, before any read or write, so
57
+ // both callers (memory-store and POST /api/memory/index) pass the same check
58
+ // and a `sourcePath` cannot stand in for a key that would be refused.
59
+ const rowKey = params.key ?? (sourcePath || null);
60
+ if (rowKey) assertKeyWritable(rowKey, params.key != null ? "key" : "sourcePath", params.writer);
61
+
43
62
  // Chunk content and create memories
44
63
  const contentChunks = chunkContent(content);
45
64
  if (contentChunks.length === 0) {
@@ -106,7 +125,7 @@ export async function indexMemoryContent(
106
125
  tags: tags || [],
107
126
  contextKey: params.contextKey ?? null,
108
127
  intent: params.intent ?? "index memory content",
109
- key: sourcePath || null,
128
+ key: rowKey,
110
129
  })),
111
130
  );
112
131
 
@@ -0,0 +1,93 @@
1
+ import { can, type RbacPrincipal } from "@/rbac";
2
+ import {
3
+ consolidatedKeyMessage,
4
+ isConsolidatedKey,
5
+ isLongtermKey,
6
+ LONGTERM_ROOT,
7
+ longtermKeyError,
8
+ MEMORY_KEY_MAX_LENGTH,
9
+ MEMORY_KEY_PATTERN,
10
+ MEMORY_KEY_PATTERN_MESSAGE,
11
+ } from "./key-paths";
12
+
13
+ /**
14
+ * The one gate for a key that is about to be written, shared by every ingestion
15
+ * path: `memory-store` and `memory-edit` (MCP) and `POST /api/memory/index`
16
+ * (HTTP). It checks the key's shape, the closed `/longterm` root list, and the
17
+ * `memory.write.consolidated` permission for the lead-only roots.
18
+ *
19
+ * A key is a tier, not a label: under `/longterm` it buys a manual memory's
20
+ * lifecycle and a ranking boost (see `tierSource`). So every route that can put
21
+ * a key on a row must pass through here, including a `sourcePath` that the
22
+ * indexer falls back to as the key.
23
+ */
24
+
25
+ /** Where a key came from. An explicit key is always held to the path shape; a `sourcePath` only under `/longterm`. */
26
+ export type MemoryKeyOrigin = "key" | "sourcePath";
27
+
28
+ /** Who is writing, in the terms `can()` takes. */
29
+ export interface MemoryKeyWriter {
30
+ principal: RbacPrincipal;
31
+ source: "mcp" | "http";
32
+ }
33
+
34
+ /** `invalid`: the key is not an allowed path (HTTP 400). `forbidden`: the writer may not use it (HTTP 403). */
35
+ export class MemoryKeyError extends Error {
36
+ constructor(
37
+ message: string,
38
+ readonly reason: "invalid" | "forbidden",
39
+ ) {
40
+ super(message);
41
+ this.name = "MemoryKeyError";
42
+ }
43
+ }
44
+
45
+ /** A writer nobody vouched for: not a lead, so lead-only roots stay closed. */
46
+ const NO_AUTHORITY: MemoryKeyWriter = {
47
+ principal: { kind: "agent", agentId: "", isLead: false },
48
+ source: "http",
49
+ };
50
+
51
+ function shapeError(key: string, origin: MemoryKeyOrigin): string | null {
52
+ if (key.length <= MEMORY_KEY_MAX_LENGTH && MEMORY_KEY_PATTERN.test(key)) return null;
53
+ const subject =
54
+ origin === "sourcePath"
55
+ ? `sourcePath "${key}" starts with ${LONGTERM_ROOT}, so it is used as the key, but it is not a valid key.`
56
+ : `Key "${key}" is not a valid key.`;
57
+ return `${subject} ${MEMORY_KEY_PATTERN_MESSAGE}`;
58
+ }
59
+
60
+ /**
61
+ * Throw a `MemoryKeyError` unless `writer` may write a row under `key`.
62
+ *
63
+ * - `origin: "key"`: the key must match the path shape wherever it points.
64
+ * - `origin: "sourcePath"`: a file path stays free-form until it falls under
65
+ * `/longterm`, where it would act as a curated key, so it gets the same
66
+ * checks as an explicit one. A path outside `/longterm` confers nothing.
67
+ * - Under `/longterm` the second segment must be an allowed root, and the
68
+ * lead-only roots need `memory.write.consolidated`. A missing `writer` has
69
+ * no authority, so it cannot reach them.
70
+ */
71
+ export function assertKeyWritable(
72
+ key: string,
73
+ origin: MemoryKeyOrigin,
74
+ writer: MemoryKeyWriter | undefined,
75
+ ): void {
76
+ if (origin === "sourcePath" && !isLongtermKey(key)) return;
77
+
78
+ const shape = shapeError(key, origin);
79
+ if (shape) throw new MemoryKeyError(shape, "invalid");
80
+
81
+ const pathError = longtermKeyError(key);
82
+ if (pathError) throw new MemoryKeyError(pathError, "invalid");
83
+
84
+ if (!isConsolidatedKey(key)) return;
85
+ const { principal, source } = writer ?? NO_AUTHORITY;
86
+ const decision = can({
87
+ principal,
88
+ verb: "memory.write.consolidated",
89
+ resource: { kind: "none" },
90
+ source,
91
+ });
92
+ if (!decision.allow) throw new MemoryKeyError(consolidatedKeyMessage(key), "forbidden");
93
+ }