@desplega.ai/agent-swarm 2.7.9 → 2.8.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 (355) hide show
  1. package/dist/acp-adapter-t949vbbp.js +15 -0
  2. package/dist/{actions-g563mbn2.js → actions-7e9czc7s.js} +19 -19
  3. package/dist/{amp-adapter-q61w05eb.js → amp-adapter-gv6cbb7d.js} +2 -3
  4. package/dist/app-b9fbkp9v.js +20 -0
  5. package/dist/{assistant-p477rjwj.js → assistant-wjb7v4c7.js} +22 -22
  6. package/dist/{boot-args-schema-h4qj462e.js → boot-args-schema-2t37e0fe.js} +1 -1
  7. package/dist/{boot-reembed-n1ehfbsw.js → boot-reembed-a35nkyr1.js} +1 -1
  8. package/dist/{boot-reembed-qw4mc0pt.js → boot-reembed-gka3zas7.js} +1 -1
  9. package/dist/{boot-scrub-sweep-9w9jp4sm.js → boot-scrub-sweep-65sdnp6c.js} +3 -3
  10. package/dist/{boot-seeds-qdaf3sdy.js → boot-seeds-x42tzytw.js} +4 -5
  11. package/dist/{claude-adapter-348p5hx9.js → claude-adapter-v221b2fd.js} +7 -8
  12. package/dist/{claude-managed-adapter-h74d06yz.js → claude-managed-adapter-29eq09wd.js} +2 -2
  13. package/dist/{claude-managed-setup-7787fxtp.js → claude-managed-setup-9m6450zk.js} +2 -2
  14. package/dist/{claude-sdk-session-hbszbt8a.js → claude-sdk-session-0q0ptaba.js} +9066 -8818
  15. package/dist/{cli-n5yexkdg.js → cli-0b4zam62.js} +1 -0
  16. package/dist/{cli-21159vea.js → cli-0jzra9ad.js} +2 -2
  17. package/dist/{cli-eqtfgfr6.js → cli-2gxeg5gr.js} +1 -1
  18. package/dist/{cli-k70e3x9e.js → cli-2wnq8jkz.js} +9 -9
  19. package/dist/{cli-cvs2r2vq.js → cli-2zp0et3v.js} +59 -6
  20. package/dist/{cli-650zv9q9.js → cli-334z18y3.js} +4 -4
  21. package/dist/{cli-12xyjhws.js → cli-3rkdne1h.js} +2 -2
  22. package/dist/{cli-2a8py3sx.js → cli-4txa0ter.js} +5 -7
  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-v3cf1ts9.js → cli-6t09sdhy.js} +3 -3
  26. package/dist/{cli-qzt90yze.js → cli-6wxjceza.js} +8 -8
  27. package/dist/{cli-9aezs55w.js → cli-7b8sbmag.js} +8 -8
  28. package/dist/{cli-3xj33nrx.js → cli-7cp6aa1q.js} +10 -3
  29. package/dist/{cli-jfx48xrj.js → cli-7p1kvkck.js} +6 -6
  30. package/dist/{cli-b932gexn.js → cli-8aes17e4.js} +2 -2
  31. package/dist/{cli-3tqcamp6.js → cli-8fknbnhw.js} +14 -13
  32. package/dist/{cli-587857ys.js → cli-8kzasymh.js} +3 -3
  33. package/dist/{cli-sgs5k6yd.js → cli-a7wvp2km.js} +1 -1
  34. package/dist/{cli-varqt4d1.js → cli-abejgen1.js} +69 -22
  35. package/dist/{cli-rwymrnaz.js → cli-bsywb58a.js} +8 -8
  36. package/dist/{cli-btc9cb4c.js → cli-c55z5chy.js} +4 -6
  37. package/dist/{cli-ms5m5r1y.js → cli-deefvewm.js} +1 -1
  38. package/dist/{cli-p17970qv.js → cli-ee0b971j.js} +3 -3
  39. package/dist/cli-f3vq58d2.js +242 -0
  40. package/dist/{cli-3xcwp3z8.js → cli-ffhtssbp.js} +2 -2
  41. package/dist/{cli-hwprv9e4.js → cli-g70vxtjh.js} +2 -2
  42. package/dist/{cli-4t0fmf3z.js → cli-gxkx0zzp.js} +1 -1
  43. package/dist/{cli-neyag5p6.js → cli-h38x262p.js} +3365 -429
  44. package/dist/{cli-2ccpqyyf.js → cli-j790gp2w.js} +105 -22
  45. package/dist/{cli-f2zenhja.js → cli-kc7v1nfv.js} +1 -1
  46. package/dist/{cli-vxh6acp7.js → cli-m23zjcy2.js} +10 -10
  47. package/dist/{cli-y8nbefpb.js → cli-m28atx8q.js} +12 -10
  48. package/dist/{cli-serm8zrx.js → cli-m4dqmnbp.js} +1 -1
  49. package/dist/{cli-ybjdc978.js → cli-mrt48bx7.js} +7 -4
  50. package/dist/{cli-y5rbvxhc.js → cli-n515ex5z.js} +14 -14
  51. package/dist/{cli-ypff1qwp.js → cli-n9ftpys4.js} +7 -7
  52. package/dist/{cli-605nn699.js → cli-p1bq50aa.js} +894 -226
  53. package/dist/{cli-qkdmz8c8.js → cli-p1w18yhx.js} +1 -1
  54. package/dist/{cli-xk879m3k.js → cli-p2gfst4m.js} +52 -43
  55. package/dist/{cli-sya22y84.js → cli-pasjcnmj.js} +12 -12
  56. package/dist/{cli-0whpms1z.js → cli-qa4wdgsy.js} +5 -5
  57. package/dist/{cli-ejkvvqbe.js → cli-qfedvmcr.js} +50 -24
  58. package/dist/{cli-tqq0hspb.js → cli-qmqk2yc2.js} +1 -1
  59. package/dist/{cli-qmd3mse0.js → cli-qsnnd04k.js} +1 -1
  60. package/dist/{cli-agyaeef4.js → cli-qwca7s44.js} +3 -3
  61. package/dist/{cli-fayav105.js → cli-rfywm85n.js} +724 -792
  62. package/dist/{cli-zgv8gxgs.js → cli-rmmpt0wm.js} +6 -6
  63. package/dist/{cli-hae9j8sv.js → cli-rzsy6nc6.js} +12 -8
  64. package/dist/{cli-btf6fw39.js → cli-s7t6p9my.js} +1 -1
  65. package/dist/{cli-cseh6f8w.js → cli-sdtt3men.js} +1 -1
  66. package/dist/{cli-9r5gtwjr.js → cli-tk7cjj8h.js} +197 -2
  67. package/dist/{cli-q26b9wre.js → cli-tph5wt3y.js} +4 -4
  68. package/dist/{cli-gce09r66.js → cli-tqegb8eq.js} +3 -3
  69. package/dist/{cli-kf3pxxdg.js → cli-v1dv1r37.js} +1 -1
  70. package/dist/{cli-09kmfkmq.js → cli-wcg8x116.js} +1 -1
  71. package/dist/{cli-mnrkgg60.js → cli-wk18cm92.js} +5 -5
  72. package/dist/{cli-p0m0p34z.js → cli-x1wa213s.js} +3 -3
  73. package/dist/{cli-jrp1dt73.js → cli-xzm9vcfg.js} +1 -1
  74. package/dist/{cli-715t1gx6.js → cli-y97qxcfx.js} +9 -9
  75. package/dist/{cli-bc779n4v.js → cli-yq3zak69.js} +1 -1
  76. package/dist/cli.js +17 -17
  77. package/dist/{codex-adapter-ysq6bzha.js → codex-adapter-30j9bpzd.js} +5 -6
  78. package/dist/{codex-hook-fac6175r.js → codex-hook-h3vk6xzr.js} +1 -1
  79. package/dist/{codex-session-runner-qakzfx93.js → codex-session-runner-8vp57v8w.js} +5 -6
  80. package/dist/{commands-rs7hkv9r.js → commands-bngnz9g7.js} +3 -3
  81. package/dist/{controller-r5x9bg6e.js → controller-hxx8wwy1.js} +2 -2
  82. package/dist/{controllers-connect-498hrxvk.js → controllers-connect-e2b4gyxc.js} +20 -20
  83. package/dist/{cursor-adapter-d46qszer.js → cursor-adapter-n5nc3mfe.js} +1 -2
  84. package/dist/{db-s13dqhr6.js → db-bgm7vkc0.js} +3 -3
  85. package/dist/{db-pm96nhdb.js → db-c6np41ca.js} +12 -2
  86. package/dist/{devin-adapter-z46ep5ph.js → devin-adapter-xedz98zv.js} +1 -1
  87. package/dist/{dispatcher-j3h81t7m.js → dispatcher-jnybck15.js} +18 -18
  88. package/dist/{dsh-adapter-rw0d5rc4.js → dsh-adapter-nrhbrjz8.js} +1 -2
  89. package/dist/{easter-egg-3d-qtgfxgze.js → easter-egg-3d-533knw22.js} +1 -1
  90. package/dist/{embedding-space-xh8p4q4x.js → embedding-space-crsm2zp0.js} +6 -6
  91. package/dist/{embeddings-wp745m91.js → embeddings-e7z3f27f.js} +1 -1
  92. package/dist/{execute-2fzb9z74.js → execute-b3mrb1mv.js} +1 -1
  93. package/dist/{external-channel-ys21h3sy.js → external-channel-m77wf5z3.js} +2 -2
  94. package/dist/{fx-adapter-vz0b9z3g.js → fx-adapter-b6w0kf56.js} +7 -8
  95. package/dist/{google-generative-ai-ytpgncx9.js → google-generative-ai-h7s3e9kk.js} +1 -1
  96. package/dist/{google-vertex-tqhze5j7.js → google-vertex-fhxaafzw.js} +1 -1
  97. package/dist/{grok-adapter-spea7zkj.js → grok-adapter-4sqtebdk.js} +7 -8
  98. package/dist/handlers-kdjcyzdj.js +32 -0
  99. package/dist/heartbeat-xgb036sx.js +43 -0
  100. package/dist/{hook-amcj4s10.js → hook-5h02c9ga.js} +6 -6
  101. package/dist/{hook-bc6n49qn.js → hook-xsk1jbha.js} +5 -5
  102. package/dist/{http-7374brv5.js → http-txe7qhvn.js} +448 -165
  103. package/dist/{index-pxn30mse.js → index-0eny15vj.js} +8 -8
  104. package/dist/{index-5a9jtqde.js → index-0rvk3vd4.js} +46 -46
  105. package/dist/{index-fvzke5kx.js → index-1qw6f2dc.js} +10 -10
  106. package/dist/{index-q5cmtbz5.js → index-4a0670yh.js} +15939 -14244
  107. package/dist/index-835xdgnm.js +33 -0
  108. package/dist/index-d469300x.js +37 -0
  109. package/dist/{index-h7f61sy9.js → index-e5pfbsys.js} +3 -3
  110. package/dist/{index-hsad2t3r.js → index-m5gx1xd6.js} +38 -38
  111. package/dist/{index-5fx3b3kw.js → index-rvccek1w.js} +9 -9
  112. package/dist/index-rzqwp11g.js +32 -0
  113. package/dist/{index-w4m9z29z.js → index-tvfafeyy.js} +1 -1
  114. package/dist/{index-c9y31ytf.js → index-vk63emp7.js} +979 -35
  115. package/dist/{index-514d9pf6.js → index-w7em4ktq.js} +8 -8
  116. package/dist/{index-p4hjwbvw.js → index-ysvbhg5m.js} +1 -1
  117. package/dist/{keepalive-wy29kbrg.js → keepalive-4zsrce78.js} +3 -3
  118. package/dist/lead-yqt47dkr.js +70 -0
  119. package/dist/{maintenance-h2ds9w6c.js → maintenance-86jvartk.js} +1 -1
  120. package/dist/{oauth-refresh-sweep-q7mtbyp3.js → oauth-refresh-sweep-j52kg9pr.js} +2 -2
  121. package/dist/{onboard-vw8r2fdw.js → onboard-c2aj5p8q.js} +3 -3
  122. package/dist/{opencode-adapter-mtb0953j.js → opencode-adapter-dsagkhtw.js} +5 -6
  123. package/dist/{otel-impl-j42czw3r.js → otel-impl-yyy203z8.js} +1 -1
  124. package/dist/{pi-mono-adapter-zk8pg9jr.js → pi-mono-adapter-546cd1cc.js} +9 -9
  125. package/dist/{pricing-refresh-x7nhv23d.js → pricing-refresh-1rgzqyzz.js} +2 -3
  126. package/dist/{rbac-roles-9044425x.js → rbac-roles-e70xfeyj.js} +4 -6
  127. package/dist/{rbac-roles-bzvee6cf.js → rbac-roles-q89qe8er.js} +3 -3
  128. package/dist/{registry-hpjfmcfz.js → registry-32b1mft6.js} +1 -1
  129. package/dist/{render-v2-t7bn4skz.js → render-v2-k6tt107q.js} +9 -4
  130. package/dist/{resume-x94gemep.js → resume-cnnrjfxa.js} +6 -6
  131. package/dist/{runtime-breq6fmv.js → runtime-1hv06jsn.js} +1 -1
  132. package/dist/{session-access-q7dmqjvt.js → session-access-xkxkjw3n.js} +4 -4
  133. package/dist/{session-source-backfill-440ysamr.js → session-source-backfill-1d5pdwww.js} +2 -2
  134. package/dist/{setup-07n4727s.js → setup-se8q7gkc.js} +1 -1
  135. package/dist/{virtual-modules-z5h6mcyf.js → virtual-modules-gazyapte.js} +3 -3
  136. package/dist/{work-objects-pnq5y534.js → work-objects-1kxnbzy5.js} +22 -22
  137. package/dist/{worker-follow-up-7z1gfkr8.js → worker-follow-up-zqm8apt4.js} +18 -18
  138. package/dist/worker-j6xxtq7p.js +70 -0
  139. package/openapi.json +334 -7
  140. package/package.json +4 -4
  141. package/src/apps/catalog.generated.json +55 -0
  142. package/src/apps/definition.ts +11 -0
  143. package/src/apps/page-validator.ts +19 -0
  144. package/src/apps/store.ts +28 -8
  145. package/src/assets/key.ts +77 -4
  146. package/src/be/db/model-profiles.ts +147 -38
  147. package/src/be/db/session-labels.ts +57 -0
  148. package/src/be/db/session-tree.ts +51 -7
  149. package/src/be/db/slack-trees.ts +146 -0
  150. package/src/be/db/tasks/read.ts +107 -8
  151. package/src/be/db/workflow-run-definitions.ts +117 -0
  152. package/src/be/db-client.ts +8 -2
  153. package/src/be/db.ts +119 -87
  154. package/src/be/event-loop-lag.ts +146 -0
  155. package/src/be/mcp-overflow-sweep.ts +2 -1
  156. package/src/be/memory/constants.ts +14 -1
  157. package/src/be/memory/key-paths.ts +8 -0
  158. package/src/be/memory/providers/sqlite-store.ts +199 -18
  159. package/src/be/memory/task-learning.ts +79 -14
  160. package/src/be/memory/types.ts +24 -1
  161. package/src/be/migrations/278_slack_render_v2_reconcile.sql +108 -0
  162. package/src/be/migrations/279_backfill_learning_expiry.sql +15 -0
  163. package/src/be/migrations/281_model_profiles_pr2.sql +28 -0
  164. package/src/be/migrations/283_workflow_run_definitions.sql +14 -0
  165. package/src/be/model-profile-check.ts +284 -0
  166. package/src/be/model-tier-resolution.ts +112 -12
  167. package/src/be/multi-runtime.ts +27 -0
  168. package/src/be/runtime-pools/routing.ts +52 -4
  169. package/src/be/scripts/typecheck.ts +1 -0
  170. package/src/be/seed-scripts/catalog/dreaming-learnings.ts +552 -0
  171. package/src/be/seed-scripts/catalog/dreaming-memtax-create.ts +389 -14
  172. package/src/be/seed-scripts/catalog/dreaming-memtax.ts +6 -3
  173. package/src/be/seed-scripts/index.ts +9 -0
  174. package/src/be/steering.ts +8 -2
  175. package/src/be/swarm-config-guard.ts +2 -0
  176. package/src/commands/context-preamble.ts +258 -0
  177. package/src/commands/onboard/agent-fs-version.ts +1 -1
  178. package/src/commands/runner.ts +32 -1
  179. package/src/extensions/catalog.generated.json +3 -3
  180. package/src/fs/provider.ts +17 -3
  181. package/src/heartbeat/heartbeat.ts +17 -5
  182. package/src/heartbeat/index.ts +1 -0
  183. package/src/http/agents.ts +56 -4
  184. package/src/http/apps.ts +3 -1
  185. package/src/http/config.ts +2 -6
  186. package/src/http/core.ts +9 -3
  187. package/src/http/index.ts +12 -9
  188. package/src/http/memory.ts +9 -4
  189. package/src/http/model-profiles.ts +58 -10
  190. package/src/http/poll.ts +36 -3
  191. package/src/http/schedules.ts +42 -3
  192. package/src/http/sessions.ts +16 -3
  193. package/src/http/tasks.ts +37 -12
  194. package/src/http/utils.ts +18 -0
  195. package/src/http/webhooks.ts +48 -0
  196. package/src/http/workflows.ts +15 -2
  197. package/src/integrations/chat-sdk/commands.ts +167 -31
  198. package/src/integrations/chat-sdk/inbound.ts +10 -8
  199. package/src/integrations/chat-sdk/message-text.ts +117 -0
  200. package/src/prompts/session-templates.ts +1 -1
  201. package/src/providers/acp-targets.ts +11 -6
  202. package/src/providers/amp-adapter.ts +1 -1
  203. package/src/providers/claude-sdk-session.ts +132 -23
  204. package/src/providers/codex-skill-resolver.ts +10 -4
  205. package/src/providers/cursor-adapter.ts +1 -1
  206. package/src/providers/devin-skill-resolver.ts +5 -5
  207. package/src/providers/dsh-adapter.ts +1 -1
  208. package/src/scheduler/schedule-task.ts +1 -0
  209. package/src/scheduler/scheduler.ts +4 -1
  210. package/src/scripts-runtime/executors/quickjs-runner.ts +2 -0
  211. package/src/scripts-runtime/executors/quickjs-structured-clone.ts +180 -0
  212. package/src/scripts-runtime/quickjs-compat.ts +0 -1
  213. package/src/scripts-runtime/sdk-allowlist.ts +1 -0
  214. package/src/scripts-runtime/swarm-sdk.ts +18 -1
  215. package/src/scripts-runtime/types/stdlib.d.ts +1 -0
  216. package/src/scripts-runtime/types/swarm-sdk.d.ts +1 -0
  217. package/src/server.ts +2 -0
  218. package/src/slack/app.ts +425 -10
  219. package/src/slack/handlers.ts +9 -2
  220. package/src/slack/inbound-dispatch.ts +18 -1
  221. package/src/slack/index.ts +7 -1
  222. package/src/slack/lifecycle-lock.ts +29 -0
  223. package/src/slack/render-v2.ts +424 -212
  224. package/src/slack/socket-fence.ts +64 -0
  225. package/src/slack/watcher.ts +42 -8
  226. package/src/slack/workspace-guard.ts +345 -0
  227. package/src/tasks/task-terminal-effects.ts +4 -0
  228. package/src/tasks/worker-follow-up.ts +102 -2
  229. package/src/tests/acp-adapter.test.ts +82 -0
  230. package/src/tests/apps-icon.test.ts +120 -0
  231. package/src/tests/apps-schema-form.test.ts +151 -0
  232. package/src/tests/chained-task-follow-up.test.ts +248 -0
  233. package/src/tests/chat-sdk-commands.test.ts +359 -2
  234. package/src/tests/chat-sdk-inbound.test.ts +20 -0
  235. package/src/tests/chat-sdk-slack.test.ts +189 -1
  236. package/src/tests/check-pr-body.test.ts +40 -0
  237. package/src/tests/claude-sdk-lifecycle.test.ts +216 -1
  238. package/src/tests/claude-sdk-process.fixture.ts +57 -0
  239. package/src/tests/codex-skill-resolver.test.ts +31 -0
  240. package/src/tests/credentials-allowlist.test.ts +470 -0
  241. package/src/tests/db-client-busy-retry.test.ts +69 -18
  242. package/src/tests/db-client.test.ts +26 -1
  243. package/src/tests/db-task-read-contract.test.ts +7 -0
  244. package/src/tests/db-task-write-contract.test.ts +6 -0
  245. package/src/tests/deferred-wake-follow-up.test.ts +47 -0
  246. package/src/tests/docs-index-footprint.test.js +3 -3
  247. package/src/tests/dreaming-learnings.test.ts +1395 -0
  248. package/src/tests/dsh-adapter.test.ts +1 -1
  249. package/src/tests/event-loop-lag.test.ts +184 -0
  250. package/src/tests/explicit-model-validation.test.ts +2 -0
  251. package/src/tests/extensions-example-comms-adherence-gate.test.ts +115 -0
  252. package/src/tests/fs-provider.test.ts +42 -0
  253. package/src/tests/github-webhook-early-ack.test.ts +144 -0
  254. package/src/tests/heartbeat.test.ts +28 -1
  255. package/src/tests/http-api-integration.test.ts +2 -0
  256. package/src/tests/http-log-scrubbing.test.ts +68 -2
  257. package/src/tests/human-free-reclassify.test.ts +5 -1
  258. package/src/tests/kv-storage.test.ts +92 -1
  259. package/src/tests/list-endpoint-slimming.test.ts +17 -0
  260. package/src/tests/memory-key-paths.test.ts +57 -0
  261. package/src/tests/memory-retrieval-purge.test.ts +19 -0
  262. package/src/tests/migration-283-workflow-run-definitions.test.ts +69 -0
  263. package/src/tests/model-profile-check.test.ts +387 -0
  264. package/src/tests/model-profiles-api.test.ts +528 -1
  265. package/src/tests/profile-claim.test.ts +415 -3
  266. package/src/tests/profile-tier-alias.test.ts +382 -0
  267. package/src/tests/quickjs-compat.test.ts +1 -1
  268. package/src/tests/runner-context-preamble.test.ts +552 -0
  269. package/src/tests/schedule-profile.test.ts +359 -0
  270. package/src/tests/script-connections.test.ts +9 -0
  271. package/src/tests/script-executor-conformance.test.ts +188 -0
  272. package/src/tests/script-per-script-executor.test.ts +1 -0
  273. package/src/tests/scripts-sdk-bridge-tool-failure.test.ts +141 -0
  274. package/src/tests/seed-scripts.test.ts +2 -2
  275. package/src/tests/sessions-tree.test.ts +133 -2
  276. package/src/tests/slack-app-icon.test.ts +4 -0
  277. package/src/tests/slack-dm-implicit-mention.test.ts +236 -0
  278. package/src/tests/slack-file-tools-attachments.test.ts +1 -0
  279. package/src/tests/slack-inbound-receipts.test.ts +22 -2
  280. package/src/tests/slack-read-boundaries.test.ts +4 -3
  281. package/src/tests/slack-render-v2-query-plans.test.ts +262 -3
  282. package/src/tests/slack-render-v2-reconcile.test.ts +201 -0
  283. package/src/tests/slack-socket-ack.test.ts +16 -1
  284. package/src/tests/slack-socket-watchdog.test.ts +748 -0
  285. package/src/tests/slack-workspace-guard.test.ts +905 -0
  286. package/src/tests/steering-core.test.ts +40 -0
  287. package/src/tests/store-progress-learning.test.ts +605 -20
  288. package/src/tests/tool-annotations.test.ts +1 -1
  289. package/src/tests/vcs-identity-inheritance.test.ts +85 -0
  290. package/src/tests/workflow-convergence.test.ts +46 -40
  291. package/src/tests/workflow-definition-pinning-recovery.test.ts +552 -0
  292. package/src/tests/workflow-definition-pinning.test.ts +645 -0
  293. package/src/tests/workflow-executors.test.ts +16 -7
  294. package/src/tests/workflow-foreach.test.ts +43 -20
  295. package/src/tests/workflow-notify-slack-ready.test.ts +161 -0
  296. package/src/tests/workflow-profile.test.ts +328 -0
  297. package/src/tools/app-upsert.ts +1 -1
  298. package/src/tools/memory-edit.ts +2 -1
  299. package/src/tools/model-profiles/check-model-profile.ts +63 -0
  300. package/src/tools/schedules/create-schedule.ts +45 -4
  301. package/src/tools/schedules/patch-schedule.ts +50 -4
  302. package/src/tools/schedules/update-schedule.ts +50 -4
  303. package/src/tools/send-task.ts +17 -2
  304. package/src/tools/store-progress.ts +15 -3
  305. package/src/tools/task-action.ts +9 -1
  306. package/src/tools/templates.ts +13 -0
  307. package/src/tools/tool-config.ts +2 -1
  308. package/src/tools/utils.ts +77 -11
  309. package/src/tools/workflows/create-workflow.ts +1 -1
  310. package/src/tools/workflows/retry-workflow-run.ts +1 -1
  311. package/src/tools/workflows/update-workflow.ts +10 -1
  312. package/src/types.ts +56 -1
  313. package/src/utils/credentials.ts +89 -12
  314. package/src/workflows/engine.ts +10 -1
  315. package/src/workflows/executors/agent-task.ts +21 -2
  316. package/src/workflows/executors/foreach.ts +4 -1
  317. package/src/workflows/executors/notify.ts +62 -6
  318. package/src/workflows/executors/sub-workflow.ts +1 -1
  319. package/src/workflows/executors/swarm-script.ts +4 -1
  320. package/src/workflows/foreach-driver.ts +8 -5
  321. package/src/workflows/limits.ts +2 -1
  322. package/src/workflows/model-validation.ts +27 -2
  323. package/src/workflows/patch-definition.ts +3 -1
  324. package/src/workflows/recovery.ts +6 -6
  325. package/src/workflows/resume.ts +9 -9
  326. package/src/workflows/retry-poller.ts +2 -2
  327. package/templates/extensions/comms-adherence-gate/README.md +25 -0
  328. package/templates/extensions/comms-adherence-gate/hooks.ts +100 -11
  329. package/templates/extensions/comms-adherence-gate/manifest.json +1 -1
  330. package/templates/skills/apps/SKILL.md +9 -0
  331. package/templates/skills/apps/content.md +9 -0
  332. package/templates/skills/code-quality/content.md +12 -0
  333. package/templates/skills/memory/content.md +8 -0
  334. package/templates/skills/scheduling/config.json +1 -1
  335. package/templates/skills/scheduling/content.md +2 -2
  336. package/templates/skills/swarm-docs/content.md +4 -0
  337. package/templates/skills/swarm-extensions/content.md +1 -1
  338. package/templates/skills/swarm-scripts/SKILL.md +1 -1
  339. package/templates/skills/swarm-scripts/content.md +1 -1
  340. package/templates/skills/work-on-task/SKILL.md +2 -0
  341. package/templates/skills/work-on-task/content.md +2 -0
  342. package/templates/workflows/dreaming/content.md +174 -7
  343. package/dist/acp-adapter-dn4gdsgr.js +0 -16
  344. package/dist/app-a66ssc4k.js +0 -17
  345. package/dist/cli-530hkwdy.js +0 -779
  346. package/dist/cli-a0657jmf.js +0 -339
  347. package/dist/cli-cyn9v8zr.js +0 -748
  348. package/dist/handlers-crckt5dq.js +0 -32
  349. package/dist/heartbeat-8phn1kdq.js +0 -41
  350. package/dist/index-4x08sjtk.js +0 -30
  351. package/dist/index-8ybffts4.js +0 -37
  352. package/dist/index-nfy4kkg5.js +0 -33
  353. package/dist/lead-zdqxsvjn.js +0 -71
  354. package/dist/worker-y62rvvq3.js +0 -71
  355. package/dist/{cli-gxy8y1dt.js → cli-8bpgbr8k.js} +3 -3
@@ -3,7 +3,8 @@ import { z } from "zod";
3
3
 
4
4
  // dreaming-v2 lane B, CREATE + VALIDATE + TIDY on top of B1 classify (global dreaming-memtax). Operator 2026-10-01:
5
5
  // curated memories live at name = /longterm/<path> (taxonomy dreaming-v2/memory-taxonomy.md §3.2), scope swarm.
6
- // Anything not under /longterm/ is inbox and is never written or deleted here (B2/B3).
6
+ // Anything not under /longterm/ is inbox and is never written here (B2/B3). The one exception is a learnings-triage
7
+ // drop: apply deletes those /learnings rows (pre-image, ledger, rollback) and commits the triage cursor.
7
8
  // plan -> read-only. Ingest every /longterm/* doc (chunk 0), the source records (users, agents, swarm_repos)
8
9
  // and tonight's B1 classifications. Propose deterministic entity docs, B1 clusters to distill,
9
10
  // validate verdicts (ok / stale / drift / duplicate / bad-path) and tidy ops inside /longterm/.
@@ -40,13 +41,21 @@ export const argsSchema = z.object({
40
41
  budget: z.unknown().optional(), // gather.result.budget
41
42
  classifyPlan: z.unknown().optional(), // memtax-plan.result (B1)
42
43
  classify: z.unknown().optional(), // memtax-classify foreach aggregate (B1)
44
+ learnings: z.unknown().optional(), // learnings-report.result (dreaming-learnings): promotions, how-to keeps, drops, cursor
43
45
  plan: z.unknown().optional(), // memtax-create-plan.result (apply)
44
46
  distill: z.unknown().optional(), // memtax-distill foreach aggregate (apply)
45
47
  leadAgentId: z.string().optional(), // gather.result.leadAgentId: apply trusts only distill tasks this agent ran
46
48
  maxCreates: z.number().int().min(0).max(80).default(40),
47
49
  maxEdits: z.number().int().min(0).max(60).default(20),
48
50
  maxDeletes: z.number().int().min(0).max(20).default(5),
49
- maxClusters: z.number().int().min(0).max(40).default(12),
51
+ maxLearningDrops: z.number().int().min(0).max(200).default(60),
52
+ // Near-duplicate guard on creates: cosine between the create's evidence (the mean of its source memories' embeddings)
53
+ // and each /longterm chunk-0 doc. A twin at >= twinCos under any name, or at >= nearDupCos about the same subject (same
54
+ // slug or a shared alias), turns the create into an edit of that doc. Templated siblings sit at 0.80-0.93 (two customer
55
+ // docs, two company-story sections), so 0.80 alone would merge different subjects.
56
+ nearDupCos: z.number().min(0.5).max(1).default(0.8),
57
+ twinCos: z.number().min(0.5).max(1).default(0.95),
58
+ maxClusters: z.number().int().min(0).max(40).default(24),
50
59
  clustersPerJob: z.number().int().min(1).max(12).default(6),
51
60
  memberChars: z.number().int().min(200).max(1500).default(900),
52
61
  sampleCount: z.number().int().min(0).max(100).default(20),
@@ -65,6 +74,27 @@ export const argsSchema = z.object({
65
74
  });
66
75
 
67
76
  const NS = "dreaming-v2";
77
+ // Drops a live night could not delete (cap, write budget, a failed delete), retried first on the next live night.
78
+ // They drive Lead deletes, so they live in the Lead's own agent namespace: any agent can write dreaming-v2, but only
79
+ // the Lead can write task:agent:<leadId>.
80
+ export const LEARNINGS_PENDING_KEY = "dreaming-v2:learnings:pending-drops";
81
+ export const pendingDropsNs = (leadId: string) => `task:agent:${leadId}`;
82
+ // Same namespace for the triage cursor (dreaming-learnings CURSOR_KEY: its plan reads it, only this apply writes it) and
83
+ // for promotions a live night could not write (cluster cap, budget, a failed or refused write), re-fed to the next plan.
84
+ export const LEARNINGS_CURSOR_KEY = "dreaming-v2:learnings:cursor";
85
+ export const LEARNINGS_PENDING_PROMOTIONS_KEY = "dreaming-v2:learnings:pending-promotions";
86
+ const LEARNINGS_PENDING_MAX = 600;
87
+ // Bound a carry queue without losing a decision. Entries carried from earlier nights are past the committed cursor,
88
+ // so the queue is their only copy: they are always kept (the last write bounded them, and each yields at most one
89
+ // entry). Tonight's entries fill what is left; the ones that do not fit are `cut`, and apply then holds the cursor so
90
+ // tomorrow re-triages them instead of the queue dropping them.
91
+ export function boundCarry<T>(entries: T[], isCarried: (e: T) => boolean, max = LEARNINGS_PENDING_MAX): { keep: T[]; cut: number } {
92
+ const old = entries.filter(isCarried);
93
+ const fresh = entries.filter((e) => !isCarried(e));
94
+ const room = Math.max(0, max - old.length);
95
+ return { keep: [...old, ...fresh.slice(0, room)], cut: Math.max(0, fresh.length - room) };
96
+ }
97
+ const LEARNINGS_PENDING_TRIES = 5;
68
98
  const MAX_DOC = 1950;
69
99
  const TAGS = ["dreaming-v2", "longterm"]; // never "memtax": B1's read-only control counts memtax-tagged writes
70
100
 
@@ -460,6 +490,63 @@ export function rewriteFacts(current: Fact[], next: Fact[]): { ok: boolean; fact
460
490
  return { ok: facts.length > 0 && dropped <= maxDrop, facts, dropped, maxDrop };
461
491
  }
462
492
 
493
+ // ---- near-duplicate guard (pure) ----
494
+ // db_query returns embeddings as hex(embedding): little-endian float32.
495
+ export function decodeVec(hex: unknown): Float32Array | null {
496
+ const h = typeof hex === "string" ? hex.trim() : "";
497
+ if (!h || h.length % 8 !== 0 || !/^[0-9a-fA-F]+$/.test(h)) return null;
498
+ const bytes = new Uint8Array(h.length / 2);
499
+ for (let i = 0; i < bytes.length; i++) bytes[i] = parseInt(h.slice(i * 2, i * 2 + 2), 16);
500
+ return new Float32Array(bytes.buffer);
501
+ }
502
+ // Vectors of different dimensions (rows from two embedding models while a re-embed is in flight) are not comparable:
503
+ // a shared prefix can score 1, so they score 0 and never make a twin.
504
+ export function cosine(a: ArrayLike<number>, b: ArrayLike<number>): number {
505
+ if (a.length !== b.length) return 0;
506
+ const n = a.length;
507
+ let dot = 0;
508
+ let na = 0;
509
+ let nb = 0;
510
+ for (let i = 0; i < n; i++) {
511
+ dot += a[i]! * b[i]!;
512
+ na += a[i]! * a[i]!;
513
+ nb += b[i]! * b[i]!;
514
+ }
515
+ return na && nb ? dot / Math.sqrt(na * nb) : 0;
516
+ }
517
+ // The evidence of a create = the mean of its source memories' embeddings (the draft itself has no embedding yet).
518
+ export function centroid(vs: Array<ArrayLike<number>>): Float32Array | null {
519
+ const ok = vs.filter((v) => v && v.length && v.length === vs[0]!.length);
520
+ if (!ok.length) return null;
521
+ const out = new Float32Array(ok[0]!.length);
522
+ for (const v of ok) for (let i = 0; i < out.length; i++) out[i]! += v[i]! / ok.length;
523
+ return out;
524
+ }
525
+ // Same subject = the same last path segment, or a shared alias (kebab, 4+ chars, not a generic word). Company-story
526
+ // sections are fixed siblings of one subject (the company), so they never match by subject, only as near-identical.
527
+ export function sameSubject(a: { path: string; aliases: string[] }, b: { path: string; aliases: string[] }): boolean {
528
+ if (a.path.startsWith("/longterm/company-story/") || b.path.startsWith("/longterm/company-story/")) return false;
529
+ const slug = (p: string) => p.split("/").pop() ?? "";
530
+ if (slug(a.path) && slug(a.path) === slug(b.path)) return true;
531
+ const names = (x: { path: string; aliases: string[] }) => new Set([slug(x.path), ...x.aliases].map(kebab).filter((n) => n.length >= 4 && !GENERIC.has(n)));
532
+ const A = names(a);
533
+ for (const n of names(b)) if (A.has(n)) return true;
534
+ return false;
535
+ }
536
+ export type TwinDoc = { id: string; path: string; aliases: string[]; vec: ArrayLike<number> };
537
+ // The existing doc a create would duplicate, or null. A doc already on the create's path (an agent doc keyed there)
538
+ // is always its twin. Highest cosine wins.
539
+ export function nearestTwin(create: { path: string; aliases: string[]; vec: ArrayLike<number> }, docs: TwinDoc[], o: { nearDupCos: number; twinCos: number }): { id: string; path: string; cos: number; why: "same path" | "near-identical" | "same subject" } | null {
540
+ let best: { id: string; path: string; cos: number; why: "same path" | "near-identical" | "same subject" } | null = null;
541
+ for (const d of docs) {
542
+ const c = cosine(create.vec, d.vec);
543
+ if (d.path === create.path) return { id: d.id, path: d.path, cos: c, why: "same path" };
544
+ const why = c >= o.twinCos ? "near-identical" : c >= o.nearDupCos && sameSubject(create, d) ? "same subject" : null;
545
+ if (why && (!best || c > best.cos)) best = { id: d.id, path: d.path, cos: c, why };
546
+ }
547
+ return best;
548
+ }
549
+
463
550
  // ---- validate (pure) ----
464
551
  export type Verdict = "ok" | "ok-unsourced" | "stale" | "drift" | "duplicate" | "bad-path" | "multi-chunk" | "misfiled";
465
552
  // A people/customers path whose slug names an agent or repo record: that subject lives in its profile / get-repos.
@@ -644,6 +731,8 @@ async function runScript(args: unknown, ctx: ScriptContext) {
644
731
  return [];
645
732
  }
646
733
  };
734
+ // For reads whose failure must not look like "no rows" (a missing row is a final answer, a failed read is not).
735
+ const qStrict = async (sql: string, params: unknown[] = []): Promise<any[]> => rows(await ctx.swarm.db_query({ sql, params }));
647
736
  try {
648
737
  if (a.mode === "plan") return await plan();
649
738
  if (a.mode === "apply") return await apply();
@@ -704,16 +793,60 @@ async function runScript(args: unknown, ctx: ScriptContext) {
704
793
  const cp: any = parse(a.classifyPlan) ?? {};
705
794
  const meta = new Map<string, any>();
706
795
  for (const b of Array.isArray(cp.batches) ? cp.batches : []) for (const d of b?.docs ?? []) meta.set(String(d.id), d);
796
+ // Learnings triage (dreaming-learnings report): its rows join B1's, validated by the same rules. A promotion is
797
+ // distilled even as a singleton: the triage already decided it belongs in that subject doc.
798
+ const lt: any = parse(a.learnings) ?? {};
799
+ const ltRows: any[] = Array.isArray(lt.classifications) ? [...lt.classifications] : [];
800
+ for (const d of Array.isArray(lt.docs) ? lt.docs : []) if (d?.id && !meta.has(String(d.id))) meta.set(String(d.id), { ...d, fromLearning: true });
801
+ const promotedIds = new Set<string>((Array.isArray(lt.promotedIds) ? lt.promotedIds : []).map(String));
802
+ // Promotions an earlier live night decided but did not write (cluster cap, budget, a failed or refused write) come
803
+ // back from the Lead's queue and join tonight's rows, oldest first, with their learning re-read from the db. A
804
+ // carried row whose learning is gone (TTL, deleted) leaves the queue. Tonight's own decision for a learning wins.
805
+ const promoRows = new Map<string, any>();
806
+ for (const r of ltRows) if (r && promotedIds.has(String(r.id))) promoRows.set(String(r.id), { id: String(r.id), path: r.path, kind: r.kind, action: r.action, entitySlugs: r.entitySlugs ?? [], reason: r.reason ?? "", tries: 0 });
807
+ const leadId = String(a.leadAgentId ?? "").trim();
808
+ let promotionsRead = leadId ? "ok" : "no leadAgentId";
809
+ let carriedPromotions = 0;
810
+ // Every id in the old queue, including ones tonight's triage re-decided: apply keeps these before tonight's own.
811
+ const queuedPromotionIds: string[] = [];
812
+ if (leadId) {
813
+ try {
814
+ const v: any = (await ctx.swarm.kv_getOrNull({ namespace: pendingDropsNs(leadId), key: LEARNINGS_PENDING_PROMOTIONS_KEY }))?.value;
815
+ for (const r of Array.isArray(v?.promotions) ? v.promotions : []) if (r && typeof r.id === "string") queuedPromotionIds.push(r.id);
816
+ const carried: any[] = (Array.isArray(v?.promotions) ? v.promotions : []).filter((r: any) => r && typeof r.id === "string" && !promoRows.has(r.id) && !ltRows.some((x) => String(x?.id) === r.id));
817
+ if (carried.length) {
818
+ const cids = carried.map((r) => r.id);
819
+ const found = new Map((await qStrict(`SELECT id, name, key, createdAt, substr(content, 1, 1200) text FROM agent_memory WHERE id IN (${cids.map(() => "?").join(",")}) AND chunkIndex = 0 AND coalesce(key, '') GLOB '/learnings/*' AND (expiresAt IS NULL OR expiresAt > ?)`, [...cids, new Date().toISOString()])).map((r) => [String(r.id), r]));
820
+ for (const r of carried) {
821
+ const d = found.get(r.id);
822
+ if (!d) continue;
823
+ meta.set(r.id, { id: r.id, name: String(d.name ?? ""), key: String(d.key ?? ""), created: String(d.createdAt ?? "").slice(0, 10), text: String(d.text ?? ""), fromLearning: true });
824
+ const row = { id: r.id, path: String(r.path ?? ""), kind: String(r.kind ?? ""), action: String(r.action ?? ""), entitySlugs: Array.isArray(r.entitySlugs) ? r.entitySlugs : [], reason: String(r.reason ?? ""), tries: Number(r.tries ?? 0) || 0, carried: true };
825
+ promoRows.set(r.id, row);
826
+ ltRows.unshift({ ...row, decision: "promote" });
827
+ promotedIds.add(r.id);
828
+ carriedPromotions++;
829
+ }
830
+ }
831
+ } catch (e: any) {
832
+ // The queue cannot be rewritten without its old contents: apply keeps it and holds the cursor.
833
+ promotionsRead = "failed";
834
+ errors.push(`learnings pending promotions read: ${String(e?.message ?? e).slice(0, 200)}`);
835
+ }
836
+ }
837
+ const carriedIds = new Set([...promoRows.values()].filter((r) => r.carried).map((r) => r.id));
707
838
  const ids = new Set(meta.keys());
708
839
  const groups = new Map<string, any[]>();
709
840
  const howtoGroups = new Map<string, any[]>();
710
841
  const clusterStats = { classified: 0, inbox: 0, deleteAction: 0, deferredRoots: 0, failedBatches: 0, rejected: 0, noCreateRoot: 0, misfiled: 0, howto: 0, howtoRemapped: 0, episodic: 0, selfMember: 0 };
842
+ const feed: any[][] = [];
711
843
  for (const x of parseForeach(a.classify)) {
712
- if (x.status !== "completed") {
713
- clusterStats.failedBatches++;
714
- continue;
715
- }
716
- for (const c of Array.isArray(x.out?.classifications) ? x.out.classifications : []) {
844
+ if (x.status !== "completed") clusterStats.failedBatches++;
845
+ else feed.push(Array.isArray(x.out?.classifications) ? x.out.classifications : []);
846
+ }
847
+ feed.push(ltRows);
848
+ for (const list of feed) {
849
+ for (const c of list) {
717
850
  const v = validateClassification(c, ids);
718
851
  if (!v.ok) {
719
852
  clusterStats.rejected++;
@@ -746,15 +879,17 @@ async function runScript(args: unknown, ctx: ScriptContext) {
746
879
  clusterStats.selfMember++;
747
880
  continue;
748
881
  }
749
- groups.set(target, [...(groups.get(target) ?? []), { id: r.id, reason: r.reason }]);
882
+ groups.set(target, [...(groups.get(target) ?? []), { id: r.id, reason: r.reason, promoted: promotedIds.has(r.id), carried: carriedIds.has(r.id), tries: Number(promoRows.get(r.id)?.tries ?? 0) }]);
750
883
  }
751
884
  }
752
885
  }
753
886
  const entityPaths = new Set(entities.filter((e) => !noCreate(e.path)).map((e) => e.path));
754
887
  const allClusters = [...groups.entries()]
755
- .map(([path, ms]) => ({ path, root: pathRoot(path)!, members: ms, attach: entityPaths.has(path) || byName.has(path) }))
756
- .filter((c) => c.members.length >= 2 || c.attach)
757
- .sort((x, y) => y.members.length - x.members.length || (x.path < y.path ? -1 : 1));
888
+ .map(([path, ms]) => ({ path, root: pathRoot(path)!, members: ms, attach: entityPaths.has(path) || byName.has(path), promoted: ms.filter((m: any) => m.promoted).length, carried: ms.some((m: any) => m.carried), tries: Math.min(...ms.filter((m: any) => m.carried).map((m: any) => m.tries), 99) }))
889
+ .filter((c) => c.members.length >= 2 || c.attach || c.promoted > 0)
890
+ // Promotions first (carried ones before tonight's, fewest attempts first so a capped one is not starved): the TTL
891
+ // deletes an undistilled learning, a B1 doc only waits.
892
+ .sort((x, y) => Number(y.carried) - Number(x.carried) || x.tries - y.tries || Number(y.promoted > 0) - Number(x.promoted > 0) || y.members.length - x.members.length || (x.path < y.path ? -1 : 1));
758
893
  // Skill routing: how-to clusters leave lane B before distill, so they never reach /longterm or use a cluster slot.
759
894
  const skillRows = (await q("skills", `SELECT name, description FROM skills WHERE isEnabled = 1 ORDER BY name`)) as SkillRow[];
760
895
  const scriptRows = (await q("scripts", `SELECT name, description FROM scripts WHERE scope = 'global' AND isScratch = 0 ORDER BY name`)) as SkillRow[];
@@ -781,6 +916,9 @@ async function runScript(args: unknown, ctx: ScriptContext) {
781
916
  const singletons = [...groups.values()].filter((ms) => ms.length === 1).length - clusters.filter((c) => c.members.length === 1).length;
782
917
  const distillOn = !overCap && a.maxClusters > 0;
783
918
  const picked = distillOn ? clusters.slice(0, a.maxClusters) : [];
919
+ // Promotions in a memory cluster the cap or the budget left out were never attempted: apply carries them untouched.
920
+ const pickedIds = new Set(picked.flatMap((c) => c.members.map((m: any) => String(m.id))));
921
+ const deferredPromotionIds = [...promoRows.keys()].filter((id) => !pickedIds.has(id) && clusters.some((c) => c.members.some((m: any) => String(m.id) === id)));
784
922
  const jobs: any[] = [];
785
923
  for (let i = 0; i < picked.length; i += a.clustersPerJob) {
786
924
  const slice = picked.slice(i, i + a.clustersPerJob);
@@ -833,7 +971,12 @@ async function runScript(args: unknown, ctx: ScriptContext) {
833
971
  recallLeft,
834
972
  skillCatalog: skillRows.length,
835
973
  scriptCatalog: scriptRows.length,
836
- clusterStats: { ...clusterStats, singletonsLeftForB2: singletons, overCap, routedToSkills: skillRoutes.length },
974
+ clusterStats: { ...clusterStats, singletonsLeftForB2: singletons, overCap, routedToSkills: skillRoutes.length, learningRows: ltRows.length, promotedClusters: picked.filter((c) => c.promoted > 0).length, promotedOverCap: clusters.slice(picked.length).reduce((n, c) => n + c.promoted, 0) },
975
+ // Carried to apply: the drops it deletes and the cursor it commits on a live run.
976
+ learnings:
977
+ lt.counts || ltRows.length || Array.isArray(lt.drops) || carriedPromotions || promotionsRead === "failed"
978
+ ? { drops: Array.isArray(lt.drops) ? lt.drops : [], cursor: lt.cursor ?? null, counts: lt.counts ?? null, promotedIds: [...promotedIds], promotions: [...promoRows.values()], deferredPromotionIds, queuedPromotionIds, carriedPromotions, promotionsRead, skipReason: lt.skipReason ?? null }
979
+ : null,
837
980
  jobs,
838
981
  tidy,
839
982
  memberNames: Object.fromEntries([...meta.entries()].map(([id, d]) => [id, String(d.name ?? "").slice(0, 120)])),
@@ -901,6 +1044,46 @@ async function runScript(args: unknown, ctx: ScriptContext) {
901
1044
  if (r.route === "skill-update" || r.route === "skill-new") skillRoutes.push({ ...handoffRow(hp, r, texts, scriptRows, ids), from: cl.path, flaggedBy: "distill" });
902
1045
  }
903
1046
  }
1047
+ // Near-duplicate guard, before any create is composed: a distilled doc with no home yet whose evidence matches an
1048
+ // existing /longterm doc folds into that doc as an edit (merged bullets) instead of becoming a second copy. A twin
1049
+ // the lane cannot edit safely (an agent-written doc, multi-chunk, or a retired root) refuses the create instead.
1050
+ const nearDup = { checked: 0, unchecked: 0, redirected: [] as any[], refused: [] as any[] };
1051
+ const createPaths = [...distilled.keys()].filter((path) => !byName.has(path) && !src.entities.some((e) => e.path === path) && !noCreate(path) && !routedPaths.has(path) && !HOWTO_ROOTS.some((r) => path.startsWith(`${r}/`)));
1052
+ if (createPaths.length) {
1053
+ const srcIds = [...new Set(createPaths.flatMap((path) => distilled.get(path)!.facts.flatMap((f) => f.src)))];
1054
+ const vecs = new Map<string, Float32Array>();
1055
+ const srcRows = srcIds.length ? await q("near-dup-sources", `SELECT id, hex(embedding) e FROM agent_memory WHERE id IN (${srcIds.map(() => "?").join(",")}) AND embedding IS NOT NULL`, srcIds) : [];
1056
+ for (const r of srcRows) {
1057
+ const v = decodeVec(r.e);
1058
+ if (v) vecs.set(String(r.id), v);
1059
+ }
1060
+ const twins: TwinDoc[] = [];
1061
+ for (const r of await q("near-dup-docs", `SELECT id, name, key, substr(content, 1, 600) head, hex(embedding) e FROM agent_memory WHERE chunkIndex = 0 AND (name GLOB '/longterm/*' OR coalesce(key, '') GLOB '/longterm/*') AND embedding IS NOT NULL ORDER BY createdAt, id LIMIT 1000`)) {
1062
+ const v = decodeVec(r.e);
1063
+ const path = String(r.name ?? "").startsWith("/longterm/") ? String(r.name) : String(r.key ?? "");
1064
+ if (v) twins.push({ id: String(r.id), path, aliases: parseDoc(String(r.head ?? "")).aliases, vec: v });
1065
+ }
1066
+ for (const path of createPaths) {
1067
+ const d = distilled.get(path)!;
1068
+ const vec = centroid([...new Set(d.facts.flatMap((f) => f.src))].map((id) => vecs.get(id)).filter((v): v is Float32Array => !!v));
1069
+ if (!vec) {
1070
+ nearDup.unchecked++;
1071
+ continue;
1072
+ }
1073
+ nearDup.checked++;
1074
+ const twin = nearestTwin({ path, aliases: d.aliases, vec }, twins, { nearDupCos: a.nearDupCos, twinCos: a.twinCos });
1075
+ if (!twin) continue;
1076
+ const cos = Math.round(twin.cos * 1000) / 1000;
1077
+ const lane = byName.get(twin.path)?.[0];
1078
+ const editable = !!lane && Number(lane.totalChunks) === 1 && /^type: /.test(String(lane.content ?? "")) && guardLongtermWrite({ op: "edit", name: twin.path }).ok && !routedPaths.has(twin.path);
1079
+ distilled.delete(path);
1080
+ if (editable) {
1081
+ const prev = distilled.get(twin.path);
1082
+ distilled.set(twin.path, prev ? { aliases: [...new Set([...prev.aliases, ...d.aliases])].slice(0, 6), facts: mergeFacts(prev.facts, d.facts), rewrite: prev.rewrite } : { aliases: d.aliases, facts: d.facts, rewrite: false });
1083
+ nearDup.redirected.push({ from: path, to: twin.path, cos, why: twin.why });
1084
+ } else nearDup.refused.push({ from: path, twin: twin.path, cos, why: twin.why, reason: lane ? "twin is multi-chunk, not lane format, or on a retired root" : "twin is an agent-written doc the lane does not edit" });
1085
+ }
1086
+ }
904
1087
  // Compose proposals.
905
1088
  type Prop = { op: "create" | "edit" | "delete"; why: string; name: string; id?: string; content?: string; beforeContent?: string; beforeSha?: string; sources: string[]; verdict: string; kind: string; omitted?: number };
906
1089
  const props: Prop[] = [];
@@ -1037,6 +1220,21 @@ async function runScript(args: unknown, ctx: ScriptContext) {
1037
1220
  const overCap = { creates: Math.max(0, creates.length - a.maxCreates), edits: Math.max(0, edits.length - a.maxEdits), deletes: Math.max(0, deletes.length - a.maxDeletes) };
1038
1221
  const refused = [...props.filter((x) => x.verdict !== "ok" && x.op === "create" && !blocked.has(x)).map((x) => ({ name: x.name, verdict: x.verdict })), ...[...blocked].map(([x, why]) => ({ name: x.name, op: x.op, verdict: why }))];
1039
1222
 
1223
+ // Learnings triage carried by the plan: drops to delete (capped) and the cursor to commit.
1224
+ const ltPlan: any = pl.learnings && typeof pl.learnings === "object" ? pl.learnings : null;
1225
+ const allDrops: any[] = Array.isArray(ltPlan?.drops) ? ltPlan.drops.filter((d: any) => d && typeof d.id === "string") : [];
1226
+ let learningDrops = allDrops.slice(0, a.maxLearningDrops);
1227
+ let dropsLeft = allDrops.length - learningDrops.length;
1228
+ let dropsCarried = 0;
1229
+ let dropsPending: number | null = null;
1230
+ let dropsQueueOk = true;
1231
+ let promotionsQueueOk = true;
1232
+ let promotionsPending: number | null = null;
1233
+ let dropsOverflow = 0;
1234
+ let promotionsOverflow = 0;
1235
+ const promotions: any[] = Array.isArray(ltPlan?.promotions) ? ltPlan.promotions.filter((r: any) => r && typeof r.id === "string") : [];
1236
+ const carriedRead = String(ltPlan?.promotionsRead ?? (promotions.length ? "ok" : "none"));
1237
+ let cursorState = !ltPlan ? "none (no triage tonight)" : runDry ? "not committed (dry run)" : "not committed (v3Writes off)";
1040
1238
  // Writes (live only).
1041
1239
  const writes: any[] = [];
1042
1240
  const ledgerItems: any[] = [];
@@ -1109,6 +1307,109 @@ async function runScript(args: unknown, ctx: ScriptContext) {
1109
1307
  writes.push({ actionId, op: x.op, id: x.id ?? null, name: x.name, status: "failed", why: String(e?.message ?? e).slice(0, 200) });
1110
1308
  }
1111
1309
  }
1310
+ // Learnings-triage drops: delete each /learnings row after the /longterm writes, inside the same write budget.
1311
+ // Re-checked live: still a /learnings row, one chunk, unchanged since the triage read it. A drop the cap or the
1312
+ // budget leaves, or whose delete fails, is carried to the next live night in learnings:pending-drops: the cursor
1313
+ // moves past the row either way, so the carry is what retries the decision. Earlier carried drops go first.
1314
+ // The queue is rewritten whole, so a failed read deletes nothing and writes nothing tonight: the old queue stays
1315
+ // and the cursor holds, so tonight's drops are re-triaged instead of lost.
1316
+ let carried: any[] = [];
1317
+ try {
1318
+ if (!leadId) throw new Error("no leadAgentId: the pending-drop queue lives in the Lead's namespace");
1319
+ const v: any = (await ctx.swarm.kv_getOrNull({ namespace: pendingDropsNs(leadId), key: LEARNINGS_PENDING_KEY }))?.value;
1320
+ carried = Array.isArray(v?.drops) ? v.drops.filter((d: any) => d && typeof d.id === "string") : [];
1321
+ } catch (e: any) {
1322
+ dropsQueueOk = false;
1323
+ errors.push(`learnings pending drops read: ${String(e?.message ?? e).slice(0, 200)}`);
1324
+ }
1325
+ if (dropsQueueOk) {
1326
+ const merged = new Map<string, any>();
1327
+ for (const d of [...carried, ...allDrops]) if (!merged.has(d.id)) merged.set(d.id, d);
1328
+ const queue = [...merged.values()];
1329
+ dropsCarried = carried.length;
1330
+ learningDrops = queue.slice(0, a.maxLearningDrops);
1331
+ dropsLeft = queue.length - learningDrops.length;
1332
+ const pending: any[] = queue.slice(learningDrops.length);
1333
+ const retry = (dr: any) => {
1334
+ const tries = Number(dr.tries ?? 0) + 1;
1335
+ if (tries < LEARNINGS_PENDING_TRIES) pending.push({ ...dr, tries });
1336
+ };
1337
+ for (const [i, dr] of learningDrops.entries()) {
1338
+ if (Date.now() - t0 > (a.writeBudgetMs ?? 90000)) {
1339
+ dropsLeft += learningDrops.length - i;
1340
+ pending.push(...learningDrops.slice(i));
1341
+ errors.push(`write budget reached; ${learningDrops.length - i} learning drops carried to the next night`);
1342
+ break;
1343
+ }
1344
+ const actionId = `LT${i + 1}`;
1345
+ try {
1346
+ // A failed read throws (retried), so only a row that is really gone or changed is skipped for good.
1347
+ const cur = await qStrict(`SELECT id, name, key, tags, content, contentHash, totalChunks FROM agent_memory WHERE id = ? AND chunkIndex = 0`, [dr.id]);
1348
+ if (!cur.length || !String(cur[0].key ?? "").startsWith("/learnings/") || !dr.contentHash || cur[0].contentHash !== dr.contentHash || Number(cur[0].totalChunks) !== 1) {
1349
+ writes.push({ actionId, op: "delete", kind: "learning", id: dr.id, name: dr.name, status: "skipped", why: "gone, not a /learnings row, multi-chunk, no content hash, or changed since triage" });
1350
+ continue;
1351
+ }
1352
+ const preimageKey = `memtax-create:pre:${runId}:${dr.id}`;
1353
+ await ctx.swarm.kv_set({ namespace: NS, key: preimageKey, value: { rows: [{ id: dr.id, name: cur[0].name, key: cur[0].key, tags: cur[0].tags, content: cur[0].content }], sha256: cur[0].contentHash, at: new Date().toISOString() } as any });
1354
+ const res: any = await ctx.swarm.memory_delete({ id: dr.id });
1355
+ if (res?.data?.success === false) {
1356
+ writes.push({ actionId, op: "delete", kind: "learning", id: dr.id, name: dr.name, status: "failed", why: String(res.data.message ?? "refused").slice(0, 200), preimageKey });
1357
+ retry(dr);
1358
+ continue;
1359
+ }
1360
+ const back = await q("post-drop", `SELECT COUNT(*) n FROM agent_memory WHERE id = ?`, [dr.id]);
1361
+ writes.push({ actionId, op: "delete", kind: "learning", id: dr.id, name: String(cur[0].name ?? ""), key: cur[0].key, beforeSha: cur[0].contentHash, afterSha: null, preimageKey, why: `${dr.dropWhy}: ${String(dr.reason ?? "").slice(0, 120)}`, status: Number(back[0]?.n) === 0 ? "verified" : "unverified" });
1362
+ ledgerItems.push({ actionId, lane: "memtax", kind: "memory-delete", target: { name: String(cur[0].name ?? ""), memoryIds: [dr.id] }, preimageKey });
1363
+ if (Number(back[0]?.n) !== 0) retry(dr);
1364
+ } catch (e: any) {
1365
+ writes.push({ actionId, op: "delete", kind: "learning", id: dr.id, name: dr.name, status: "failed", why: String(e?.message ?? e).slice(0, 200) });
1366
+ retry(dr);
1367
+ }
1368
+ }
1369
+ // A skipped drop (gone, multi-chunk, or edited since triage, so the decision no longer matches the row) is final.
1370
+ // The carry list is bounded; a row whose delete failed LEARNINGS_PENDING_TRIES nights in a row is left to its TTL.
1371
+ try {
1372
+ const carriedIds = new Set(carried.map((d) => d.id));
1373
+ const { keep, cut } = boundCarry(pending, (d) => carriedIds.has(d.id));
1374
+ await ctx.swarm.kv_set({ namespace: pendingDropsNs(leadId), key: LEARNINGS_PENDING_KEY, value: { drops: keep, runId, at: new Date().toISOString() } as any });
1375
+ dropsPending = keep.length;
1376
+ dropsOverflow = cut;
1377
+ } catch (e: any) {
1378
+ dropsQueueOk = false;
1379
+ errors.push(`learnings pending drops write: ${String(e?.message ?? e).slice(0, 200)}`);
1380
+ }
1381
+ }
1382
+ // Promotions: one counts as written once a verified /longterm write cites it. The rest are carried in the Lead's
1383
+ // queue to the next live night's plan. A promotion the plan attempted (picked for distill, or refused, rejected
1384
+ // or routed on the way) gets a try; one the cluster cap or the budget left out keeps its count. After
1385
+ // LEARNINGS_PENDING_TRIES attempts it is left to its TTL. A failed read at plan time means the queue is not
1386
+ // rewritten tonight, and the cursor holds.
1387
+ if (promotions.length || carriedRead === "failed") {
1388
+ if (carriedRead !== "ok") {
1389
+ promotionsQueueOk = false;
1390
+ if (carriedRead !== "failed") errors.push(`learnings pending promotions: ${carriedRead}`);
1391
+ } else {
1392
+ const verified = new Set(writes.filter((w) => w.status === "verified" && w.kind !== "learning").map((w) => w.name));
1393
+ const written = new Set(planned.filter((x) => verified.has(x.name)).flatMap((x) => x.sources));
1394
+ const deferred = new Set<string>((Array.isArray(ltPlan?.deferredPromotionIds) ? ltPlan.deferredPromotionIds : []).map(String));
1395
+ const next: any[] = [];
1396
+ for (const r of promotions) {
1397
+ if (written.has(r.id)) continue;
1398
+ const tries = (Number(r.tries ?? 0) || 0) + (deferred.has(r.id) ? 0 : 1);
1399
+ if (tries < LEARNINGS_PENDING_TRIES) next.push({ id: r.id, path: r.path, kind: r.kind, action: r.action, entitySlugs: r.entitySlugs ?? [], reason: String(r.reason ?? "").slice(0, 300), tries });
1400
+ }
1401
+ try {
1402
+ const queued = new Set<string>((Array.isArray(ltPlan?.queuedPromotionIds) ? ltPlan.queuedPromotionIds : []).map(String));
1403
+ const { keep, cut } = boundCarry(next, (r) => queued.has(r.id));
1404
+ await ctx.swarm.kv_set({ namespace: pendingDropsNs(leadId), key: LEARNINGS_PENDING_PROMOTIONS_KEY, value: { promotions: keep, runId, at: new Date().toISOString() } as any });
1405
+ promotionsPending = keep.length;
1406
+ promotionsOverflow = cut;
1407
+ } catch (e: any) {
1408
+ promotionsQueueOk = false;
1409
+ errors.push(`learnings pending promotions write: ${String(e?.message ?? e).slice(0, 200)}`);
1410
+ }
1411
+ }
1412
+ }
1112
1413
  // Write log for rollback + ledger items for the next night's dreaming-verify survival check. verify already
1113
1414
  // wrote ledger:<runId> earlier in this run (verify -> learn -> memtax), so this read-append-write has no racer.
1114
1415
  try {
@@ -1124,6 +1425,20 @@ async function runScript(args: unknown, ctx: ScriptContext) {
1124
1425
  } catch (e: any) {
1125
1426
  errors.push(`log: ${String(e?.message ?? e).slice(0, 200)}`);
1126
1427
  }
1428
+ // Commit the triage cursor only now, after the writes: a skipped or failed night re-reads the same learnings.
1429
+ // A failed distill job may have held a promotion, and a queue that could not be read or written would lose the
1430
+ // drops and promotions it carries, so each holds the cursor too (re-triage is cheap and idempotent).
1431
+ const to = ltPlan?.cursor?.to;
1432
+ const hold = !to ? null : !leadId ? "no leadAgentId" : failedJobs.length ? "a distill job failed" : !dropsQueueOk ? "the pending-drop queue could not be read or written" : !promotionsQueueOk ? "the pending-promotion queue could not be read or written" : dropsOverflow ? `the pending-drop queue is full (${dropsOverflow} of tonight's drops did not fit)` : promotionsOverflow ? `the pending-promotion queue is full (${promotionsOverflow} of tonight's promotions did not fit)` : null;
1433
+ if (to && !hold) {
1434
+ try {
1435
+ await ctx.swarm.kv_set({ namespace: pendingDropsNs(leadId), key: LEARNINGS_CURSOR_KEY, value: { createdAt: String(to.createdAt ?? ""), id: String(to.id ?? ""), at: String(to.at ?? ""), atId: String(to.atId ?? ""), runId, committedAt: new Date().toISOString() } as any });
1436
+ cursorState = `committed to ${String(to.createdAt ?? "").slice(0, 19) || "start"}`;
1437
+ } catch (e: any) {
1438
+ errors.push(`learnings cursor: ${String(e?.message ?? e).slice(0, 200)}`);
1439
+ cursorState = "commit failed; tomorrow re-reads the same learnings";
1440
+ }
1441
+ } else cursorState = hold ? `not committed: ${hold}, tomorrow re-reads the same learnings` : "none (no triage tonight)";
1127
1442
  }
1128
1443
  // Handoff to the next night's synthesize (it runs before lane B). Not a memory write, so it does not wait on
1129
1444
  // v3Writes; dry runs write nothing. Fixed key :latest so synthesize reads it by exact name.
@@ -1156,7 +1471,7 @@ async function runScript(args: unknown, ctx: ScriptContext) {
1156
1471
  edits: edits.length,
1157
1472
  deletes: deletes.length,
1158
1473
  planned: planned.length,
1159
- written: writes.filter((w) => w.status === "verified").length,
1474
+ written: writes.filter((w) => w.status === "verified" && w.kind !== "learning").length,
1160
1475
  unverified: writes.filter((w) => w.status === "unverified" || w.status === "failed").length,
1161
1476
  stale: verdicts.filter((v) => v.verdict === "stale").length,
1162
1477
  drift: verdicts.filter((v) => v.verdict === "drift").length,
@@ -1179,10 +1494,39 @@ async function runScript(args: unknown, ctx: ScriptContext) {
1179
1494
  // Operator 2026-10-08 invariant: rendered docs refused before the write, and existing docs that break it.
1180
1495
  invariantRefused: invBlocked.size + writes.filter((w) => w.status === "refused" && String(w.why).startsWith("invariant")).length,
1181
1496
  invariantExisting: verdicts.filter((v) => v.invariant.length).length,
1497
+ nearDupChecked: nearDup.checked,
1498
+ nearDupRedirected: nearDup.redirected.length,
1499
+ nearDupRefused: nearDup.refused.length,
1182
1500
  existingDocs: existing.length,
1183
1501
  longtermRowsBefore: pl.longtermRowsBefore ?? null,
1184
1502
  longtermRowsAfter,
1185
1503
  };
1504
+ // Learnings triage, applied: what tonight's decisions became. A promotion counts once a /longterm write cites it.
1505
+ const promotedSet = new Set<string>((Array.isArray(ltPlan?.promotedIds) ? ltPlan.promotedIds : []).map(String));
1506
+ const verifiedNames = new Set(writes.filter((w) => w.status === "verified" && w.kind !== "learning").map((w) => w.name));
1507
+ const cites = (xs: Prop[]) => new Set(xs.flatMap((x) => x.sources).filter((id) => promotedSet.has(id))).size;
1508
+ const ltc: any = ltPlan?.counts ?? {};
1509
+ const learnings = ltPlan || dropsCarried
1510
+ ? {
1511
+ read: Number(ltc.read ?? 0),
1512
+ promoted: Number(ltc.promoted ?? 0),
1513
+ kept: Number(ltc.kept ?? 0),
1514
+ dropped: Number(ltc.dropped ?? 0),
1515
+ promotedPlanned: cites(planned),
1516
+ promotedWritten: live ? cites(planned.filter((x) => verifiedNames.has(x.name))) : 0,
1517
+ dropsPlanned: learningDrops.length,
1518
+ dropsDeleted: writes.filter((w) => w.kind === "learning" && w.status === "verified").length,
1519
+ dropsSkipped: writes.filter((w) => w.kind === "learning" && w.status === "skipped").length,
1520
+ dropsLeft,
1521
+ dropsCarried,
1522
+ dropsPending,
1523
+ dropsOverflow,
1524
+ promotionsCarried: Number(ltPlan?.carriedPromotions ?? 0),
1525
+ promotionsPending,
1526
+ promotionsOverflow,
1527
+ cursor: cursorState,
1528
+ }
1529
+ : null;
1186
1530
  const L: string[] = ["## Long-term memories (lane B, create/validate/tidy)"];
1187
1531
  L.push(
1188
1532
  live
@@ -1202,6 +1546,15 @@ async function runScript(args: unknown, ctx: ScriptContext) {
1202
1546
  for (const r of skillRoutes) L.push(`| \`${r.path}\` | ${r.lane} ${r.op} | ${r.skill ? `\`${r.skill}\`` : "new"} | ${r.scriptExisting ? `wire \`${r.scriptExisting}\`` : r.script ? "new" : "-"} | ${(r.memberIds ?? []).length} |`);
1203
1547
  L.push("");
1204
1548
  }
1549
+ if (learnings) {
1550
+ L.push(
1551
+ `**Learnings triage (applied)**: ${learnings.read} read, ${learnings.promoted} promoted, ${learnings.kept} kept, ${learnings.dropped} dropped · ` +
1552
+ (live ? `${learnings.promotedWritten} promoted learnings cited by verified /longterm writes · ${learnings.dropsDeleted} of ${learnings.dropsPlanned} drops deleted` : `${learnings.promotedPlanned} promoted learnings cited by planned /longterm writes · ${learnings.dropsPlanned} drops would be deleted`) +
1553
+ `${learnings.dropsCarried ? ` (${learnings.dropsCarried} carried from earlier nights)` : ""}${learnings.dropsLeft ? `, ${learnings.dropsLeft} over the cap ${a.maxLearningDrops} or the write budget` : ""}${learnings.dropsPending != null ? `, ${learnings.dropsPending} carried to the next live night` : ""} · promotions: ${learnings.promotionsCarried} carried in${learnings.promotionsPending != null ? `, ${learnings.promotionsPending} carried to the next live night` : ""} · cursor ${learnings.cursor}.`,
1554
+ );
1555
+ }
1556
+ const nd = (x: any) => `\`${x.from}\` -> \`${x.to ?? x.twin}\` (${x.why}, cos ${x.cos})`;
1557
+ L.push(`**Near-duplicate guard** (creates vs existing /longterm docs): ${nearDup.checked} checked, ${nearDup.redirected.length} turned into edits${nearDup.redirected.length ? ` (${nearDup.redirected.map(nd).join("; ")})` : ""}, ${nearDup.refused.length} refused${nearDup.refused.length ? ` (${nearDup.refused.map(nd).join("; ")})` : ""}${nearDup.unchecked ? `, ${nearDup.unchecked} with no embedded source to compare` : ""}.`);
1205
1558
  if (Object.values(overCap).some((n) => n > 0)) L.push(`Over the nightly cap, left for tomorrow: ${Object.entries(overCap).filter(([, n]) => n > 0).map(([k, n]) => `${k} ${n}`).join(", ")}.`);
1206
1559
  if (src.skipped.length) L.push(`Source records skipped: ${src.skipped.map((s) => `${s.name} (${s.why})`).slice(0, 12).join("; ")}.`);
1207
1560
  L.push("", "| path | create | edit | delete |", "|---|---:|---:|---:|");
@@ -1228,6 +1581,8 @@ async function runScript(args: unknown, ctx: ScriptContext) {
1228
1581
  distillRejected,
1229
1582
  writes,
1230
1583
  ledgerItems: ledgerItems.length,
1584
+ nearDup,
1585
+ learnings,
1231
1586
  markdown: L.join("\n"),
1232
1587
  errors,
1233
1588
  };
@@ -1257,8 +1612,13 @@ async function runScript(args: unknown, ctx: ScriptContext) {
1257
1612
  step.undo = `restore content of ${w.id} (sha ${String(w.beforeSha).slice(0, 12)})`;
1258
1613
  if (a.execute) await ctx.swarm.memory_edit({ memoryId: w.id, mode: "replace", content, intent: `rollback memtax-create ${rid} ${w.actionId}` });
1259
1614
  } else {
1615
+ // A learnings-triage drop comes back under its own key and tags, so it is a learning again.
1616
+ const row: any = pre?.value?.rows?.[0] ?? {};
1617
+ const key = typeof row.key === "string" && row.key.startsWith("/learnings/") ? row.key : undefined;
1618
+ const prior = parse(row.tags);
1619
+ const tags = key ? [...new Set([...(Array.isArray(prior) ? prior.map(String) : ["learning"]), "rollback"])] : [...TAGS, "rollback"];
1260
1620
  step.undo = `re-store ${w.name} (new id)`;
1261
- if (a.execute) await ctx.swarm.memory_store({ name: w.name, content, scope: "swarm", tags: [...TAGS, "rollback"], intent: `rollback memtax-create ${rid} ${w.actionId}` });
1621
+ if (a.execute) await ctx.swarm.memory_store({ name: w.name, content, scope: "swarm", tags, ...(key ? { key } : {}), intent: `rollback memtax-create ${rid} ${w.actionId}` });
1262
1622
  }
1263
1623
  }
1264
1624
  step.status = a.execute ? "done" : "would";
@@ -1439,6 +1799,21 @@ async function runScript(args: unknown, ctx: ScriptContext) {
1439
1799
  t("handoff: covered how-to -> skill-refactor skill-update, no script", h2.lane === "skill-refactor" && h2.op === "skill-update" && h2.skill === "agentmail-sending" && h2.scriptLane === null, h2);
1440
1800
  const h3 = handoffRow("/howto/bluesky", routeCluster("/howto/bluesky", sk), ["POST /xrpc/com.atproto.repo.createRecord with Bearer token"], scr, ["d4", "d5"]);
1441
1801
  t("handoff: API how-to with no script -> script candidate", h3.scriptExisting === null && h3.script === true && h3.scriptLane === "scriptify", h3);
1802
+ // Near-duplicate guard. Vectors with a known cosine: [1, 0] vs [c, sqrt(1 - c^2)].
1803
+ const at = (c: number) => [c, Math.sqrt(1 - c * c)];
1804
+ const o = { nearDupCos: 0.8, twinCos: 0.95 };
1805
+ const ndTwin = nearestTwin({ path: "/longterm/entities/customers/jan-carbonell", aliases: ["jan"], vec: [1, 0] }, [{ id: "p1", path: "/longterm/entities/people/jan-carbonell", aliases: ["jan carbonell"], vec: at(0.82) }], o);
1806
+ t("near-dup: same person under another root at 0.82 -> twin (positive control)", ndTwin?.path === "/longterm/entities/people/jan-carbonell" && ndTwin.why === "same subject", ndTwin);
1807
+ const ndSibling = nearestTwin({ path: "/longterm/entities/customers/aurica", aliases: ["aurica"], vec: [1, 0] }, [{ id: "c1", path: "/longterm/entities/customers/evalion", aliases: ["evalion"], vec: at(0.928) }], o);
1808
+ const ndStory = nearestTwin({ path: "/longterm/company-story/history", aliases: [], vec: [1, 0] }, [{ id: "s1", path: "/longterm/company-story/overview", aliases: [], vec: at(0.837) }], o);
1809
+ t("near-dup: templated siblings at 0.84-0.93 are not twins (negative control)", ndSibling === null && ndStory === null, { ndSibling, ndStory });
1810
+ const ndIdent = nearestTwin({ path: "/longterm/workstreams/active/boxd", aliases: [], vec: [1, 0] }, [{ id: "w1", path: "/longterm/workstreams/active/boxd-self-host", aliases: [], vec: at(0.97) }, { id: "w2", path: "/longterm/workstreams/active/other", aliases: [], vec: at(0.5) }], o);
1811
+ t("near-dup: near-identical under another name -> twin", ndIdent?.id === "w1" && ndIdent.why === "near-identical", ndIdent);
1812
+ t("near-dup: an agent doc keyed on the create's path is a twin", nearestTwin({ path: "/longterm/workstreams/active/x", aliases: [], vec: [1, 0] }, [{ id: "k1", path: "/longterm/workstreams/active/x", aliases: [], vec: [0, 1] }], o)?.why === "same path");
1813
+ const hex = Array.from(new Uint8Array(new Float32Array([1, 0.5, -2]).buffer)).map((x) => x.toString(16).padStart(2, "0")).join("");
1814
+ const dv0 = decodeVec(hex);
1815
+ t("near-dup: hex(embedding) decodes as float32; garbage -> null", !!dv0 && dv0.length === 3 && dv0[1] === 0.5 && dv0[2] === -2 && decodeVec("xyz") === null && decodeVec("") === null, dv0);
1816
+ t("near-dup: centroid of one vector is that vector", cosine(centroid([[3, 4]])!, [3, 4]) > 0.9999 && centroid([]) === null);
1442
1817
  return { ok: cases.every((c) => c.pass), mode: "controls", passed: cases.filter((c) => c.pass).length, total: cases.length, failed: cases.filter((c) => !c.pass), errors };
1443
1818
  }
1444
1819
  }
@@ -33,6 +33,9 @@ export const argsSchema = z.object({
33
33
 
34
34
  const NS = "dreaming-v2";
35
35
  const CURSOR_KEY = "memtax:cursor";
36
+ // /learnings rows belong to the learnings-triage step (script dreaming-learnings): it classifies each one once, in
37
+ // cursor order, with the same path enum, and hands its rows to lane B. B1 skips them so no learning is classified twice.
38
+ export const NOT_LEARNING = (alias: string) => `coalesce(${alias}key, '') NOT GLOB '/learnings/*'`;
36
39
 
37
40
  // Closed path enum, taxonomy §3.2, every long-term path under /longterm/ (2026-10-01). Anything not under
38
41
  // /longterm/ is inbox; `/inbox/<id>` is the explicit "fits nowhere" answer. `<slug>` = kebab, `<id>` = memory id.
@@ -270,7 +273,7 @@ export default async function (args: unknown, ctx: ScriptContext) {
270
273
  SUM(CASE WHEN source='manual' AND (createdAt >= ?1 OR updatedAt >= ?1) THEN 1 ELSE 0 END) AS today,
271
274
  SUM(CASE WHEN (createdAt > ?2 OR (createdAt = ?2 AND id > ?3)) THEN 1 ELSE 0 END) AS backlogLeft,
272
275
  COUNT(*) AS curated
273
- FROM agent_memory WHERE chunkIndex = 0 AND source IN ('manual','file_index')`,
276
+ FROM agent_memory WHERE chunkIndex = 0 AND source IN ('manual','file_index') AND ${NOT_LEARNING("")}`,
274
277
  [since, cursor.createdAt ?? "", cursor.id ?? ""],
275
278
  )
276
279
  )[0] ?? {};
@@ -282,13 +285,13 @@ export default async function (args: unknown, ctx: ScriptContext) {
282
285
  FROM agent_memory m WHERE m.chunkIndex = 0 AND ${where}`;
283
286
  const P = a.previewChars;
284
287
  const today = todayCap
285
- ? await q("today", docSql(`m.source = 'manual' AND (m.createdAt >= ? OR m.updatedAt >= ?) ORDER BY m.createdAt, m.id LIMIT ?`).replaceAll("?P", String(P)), [since, since, Math.min(todayCap, 400)])
288
+ ? await q("today", docSql(`m.source = 'manual' AND ${NOT_LEARNING("m.")} AND (m.createdAt >= ? OR m.updatedAt >= ?) ORDER BY m.createdAt, m.id LIMIT ?`).replaceAll("?P", String(P)), [since, since, Math.min(todayCap, 400)])
286
289
  : [];
287
290
  const todayIds = new Set(today.map((r) => r.id));
288
291
  const backlogRaw = backlogCap
289
292
  ? await q(
290
293
  "backlog",
291
- docSql(`m.source IN ('manual','file_index') AND (m.createdAt > ? OR (m.createdAt = ? AND m.id > ?)) ORDER BY m.createdAt, m.id LIMIT ?`).replaceAll("?P", String(P)),
294
+ docSql(`m.source IN ('manual','file_index') AND ${NOT_LEARNING("m.")} AND (m.createdAt > ? OR (m.createdAt = ? AND m.id > ?)) ORDER BY m.createdAt, m.id LIMIT ?`).replaceAll("?P", String(P)),
292
295
  [cursor.createdAt ?? "", cursor.createdAt ?? "", cursor.id ?? "", Math.min(backlogCap + todayIds.size, 400)],
293
296
  )
294
297
  : [];
@@ -34,6 +34,7 @@ import dreamingApplySrc from "./catalog/dreaming-apply.ts" with { type: "text" }
34
34
  import dreamingGatherSrc from "./catalog/dreaming-gather.ts" with { type: "text" };
35
35
  import dreamingHeartbeatSrc from "./catalog/dreaming-heartbeat.ts" with { type: "text" };
36
36
  import dreamingLearnSrc from "./catalog/dreaming-learn.ts" with { type: "text" };
37
+ import dreamingLearningsSrc from "./catalog/dreaming-learnings.ts" with { type: "text" };
37
38
  import dreamingMemtaxSrc from "./catalog/dreaming-memtax.ts" with { type: "text" };
38
39
  import dreamingMemtaxCreateSrc from "./catalog/dreaming-memtax-create.ts" with { type: "text" };
39
40
  import dreamingOwnersSrc from "./catalog/dreaming-owners.ts" with { type: "text" };
@@ -350,6 +351,14 @@ export const SEED_SCRIPTS: SeedScript[] = [
350
351
  intent: "Score the effect of earlier dreaming changes so the next night can learn from them.",
351
352
  source: asText(dreamingLearnSrc),
352
353
  },
354
+ {
355
+ name: "dreaming-learnings",
356
+ description:
357
+ "Dreaming learnings triage: plan (cursor-ordered and reused learnings in bounded batches), report (promote, keep or drop per learning, as rows for lane B) and controls. No writes.",
358
+ intent:
359
+ "Decide each learning's fate before its TTL: promote it into /longterm, keep it, or drop it.",
360
+ source: asText(dreamingLearningsSrc),
361
+ },
353
362
  {
354
363
  name: "dreaming-memtax",
355
364
  description: