@mastra/core 1.87.0-alpha.10 → 1.87.0-alpha.11

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 (368) hide show
  1. package/dist/_types/@internal_core@0.1.4/dist/knowledge-compat/index.d.ts +49 -0
  2. package/dist/agent/durable/index.cjs +1 -1
  3. package/dist/agent/durable/index.js +1 -1
  4. package/dist/agent/index.cjs +2 -2
  5. package/dist/agent/index.js +2 -2
  6. package/dist/agent-builder/ee/index.cjs +1 -1
  7. package/dist/agent-builder/ee/index.js +1 -1
  8. package/dist/agent-controller/index.cjs +1 -1
  9. package/dist/agent-controller/index.js +1 -1
  10. package/dist/agent-controller/session.d.ts +11 -1
  11. package/dist/{agent-controller--gKWI81G.js → agent-controller-BrRzZy4-.js} +21 -12
  12. package/dist/{agent-controller-BolLBwDm.cjs → agent-controller-DKI-d-np.cjs} +21 -12
  13. package/dist/background-tasks/index.cjs +1 -1
  14. package/dist/background-tasks/index.js +1 -1
  15. package/dist/{background-tasks-CgzXjBfE.js → background-tasks-CDP3Pgeu.js} +1 -1
  16. package/dist/{background-tasks-DYtlijQ1.cjs → background-tasks-CDgdfRmB.cjs} +1 -1
  17. package/dist/browser/index.cjs +1 -1
  18. package/dist/browser/index.js +1 -1
  19. package/dist/{builder-Dz-g-9CZ.cjs → builder-Bs4CtyqT.cjs} +2 -2
  20. package/dist/{builder-emNPaIaC.js → builder-DuT0Iqb5.js} +2 -2
  21. package/dist/capabilities/302ai.json +201 -201
  22. package/dist/capabilities/abliteratedllm.json +38 -38
  23. package/dist/capabilities/abliteration-ai.json +4 -4
  24. package/dist/capabilities/above.json +19 -19
  25. package/dist/capabilities/adaption.json +13 -13
  26. package/dist/capabilities/adzuki.json +30 -30
  27. package/dist/capabilities/agentrouter.json +12 -12
  28. package/dist/capabilities/agnes.json +2 -2
  29. package/dist/capabilities/ai-router.json +4 -4
  30. package/dist/capabilities/aiand.json +23 -23
  31. package/dist/capabilities/aigrow.json +9 -9
  32. package/dist/capabilities/aimlapi.json +153 -153
  33. package/dist/capabilities/aipg.json +2 -2
  34. package/dist/capabilities/aixy.json +22 -22
  35. package/dist/capabilities/aki-io.json +10 -10
  36. package/dist/capabilities/alibaba-cn.json +99 -99
  37. package/dist/capabilities/alibaba-coding-plan-cn.json +6 -6
  38. package/dist/capabilities/alibaba-coding-plan.json +6 -6
  39. package/dist/capabilities/alibaba-token-plan-cn.json +51 -51
  40. package/dist/capabilities/alibaba-token-plan.json +52 -52
  41. package/dist/capabilities/alibaba.json +73 -73
  42. package/dist/capabilities/ambient.json +17 -17
  43. package/dist/capabilities/amd.json +10 -10
  44. package/dist/capabilities/anthropic.json +41 -41
  45. package/dist/capabilities/anyapi.json +47 -47
  46. package/dist/capabilities/apiko.json +4 -4
  47. package/dist/capabilities/arcee.json +11 -11
  48. package/dist/capabilities/augure.json +6 -6
  49. package/dist/capabilities/auriko.json +18 -18
  50. package/dist/capabilities/bailing.json +4 -4
  51. package/dist/capabilities/baseten.json +33 -33
  52. package/dist/capabilities/bee.json +5 -5
  53. package/dist/capabilities/berget.json +6 -6
  54. package/dist/capabilities/bothub.json +10 -10
  55. package/dist/capabilities/boundless.json +34 -34
  56. package/dist/capabilities/bumo.json +43 -43
  57. package/dist/capabilities/byteplus.json +31 -31
  58. package/dist/capabilities/cheapaimodel.json +5 -5
  59. package/dist/capabilities/cheapest-token.json +27 -27
  60. package/dist/capabilities/chutes.json +10 -10
  61. package/dist/capabilities/clarifai.json +2 -2
  62. package/dist/capabilities/cline-pass.json +37 -37
  63. package/dist/capabilities/cloudcode.json +8 -8
  64. package/dist/capabilities/cloudferro-sherlock.json +4 -4
  65. package/dist/capabilities/cloudflare-workers-ai.json +17 -17
  66. package/dist/capabilities/commandcode.json +151 -151
  67. package/dist/capabilities/concentrate.json +277 -269
  68. package/dist/capabilities/cortecs.json +108 -108
  69. package/dist/capabilities/crossmodel.json +172 -172
  70. package/dist/capabilities/crusoe.json +16 -16
  71. package/dist/capabilities/daoxe.json +8 -8
  72. package/dist/capabilities/databricks.json +128 -128
  73. package/dist/capabilities/deepinfra.json +97 -91
  74. package/dist/capabilities/deepseek.json +3 -3
  75. package/dist/capabilities/digitalocean.json +113 -113
  76. package/dist/capabilities/dothoosh.json +23 -23
  77. package/dist/capabilities/doubleword.json +27 -27
  78. package/dist/capabilities/edenai.json +279 -279
  79. package/dist/capabilities/empiriolabs.json +160 -160
  80. package/dist/capabilities/engy.json +20 -20
  81. package/dist/capabilities/entrim.json +8 -8
  82. package/dist/capabilities/evroc.json +18 -18
  83. package/dist/capabilities/ezkielyna.json +11 -11
  84. package/dist/capabilities/fastrouter.json +87 -87
  85. package/dist/capabilities/fireworks-ai.json +83 -83
  86. package/dist/capabilities/freemodel.json +19 -19
  87. package/dist/capabilities/friendli.json +7 -7
  88. package/dist/capabilities/frogbot.json +88 -88
  89. package/dist/capabilities/gisoo.json +18 -18
  90. package/dist/capabilities/gmicloud.json +20 -20
  91. package/dist/capabilities/google.json +55 -55
  92. package/dist/capabilities/graphn.json +6 -6
  93. package/dist/capabilities/greenpt.json +34 -34
  94. package/dist/capabilities/helicone.json +81 -81
  95. package/dist/capabilities/hetzner.json +5 -5
  96. package/dist/capabilities/hopper.json +2 -2
  97. package/dist/capabilities/hostinger-router.json +10 -10
  98. package/dist/capabilities/hpc-ai.json +11 -11
  99. package/dist/capabilities/huawei-maas.json +15 -15
  100. package/dist/capabilities/hubris.json +31 -31
  101. package/dist/capabilities/huggingface.json +93 -85
  102. package/dist/capabilities/humain.json +2 -2
  103. package/dist/capabilities/hyper.json +27 -27
  104. package/dist/capabilities/impossibl.json +165 -165
  105. package/dist/capabilities/inception.json +3 -3
  106. package/dist/capabilities/inceptron.json +8 -8
  107. package/dist/capabilities/inco.json +5 -5
  108. package/dist/capabilities/infer.json +13 -13
  109. package/dist/capabilities/inferall.json +6 -6
  110. package/dist/capabilities/inference-coop.json +15 -15
  111. package/dist/capabilities/inferenceapis.json +20 -20
  112. package/dist/capabilities/inferris.json +3 -3
  113. package/dist/capabilities/infersia.json +8 -8
  114. package/dist/capabilities/infomaniak.json +4 -4
  115. package/dist/capabilities/io-net.json +5 -5
  116. package/dist/capabilities/iteracompute.json +29 -29
  117. package/dist/capabilities/jad-ai.json +3 -3
  118. package/dist/capabilities/jalapeno.json +11 -11
  119. package/dist/capabilities/jiekou.json +61 -61
  120. package/dist/capabilities/joingonka.json +4 -4
  121. package/dist/capabilities/jzstoken.json +57 -57
  122. package/dist/capabilities/keln.json +23 -23
  123. package/dist/capabilities/kenari.json +121 -121
  124. package/dist/capabilities/kilo.json +615 -615
  125. package/dist/capabilities/kimi-code-plan-cn.json +6 -6
  126. package/dist/capabilities/kimi-code-plan-global.json +6 -6
  127. package/dist/capabilities/kitani.json +4 -4
  128. package/dist/capabilities/klavo.json +13 -13
  129. package/dist/capabilities/korouter.json +29 -29
  130. package/dist/capabilities/kunavo.json +2 -2
  131. package/dist/capabilities/liquid.json +10 -10
  132. package/dist/capabilities/lithosai.json +3 -3
  133. package/dist/capabilities/llmgateway-providers.json +926 -926
  134. package/dist/capabilities/llmgateway.json +330 -330
  135. package/dist/capabilities/llmtr.json +26 -26
  136. package/dist/capabilities/logits.json +2 -2
  137. package/dist/capabilities/longcat.json +2 -2
  138. package/dist/capabilities/lowrouter.json +65 -65
  139. package/dist/capabilities/lyceum.json +8 -8
  140. package/dist/capabilities/melious.json +9 -9
  141. package/dist/capabilities/merge-gateway.json +269 -269
  142. package/dist/capabilities/meta.json +8 -8
  143. package/dist/capabilities/mistral.json +19 -19
  144. package/dist/capabilities/mixlayer.json +4 -4
  145. package/dist/capabilities/modal.json +11 -11
  146. package/dist/capabilities/model-oracle-ai.json +24 -24
  147. package/dist/capabilities/modelis.json +23 -23
  148. package/dist/capabilities/modelscope.json +2 -2
  149. package/dist/capabilities/modular.json +13 -13
  150. package/dist/capabilities/moneo.json +8 -8
  151. package/dist/capabilities/moonshotai-cn.json +6 -6
  152. package/dist/capabilities/moonshotai.json +6 -6
  153. package/dist/capabilities/morph.json +15 -15
  154. package/dist/capabilities/munito-eu.json +8 -8
  155. package/dist/capabilities/munito.json +10 -10
  156. package/dist/capabilities/nan.json +28 -28
  157. package/dist/capabilities/nano-gpt.json +578 -578
  158. package/dist/capabilities/nearai.json +106 -106
  159. package/dist/capabilities/nebius.json +32 -32
  160. package/dist/capabilities/neon.json +121 -121
  161. package/dist/capabilities/neuralwatt.json +40 -40
  162. package/dist/capabilities/nokeep.json +4 -4
  163. package/dist/capabilities/novita-ai.json +148 -148
  164. package/dist/capabilities/nvidia.json +44 -44
  165. package/dist/capabilities/oathbreaker.json +5 -5
  166. package/dist/capabilities/obscurify.json +24 -24
  167. package/dist/capabilities/oci.json +6 -6
  168. package/dist/capabilities/ofox.json +349 -349
  169. package/dist/capabilities/ollama-cloud.json +54 -54
  170. package/dist/capabilities/openai.json +59 -59
  171. package/dist/capabilities/opencode-go.json +84 -84
  172. package/dist/capabilities/openrouter.json +538 -539
  173. package/dist/capabilities/opper.json +25 -25
  174. package/dist/capabilities/orcarouter.json +206 -206
  175. package/dist/capabilities/outerlabs.json +28 -28
  176. package/dist/capabilities/ovhcloud.json +19 -19
  177. package/dist/capabilities/pareto.json +5 -5
  178. package/dist/capabilities/pendra.json +4 -4
  179. package/dist/capabilities/perplexity-agent.json +62 -62
  180. package/dist/capabilities/phala.json +20 -20
  181. package/dist/capabilities/pioneer.json +32 -32
  182. package/dist/capabilities/poe.json +131 -131
  183. package/dist/capabilities/poolside.json +2 -2
  184. package/dist/capabilities/powerspring.json +11 -11
  185. package/dist/capabilities/primalabs.json +7 -7
  186. package/dist/capabilities/prime.json +112 -112
  187. package/dist/capabilities/privatemode-ai.json +11 -11
  188. package/dist/capabilities/proxystacks.json +6 -6
  189. package/dist/capabilities/qiniu-ai.json +14 -14
  190. package/dist/capabilities/refuseless.json +10 -10
  191. package/dist/capabilities/regolo-ai.json +5 -5
  192. package/dist/capabilities/requesty.json +259 -200
  193. package/dist/capabilities/ruapi.json +16 -16
  194. package/dist/capabilities/runcrate.json +15 -15
  195. package/dist/capabilities/runinfra.json +19 -19
  196. package/dist/capabilities/sakana.json +7 -7
  197. package/dist/capabilities/sandbase.json +21 -21
  198. package/dist/capabilities/sarvam.json +11 -11
  199. package/dist/capabilities/scaleway.json +16 -16
  200. package/dist/capabilities/scnet-token-plan.json +10 -10
  201. package/dist/capabilities/scx-ai.json +21 -21
  202. package/dist/capabilities/sensenova.json +15 -15
  203. package/dist/capabilities/siliconflow-cn.json +58 -58
  204. package/dist/capabilities/siliconflow.json +61 -61
  205. package/dist/capabilities/snowflake-cortex.json +18 -18
  206. package/dist/capabilities/sokkan.json +5 -5
  207. package/dist/capabilities/sparrowcodes.json +20 -20
  208. package/dist/capabilities/standardcompute.json +95 -95
  209. package/dist/capabilities/steadyrouter.json +33 -33
  210. package/dist/capabilities/stepfun-ai-step-plan.json +4 -4
  211. package/dist/capabilities/stepfun-ai.json +4 -4
  212. package/dist/capabilities/stepfun-step-plan.json +4 -4
  213. package/dist/capabilities/stepfun.json +4 -4
  214. package/dist/capabilities/stepping-stone.json +17 -17
  215. package/dist/capabilities/superbot-gg.json +4 -4
  216. package/dist/capabilities/synthetic.json +11 -11
  217. package/dist/capabilities/synthorai.json +23 -23
  218. package/dist/capabilities/teamorouter.json +22 -22
  219. package/dist/capabilities/teapot-router.json +15 -15
  220. package/dist/capabilities/tencent-token-plan-intl.json +22 -22
  221. package/dist/capabilities/tencent-token-plan.json +43 -43
  222. package/dist/capabilities/tencent-tokenhub.json +47 -47
  223. package/dist/capabilities/tensorx.json +37 -37
  224. package/dist/capabilities/tenstorrent.json +8 -8
  225. package/dist/capabilities/the-grid-ai.json +30 -30
  226. package/dist/capabilities/thinkingmachines.json +78 -78
  227. package/dist/capabilities/tinfoil.json +9 -9
  228. package/dist/capabilities/togetherai.json +55 -55
  229. package/dist/capabilities/tokengo.json +19 -19
  230. package/dist/capabilities/tokenify.json +2 -2
  231. package/dist/capabilities/trustedrouter.json +6 -6
  232. package/dist/capabilities/trustedtokens.json +17 -17
  233. package/dist/capabilities/umans-ai-coding-plan.json +14 -14
  234. package/dist/capabilities/umans-ai.json +10 -10
  235. package/dist/capabilities/uncensuredai.json +4 -4
  236. package/dist/capabilities/unrestricted.json +6 -6
  237. package/dist/capabilities/uplinkswitch.json +21 -21
  238. package/dist/capabilities/upstage.json +6 -6
  239. package/dist/capabilities/vancine.json +16 -16
  240. package/dist/capabilities/vercel.json +578 -578
  241. package/dist/capabilities/vivgrid.json +86 -86
  242. package/dist/capabilities/volcengine-coding-plan.json +26 -26
  243. package/dist/capabilities/volcengine.json +23 -23
  244. package/dist/capabilities/vultr.json +34 -34
  245. package/dist/capabilities/wafer.ai.json +17 -17
  246. package/dist/capabilities/wallaby.json +2 -2
  247. package/dist/capabilities/wally.json +13 -13
  248. package/dist/capabilities/wandb.json +21 -21
  249. package/dist/capabilities/watt.json +26 -26
  250. package/dist/capabilities/xai.json +6 -6
  251. package/dist/capabilities/xiaomi-token-plan-ams.json +2 -2
  252. package/dist/capabilities/xiaomi-token-plan-cn.json +2 -2
  253. package/dist/capabilities/xiaomi-token-plan-sgp.json +2 -2
  254. package/dist/capabilities/xiaomi.json +3 -3
  255. package/dist/capabilities/xpersona.json +12 -12
  256. package/dist/capabilities/xxapi.json +28 -28
  257. package/dist/capabilities/zai-coding-plan.json +18 -18
  258. package/dist/capabilities/zai.json +30 -30
  259. package/dist/capabilities/zenifra.json +31 -31
  260. package/dist/capabilities/zenmux.json +202 -202
  261. package/dist/capabilities/zerogpu.json +8 -8
  262. package/dist/capabilities/zhipuai-coding-plan.json +6 -6
  263. package/dist/capabilities/zhipuai.json +28 -28
  264. package/dist/capabilities/zro.json +4 -4
  265. package/dist/channels/index.cjs +2 -2
  266. package/dist/channels/index.js +2 -2
  267. package/dist/{channels-BVnDIsZS.cjs → channels-Bkd_v8M1.cjs} +1 -1
  268. package/dist/{channels-CndspFXP.js → channels-CkRMEIQ6.js} +1 -1
  269. package/dist/coding-agent/index.cjs +1 -1
  270. package/dist/coding-agent/index.js +1 -1
  271. package/dist/datasets/index.cjs +2 -2
  272. package/dist/datasets/index.js +2 -2
  273. package/dist/docs/SKILL.md +1 -1
  274. package/dist/docs/assets/SOURCE_MAP.json +570 -570
  275. package/dist/docs/references/reference-agent-controller-session.md +29 -1
  276. package/dist/evals/index.cjs +1 -1
  277. package/dist/evals/index.js +1 -1
  278. package/dist/evals/scoreTraces/index.cjs +1 -1
  279. package/dist/evals/scoreTraces/index.js +1 -1
  280. package/dist/harness/index.cjs +1 -1
  281. package/dist/harness/index.js +1 -1
  282. package/dist/index.cjs +1 -1
  283. package/dist/index.js +1 -1
  284. package/dist/knowledge/importers/overlay.d.ts +138 -0
  285. package/dist/knowledge/importers/sink.d.ts +6 -0
  286. package/dist/knowledge/importers/types.d.ts +5 -0
  287. package/dist/knowledge/index.cjs +1412 -139
  288. package/dist/knowledge/index.js +1412 -139
  289. package/dist/knowledge/links.d.ts +27 -0
  290. package/dist/llm/index.cjs +3 -3
  291. package/dist/llm/index.js +3 -3
  292. package/dist/llm/model/provider-types.generated.d.ts +7619 -7605
  293. package/dist/{llm-B1semiTO.cjs → llm-DAw2eouV.cjs} +2 -2
  294. package/dist/{llm-CytL7cpw.js → llm-DFT5EKp4.js} +2 -2
  295. package/dist/loop/index.cjs +2 -2
  296. package/dist/loop/index.js +2 -2
  297. package/dist/{manager-DnTzA9GL.js → manager-DiDnvKLM.js} +2 -2
  298. package/dist/{manager-BwyfS4ha.cjs → manager-hxzEe4U5.cjs} +2 -2
  299. package/dist/mastra/index.cjs +1 -1
  300. package/dist/mastra/index.js +1 -1
  301. package/dist/{mastra-Dj35Lj_J.cjs → mastra-1diaq68N.cjs} +16 -16
  302. package/dist/{mastra-DTkZPpch.js → mastra-BPaPxG5t.js} +16 -16
  303. package/dist/memory/index.cjs +2 -2
  304. package/dist/memory/index.js +2 -2
  305. package/dist/{model-DyQ07rPH.js → model-CUBZjm0T.js} +1 -1
  306. package/dist/{model-eDfetuno.cjs → model-DSMHJM3c.cjs} +1 -1
  307. package/dist/{netlify-BC4v7Ufv.cjs → netlify-C21T9ozJ.cjs} +1 -1
  308. package/dist/{netlify-BUvdxfHe.js → netlify-D1BKjns0.js} +1 -1
  309. package/dist/notifications/index.cjs +1 -1
  310. package/dist/notifications/index.js +1 -1
  311. package/dist/processor-provider/index.cjs +1 -1
  312. package/dist/processor-provider/index.js +1 -1
  313. package/dist/processors/index.cjs +2 -2
  314. package/dist/processors/index.js +2 -2
  315. package/dist/{provider-registry-CP_5SNiw.js → provider-registry-BAlFFX5o.js} +22725 -22697
  316. package/dist/{provider-registry-Bn01gq9y.cjs → provider-registry-ChojUVJa.cjs} +22725 -22697
  317. package/dist/provider-registry.json +22472 -22444
  318. package/dist/{registry-generator-CDPyxbzt.js → registry-generator-BbWSH6W4.js} +1 -1
  319. package/dist/{registry-generator-CNFKGRFQ.cjs → registry-generator-CAUL9Hek.cjs} +1 -1
  320. package/dist/{rehydrate-DExpzlNS.cjs → rehydrate-0xSq47n9.cjs} +2 -2
  321. package/dist/{rehydrate-CnGNY2zq.js → rehydrate-CzUnNFU6.js} +2 -2
  322. package/dist/relevance/index.cjs +2 -2
  323. package/dist/relevance/index.js +2 -2
  324. package/dist/{run-registry-CibQoN6K.cjs → run-registry-CrTsH9iL.cjs} +403 -11
  325. package/dist/{run-registry-BL_kKvFE.js → run-registry-DJT02z_9.js} +380 -12
  326. package/dist/storage/domains/knowledge/base.d.ts +86 -1
  327. package/dist/storage/domains/knowledge/importers-inmemory.d.ts +9 -0
  328. package/dist/storage/domains/knowledge/importers.d.ts +31 -0
  329. package/dist/storage/domains/knowledge/inmemory.d.ts +7 -0
  330. package/dist/storage/domains/knowledge/pages-inmemory.d.ts +31 -1
  331. package/dist/storage/domains/knowledge/pages.d.ts +74 -0
  332. package/dist/storage/index.cjs +2 -2
  333. package/dist/storage/index.js +2 -2
  334. package/dist/storage/types.d.ts +6 -0
  335. package/dist/stream/index.cjs +2 -2
  336. package/dist/stream/index.js +2 -2
  337. package/dist/{stream-1DGoEkG2.js → stream-CG9OooRx.js} +1 -1
  338. package/dist/{stream-D_7tMaJe.cjs → stream-CMKRczs4.cjs} +1 -1
  339. package/dist/test-utils/llm-mock.cjs +1 -1
  340. package/dist/test-utils/llm-mock.js +1 -1
  341. package/dist/tool-loop-agent/index.cjs +1 -1
  342. package/dist/tool-loop-agent/index.js +1 -1
  343. package/dist/{tool-loop-agent-CLB1r3X3.cjs → tool-loop-agent-14o3Z1qo.cjs} +3 -3
  344. package/dist/{tool-loop-agent-BXya_RYj.js → tool-loop-agent-Bi6z_q7o.js} +3 -3
  345. package/dist/{utils-B-KOMA_Q.cjs → utils-DkvbP8EA.cjs} +1 -1
  346. package/dist/{utils-C55ZdVaj.js → utils-Fag7YDBU.js} +1 -1
  347. package/dist/utils.cjs +1 -1
  348. package/dist/utils.js +1 -1
  349. package/dist/{validate-CmZhnsmX.cjs → validate-Bhrlve2E.cjs} +1 -1
  350. package/dist/{validate-BDfYr72F.js → validate-DLER0nlQ.js} +1 -1
  351. package/dist/vector/index.cjs +1 -1
  352. package/dist/vector/index.js +1 -1
  353. package/dist/worker/index.cjs +1 -1
  354. package/dist/worker/index.js +1 -1
  355. package/dist/{worker-D2B-x7Le.cjs → worker-0gczpztM.cjs} +2 -2
  356. package/dist/{worker-BoybIUTI.cjs → worker-BwJyrFQN.cjs} +2 -2
  357. package/dist/{worker-BG1rw_dg.js → worker-D-em3hyS.js} +2 -2
  358. package/dist/{worker-CuK2RaC0.js → worker-leYV1Y91.js} +2 -2
  359. package/dist/{workflow-CTKqeRXU.cjs → workflow-DWdcEcxw.cjs} +3 -3
  360. package/dist/{workflow-Bt09PcH1.js → workflow-FikHVwog.js} +3 -3
  361. package/dist/workflows/builder/index.cjs +1 -1
  362. package/dist/workflows/builder/index.js +1 -1
  363. package/dist/workflows/evented/index.cjs +1 -1
  364. package/dist/workflows/evented/index.js +1 -1
  365. package/dist/workflows/index.cjs +4 -4
  366. package/dist/workflows/index.js +4 -4
  367. package/package.json +8 -8
  368. package/src/llm/model/provider-types.generated.d.ts +7619 -7605
@@ -1,6 +1,6 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
2
  const require_base = require("../base-BIzR1D3_.cjs");
3
- const require_run_registry = require("../run-registry-CibQoN6K.cjs");
3
+ const require_run_registry = require("../run-registry-CrTsH9iL.cjs");
4
4
  const require_tool = require("../tool-CYlT2UA-.cjs");
5
5
  let crypto = require("crypto");
6
6
  let _mastra_schema_compat_schema = require("@mastra/schema-compat/schema");
@@ -23,6 +23,39 @@ const note = (op) => (result) => {
23
23
  noteId: id
24
24
  };
25
25
  };
26
+ /** The event each single write would emit for `write`, so a batch emits what its single writes would. */
27
+ function describePageWrite(write) {
28
+ switch (write.op) {
29
+ case "create":
30
+ case "update":
31
+ case "delete": return {
32
+ kind: "page",
33
+ op: write.op,
34
+ pageId: write.id,
35
+ scopeId: write.scopeId
36
+ };
37
+ case "move": return {
38
+ kind: "page",
39
+ op: "move",
40
+ pageId: write.id,
41
+ scopeId: write.scopeId,
42
+ fromScopeId: write.fromScopeId
43
+ };
44
+ case "add-note": return {
45
+ kind: "note",
46
+ op: "add",
47
+ pageId: write.pageId,
48
+ noteId: write.id
49
+ };
50
+ case "remove-note": return {
51
+ kind: "note",
52
+ op: "remove",
53
+ pageId: write.pageId,
54
+ noteId: write.id
55
+ };
56
+ case "replace-links": return null;
57
+ }
58
+ }
26
59
  /** The page-store writes that emit, and the event each one's result maps to. */
27
60
  const WRITES = {
28
61
  materializeScope: (result) => {
@@ -58,6 +91,7 @@ const WRITES = {
58
91
  fromScopeId
59
92
  };
60
93
  },
94
+ applyPageWrites: (_result, input) => input.writes.map(describePageWrite).filter((change) => change !== null),
61
95
  addNote: note("add"),
62
96
  restampNote: note("restamp"),
63
97
  removeNote: note("remove"),
@@ -143,9 +177,15 @@ function emitKnowledgeChanges(storage, emit, listening, onError, chain) {
143
177
  }
144
178
  const result = await value.call(target, input, ...rest);
145
179
  if (!listening()) return result;
180
+ let changes = [];
146
181
  try {
147
182
  const change = describe(result, input, fromScopeId);
148
- if (change) report(change);
183
+ changes = Array.isArray(change) ? change : change ? [change] : [];
184
+ } catch (error) {
185
+ onError(error);
186
+ }
187
+ for (const one of changes) try {
188
+ report(one);
149
189
  } catch (error) {
150
190
  onError(error);
151
191
  }
@@ -1033,6 +1073,889 @@ async function finishRun(host, request, lastSeq, unsettledSeq, withRetries) {
1033
1073
  function encodedBytes(value) {
1034
1074
  return new TextEncoder().encode(JSON.stringify(value)).byteLength;
1035
1075
  }
1076
+ // src/knowledge/importers/overlay.ts
1077
+ /**
1078
+ * The working copy a batched importer flush decides over (batched-flush plan v3.1 §1). The sink's
1079
+ * rule code runs unchanged against {@link ImportOverlay.storage} and {@link ImportOverlay.importers}:
1080
+ * reads come from rows gathered in a few set-based queries and locked, writes are applied to the
1081
+ * working copy and kept, in call order, for one batched write after every op is decided.
1082
+ *
1083
+ * A read of something not gathered throws {@link KnowledgeImportNotGatheredError} and names it, so
1084
+ * the caller gathers it and decides again. A call the working copy can't model throws
1085
+ * {@link KnowledgeImportBatchUnsupportedError}, and the flush takes the per-op path instead.
1086
+ *
1087
+ * @internal
1088
+ */
1089
+ /** The overlay was asked for a row it wasn't given. The caller gathers it and decides again. */
1090
+ var KnowledgeImportNotGatheredError = class extends Error {
1091
+ constructor(what) {
1092
+ super(`Not gathered for the batched import flush: ${what}`);
1093
+ this.name = "KnowledgeImportNotGatheredError";
1094
+ }
1095
+ };
1096
+ /** The flush needs a call the overlay doesn't model: it falls back to the per-op path. */
1097
+ var KnowledgeImportBatchUnsupportedError = class extends Error {
1098
+ call;
1099
+ constructor(call) {
1100
+ super(`Not supported by the batched import flush: ${call}`);
1101
+ this.call = call;
1102
+ this.name = "KnowledgeImportBatchUnsupportedError";
1103
+ }
1104
+ };
1105
+ const nodeKey = (bindingId, sourceId) => `${bindingId}\u0000${sourceId}`;
1106
+ const pathKey = (scopeId, path) => JSON.stringify([scopeId, ...path]);
1107
+ const childKey = (parentId, key) => `${parentId}\u0000${key}`;
1108
+ const byPosition = (a, b) => a.position < b.position ? -1 : a.position > b.position ? 1 : a.id < b.id ? -1 : a.id > b.id ? 1 : 0;
1109
+ /** UTF-8 byte order, as the stores sort source IDs. */
1110
+ const byteOrder = (a, b) => Buffer.compare(Buffer.from(a), Buffer.from(b));
1111
+ const emptyImportOverlayMissing = () => ({
1112
+ pages: /* @__PURE__ */ new Set(),
1113
+ nodes: /* @__PURE__ */ new Set(),
1114
+ nodesByPage: /* @__PURE__ */ new Set(),
1115
+ paths: /* @__PURE__ */ new Map(),
1116
+ notes: /* @__PURE__ */ new Set(),
1117
+ positions: /* @__PURE__ */ new Set(),
1118
+ locks: /* @__PURE__ */ new Set(),
1119
+ subtrees: /* @__PURE__ */ new Set(),
1120
+ linkTargets: /* @__PURE__ */ new Set(),
1121
+ bindings: /* @__PURE__ */ new Set()
1122
+ });
1123
+ const emptyImportOverlayRows = () => ({
1124
+ pages: /* @__PURE__ */ new Map(),
1125
+ nodes: /* @__PURE__ */ new Map(),
1126
+ nodesByPage: /* @__PURE__ */ new Map(),
1127
+ paths: /* @__PURE__ */ new Map(),
1128
+ notes: /* @__PURE__ */ new Map(),
1129
+ positions: /* @__PURE__ */ new Map(),
1130
+ locked: /* @__PURE__ */ new Set(),
1131
+ complete: /* @__PURE__ */ new Set(),
1132
+ tooLarge: /* @__PURE__ */ new Set(),
1133
+ linkTargets: /* @__PURE__ */ new Set(),
1134
+ tooManyLinkers: /* @__PURE__ */ new Set()
1135
+ });
1136
+ /** The binding and targets of a deferred mark, so back-to-back marks for one binding run as one. */
1137
+ const markTargets = /* @__PURE__ */ new WeakMap();
1138
+ const copyRows = (rows) => ({
1139
+ pages: new Map(rows.pages),
1140
+ nodes: new Map(rows.nodes),
1141
+ nodesByPage: new Map(rows.nodesByPage),
1142
+ paths: new Map(rows.paths),
1143
+ notes: new Map(rows.notes),
1144
+ positions: new Map(rows.positions),
1145
+ locked: new Set(rows.locked),
1146
+ complete: new Set(rows.complete),
1147
+ tooLarge: new Set(rows.tooLarge),
1148
+ linkTargets: new Set(rows.linkTargets),
1149
+ tooManyLinkers: new Set(rows.tooManyLinkers),
1150
+ ...rows.bindings ? { bindings: rows.bindings } : {}
1151
+ });
1152
+ const copyState = (state) => ({
1153
+ rows: copyRows(state.rows),
1154
+ writes: [...state.writes],
1155
+ touched: new Set(state.touched),
1156
+ marks: [...state.marks],
1157
+ links: [...state.links],
1158
+ moved: new Set(state.moved),
1159
+ freed: new Set(state.freed),
1160
+ stalePositions: new Set(state.stalePositions)
1161
+ });
1162
+ /** Every method the given implementation lacks throws {@link KnowledgeImportBatchUnsupportedError}. */
1163
+ function only(impl, name) {
1164
+ return new Proxy(impl, { get(target, prop, receiver) {
1165
+ if (prop in target) return Reflect.get(target, prop, receiver);
1166
+ if (typeof prop !== "string" || prop === "then") return void 0;
1167
+ return () => {
1168
+ throw new KnowledgeImportBatchUnsupportedError(`${name}.${prop}`);
1169
+ };
1170
+ } });
1171
+ }
1172
+ var ImportOverlay = class {
1173
+ missing = emptyImportOverlayMissing();
1174
+ #state;
1175
+ storage;
1176
+ importers;
1177
+ constructor(base, now = () => /* @__PURE__ */ new Date()) {
1178
+ this.#state = {
1179
+ rows: copyRows(base),
1180
+ writes: [],
1181
+ touched: /* @__PURE__ */ new Set(),
1182
+ marks: [],
1183
+ links: [],
1184
+ moved: /* @__PURE__ */ new Set(),
1185
+ freed: /* @__PURE__ */ new Set(),
1186
+ stalePositions: /* @__PURE__ */ new Set()
1187
+ };
1188
+ this.storage = this.#storage(now);
1189
+ this.importers = this.#importers();
1190
+ }
1191
+ get writes() {
1192
+ return this.#state.writes;
1193
+ }
1194
+ get marks() {
1195
+ return this.#state.marks;
1196
+ }
1197
+ get links() {
1198
+ return this.#state.links;
1199
+ }
1200
+ /** Link-index work the sink would run now; it runs, in one batch, after the batched write instead. */
1201
+ deferLinks(...work) {
1202
+ this.#state.links.push(...work);
1203
+ }
1204
+ /** The node writes decided: each touched node's last record, or a delete when it ends up gone. */
1205
+ nodeWrites(base) {
1206
+ const deletes = [];
1207
+ const saves = [];
1208
+ for (const key of this.#state.touched) {
1209
+ const node = this.#state.rows.nodes.get(key);
1210
+ if (node) {
1211
+ const { updatedAt: _updatedAt, ...record } = node;
1212
+ saves.push(record);
1213
+ } else if (base.nodes.get(key)) {
1214
+ const [bindingId, sourceId] = key.split("\0");
1215
+ deletes.push({
1216
+ bindingId,
1217
+ sourceId
1218
+ });
1219
+ }
1220
+ }
1221
+ return {
1222
+ deletes,
1223
+ saves
1224
+ };
1225
+ }
1226
+ #page(id) {
1227
+ const { pages } = this.#state.rows;
1228
+ if (!pages.has(id)) {
1229
+ this.missing.pages.add(id);
1230
+ throw new KnowledgeImportNotGatheredError(`page ${id}`);
1231
+ }
1232
+ return pages.get(id);
1233
+ }
1234
+ #livePage(id) {
1235
+ const page = this.#page(id);
1236
+ if (!page || page.deletedAt || page.mergedInto) throw new require_run_registry.KnowledgeNotFoundError("page", id);
1237
+ return page;
1238
+ }
1239
+ /** Levels below the home scope, from the working copy's chain. */
1240
+ #depth(page) {
1241
+ let depth = 0;
1242
+ let at = page;
1243
+ while (at && !at.isScope) {
1244
+ depth++;
1245
+ at = at.parentId ? this.#page(at.parentId) : null;
1246
+ }
1247
+ return depth;
1248
+ }
1249
+ /** The page's key path from its scope, or null when the chain doesn't reach one. */
1250
+ #keys(page) {
1251
+ const path = [];
1252
+ let at = page;
1253
+ while (at && !at.isScope) {
1254
+ if (at.key === void 0 || at.deletedAt || at.mergedInto) return null;
1255
+ path.unshift(at.key);
1256
+ at = at.parentId ? this.#page(at.parentId) : null;
1257
+ }
1258
+ return at ? {
1259
+ scopeId: at.id,
1260
+ path
1261
+ } : null;
1262
+ }
1263
+ /**
1264
+ * Live ordinary children by parent, sorted by position: built on first use, dropped on each page
1265
+ * write, and keyed by the pages map, which a rolled-back transaction replaces.
1266
+ */
1267
+ #childIndex;
1268
+ #setPage(id, page) {
1269
+ this.#state.rows.pages.set(id, page);
1270
+ this.#childIndex = void 0;
1271
+ }
1272
+ /** Live ordinary children by position, once gathered. */
1273
+ #children(parentId) {
1274
+ const { pages, complete } = this.#state.rows;
1275
+ if (!complete.has(parentId)) {
1276
+ this.missing.subtrees.add(parentId);
1277
+ throw new KnowledgeImportNotGatheredError(`children of ${parentId}`);
1278
+ }
1279
+ if (this.#childIndex?.pages !== pages) {
1280
+ const byParent = /* @__PURE__ */ new Map();
1281
+ for (const page of pages.values()) {
1282
+ if (!page || !page.parentId || page.isScope || page.deletedAt) continue;
1283
+ const siblings = byParent.get(page.parentId);
1284
+ if (siblings) siblings.push(page);
1285
+ else byParent.set(page.parentId, [page]);
1286
+ }
1287
+ for (const siblings of byParent.values()) siblings.sort(byPosition);
1288
+ this.#childIndex = {
1289
+ pages,
1290
+ byParent
1291
+ };
1292
+ }
1293
+ return [...this.#childIndex.byParent.get(parentId) ?? []];
1294
+ }
1295
+ /** The next position under a parent, as `createPage` and `movePage` would place a page. */
1296
+ #nextPosition(parentId) {
1297
+ const { positions, complete } = this.#state.rows;
1298
+ if (this.#state.stalePositions.has(parentId)) {
1299
+ if (!complete.has(parentId)) throw new KnowledgeImportBatchUnsupportedError("a position under a parent its last child left");
1300
+ return require_run_registry.knowledgePositionBetween(this.#children(parentId).at(-1)?.position);
1301
+ }
1302
+ if (!positions.has(parentId)) {
1303
+ this.missing.positions.add(parentId);
1304
+ throw new KnowledgeImportNotGatheredError(`last child position of ${parentId}`);
1305
+ }
1306
+ return require_run_registry.knowledgePositionBetween(positions.get(parentId) ?? void 0);
1307
+ }
1308
+ /** A page left `parentId`: its next position is still the gathered one unless it was the last child. */
1309
+ #left(parentId, position) {
1310
+ if (!parentId) return;
1311
+ const last = this.#state.rows.positions.get(parentId);
1312
+ if (last === void 0 || last === position) this.#state.stalePositions.add(parentId);
1313
+ }
1314
+ /** Points the path map at where `pages` are now; `before` holds their old paths. */
1315
+ #repath(pages, before) {
1316
+ const { paths } = this.#state.rows;
1317
+ const ids = new Set(pages.map((page) => page.id));
1318
+ for (const [key, id] of paths) if (id && ids.has(id)) paths.set(key, null);
1319
+ for (const old of before) if (old) paths.set(pathKey(old.scopeId, old.path), null);
1320
+ for (const page of pages) {
1321
+ const keys = this.#rowKeys(page);
1322
+ if (keys) paths.set(pathKey(keys.scopeId, keys.path), page.id);
1323
+ }
1324
+ }
1325
+ /** {@link #keys} on the working copy's current row. */
1326
+ #rowKeys(page) {
1327
+ return this.#keys(this.#state.rows.pages.get(page.id) ?? page);
1328
+ }
1329
+ #node(key) {
1330
+ const { nodes } = this.#state.rows;
1331
+ if (!nodes.has(key)) {
1332
+ this.missing.nodes.add(key);
1333
+ throw new KnowledgeImportNotGatheredError(`node ${key}`);
1334
+ }
1335
+ return nodes.get(key);
1336
+ }
1337
+ #setNode(key, node) {
1338
+ const { nodes, nodesByPage } = this.#state.rows;
1339
+ const before = nodes.get(key);
1340
+ if (before && nodesByPage.get(before.pageId) === key) nodesByPage.set(before.pageId, null);
1341
+ nodes.set(key, node);
1342
+ if (node) nodesByPage.set(node.pageId, key);
1343
+ this.#state.touched.add(key);
1344
+ }
1345
+ #storage(now) {
1346
+ const rows = () => this.#state.rows;
1347
+ const impl = {
1348
+ transaction: async (fn) => {
1349
+ const saved = copyState(this.#state);
1350
+ try {
1351
+ return await fn(this.storage);
1352
+ } catch (error) {
1353
+ this.#state = saved;
1354
+ throw error;
1355
+ }
1356
+ },
1357
+ getPage: async ({ id }) => this.#page(id),
1358
+ getPageParents: async ({ parentId }) => {
1359
+ const parents = [];
1360
+ let id = parentId;
1361
+ while (id && parents.length <= 10) {
1362
+ const page = this.#page(id);
1363
+ if (!page) break;
1364
+ parents.push(page);
1365
+ id = page.parentId;
1366
+ }
1367
+ return parents;
1368
+ },
1369
+ getPageByPath: async ({ scopeId, path }) => {
1370
+ if (path.length === 0) return null;
1371
+ const key = pathKey(scopeId, path);
1372
+ if (!rows().paths.has(key)) {
1373
+ this.missing.paths.set(key, {
1374
+ scopeId,
1375
+ path
1376
+ });
1377
+ throw new KnowledgeImportNotGatheredError(`path ${key}`);
1378
+ }
1379
+ const id = rows().paths.get(key);
1380
+ return id ? this.#page(id) : null;
1381
+ },
1382
+ lockPages: async (ids) => {
1383
+ const unlocked = ids.filter((id) => !rows().locked.has(id));
1384
+ if (unlocked.length) {
1385
+ for (const id of unlocked) this.missing.locks.add(id);
1386
+ throw new KnowledgeImportNotGatheredError(`locks ${unlocked.join(", ")}`);
1387
+ }
1388
+ },
1389
+ listNotes: async ({ pageId }) => {
1390
+ if (!rows().notes.has(pageId)) {
1391
+ this.missing.notes.add(pageId);
1392
+ throw new KnowledgeImportNotGatheredError(`notes of ${pageId}`);
1393
+ }
1394
+ return { notes: rows().notes.get(pageId).filter((note) => !note.deletedAt) };
1395
+ },
1396
+ createPage: async (input) => {
1397
+ if (input.id !== void 0 || input.position !== void 0) throw new KnowledgeImportBatchUnsupportedError("createPage with id or position");
1398
+ if (!input.name.trim()) throw new Error("Knowledge page name must not be empty");
1399
+ require_run_registry.assertKnowledgePageDescriptionWithinBound(input.description || void 0);
1400
+ const parent = this.#livePage(input.parentId);
1401
+ const scopeId = parent.isScope ? parent.id : parent.scopeId;
1402
+ const id = (0, crypto.randomUUID)();
1403
+ const depth = this.#depth(parent) + 1;
1404
+ if (depth > 10) throw new require_run_registry.KnowledgePageDepthError(id);
1405
+ let path = null;
1406
+ if (input.key !== void 0) {
1407
+ const problem = require_run_registry.knowledgePageKeyProblem(input.key);
1408
+ if (problem) throw new Error(problem);
1409
+ const parentKeys = parent.isScope ? {
1410
+ scopeId: parent.id,
1411
+ path: []
1412
+ } : this.#keys(parent);
1413
+ if (!parentKeys) throw new KnowledgeImportBatchUnsupportedError("createPage under a broken chain");
1414
+ path = [...parentKeys.path, input.key];
1415
+ if (await impl.getPageByPath({
1416
+ scopeId,
1417
+ path,
1418
+ read: "all"
1419
+ })) throw new require_run_registry.KnowledgePageKeyConflictError(input.key, parent.id);
1420
+ }
1421
+ if (input.key !== void 0 && this.#state.freed.has(childKey(parent.id, input.key))) throw new KnowledgeImportBatchUnsupportedError("createPage at a key a move left");
1422
+ const position = this.#nextPosition(parent.id);
1423
+ const at = now();
1424
+ const page = {
1425
+ id,
1426
+ scopeId,
1427
+ parentId: parent.id,
1428
+ isScope: false,
1429
+ ...input.key !== void 0 ? { key: input.key } : {},
1430
+ position,
1431
+ name: input.name,
1432
+ ...input.description ? { description: input.description } : {},
1433
+ ...input.body !== void 0 ? { body: input.body } : {},
1434
+ version: 1,
1435
+ createdBy: structuredClone(input.provenance),
1436
+ updatedBy: structuredClone(input.provenance),
1437
+ createdAt: at,
1438
+ updatedAt: at
1439
+ };
1440
+ const state = rows();
1441
+ this.#setPage(id, page);
1442
+ state.positions.set(parent.id, position);
1443
+ state.positions.set(id, null);
1444
+ state.notes.set(id, []);
1445
+ state.nodesByPage.set(id, null);
1446
+ state.locked.add(id);
1447
+ state.complete.add(id);
1448
+ if (path) state.paths.set(pathKey(scopeId, path), id);
1449
+ this.#state.writes.push({
1450
+ op: "create",
1451
+ id,
1452
+ scopeId,
1453
+ parentId: parent.id,
1454
+ ...input.key !== void 0 ? { key: input.key } : {},
1455
+ name: input.name,
1456
+ ...input.description !== void 0 ? { description: input.description } : {},
1457
+ ...input.body !== void 0 ? { body: input.body } : {},
1458
+ position,
1459
+ depth,
1460
+ provenance: input.provenance
1461
+ });
1462
+ return structuredClone(page);
1463
+ },
1464
+ updatePage: async (input) => {
1465
+ const page = this.#livePage(input.id);
1466
+ if (page.version !== input.expectedVersion) throw new require_run_registry.KnowledgeConflictError(page.id);
1467
+ if (input.name !== void 0 && !input.name.trim()) throw new Error("Knowledge page name must not be empty");
1468
+ require_run_registry.assertKnowledgePageDescriptionWithinBound(input.description || void 0);
1469
+ const next = {
1470
+ ...page,
1471
+ version: page.version + 1,
1472
+ updatedBy: structuredClone(input.provenance)
1473
+ };
1474
+ next.updatedAt = now();
1475
+ if (input.name !== void 0) next.name = input.name;
1476
+ if (input.description !== void 0) {
1477
+ if (input.description) next.description = input.description;
1478
+ else delete next.description;
1479
+ }
1480
+ if (input.body !== void 0) next.body = input.body;
1481
+ this.#setPage(page.id, next);
1482
+ this.#state.writes.push({
1483
+ op: "update",
1484
+ id: page.id,
1485
+ scopeId: page.scopeId,
1486
+ expectedVersion: input.expectedVersion,
1487
+ ...input.name !== void 0 ? { name: input.name } : {},
1488
+ ...input.description !== void 0 ? { description: input.description } : {},
1489
+ ...input.body !== void 0 ? { body: input.body } : {},
1490
+ provenance: input.provenance
1491
+ });
1492
+ return structuredClone(next);
1493
+ },
1494
+ listChildPages: async ({ parentId, read, cursor, limit }) => {
1495
+ if (read !== "all") throw new KnowledgeImportBatchUnsupportedError("listChildPages with a read scope");
1496
+ const children = this.#children(parentId);
1497
+ const start = cursor ? Number(cursor) : 0;
1498
+ const end = limit === void 0 ? children.length : start + limit;
1499
+ return {
1500
+ pages: children.slice(start, end).map((page) => structuredClone(page)),
1501
+ ...end < children.length ? { nextCursor: String(end) } : {}
1502
+ };
1503
+ },
1504
+ countChildPages: async ({ parentIds, read }) => {
1505
+ if (read !== "all") throw new KnowledgeImportBatchUnsupportedError("countChildPages with a read scope");
1506
+ return Object.fromEntries(parentIds.map((id) => [id, this.#children(id).length]));
1507
+ },
1508
+ lockSubtree: async (rootId) => {
1509
+ if (rows().tooLarge.has(rootId)) throw new require_run_registry.KnowledgeMoveTooLargeError(rootId, 501);
1510
+ const ids = [];
1511
+ const parents = [rootId];
1512
+ while (parents.length) {
1513
+ for (const child of this.#children(parents.shift())) {
1514
+ ids.push(child.id);
1515
+ parents.push(child.id);
1516
+ }
1517
+ if (ids.length >= 500) throw new require_run_registry.KnowledgeMoveTooLargeError(rootId, ids.length + 1);
1518
+ }
1519
+ const unlocked = ids.filter((id) => !rows().locked.has(id));
1520
+ if (unlocked.length) {
1521
+ for (const id of unlocked) this.missing.locks.add(id);
1522
+ throw new KnowledgeImportNotGatheredError(`locks ${unlocked.join(", ")}`);
1523
+ }
1524
+ return ids;
1525
+ },
1526
+ movePage: async (input) => {
1527
+ if (input.position !== void 0) throw new KnowledgeImportBatchUnsupportedError("movePage with a position");
1528
+ const page = this.#livePage(input.id);
1529
+ if (page.isScope) throw new Error(`Knowledge scope page ${page.id} can't be moved`);
1530
+ if (page.version !== input.expectedVersion) throw new require_run_registry.KnowledgeConflictError(page.id);
1531
+ const parent = this.#livePage(input.parentId);
1532
+ const subtree = [];
1533
+ const visit = (at, depth) => {
1534
+ subtree.push({
1535
+ page: at,
1536
+ depth
1537
+ });
1538
+ for (const child of this.#children(at.id)) visit(child, depth + 1);
1539
+ };
1540
+ visit(page, 0);
1541
+ if (subtree.some((entry) => entry.page.id === parent.id)) throw new Error(`Knowledge page ${page.id} can't move under itself or its own subtree`);
1542
+ if (subtree.length > 500) throw new require_run_registry.KnowledgeMoveTooLargeError(page.id, subtree.length);
1543
+ const parentDepth = parent.isScope ? 0 : this.#depth(parent);
1544
+ if (parentDepth + 1 + Math.max(...subtree.map((entry) => entry.depth)) > 10) throw new require_run_registry.KnowledgePageDepthError(page.id);
1545
+ const scopeId = parent.isScope ? parent.id : parent.scopeId;
1546
+ if (scopeId !== page.scopeId) throw new KnowledgeImportBatchUnsupportedError("movePage across scopes");
1547
+ if (page.key !== void 0) {
1548
+ const parentKeys = parent.isScope ? {
1549
+ scopeId: parent.id,
1550
+ path: []
1551
+ } : this.#keys(parent);
1552
+ if (!parentKeys) throw new KnowledgeImportBatchUnsupportedError("movePage under a broken chain");
1553
+ const clash = await impl.getPageByPath({
1554
+ scopeId,
1555
+ path: [...parentKeys.path, page.key],
1556
+ read: "all"
1557
+ });
1558
+ if (clash && clash.id !== page.id) throw new require_run_registry.KnowledgePageKeyConflictError(page.key, parent.id);
1559
+ }
1560
+ if (this.#state.moved.has(page.id)) throw new KnowledgeImportBatchUnsupportedError("a second move of a page");
1561
+ const position = this.#nextPosition(parent.id);
1562
+ const before = subtree.map((entry) => this.#keys(entry.page));
1563
+ const at = now();
1564
+ const moved = {
1565
+ ...page,
1566
+ parentId: parent.id,
1567
+ position,
1568
+ version: page.version + 1,
1569
+ updatedBy: structuredClone(input.provenance),
1570
+ updatedAt: at
1571
+ };
1572
+ const state = rows();
1573
+ this.#setPage(page.id, moved);
1574
+ state.positions.set(parent.id, position);
1575
+ this.#left(page.parentId, page.position);
1576
+ if (page.parentId && page.key !== void 0) this.#state.freed.add(childKey(page.parentId, page.key));
1577
+ this.#state.moved.add(page.id);
1578
+ this.#repath(subtree.map((entry) => state.pages.get(entry.page.id)), before);
1579
+ this.#state.writes.push({
1580
+ op: "move",
1581
+ id: page.id,
1582
+ fromScopeId: page.scopeId,
1583
+ expectedVersion: input.expectedVersion,
1584
+ parentId: parent.id,
1585
+ scopeId,
1586
+ depth: parentDepth + 1,
1587
+ position,
1588
+ provenance: input.provenance
1589
+ });
1590
+ return structuredClone(moved);
1591
+ },
1592
+ deletePage: async (input) => {
1593
+ const page = this.#livePage(input.id);
1594
+ if (page.isScope) throw new Error(`Knowledge scope page ${page.id} can't be deleted`);
1595
+ if (page.version !== input.expectedVersion) throw new require_run_registry.KnowledgeConflictError(page.id);
1596
+ if (this.#children(page.id).length) throw new require_run_registry.KnowledgePageHasChildrenError(page.id);
1597
+ const at = now();
1598
+ const deleted = {
1599
+ ...page,
1600
+ deletedAt: at,
1601
+ deletedBy: input.deletedBy,
1602
+ version: page.version + 1,
1603
+ updatedAt: at
1604
+ };
1605
+ this.#setPage(page.id, deleted);
1606
+ this.#left(page.parentId, page.position);
1607
+ for (const [key, id] of rows().paths) if (id === page.id) rows().paths.set(key, null);
1608
+ this.#state.writes.push({
1609
+ op: "delete",
1610
+ id: page.id,
1611
+ scopeId: page.scopeId,
1612
+ expectedVersion: input.expectedVersion,
1613
+ deletedBy: input.deletedBy
1614
+ });
1615
+ return structuredClone(deleted);
1616
+ },
1617
+ addNote: async (input) => {
1618
+ const page = this.#livePage(input.pageId);
1619
+ require_run_registry.assertKnowledgeNoteTextWithinBound(input.text);
1620
+ if (input.mentions.length) throw new KnowledgeImportBatchUnsupportedError("addNote with mentions");
1621
+ const notes = this.#notesOf(page.id);
1622
+ const id = input.id ?? (0, crypto.randomUUID)();
1623
+ if (notes.some((note) => note.id === id)) throw new require_run_registry.KnowledgeConflictError(id);
1624
+ const at = now();
1625
+ const note = {
1626
+ id,
1627
+ pageId: page.id,
1628
+ text: input.text,
1629
+ ...input.when ? { when: new Date(input.when) } : {},
1630
+ stampScopeIds: [...new Set(input.stampScopeIds)],
1631
+ mentions: [],
1632
+ provenance: structuredClone(input.provenance),
1633
+ version: 1,
1634
+ createdAt: at,
1635
+ updatedAt: at
1636
+ };
1637
+ rows().notes.set(page.id, [...notes, note]);
1638
+ this.#state.writes.push({
1639
+ op: "add-note",
1640
+ id,
1641
+ pageId: page.id,
1642
+ scopeId: page.scopeId,
1643
+ text: input.text,
1644
+ ...input.when ? { when: input.when } : {},
1645
+ stampScopeIds: input.stampScopeIds,
1646
+ mentions: [],
1647
+ provenance: input.provenance
1648
+ });
1649
+ return structuredClone(note);
1650
+ },
1651
+ removeNote: async (input) => {
1652
+ for (const [pageId, notes] of rows().notes) {
1653
+ const note = notes.find((each) => each.id === input.id);
1654
+ if (!note) continue;
1655
+ if (note.deletedAt) throw new require_run_registry.KnowledgeNotFoundError("note", input.id);
1656
+ if (this.#state.writes.some((write) => write.op === "add-note" && write.id === input.id)) throw new KnowledgeImportBatchUnsupportedError("removeNote of a note this flush added");
1657
+ const page = this.#livePage(pageId);
1658
+ const at = now();
1659
+ const removed = {
1660
+ ...note,
1661
+ deletedAt: at,
1662
+ deletedBy: input.deletedBy,
1663
+ version: note.version + 1,
1664
+ updatedAt: at
1665
+ };
1666
+ rows().notes.set(pageId, notes.map((each) => each.id === input.id ? removed : each));
1667
+ this.#state.writes.push({
1668
+ op: "remove-note",
1669
+ id: input.id,
1670
+ pageId,
1671
+ scopeId: page.scopeId,
1672
+ deletedBy: input.deletedBy,
1673
+ provenance: input.provenance
1674
+ });
1675
+ return structuredClone(removed);
1676
+ }
1677
+ throw new KnowledgeImportBatchUnsupportedError("removeNote of a note not gathered");
1678
+ }
1679
+ };
1680
+ return only(impl, "storage");
1681
+ }
1682
+ #notesOf(pageId) {
1683
+ const { notes } = this.#state.rows;
1684
+ if (!notes.has(pageId)) {
1685
+ this.missing.notes.add(pageId);
1686
+ throw new KnowledgeImportNotGatheredError(`notes of ${pageId}`);
1687
+ }
1688
+ return notes.get(pageId);
1689
+ }
1690
+ #importers() {
1691
+ const rows = () => this.#state.rows;
1692
+ return only({
1693
+ getNode: async (bindingId, sourceId) => structuredClone(this.#node(nodeKey(bindingId, sourceId))),
1694
+ getNodes: async (bindingId, sourceIds) => {
1695
+ const nodes = [];
1696
+ const unread = [...new Set(sourceIds)].filter((sourceId) => !rows().nodes.has(nodeKey(bindingId, sourceId)));
1697
+ if (unread.length) {
1698
+ for (const sourceId of unread) this.missing.nodes.add(nodeKey(bindingId, sourceId));
1699
+ throw new KnowledgeImportNotGatheredError(`nodes ${unread.join(", ")}`);
1700
+ }
1701
+ for (const sourceId of new Set(sourceIds)) {
1702
+ const node = rows().nodes.get(nodeKey(bindingId, sourceId));
1703
+ if (node) nodes.push(structuredClone(node));
1704
+ }
1705
+ return nodes;
1706
+ },
1707
+ getNodeByPage: async (pageId) => {
1708
+ if (!rows().nodesByPage.has(pageId)) {
1709
+ this.missing.nodesByPage.add(pageId);
1710
+ throw new KnowledgeImportNotGatheredError(`node of page ${pageId}`);
1711
+ }
1712
+ const key = rows().nodesByPage.get(pageId);
1713
+ return key ? structuredClone(this.#node(key)) : null;
1714
+ },
1715
+ saveNode: async (node) => {
1716
+ const key = nodeKey(node.bindingId, node.sourceId);
1717
+ const mapped = rows().nodesByPage.get(node.pageId);
1718
+ if (mapped === void 0) {
1719
+ this.missing.nodesByPage.add(node.pageId);
1720
+ throw new KnowledgeImportNotGatheredError(`node of page ${node.pageId}`);
1721
+ }
1722
+ if (mapped && mapped !== key) throw new KnowledgeImportBatchUnsupportedError("saveNode onto a mapped page");
1723
+ this.#setNode(key, {
1724
+ ...structuredClone(node),
1725
+ updatedAt: /* @__PURE__ */ new Date()
1726
+ });
1727
+ },
1728
+ deleteNode: async (bindingId, sourceId) => {
1729
+ const key = nodeKey(bindingId, sourceId);
1730
+ this.#node(key);
1731
+ this.#setNode(key, null);
1732
+ },
1733
+ markLinkingNodesUnsettled: async (bindingId, targetSourceIds) => {
1734
+ const targets = new Set(targetSourceIds);
1735
+ for (const [key, node] of rows().nodes) if (node && node.bindingId === bindingId && node.links.some((link) => targets.has(link.sourceId))) rows().nodes.set(key, {
1736
+ ...node,
1737
+ unsettled: true
1738
+ });
1739
+ const marks = this.#state.marks;
1740
+ const last = marks.at(-1);
1741
+ const prior = last && markTargets.get(last);
1742
+ const all = prior?.bindingId === bindingId ? [.../* @__PURE__ */ new Set([...prior.targets, ...targetSourceIds])] : [...targetSourceIds];
1743
+ if (prior?.bindingId === bindingId) marks.pop();
1744
+ const mark = (_, importers) => importers.markLinkingNodesUnsettled(bindingId, all);
1745
+ markTargets.set(mark, {
1746
+ bindingId,
1747
+ targets: all
1748
+ });
1749
+ marks.push(mark);
1750
+ },
1751
+ setState: async (bindingId, state) => {
1752
+ this.#state.marks.push((_, importers) => importers.setState(bindingId, state));
1753
+ },
1754
+ listLinkingNodes: async (bindingId, targetSourceIds, options = {}) => {
1755
+ const keys = [...new Set(targetSourceIds)].map((sourceId) => nodeKey(bindingId, sourceId));
1756
+ if (keys.some((key) => rows().tooManyLinkers.has(key))) throw new KnowledgeImportBatchUnsupportedError("listLinkingNodes past the gathered linking nodes");
1757
+ const unread = keys.filter((key) => !rows().linkTargets.has(key));
1758
+ if (unread.length) {
1759
+ for (const key of unread) this.missing.linkTargets.add(key);
1760
+ throw new KnowledgeImportNotGatheredError(`linking nodes of ${unread.join(", ")}`);
1761
+ }
1762
+ const targets = new Set(targetSourceIds);
1763
+ const ids = [...rows().nodes.values()].filter((node) => !!node && node.bindingId === bindingId && node.links.some((link) => targets.has(link.sourceId))).map((node) => node.sourceId).filter((id) => options.after === void 0 || byteOrder(id, options.after) > 0).sort(byteOrder);
1764
+ const limit = options.limit ?? 500;
1765
+ const items = ids.slice(0, limit);
1766
+ return {
1767
+ items,
1768
+ next: ids.length > limit ? items[items.length - 1] : null
1769
+ };
1770
+ },
1771
+ listBindings: async () => {
1772
+ const { bindings } = rows();
1773
+ if (!bindings) {
1774
+ this.missing.bindings.add("bindings");
1775
+ throw new KnowledgeImportNotGatheredError("bindings");
1776
+ }
1777
+ return structuredClone(bindings);
1778
+ }
1779
+ }, "importers");
1780
+ }
1781
+ };
1782
+ /** True when the stores implement every set-based method the batched flush needs. */
1783
+ function canBatchImportFlush(storage, importers) {
1784
+ return !!(storage.getPageChains && storage.getPagesByPaths && storage.getLastChildPositions && storage.listNotesByPages && storage.getPageSubtrees && storage.applyPageWrites && require_run_registry.canRepairKnowledgeLinksInBatch(storage) && importers.getNodes && importers.getNodesByPages && importers.writeNodes);
1785
+ }
1786
+ async function readImportRows(input) {
1787
+ const { storage, importers, bindingId, missing } = input;
1788
+ const rows = emptyImportOverlayRows();
1789
+ const sourceIds = new Set(input.sourceIds);
1790
+ for (const key of missing?.nodes ?? []) {
1791
+ const [binding, sourceId] = key.split("\0");
1792
+ if (binding === bindingId) sourceIds.add(sourceId);
1793
+ }
1794
+ const nodes = sourceIds.size ? await importers.getNodes(bindingId, [...sourceIds]) : [];
1795
+ for (const sourceId of sourceIds) rows.nodes.set(nodeKey(bindingId, sourceId), null);
1796
+ for (const node of nodes) {
1797
+ rows.nodes.set(nodeKey(node.bindingId, node.sourceId), node);
1798
+ rows.nodesByPage.set(node.pageId, nodeKey(node.bindingId, node.sourceId));
1799
+ }
1800
+ const addChains = async (ids) => {
1801
+ const wanted = [...ids].filter((id) => !rows.pages.has(id));
1802
+ if (!wanted.length) return;
1803
+ const chains = await storage.getPageChains({
1804
+ ids: wanted,
1805
+ read: "all"
1806
+ });
1807
+ for (const id of wanted) {
1808
+ const chain = chains[id] ?? [];
1809
+ if (!chain.length) rows.pages.set(id, null);
1810
+ for (const page of chain) rows.pages.set(page.id, page);
1811
+ const last = chain.at(-1);
1812
+ if (last?.parentId && chain.length <= 10 && !rows.pages.has(last.parentId)) rows.pages.set(last.parentId, null);
1813
+ }
1814
+ };
1815
+ await addChains(/* @__PURE__ */ new Set([
1816
+ ...input.pageIds,
1817
+ ...nodes.map((node) => node.pageId),
1818
+ ...missing?.pages ?? [],
1819
+ ...missing?.locks ?? []
1820
+ ]));
1821
+ const plan = input.plan(rows);
1822
+ const roots = [.../* @__PURE__ */ new Set([...plan.subtrees, ...missing?.subtrees ?? []])].filter((id) => !rows.complete.has(id));
1823
+ const carried = [];
1824
+ if (roots.length) {
1825
+ const subtrees = await storage.getPageSubtrees({
1826
+ rootIds: roots,
1827
+ limit: 499
1828
+ });
1829
+ for (const root of roots) {
1830
+ const pages = subtrees[root];
1831
+ if (!pages) {
1832
+ rows.tooLarge.add(root);
1833
+ continue;
1834
+ }
1835
+ rows.complete.add(root);
1836
+ for (const page of pages) {
1837
+ rows.pages.set(page.id, page);
1838
+ rows.complete.add(page.id);
1839
+ carried.push(page.id);
1840
+ }
1841
+ }
1842
+ const unmapped = carried.filter((id) => !rows.nodesByPage.has(id));
1843
+ if (unmapped.length) {
1844
+ for (const id of unmapped) rows.nodesByPage.set(id, null);
1845
+ for (const node of await importers.getNodesByPages(unmapped)) {
1846
+ const key = nodeKey(node.bindingId, node.sourceId);
1847
+ rows.nodes.set(key, node);
1848
+ rows.nodesByPage.set(node.pageId, key);
1849
+ }
1850
+ }
1851
+ }
1852
+ const targets = new Set(plan.linkTargets);
1853
+ for (const id of carried) {
1854
+ const key = rows.nodesByPage.get(id);
1855
+ const node = key ? rows.nodes.get(key) : null;
1856
+ if (node?.bindingId === bindingId) targets.add(node.sourceId);
1857
+ }
1858
+ for (const key of missing?.linkTargets ?? []) {
1859
+ const [binding, sourceId] = key.split("\0");
1860
+ if (binding === bindingId) targets.add(sourceId);
1861
+ }
1862
+ const wanted = [...targets].filter((sourceId) => !rows.linkTargets.has(nodeKey(bindingId, sourceId)));
1863
+ if (wanted.length) {
1864
+ const linking = await importers.listLinkingNodes(bindingId, wanted, { limit: LINKING_NODES_READ });
1865
+ for (const sourceId of wanted) (linking.next ? rows.tooManyLinkers : rows.linkTargets).add(nodeKey(bindingId, sourceId));
1866
+ const readNodes = async (sourceIds) => {
1867
+ const unread = [...new Set(sourceIds)].filter((sourceId) => !rows.nodes.has(nodeKey(bindingId, sourceId)));
1868
+ if (!unread.length) return [];
1869
+ for (const sourceId of unread) rows.nodes.set(nodeKey(bindingId, sourceId), null);
1870
+ const read = await importers.getNodes(bindingId, unread);
1871
+ for (const node of read) {
1872
+ rows.nodes.set(nodeKey(node.bindingId, node.sourceId), node);
1873
+ rows.nodesByPage.set(node.pageId, nodeKey(node.bindingId, node.sourceId));
1874
+ }
1875
+ return read;
1876
+ };
1877
+ const linkers = await readNodes(linking.items);
1878
+ const reached = await readNodes(linking.items.map((sourceId) => rows.nodes.get(nodeKey(bindingId, sourceId))).filter((n) => !!n).flatMap((node) => [...node.links.map((link) => link.sourceId), ...node.parentSourceId ? [node.parentSourceId] : []]));
1879
+ await addChains(new Set([...linkers, ...reached].map((node) => node.pageId)));
1880
+ }
1881
+ if (plan.bindings || missing?.bindings.size) rows.bindings ??= await importers.listBindings();
1882
+ const paths = new Map(plan.paths.map((each) => [pathKey(each.scopeId, each.path), each]));
1883
+ for (const [key, each] of missing?.paths ?? []) paths.set(key, each);
1884
+ const byScope = /* @__PURE__ */ new Map();
1885
+ for (const [key, { scopeId, path }] of paths) {
1886
+ if (path.length === 0) continue;
1887
+ byScope.set(scopeId, [...byScope.get(scopeId) ?? [], {
1888
+ key,
1889
+ path
1890
+ }]);
1891
+ }
1892
+ for (const [scopeId, entries] of byScope) {
1893
+ const found = await storage.getPagesByPaths({
1894
+ scopeId,
1895
+ paths: entries.map((each) => each.path),
1896
+ read: "all"
1897
+ });
1898
+ entries.forEach((each, i) => {
1899
+ const page = found[i] ?? null;
1900
+ rows.paths.set(each.key, page?.id ?? null);
1901
+ if (page && !rows.pages.has(page.id)) rows.pages.set(page.id, page);
1902
+ });
1903
+ }
1904
+ const held = [...rows.paths.values()].filter((id) => !!id);
1905
+ await addChains(new Set(held.map((id) => rows.pages.get(id)?.parentId).filter((id) => !!id)));
1906
+ const byPage = [...new Set([...held, ...missing?.nodesByPage ?? []].filter((id) => !rows.nodesByPage.has(id)))];
1907
+ if (byPage.length) {
1908
+ for (const id of byPage) rows.nodesByPage.set(id, null);
1909
+ for (const node of await importers.getNodesByPages(byPage)) {
1910
+ const key = nodeKey(node.bindingId, node.sourceId);
1911
+ rows.nodes.set(key, node);
1912
+ rows.nodesByPage.set(node.pageId, key);
1913
+ }
1914
+ }
1915
+ const notes = [.../* @__PURE__ */ new Set([
1916
+ ...plan.notes,
1917
+ ...held,
1918
+ ...missing?.notes ?? []
1919
+ ])];
1920
+ if (notes.length) {
1921
+ const listed = await storage.listNotesByPages({
1922
+ pageIds: notes,
1923
+ read: "all"
1924
+ });
1925
+ for (const id of notes) rows.notes.set(id, listed[id] ?? []);
1926
+ }
1927
+ const positions = [.../* @__PURE__ */ new Set([...plan.positions, ...missing?.positions ?? []])];
1928
+ if (positions.length) {
1929
+ const last = await storage.getLastChildPositions({ parentIds: positions });
1930
+ for (const id of positions) rows.positions.set(id, last[id] ?? null);
1931
+ }
1932
+ return rows;
1933
+ }
1934
+ /** Most linking nodes one gather reads; past it, a flush that lists them is saved op by op. */
1935
+ const LINKING_NODES_READ = 500;
1936
+ /** Live, non-scope pages among the rows: the ones a decide pass may lock. */
1937
+ const lockable = (rows) => [...rows.pages.values()].filter((page) => !!page && !page.isScope && !page.deletedAt && !page.mergedInto).map((page) => page.id);
1938
+ /**
1939
+ * Reads every row a decide pass needs in a few set-based queries, locks the live pages among them
1940
+ * in one sorted call, and reads again under the lock: what the second read returns can't change
1941
+ * until commit (a new page at an empty path is refused by the unique key when written). Pages the
1942
+ * second read finds that the first didn't are locked too, and read again, up to `rounds` times.
1943
+ */
1944
+ async function gatherImportRows(input) {
1945
+ const locked = new Set(input.locked ?? []);
1946
+ let rows = await readImportRows(input);
1947
+ for (let round = 0; round < (input.rounds ?? 3); round++) {
1948
+ const unlocked = lockable(rows).filter((id) => !locked.has(id));
1949
+ if (!unlocked.length) {
1950
+ rows.locked = locked;
1951
+ return rows;
1952
+ }
1953
+ await input.storage.lockPages(unlocked.sort());
1954
+ for (const id of unlocked) locked.add(id);
1955
+ rows = await readImportRows(input);
1956
+ }
1957
+ return null;
1958
+ }
1036
1959
  // src/knowledge/importers/sink.ts
1037
1960
  /**
1038
1961
  * Applies one flush's ops to pages and the node map, on a transaction view. Pages are found by id
@@ -1089,6 +2012,17 @@ const ownText = (body, section) => {
1089
2012
  if (body === section) return "";
1090
2013
  return body.endsWith(`\n\n${section}`) ? body.slice(0, body.length - section.length - 2) : null;
1091
2014
  };
2015
+ /** Decide passes a batched flush makes before it falls back: each reads what the last one lacked. */
2016
+ const BATCH_DECIDE_PASSES = 4;
2017
+ /** The batched flush can't land this one: its savepoint rolls back and the ops go one by one. */
2018
+ var BatchFallback = class extends Error {
2019
+ reason;
2020
+ constructor(reason) {
2021
+ super(`Batched import flush fell back: ${reason}`);
2022
+ this.reason = reason;
2023
+ this.name = "BatchFallback";
2024
+ }
2025
+ };
1092
2026
  /** A per-item refusal: its savepoint rolls back and the flush goes on. */
1093
2027
  var KnowledgeImportRefusalError = class extends Error {
1094
2028
  reason;
@@ -1184,7 +2118,27 @@ function order(ops) {
1184
2118
  return [...sorted, ...removes];
1185
2119
  }
1186
2120
  async function applyKnowledgeImportFlush(input) {
1187
- const { storage, importers, binding, scope, provenance } = input;
2121
+ const { binding, scope, provenance } = input;
2122
+ let { storage, importers } = input;
2123
+ let overlay = null;
2124
+ /**
2125
+ * Link-index work for a written page: a sync of its body links, then maybe a refresh of the links to
2126
+ * it. Run now, or after the batched write in one repair when deciding over the working copy.
2127
+ */
2128
+ const links = async (sync, refresh) => {
2129
+ if (overlay) {
2130
+ if (sync) overlay.deferLinks({ sync });
2131
+ for (const page of refresh?.pages ?? []) overlay.deferLinks({
2132
+ refresh: page,
2133
+ withDescendants: !!refresh.withDescendants
2134
+ });
2135
+ return;
2136
+ }
2137
+ await syncLinks(async () => {
2138
+ if (sync) await require_run_registry.syncKnowledgePageBodyLinks(storage, sync);
2139
+ if (refresh) await require_run_registry.refreshKnowledgeLinksTo(storage, refresh.pages, { withDescendants: refresh.withDescendants });
2140
+ });
2141
+ };
1188
2142
  const target = parseKnowledgeImportTarget(binding.target);
1189
2143
  const result = {
1190
2144
  counts: {
@@ -1436,7 +2390,7 @@ async function applyKnowledgeImportFlush(input) {
1436
2390
  });
1437
2391
  await importers.markLinkingNodesUnsettled(binding.id, [node.sourceId]);
1438
2392
  await importers.deleteNode(binding.id, node.sourceId);
1439
- if (old) await syncLinks(() => require_run_registry.refreshKnowledgeLinksTo(storage, [old]));
2393
+ if (old) await links(null, { pages: [old] });
1440
2394
  };
1441
2395
  const liveNodeOf = async (sourceId) => {
1442
2396
  const node = await nodeOf(sourceId);
@@ -1523,7 +2477,7 @@ async function applyKnowledgeImportFlush(input) {
1523
2477
  body,
1524
2478
  provenance
1525
2479
  });
1526
- await syncLinks(() => require_run_registry.syncKnowledgePageBodyLinks(storage, page));
2480
+ await links(page);
1527
2481
  return {
1528
2482
  page,
1529
2483
  changed: true,
@@ -1731,10 +2685,10 @@ async function applyKnowledgeImportFlush(input) {
1731
2685
  adopted,
1732
2686
  unsettled: misplaced || (rendered ? rendered.unresolved : existing?.unresolvedLinks ?? []).length > 0
1733
2687
  });
1734
- if (change !== "unchanged" || existing?.stub) await syncLinks(async () => {
1735
- await require_run_registry.syncKnowledgePageBodyLinks(storage, page);
1736
- if (change === "created" || renamed || moved) await require_run_registry.refreshKnowledgeLinksTo(storage, [page], { withDescendants: moved });
1737
- });
2688
+ if (change !== "unchanged" || existing?.stub) await links(page, change === "created" || renamed || moved ? {
2689
+ pages: [page],
2690
+ withDescendants: moved
2691
+ } : void 0);
1738
2692
  return {
1739
2693
  page,
1740
2694
  change,
@@ -1742,143 +2696,150 @@ async function applyKnowledgeImportFlush(input) {
1742
2696
  relinked
1743
2697
  };
1744
2698
  };
1745
- const depth = /* @__PURE__ */ new Map();
1746
- for (const op of ops) {
1747
- if (op.op !== "remove") continue;
1748
- const node = await importers.getNode(binding.id, op.sourceId);
1749
- const page = node ? await storage.getPage({
1750
- id: node.pageId,
1751
- read: "all"
1752
- }) : null;
1753
- const path = live(page) ? await keyPath(page) : null;
1754
- depth.set(op.sourceId, path?.keys.length ?? 0);
1755
- }
1756
- const writes = ops.filter((op) => op.op !== "remove");
1757
- const removes = ops.filter((op) => op.op === "remove").sort((a, b) => depth.get(b.sourceId) - depth.get(a.sourceId));
1758
- for (const op of [...writes, ...removes]) {
1759
- const sourceId = op.op === "remove" ? op.sourceId : op.item.sourceId;
1760
- const embeds = [];
1761
- try {
1762
- await storage.transaction(async () => {
1763
- if (op.op === "remove") {
1764
- const node = await importers.getNode(binding.id, sourceId);
1765
- if (!node) return;
1766
- const state = await stateOf(node);
1767
- if (state === "merged") return;
1768
- if (state === "gone") {
1769
- await forget(node);
2699
+ const runOps = async () => {
2700
+ const depth = /* @__PURE__ */ new Map();
2701
+ for (const op of ops) {
2702
+ if (op.op !== "remove") continue;
2703
+ const node = await importers.getNode(binding.id, op.sourceId);
2704
+ const page = node ? await storage.getPage({
2705
+ id: node.pageId,
2706
+ read: "all"
2707
+ }) : null;
2708
+ const path = live(page) ? await keyPath(page) : null;
2709
+ depth.set(op.sourceId, path?.keys.length ?? 0);
2710
+ }
2711
+ const writes = ops.filter((op) => op.op !== "remove");
2712
+ const removes = ops.filter((op) => op.op === "remove").sort((a, b) => depth.get(b.sourceId) - depth.get(a.sourceId));
2713
+ for (const op of [...writes, ...removes]) {
2714
+ const sourceId = op.op === "remove" ? op.sourceId : op.item.sourceId;
2715
+ const embeds = [];
2716
+ try {
2717
+ await storage.transaction(async () => {
2718
+ if (op.op === "remove") {
2719
+ const node = await importers.getNode(binding.id, sourceId);
2720
+ if (!node) return;
2721
+ const state = await stateOf(node);
2722
+ if (state === "merged") return;
2723
+ if (state === "gone") {
2724
+ await forget(node);
2725
+ result.applied = true;
2726
+ return;
2727
+ }
2728
+ const current = await owned(node.pageId, sourceId);
2729
+ await storage.lockSubtree(current.page.id);
2730
+ const children = (await storage.countChildPages({
2731
+ parentIds: [current.page.id],
2732
+ read: "all"
2733
+ }))[current.page.id] ?? 0;
2734
+ const folder = (await importers.listBindings()).some((other) => other.id !== binding.id && other.anchorPageId === current.page.id);
2735
+ if (children > 0 || node.adopted || folder) {
2736
+ if (node.stub) return;
2737
+ const note = node.adopted ? (await keptBodyNotes(current.page.id)).at(-1) : void 0;
2738
+ const heading = ORIGINAL_BODY_NOTE_HEADINGS.find((h) => note?.text.startsWith(h));
2739
+ const original = heading ? note.text.slice(heading.length) : note?.text;
2740
+ const page = await storage.updatePage({
2741
+ id: current.page.id,
2742
+ expectedVersion: current.page.version,
2743
+ body: original || (children > 0 ? "Removed from the source. Kept because pages are still nested under it." : folder ? "Removed from the source. Kept because another importer writes under it." : "Removed from the source. Kept because the page was here before the import."),
2744
+ provenance
2745
+ });
2746
+ await importers.saveNode({
2747
+ ...node,
2748
+ stub: true
2749
+ });
2750
+ await links(page);
2751
+ embeds.push({
2752
+ kind: "index",
2753
+ pageId: page.id
2754
+ });
2755
+ result.counts.stubbed++;
2756
+ result.changes.push({
2757
+ sourceId,
2758
+ pageId: page.id,
2759
+ change: "stubbed",
2760
+ title: page.name,
2761
+ path: ref(current.keys)
2762
+ });
2763
+ } else {
2764
+ const deleted = await storage.deletePage({
2765
+ id: current.page.id,
2766
+ expectedVersion: current.page.version,
2767
+ deletedBy: provenance.author
2768
+ });
2769
+ await importers.deleteNode(binding.id, sourceId);
2770
+ if ((await importers.listLinkingNodes(binding.id, [sourceId], { limit: 1 })).items.length > 0) {
2771
+ await importers.markLinkingNodesUnsettled(binding.id, [sourceId]);
2772
+ await importers.setState(binding.id, { [KNOWLEDGE_IMPORT_SETTLE_RESTART_KEY]: (0, crypto.randomUUID)() });
2773
+ deferredLinkers = true;
2774
+ }
2775
+ await links(deleted, { pages: [deleted] });
2776
+ embeds.push({
2777
+ kind: "remove",
2778
+ pageId: deleted.id
2779
+ });
2780
+ result.counts.removed++;
2781
+ result.changes.push({
2782
+ sourceId,
2783
+ pageId: null,
2784
+ change: "removed",
2785
+ title: deleted.name,
2786
+ path: ref(current.keys)
2787
+ });
2788
+ }
1770
2789
  result.applied = true;
1771
2790
  return;
1772
2791
  }
1773
- const current = await owned(node.pageId, sourceId);
1774
- await storage.lockSubtree(current.page.id);
1775
- const children = (await storage.countChildPages({
1776
- parentIds: [current.page.id],
1777
- read: "all"
1778
- }))[current.page.id] ?? 0;
1779
- const folder = (await importers.listBindings()).some((other) => other.id !== binding.id && other.anchorPageId === current.page.id);
1780
- if (children > 0 || node.adopted || folder) {
1781
- if (node.stub) return;
1782
- const note = node.adopted ? (await keptBodyNotes(current.page.id)).at(-1) : void 0;
1783
- const heading = ORIGINAL_BODY_NOTE_HEADINGS.find((h) => note?.text.startsWith(h));
1784
- const original = heading ? note.text.slice(heading.length) : note?.text;
1785
- const page = await storage.updatePage({
1786
- id: current.page.id,
1787
- expectedVersion: current.page.version,
1788
- body: original || (children > 0 ? "Removed from the source. Kept because pages are still nested under it." : folder ? "Removed from the source. Kept because another importer writes under it." : "Removed from the source. Kept because the page was here before the import."),
1789
- provenance
1790
- });
1791
- await importers.saveNode({
1792
- ...node,
1793
- stub: true
1794
- });
1795
- await syncLinks(() => require_run_registry.syncKnowledgePageBodyLinks(storage, page));
1796
- embeds.push({
1797
- kind: "index",
1798
- pageId: page.id
1799
- });
1800
- result.counts.stubbed++;
1801
- result.changes.push({
1802
- sourceId,
1803
- pageId: page.id,
1804
- change: "stubbed",
1805
- title: page.name,
1806
- path: ref(current.keys)
1807
- });
1808
- } else {
1809
- const deleted = await storage.deletePage({
1810
- id: current.page.id,
1811
- expectedVersion: current.page.version,
1812
- deletedBy: provenance.author
1813
- });
1814
- await importers.deleteNode(binding.id, sourceId);
1815
- if ((await importers.listLinkingNodes(binding.id, [sourceId], { limit: 1 })).items.length > 0) {
1816
- await importers.markLinkingNodesUnsettled(binding.id, [sourceId]);
1817
- await importers.setState(binding.id, { [KNOWLEDGE_IMPORT_SETTLE_RESTART_KEY]: (0, crypto.randomUUID)() });
1818
- deferredLinkers = true;
1819
- }
1820
- await syncLinks(async () => {
1821
- await require_run_registry.syncKnowledgePageBodyLinks(storage, deleted);
1822
- await require_run_registry.refreshKnowledgeLinksTo(storage, [deleted]);
1823
- });
1824
- embeds.push({
1825
- kind: "remove",
1826
- pageId: deleted.id
1827
- });
1828
- result.counts.removed++;
1829
- result.changes.push({
1830
- sourceId,
1831
- pageId: null,
1832
- change: "removed",
1833
- title: deleted.name,
1834
- path: ref(current.keys)
1835
- });
2792
+ const written = await write(op.item, op.op === "upsert");
2793
+ if (!written) {
2794
+ result.counts.merged++;
2795
+ return;
2796
+ }
2797
+ const { page, change, moved, relinked } = written;
2798
+ recordRelinked(relinked, embeds);
2799
+ if (change === "unchanged") {
2800
+ result.counts.unchanged++;
2801
+ return;
1836
2802
  }
1837
2803
  result.applied = true;
1838
- return;
1839
- }
1840
- const written = await write(op.item, op.op === "upsert");
1841
- if (!written) {
1842
- result.counts.merged++;
1843
- return;
1844
- }
1845
- const { page, change, moved, relinked } = written;
1846
- recordRelinked(relinked, embeds);
1847
- if (change === "unchanged") {
1848
- result.counts.unchanged++;
1849
- return;
1850
- }
1851
- result.applied = true;
1852
- if (change !== "moved") embeds.push({
1853
- kind: "index",
1854
- pageId: page.id
2804
+ if (change !== "moved") embeds.push({
2805
+ kind: "index",
2806
+ pageId: page.id
2807
+ });
2808
+ if (change === "created") result.counts.created++;
2809
+ else if (change === "updated") result.counts.updated++;
2810
+ if (moved) result.counts.moved++;
2811
+ const path = await keyPath(page);
2812
+ result.changes.push({
2813
+ sourceId,
2814
+ pageId: page.id,
2815
+ change,
2816
+ title: page.name,
2817
+ path: path ? ref(path.keys) : ""
2818
+ });
1855
2819
  });
1856
- if (change === "created") result.counts.created++;
1857
- else if (change === "updated") result.counts.updated++;
1858
- if (moved) result.counts.moved++;
1859
- const path = await keyPath(page);
1860
- result.changes.push({
2820
+ result.embeds.push(...embeds);
2821
+ } catch (error) {
2822
+ const reason = refusalFor(error);
2823
+ if (!reason) throw error;
2824
+ result.refused.push({
1861
2825
  sourceId,
1862
- pageId: page.id,
1863
- change,
1864
- title: page.name,
1865
- path: path ? ref(path.keys) : ""
2826
+ reason
1866
2827
  });
1867
- });
1868
- result.embeds.push(...embeds);
1869
- } catch (error) {
1870
- const reason = refusalFor(error);
1871
- if (!reason) throw error;
1872
- result.refused.push({
1873
- sourceId,
1874
- reason
1875
- });
2828
+ }
2829
+ }
2830
+ };
2831
+ if (!canBatchImportFlush(input.storage, input.importers)) await runOps();
2832
+ else if (ops.length) {
2833
+ const fallback = await applyBatched(anchor?.page ?? null);
2834
+ if (fallback) {
2835
+ result.fallback = fallback;
2836
+ await runOps();
1876
2837
  }
1877
2838
  }
1878
2839
  if (input.settle) {
1879
2840
  if (anchor) {
1880
2841
  input.settle.onStart?.();
1881
- result.settle = await settle(input.settle);
2842
+ result.settle = await settle(input.settle, anchor.page);
1882
2843
  } else result.settle = {
1883
2844
  pending: false,
1884
2845
  cursor: null,
@@ -1888,13 +2849,314 @@ async function applyKnowledgeImportFlush(input) {
1888
2849
  }
1889
2850
  return result;
1890
2851
  /**
2852
+ * Decides every op over a working copy (overlay.ts) and writes what they decided in a few
2853
+ * set-based statements, all in one savepoint (batched-flush plan v3.1). Returns why it fell back,
2854
+ * with the savepoint rolled back and the result as before, or null once the ops landed.
2855
+ */
2856
+ async function applyBatched(folder) {
2857
+ const writeOps = new Map(ops.flatMap((op) => op.op === "remove" ? [] : [[op.item.sourceId, op]]));
2858
+ const removed = ops.flatMap((op) => op.op === "remove" ? [op.sourceId] : []);
2859
+ const sourceIds = new Set(removed);
2860
+ for (const op of writeOps.values()) {
2861
+ sourceIds.add(op.item.sourceId);
2862
+ if (op.item.parent) sourceIds.add(op.item.parent);
2863
+ if (op.item.fallbackParent) sourceIds.add(op.item.fallbackParent);
2864
+ for (const link of ("links" in op.item ? op.item.links : void 0) ?? []) sourceIds.add(link.sourceId);
2865
+ }
2866
+ const plan = (rows) => {
2867
+ const keysOf = (page) => {
2868
+ const keys = [];
2869
+ for (let at = page; at && !at.isScope; at = at.parentId ? rows.pages.get(at.parentId) : null) {
2870
+ if (!live(at) || at.key === void 0) return null;
2871
+ keys.unshift(at.key);
2872
+ if (keys.length > 10) return null;
2873
+ }
2874
+ return keys;
2875
+ };
2876
+ const at = (sourceId, seen) => {
2877
+ if (!sourceId) return null;
2878
+ const node = rows.nodes.get(`${binding.id}\u0000${sourceId}`);
2879
+ const page = node ? rows.pages.get(node.pageId) : null;
2880
+ if (live(page ?? null) && page.scopeId === scope.id) {
2881
+ const keys = keysOf(page);
2882
+ if (keys) return {
2883
+ id: page.id,
2884
+ keys
2885
+ };
2886
+ }
2887
+ const op = writeOps.get(sourceId);
2888
+ if (!op || seen.has(sourceId)) return null;
2889
+ return {
2890
+ id: null,
2891
+ keys: [...destinationOf(op, /* @__PURE__ */ new Set([...seen, sourceId])).keys, knowledgeImportKey(sourceId)]
2892
+ };
2893
+ };
2894
+ const destinationOf = (op, seen) => at(op.item.parent, seen) ?? at(op.item.fallbackParent, seen) ?? {
2895
+ id: folder.id,
2896
+ keys: anchorPath
2897
+ };
2898
+ const out = {
2899
+ paths: [],
2900
+ positions: [],
2901
+ notes: [],
2902
+ subtrees: [],
2903
+ linkTargets: removed,
2904
+ bindings: removed.length > 0
2905
+ };
2906
+ const nodeAt = (sourceId) => rows.nodes.get(`${binding.id}\u0000${sourceId}`);
2907
+ const left = /* @__PURE__ */ new Set();
2908
+ for (const op of writeOps.values()) {
2909
+ const destination = destinationOf(op, /* @__PURE__ */ new Set([op.item.sourceId]));
2910
+ out.paths.push({
2911
+ scopeId: scope.id,
2912
+ path: [...destination.keys, knowledgeImportKey(op.item.sourceId)]
2913
+ });
2914
+ if (destination.id) out.positions.push(destination.id);
2915
+ const page = rows.pages.get(nodeAt(op.item.sourceId)?.pageId ?? "");
2916
+ if (live(page ?? null) && page.parentId !== destination.id) {
2917
+ out.subtrees.push(page.id);
2918
+ if (page.parentId) left.add(page.parentId);
2919
+ }
2920
+ }
2921
+ for (const id of out.positions) if (left.has(id)) out.subtrees.push(id);
2922
+ for (const sourceId of removed) {
2923
+ const node = nodeAt(sourceId);
2924
+ if (!node) continue;
2925
+ out.subtrees.push(node.pageId);
2926
+ if (node.adopted) out.notes.push(node.pageId);
2927
+ }
2928
+ for (const node of rows.nodes.values()) if (node?.stub && node.adopted) out.notes.push(node.pageId);
2929
+ return out;
2930
+ };
2931
+ return batchedOver(folder, sourceIds, plan, runOps);
2932
+ }
2933
+ /**
2934
+ * Runs `decide` over a working copy of the rows `plan` names, then writes what it decided in a few
2935
+ * set-based statements, all in one savepoint. Returns why it fell back, with the savepoint rolled
2936
+ * back and the result as before, or null once the writes landed.
2937
+ */
2938
+ async function batchedOver(folder, sourceIds, plan, decide) {
2939
+ const real = {
2940
+ storage: input.storage,
2941
+ importers: input.importers
2942
+ };
2943
+ const before = structuredClone(result);
2944
+ const deferredBefore = deferredLinkers;
2945
+ const reset = () => {
2946
+ const copy = structuredClone(before);
2947
+ Object.assign(result, copy);
2948
+ deferredLinkers = deferredBefore;
2949
+ };
2950
+ const missing = emptyImportOverlayMissing();
2951
+ let locked = /* @__PURE__ */ new Set();
2952
+ try {
2953
+ return await real.storage.transaction(async () => {
2954
+ for (let pass = 0; pass < BATCH_DECIDE_PASSES; pass++) {
2955
+ const rows = await gatherImportRows({
2956
+ storage: real.storage,
2957
+ importers: real.importers,
2958
+ bindingId: binding.id,
2959
+ sourceIds,
2960
+ pageIds: folder ? [folder.id] : [],
2961
+ plan,
2962
+ missing,
2963
+ locked
2964
+ });
2965
+ if (!rows) throw new BatchFallback("lock-churn");
2966
+ locked = rows.locked;
2967
+ const working = new ImportOverlay(rows);
2968
+ reset();
2969
+ overlay = working;
2970
+ storage = working.storage;
2971
+ importers = working.importers;
2972
+ try {
2973
+ await decide();
2974
+ } catch (error) {
2975
+ if (error instanceof KnowledgeImportNotGatheredError) {
2976
+ for (const [name, set] of Object.entries(working.missing)) {
2977
+ const into = missing[name];
2978
+ if (into instanceof Map) for (const [k, v] of set) into.set(k, v);
2979
+ else for (const k of set) into.add(k);
2980
+ }
2981
+ continue;
2982
+ }
2983
+ if (error instanceof KnowledgeImportBatchUnsupportedError) throw new BatchFallback(error.call);
2984
+ throw error;
2985
+ } finally {
2986
+ overlay = null;
2987
+ storage = real.storage;
2988
+ importers = real.importers;
2989
+ }
2990
+ try {
2991
+ if (working.writes.length) await real.storage.applyPageWrites({ writes: working.writes });
2992
+ } catch (error) {
2993
+ if (!refusalFor(error)) throw error;
2994
+ throw new BatchFallback(`page writes: ${error.name}`);
2995
+ }
2996
+ for (const work of working.marks) await work(real.storage, real.importers);
2997
+ const nodes = working.nodeWrites(rows);
2998
+ try {
2999
+ if (nodes.deletes.length || nodes.saves.length) await real.importers.writeNodes(nodes);
3000
+ } catch (error) {
3001
+ if (!refusalFor(error)) throw error;
3002
+ throw new BatchFallback(`node writes: ${error.name}`);
3003
+ }
3004
+ try {
3005
+ await require_run_registry.repairKnowledgeLinks(real.storage, {
3006
+ synced: working.links.flatMap((work) => "sync" in work ? [work.sync] : []),
3007
+ refreshed: working.links.flatMap((work) => "refresh" in work ? [{
3008
+ page: work.refresh,
3009
+ withDescendants: work.withDescendants
3010
+ }] : [])
3011
+ });
3012
+ } catch (error) {
3013
+ if (error instanceof require_run_registry.KnowledgeLinkRepairUnsupportedError) throw new BatchFallback(error.reason);
3014
+ if (error instanceof require_run_registry.KnowledgeUnsupportedCapabilityError) throw new BatchFallback(`link repair: ${error.name}`);
3015
+ throw error;
3016
+ }
3017
+ return null;
3018
+ }
3019
+ throw new BatchFallback("gather passes");
3020
+ });
3021
+ } catch (error) {
3022
+ if (!(error instanceof BatchFallback)) throw error;
3023
+ reset();
3024
+ return error.reason;
3025
+ }
3026
+ }
3027
+ /**
1891
3028
  * One settle slice (O3 §C, §C′): visits the binding's unsettled nodes after `budget.after`, each
1892
3029
  * in its own savepoint, moving a page under a source parent that has arrived since and writing
1893
3030
  * links whose targets now resolve. Stops at the candidate, move or time cap and leaves the rest
1894
3031
  * for the next slice. A node it can't settle (refused, or still waiting) is skipped and stays
1895
3032
  * unsettled; the pass ends when it reaches the last unsettled node.
1896
3033
  */
1897
- async function settle(budget) {
3034
+ async function settle(budget, folder) {
3035
+ if (!canBatchImportFlush(input.storage, input.importers)) return settleNodeByNode(budget);
3036
+ const fromStart = (budget.after ?? void 0) === void 0;
3037
+ const window = [];
3038
+ let cursor = budget.after ?? void 0;
3039
+ let end = false;
3040
+ while (window.length < budget.candidates) {
3041
+ const page = await input.importers.listNodes(binding.id, {
3042
+ unsettled: true,
3043
+ ...cursor !== void 0 ? { after: cursor } : {},
3044
+ limit: budget.candidates - window.length
3045
+ });
3046
+ window.push(...page.items);
3047
+ cursor = page.items.at(-1)?.sourceId ?? cursor;
3048
+ if (!page.next) {
3049
+ end = true;
3050
+ break;
3051
+ }
3052
+ }
3053
+ if (!window.length) return settleNodeByNode(budget);
3054
+ const parents = new Map((await input.importers.getNodes(binding.id, [...new Set(window.flatMap((node) => node.parentSourceId ? [node.parentSourceId] : []))])).map((node) => [node.sourceId, node]));
3055
+ const pages = new Map((await input.storage.getPages({
3056
+ ids: window.map((node) => node.pageId),
3057
+ read: "all"
3058
+ })).map((page) => [page.id, page]));
3059
+ const visit = [];
3060
+ const movers = [];
3061
+ for (const node of window) {
3062
+ visit.push(node);
3063
+ const parent = node.parentSourceId ? parents.get(node.parentSourceId) : void 0;
3064
+ const page = pages.get(node.pageId);
3065
+ if (parent && page && page.parentId !== parent.pageId) {
3066
+ movers.push({
3067
+ sourceId: node.sourceId,
3068
+ page,
3069
+ destination: parent.pageId
3070
+ });
3071
+ if (movers.length >= budget.moves) break;
3072
+ }
3073
+ }
3074
+ if (visit.length < window.length) end = false;
3075
+ const sourceIds = /* @__PURE__ */ new Set();
3076
+ for (const node of visit) {
3077
+ sourceIds.add(node.sourceId);
3078
+ if (node.parentSourceId) sourceIds.add(node.parentSourceId);
3079
+ for (const link of node.links) sourceIds.add(link.sourceId);
3080
+ }
3081
+ let outcome = null;
3082
+ const fallback = await batchedOver(folder, sourceIds, (rows) => ({
3083
+ paths: movers.flatMap((mover) => {
3084
+ const keys = [];
3085
+ for (let at = rows.pages.get(mover.destination); at && !at.isScope;) {
3086
+ if (at.key === void 0) return [];
3087
+ keys.unshift(at.key);
3088
+ at = at.parentId ? rows.pages.get(at.parentId) : null;
3089
+ }
3090
+ return mover.page.key === void 0 ? [] : [{
3091
+ scopeId: scope.id,
3092
+ path: [...keys, mover.page.key]
3093
+ }];
3094
+ }),
3095
+ positions: movers.map((mover) => mover.destination),
3096
+ notes: [],
3097
+ subtrees: movers.map((mover) => mover.page.id),
3098
+ linkTargets: movers.map((mover) => mover.sourceId),
3099
+ bindings: false
3100
+ }), async () => {
3101
+ outcome = await settleWindow(budget, visit, end, fromStart);
3102
+ });
3103
+ if (fallback === null && outcome) {
3104
+ const settledSlice = outcome;
3105
+ if (!settledSlice.pending && deferredLinkers) {
3106
+ if ((await input.importers.listNodes(binding.id, {
3107
+ unsettled: true,
3108
+ limit: 1
3109
+ })).items.length > 0) return {
3110
+ ...settledSlice,
3111
+ pending: true
3112
+ };
3113
+ }
3114
+ return settledSlice;
3115
+ }
3116
+ result.fallback = result.fallback ? `${result.fallback}; settle: ${fallback}` : `settle: ${fallback}`;
3117
+ return settleNodeByNode(budget);
3118
+ }
3119
+ /**
3120
+ * The node-by-node loop over a window read ahead, for the batched slice: the same caps, the same
3121
+ * savepoint per node, over the working copy.
3122
+ */
3123
+ async function settleWindow(budget, visit, end, fromStart) {
3124
+ let after = budget.after ?? void 0;
3125
+ let moves = 0;
3126
+ let settled = 0;
3127
+ const resumeAt = () => deferredLinkers ? null : after ?? null;
3128
+ for (const node of visit) {
3129
+ if (moves >= budget.moves || Date.now() >= budget.until) return {
3130
+ pending: true,
3131
+ cursor: resumeAt(),
3132
+ settled,
3133
+ fromStart
3134
+ };
3135
+ after = node.sourceId;
3136
+ const embeds = [];
3137
+ try {
3138
+ const outcome = await storage.transaction(() => settleNode(node.sourceId, embeds, moves < budget.moves));
3139
+ if (outcome.moved) moves++;
3140
+ if (outcome.moved || outcome.relinked) settled++;
3141
+ result.embeds.push(...embeds);
3142
+ } catch (error) {
3143
+ if (!refusalFor(error)) throw error;
3144
+ }
3145
+ }
3146
+ if (!end) return {
3147
+ pending: true,
3148
+ cursor: resumeAt(),
3149
+ settled,
3150
+ fromStart
3151
+ };
3152
+ return {
3153
+ pending: false,
3154
+ cursor: null,
3155
+ settled,
3156
+ fromStart
3157
+ };
3158
+ }
3159
+ async function settleNodeByNode(budget) {
1898
3160
  let after = budget.after ?? void 0;
1899
3161
  const fromStart = after === void 0;
1900
3162
  let examined = 0;
@@ -1987,7 +3249,10 @@ async function applyKnowledgeImportFlush(input) {
1987
3249
  ({page, keys, relinked: rewrote} = await moveOwned(sourceId, page, destination));
1988
3250
  recordRelinked(rewrote, embeds);
1989
3251
  moved = true;
1990
- await syncLinks(() => require_run_registry.refreshKnowledgeLinksTo(storage, [page], { withDescendants: true }));
3252
+ await links(null, {
3253
+ pages: [page],
3254
+ withDescendants: true
3255
+ });
1991
3256
  }
1992
3257
  } else if (parent) misplaced = true;
1993
3258
  const out = await relink(node, page);
@@ -2666,8 +3931,10 @@ function createLocalKnowledgeImporterHost(writer, options) {
2666
3931
  }
2667
3932
  let embeds = [];
2668
3933
  let settling = false;
3934
+ let fallbackWarning;
2669
3935
  try {
2670
3936
  const write = (deadlineAt) => storage.transaction(async (tx) => {
3937
+ fallbackWarning = void 0;
2671
3938
  const importers = tx.importers;
2672
3939
  const guard = await importers.lockWriterGuard(peek.firstWriteAt ? "share" : "update");
2673
3940
  const run = await importers.lockRun(flush.runId);
@@ -2712,6 +3979,7 @@ function createLocalKnowledgeImporterHost(writer, options) {
2712
3979
  }
2713
3980
  } } : {}
2714
3981
  });
3982
+ if (applied.fallback) fallbackWarning = `Knowledge importer: flush ${flush.seq} of run ${run.id} saved op by op instead of batched (${applied.fallback})`;
2715
3983
  const settled = applied.settle;
2716
3984
  const hostUpdates = {};
2717
3985
  if (settled && (settled.cursor ?? "") !== (hostState[SETTLE_CURSOR_KEY] ?? "")) hostUpdates[SETTLE_CURSOR_KEY] = settled.cursor ?? "";
@@ -2722,15 +3990,18 @@ function createLocalKnowledgeImporterHost(writer, options) {
2722
3990
  ...hostUpdates
2723
3991
  };
2724
3992
  if (Object.keys(state).length) await importers.setState(binding.id, state);
2725
- for (const change of applied.changes) await importers.recordRunChange({
3993
+ const changes = applied.changes.map((change) => ({
2726
3994
  runId: run.id,
2727
3995
  ...change
2728
- });
3996
+ }));
3997
+ if (importers.recordRunChanges) await importers.recordRunChanges(changes);
3998
+ else for (const change of changes) await importers.recordRunChange(change);
2729
3999
  const receipt = {
2730
4000
  seq: flush.seq,
2731
4001
  ...applied.counts,
2732
4002
  refused: applied.refused,
2733
- pending: settled?.pending ?? false
4003
+ pending: settled?.pending ?? false,
4004
+ ...applied.fallback ? { fallback: applied.fallback } : {}
2734
4005
  };
2735
4006
  await importers.recordFlush({
2736
4007
  runId: run.id,
@@ -2741,7 +4012,8 @@ function createLocalKnowledgeImporterHost(writer, options) {
2741
4012
  counts: {
2742
4013
  ...applied.counts,
2743
4014
  refused: applied.refused.length,
2744
- settled: settled?.settled ?? 0
4015
+ settled: settled?.settled ?? 0,
4016
+ ...applied.fallback ? { fallbacks: 1 } : {}
2745
4017
  }
2746
4018
  });
2747
4019
  if (applied.applied && !guard.firstWriteAt) await importers.markFirstWrite();
@@ -2756,6 +4028,7 @@ function createLocalKnowledgeImporterHost(writer, options) {
2756
4028
  if (attempt >= MAX_LEASE_BOUND_ATTEMPTS) throw new KnowledgeImporterHostError("The flush could not be bounded by its run lease; resend it.", 503);
2757
4029
  deadlineAt = Math.min(budgetAt, error.cutoff - LEASE_CUTOFF_MARGIN_MS);
2758
4030
  }
4031
+ if (fallbackWarning) writer.warn(fallbackWarning);
2759
4032
  await runEmbeds(storage, embeds);
2760
4033
  return receipt;
2761
4034
  } catch (error) {