@mastra/core 1.87.0-alpha.2 → 1.87.0-alpha.21

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 (775) hide show
  1. package/dist/_types/@ai-sdk_openai@4.0.106/dist/index.d.ts +2034 -0
  2. package/dist/_types/@ai-sdk_openai@4.0.106/package.json +1 -0
  3. package/dist/_types/@internal_ai-sdk-v4@0.0.99/dist/index.d.ts +1 -1
  4. package/dist/_types/@internal_ai-sdk-v5@0.0.99/dist/index.d.ts +1 -1
  5. package/dist/_types/@internal_ai-v6@0.0.99/dist/index.d.ts +2075 -123
  6. package/dist/_types/@internal_ai-v7@0.0.99/dist/index.d.ts +1 -1
  7. package/dist/_types/@internal_core@0.1.4/dist/knowledge-compat/index.d.ts +79 -3
  8. package/dist/_types/@internal_voice@0.0.48/dist/_types/@internal_ai-sdk-v5@0.0.99/dist/index.d.ts +1 -1
  9. package/dist/a2a/index.cjs +1 -1
  10. package/dist/a2a/index.js +1 -1
  11. package/dist/agent/active-run-signal-queues.d.ts +49 -0
  12. package/dist/agent/agent.d.ts +22 -6
  13. package/dist/agent/agent.types.d.ts +1 -0
  14. package/dist/agent/durable/abort-transport.d.ts +1 -1
  15. package/dist/agent/durable/durable-agent.d.ts +1 -0
  16. package/dist/agent/durable/execution-engine.d.ts +12 -0
  17. package/dist/agent/durable/index.cjs +86 -86
  18. package/dist/agent/durable/index.js +2 -2
  19. package/dist/agent/durable/preparation.d.ts +17 -0
  20. package/dist/agent/durable/run-message-refs.d.ts +3 -2
  21. package/dist/agent/durable/run-registry.d.ts +56 -25
  22. package/dist/agent/durable/stored-signal-drain.d.ts +100 -0
  23. package/dist/agent/durable/types.d.ts +43 -0
  24. package/dist/agent/durable/utils/resolve-runtime.d.ts +16 -0
  25. package/dist/agent/durable/utils/serialize-state.d.ts +1 -0
  26. package/dist/agent/durable/workflows/create-durable-agentic-workflow.d.ts +1 -0
  27. package/dist/agent/durable/workflows/durable-loop-builder.d.ts +5 -0
  28. package/dist/agent/durable/workflows/finalize-run.d.ts +7 -1
  29. package/dist/agent/durable/workflows/shared/message-list-state.d.ts +6 -2
  30. package/dist/agent/durable/workflows/shared/schemas.d.ts +2 -0
  31. package/dist/agent/durable/workflows/steps/llm-execution.d.ts +1 -0
  32. package/dist/agent/index.cjs +18 -17
  33. package/dist/agent/index.d.ts +3 -0
  34. package/dist/agent/index.js +6 -6
  35. package/dist/agent/merge-persona.d.ts +15 -0
  36. package/dist/agent/message-list/adapters/AIV5Adapter.d.ts +15 -1
  37. package/dist/agent/message-list/index.cjs +2 -2
  38. package/dist/agent/message-list/index.js +2 -2
  39. package/dist/agent/message-list/state/MessageStateManager.d.ts +5 -0
  40. package/dist/agent/message-list/state/types.d.ts +5 -1
  41. package/dist/agent/message-list/types.d.ts +1 -1
  42. package/dist/agent/message-list/utils/provider-compat.d.ts +9 -1
  43. package/dist/agent/scopes.d.ts +8 -0
  44. package/dist/agent/signals.d.ts +7 -3
  45. package/dist/agent/stored-run-signals.d.ts +93 -0
  46. package/dist/agent/stored-signals.d.ts +40 -0
  47. package/dist/agent/streams/abort-transport.d.ts +10 -1
  48. package/dist/agent/streams/constants.d.ts +9 -0
  49. package/dist/agent/streams/publisher.d.ts +3 -1
  50. package/dist/agent/thread-stream-runtime.d.ts +46 -4
  51. package/dist/agent/tool-name.d.ts +21 -0
  52. package/dist/agent/types.d.ts +1 -0
  53. package/dist/agent-builder/ee/index.cjs +1 -1
  54. package/dist/agent-builder/ee/index.js +1 -1
  55. package/dist/agent-controller/agent-controller.d.ts +14 -1
  56. package/dist/agent-controller/index.cjs +3 -3
  57. package/dist/agent-controller/index.js +3 -3
  58. package/dist/agent-controller/session.d.ts +38 -1
  59. package/dist/agent-controller/types.d.ts +6 -0
  60. package/dist/agent-controller/worker-run-binding.d.ts +15 -0
  61. package/dist/{agent-controller-v64JbuDa.cjs → agent-controller-4dz2FE2a.cjs} +181 -239
  62. package/dist/{agent-controller-Dc58ARqw.js → agent-controller-Cw5t1dkE.js} +159 -217
  63. package/dist/{agent-skills-resolver-BMoCDoaK.cjs → agent-skills-resolver-2d8k7ioj.cjs} +134 -109
  64. package/dist/{agent-skills-resolver-CUEIMDbx.js → agent-skills-resolver-D2HktP6Y.js} +134 -109
  65. package/dist/background-tasks/index.cjs +2 -1
  66. package/dist/background-tasks/index.d.ts +1 -1
  67. package/dist/background-tasks/index.js +1 -1
  68. package/dist/background-tasks/manager.d.ts +3 -1
  69. package/dist/background-tasks/resolve-config.d.ts +30 -1
  70. package/dist/background-tasks/system-prompt.d.ts +8 -2
  71. package/dist/background-tasks/types.d.ts +47 -1
  72. package/dist/background-tasks/workflow-id.d.ts +42 -0
  73. package/dist/{background-tasks-E-Jjxks4.js → background-tasks-DFDfV-FJ.js} +393 -59
  74. package/dist/{background-tasks-DgiQNKh7.cjs → background-tasks-fjEu5kC8.cjs} +428 -58
  75. package/dist/browser/index.cjs +17 -8
  76. package/dist/browser/index.js +17 -8
  77. package/dist/browser/processor.d.ts +1 -0
  78. package/dist/{builder-Dfp6Ckjr.cjs → builder-DrBUrE-F.cjs} +3 -3
  79. package/dist/{builder-Dh175HnQ.js → builder-la4Jv6di.js} +2 -2
  80. package/dist/capabilities/302ai.json +209 -209
  81. package/dist/capabilities/abacus.json +2 -96
  82. package/dist/capabilities/abliteratedllm.json +38 -29
  83. package/dist/capabilities/abliteration-ai.json +8 -8
  84. package/dist/capabilities/above.json +22 -22
  85. package/dist/capabilities/adaption.json +11 -11
  86. package/dist/capabilities/adzuki.json +23 -23
  87. package/dist/capabilities/agentrouter.json +10 -10
  88. package/dist/capabilities/agnes.json +4 -4
  89. package/dist/capabilities/ai-router.json +6 -6
  90. package/dist/capabilities/aiand.json +14 -31
  91. package/dist/capabilities/aigrow.json +14 -14
  92. package/dist/capabilities/aimlapi.json +151 -156
  93. package/dist/capabilities/aixy.json +13 -13
  94. package/dist/capabilities/aki-io.json +14 -14
  95. package/dist/capabilities/alibaba-cn.json +112 -115
  96. package/dist/capabilities/alibaba-coding-plan-cn.json +5 -10
  97. package/dist/capabilities/alibaba-coding-plan.json +5 -10
  98. package/dist/capabilities/alibaba-token-plan-cn.json +61 -57
  99. package/dist/capabilities/alibaba-token-plan.json +61 -57
  100. package/dist/capabilities/alibaba.json +126 -61
  101. package/dist/capabilities/ambient.json +13 -24
  102. package/dist/capabilities/amd-tokenlab.json +41 -0
  103. package/dist/capabilities/amd.json +9 -9
  104. package/dist/capabilities/anthropic.json +37 -61
  105. package/dist/capabilities/anyapi.json +20 -20
  106. package/dist/capabilities/apiko.json +4 -4
  107. package/dist/capabilities/arcee.json +11 -11
  108. package/dist/capabilities/augure.json +4 -4
  109. package/dist/capabilities/auriko.json +18 -18
  110. package/dist/capabilities/bailing.json +3 -3
  111. package/dist/capabilities/baseten.json +28 -28
  112. package/dist/capabilities/bee.json +4 -4
  113. package/dist/capabilities/berget.json +4 -24
  114. package/dist/capabilities/bothub.json +14 -14
  115. package/dist/capabilities/boundless.json +40 -40
  116. package/dist/capabilities/bumo.json +42 -42
  117. package/dist/capabilities/byteplus.json +30 -30
  118. package/dist/capabilities/cheapaimodel.json +6 -6
  119. package/dist/capabilities/cheapest-token.json +28 -28
  120. package/dist/capabilities/chutes.json +84 -5
  121. package/dist/capabilities/claudinio.json +10 -1
  122. package/dist/capabilities/cline-pass.json +36 -49
  123. package/dist/capabilities/cloudcode.json +10 -17
  124. package/dist/capabilities/cloudflare-workers-ai.json +17 -17
  125. package/dist/capabilities/commandcode.json +144 -159
  126. package/dist/capabilities/concentrate.json +286 -295
  127. package/dist/capabilities/cortecs.json +109 -109
  128. package/dist/capabilities/crossmodel.json +189 -189
  129. package/dist/capabilities/crusoe.json +38 -9
  130. package/dist/capabilities/daoxe.json +8 -8
  131. package/dist/capabilities/databricks.json +124 -124
  132. package/dist/capabilities/deepinfra.json +105 -86
  133. package/dist/capabilities/deepseek.json +3 -3
  134. package/dist/capabilities/digitalocean.json +117 -117
  135. package/dist/capabilities/dinference.json +1 -2
  136. package/dist/capabilities/dothoosh.json +31 -31
  137. package/dist/capabilities/doubleword.json +20 -20
  138. package/dist/capabilities/edenai.json +289 -292
  139. package/dist/capabilities/empiriolabs.json +178 -169
  140. package/dist/capabilities/engy.json +22 -22
  141. package/dist/capabilities/entrim.json +2 -2
  142. package/dist/capabilities/evroc.json +10 -10
  143. package/dist/capabilities/ezkielyna.json +8 -8
  144. package/dist/capabilities/fastrouter.json +88 -92
  145. package/dist/capabilities/fireworks-ai.json +128 -67
  146. package/dist/capabilities/fortytwo.json +9 -3
  147. package/dist/capabilities/freemodel.json +4 -48
  148. package/dist/capabilities/friendli.json +8 -8
  149. package/dist/capabilities/frogbot.json +98 -106
  150. package/dist/capabilities/gisoo.json +14 -14
  151. package/dist/capabilities/gmicloud.json +24 -24
  152. package/dist/capabilities/google.json +48 -48
  153. package/dist/capabilities/graphn.json +16 -16
  154. package/dist/capabilities/greenpt.json +36 -36
  155. package/dist/capabilities/groq.json +4 -17
  156. package/dist/capabilities/helicone.json +86 -88
  157. package/dist/capabilities/hetzner.json +35 -3
  158. package/dist/capabilities/hopper.json +2 -2
  159. package/dist/capabilities/hostinger-router.json +11 -18
  160. package/dist/capabilities/hpc-ai.json +10 -26
  161. package/dist/capabilities/huawei-maas.json +15 -15
  162. package/dist/capabilities/hubris.json +30 -30
  163. package/dist/capabilities/huggingface.json +112 -155
  164. package/dist/capabilities/humain.json +2 -2
  165. package/dist/capabilities/hyper.json +23 -31
  166. package/dist/capabilities/impossibl.json +138 -185
  167. package/dist/capabilities/inception.json +2 -2
  168. package/dist/capabilities/inceptron.json +6 -6
  169. package/dist/capabilities/inco.json +4 -21
  170. package/dist/capabilities/infer.json +19 -19
  171. package/dist/capabilities/inferall.json +0 -16
  172. package/dist/capabilities/inference-coop.json +11 -11
  173. package/dist/capabilities/inference.json +2 -11
  174. package/dist/capabilities/inferenceapis.json +12 -12
  175. package/dist/capabilities/inferris.json +2 -2
  176. package/dist/capabilities/infersia.json +9 -9
  177. package/dist/capabilities/inferx.json +2 -2
  178. package/dist/capabilities/infomaniak.json +4 -4
  179. package/dist/capabilities/io-net.json +3 -13
  180. package/dist/capabilities/isoquant.json +4 -4
  181. package/dist/capabilities/iteracompute.json +43 -81
  182. package/dist/capabilities/jalapeno.json +10 -10
  183. package/dist/capabilities/jiekou.json +22 -170
  184. package/dist/capabilities/jzstoken.json +57 -58
  185. package/dist/capabilities/keln.json +16 -16
  186. package/dist/capabilities/kenari.json +139 -123
  187. package/dist/capabilities/kilo.json +638 -667
  188. package/dist/capabilities/kimchi.json +90 -0
  189. package/dist/capabilities/kimi-code-plan-cn.json +5 -5
  190. package/dist/capabilities/kimi-code-plan-global.json +5 -5
  191. package/dist/capabilities/kitani.json +2 -2
  192. package/dist/capabilities/klavo.json +25 -25
  193. package/dist/capabilities/korouter.json +28 -28
  194. package/dist/capabilities/kunavo.json +8 -8
  195. package/dist/capabilities/liquid.json +13 -13
  196. package/dist/capabilities/lithosai.json +2 -2
  197. package/dist/capabilities/llmgateway-providers.json +941 -917
  198. package/dist/capabilities/llmgateway.json +344 -329
  199. package/dist/capabilities/llmtr.json +10 -48
  200. package/dist/capabilities/logits.json +2 -2
  201. package/dist/capabilities/longcat.json +2 -2
  202. package/dist/capabilities/lowrouter.json +54 -54
  203. package/dist/capabilities/lyceum.json +21 -13
  204. package/dist/capabilities/meganova.json +0 -1
  205. package/dist/capabilities/melious.json +17 -17
  206. package/dist/capabilities/merge-gateway.json +313 -298
  207. package/dist/capabilities/meta.json +9 -9
  208. package/dist/capabilities/mistral.json +15 -31
  209. package/dist/capabilities/mixlayer.json +4 -4
  210. package/dist/capabilities/moark.json +0 -2
  211. package/dist/capabilities/modal.json +9 -9
  212. package/dist/capabilities/model-oracle-ai.json +22 -30
  213. package/dist/capabilities/modelis.json +23 -23
  214. package/dist/capabilities/modular.json +29 -7
  215. package/dist/capabilities/moneo.json +4 -35
  216. package/dist/capabilities/moonshotai-cn.json +6 -6
  217. package/dist/capabilities/moonshotai.json +6 -6
  218. package/dist/capabilities/morph.json +21 -13
  219. package/dist/capabilities/munito-eu.json +4 -4
  220. package/dist/capabilities/munito.json +6 -6
  221. package/dist/capabilities/nan.json +26 -26
  222. package/dist/capabilities/nano-gpt.json +599 -592
  223. package/dist/capabilities/nearai.json +91 -91
  224. package/dist/capabilities/nebius.json +26 -27
  225. package/dist/capabilities/neon.json +129 -129
  226. package/dist/capabilities/neuralwatt.json +45 -45
  227. package/dist/capabilities/nokeep.json +5 -5
  228. package/dist/capabilities/novita-ai.json +124 -238
  229. package/dist/capabilities/nvidia.json +26 -67
  230. package/dist/capabilities/oathbreaker.json +25 -2
  231. package/dist/capabilities/obscurify.json +30 -30
  232. package/dist/capabilities/oci.json +7 -7
  233. package/dist/capabilities/ofox.json +216 -580
  234. package/dist/capabilities/ollama-cloud.json +57 -57
  235. package/dist/capabilities/openai.json +61 -61
  236. package/dist/capabilities/opencode-go.json +96 -88
  237. package/dist/capabilities/openrouter.json +541 -559
  238. package/dist/capabilities/opper.json +30 -35
  239. package/dist/capabilities/orcarouter.json +440 -241
  240. package/dist/capabilities/outerlabs.json +27 -27
  241. package/dist/capabilities/ovhcloud.json +20 -21
  242. package/dist/capabilities/pareto.json +2 -7
  243. package/dist/capabilities/perplexity-agent.json +113 -78
  244. package/dist/capabilities/perplexity.json +2 -2
  245. package/dist/capabilities/phala.json +35 -35
  246. package/dist/capabilities/pioneer.json +3 -120
  247. package/dist/capabilities/poe.json +127 -127
  248. package/dist/capabilities/poolside.json +2 -2
  249. package/dist/capabilities/powerspring.json +12 -12
  250. package/dist/capabilities/primalabs.json +7 -7
  251. package/dist/capabilities/prime.json +138 -120
  252. package/dist/capabilities/privatemode-ai.json +9 -37
  253. package/dist/capabilities/proxystacks.json +7 -7
  254. package/dist/capabilities/qihang-ai.json +3 -15
  255. package/dist/capabilities/qiniu-ai.json +13 -87
  256. package/dist/capabilities/refuseless.json +6 -13
  257. package/dist/capabilities/regolo-ai.json +8 -12
  258. package/dist/capabilities/requesty.json +442 -186
  259. package/dist/capabilities/routing-run.json +3 -40
  260. package/dist/capabilities/ruapi.json +33 -17
  261. package/dist/capabilities/runcrate.json +8 -8
  262. package/dist/capabilities/runinfra.json +12 -12
  263. package/dist/capabilities/sakana.json +2 -2
  264. package/dist/capabilities/sambanova.json +9 -9
  265. package/dist/capabilities/sandbase.json +25 -25
  266. package/dist/capabilities/sarvam.json +19 -10
  267. package/dist/capabilities/scaleway.json +20 -20
  268. package/dist/capabilities/scnet-token-plan.json +9 -9
  269. package/dist/capabilities/scx-ai.json +22 -38
  270. package/dist/capabilities/sensenova.json +12 -12
  271. package/dist/capabilities/siliconflow-cn.json +40 -74
  272. package/dist/capabilities/siliconflow.json +59 -59
  273. package/dist/capabilities/snowflake-cortex.json +17 -17
  274. package/dist/capabilities/sokkan.json +5 -17
  275. package/dist/capabilities/sparrowcodes.json +21 -21
  276. package/dist/capabilities/stackit.json +1 -2
  277. package/dist/capabilities/standardcompute.json +80 -116
  278. package/dist/capabilities/steadyrouter.json +42 -42
  279. package/dist/capabilities/stepfun-ai-step-plan.json +13 -7
  280. package/dist/capabilities/stepfun-ai.json +20 -6
  281. package/dist/capabilities/stepfun-step-plan.json +13 -6
  282. package/dist/capabilities/stepfun.json +20 -6
  283. package/dist/capabilities/stepping-stone.json +18 -18
  284. package/dist/capabilities/superbot-gg.json +4 -4
  285. package/dist/capabilities/synthetic.json +11 -20
  286. package/dist/capabilities/synthorai.json +24 -24
  287. package/dist/capabilities/teamorouter.json +24 -24
  288. package/dist/capabilities/teapot-router.json +9 -9
  289. package/dist/capabilities/tencent-token-plan-intl.json +126 -0
  290. package/dist/capabilities/tencent-token-plan.json +39 -39
  291. package/dist/capabilities/tencent-tokenhub.json +57 -42
  292. package/dist/capabilities/tensorx.json +47 -47
  293. package/dist/capabilities/tenstorrent.json +2 -2
  294. package/dist/capabilities/the-grid-ai.json +25 -25
  295. package/dist/capabilities/thinkingmachines.json +77 -77
  296. package/dist/capabilities/tinfoil.json +10 -10
  297. package/dist/capabilities/toapis.json +2 -2
  298. package/dist/capabilities/togetherai.json +45 -53
  299. package/dist/capabilities/tokengo.json +22 -22
  300. package/dist/capabilities/tokenharbor.json +738 -0
  301. package/dist/capabilities/tokenify.json +8 -8
  302. package/dist/capabilities/tokenwatt.json +10 -2
  303. package/dist/capabilities/trustedrouter.json +7 -7
  304. package/dist/capabilities/trustedtokens.json +16 -16
  305. package/dist/capabilities/umans-ai-coding-plan.json +14 -14
  306. package/dist/capabilities/umans-ai.json +9 -9
  307. package/dist/capabilities/unorouter.json +1 -22
  308. package/dist/capabilities/unrestricted.json +2 -18
  309. package/dist/capabilities/uplinkswitch.json +17 -17
  310. package/dist/capabilities/upstage.json +3 -15
  311. package/dist/capabilities/vancine.json +27 -27
  312. package/dist/capabilities/vercel.json +613 -584
  313. package/dist/capabilities/verda.json +8 -1
  314. package/dist/capabilities/vivgrid.json +60 -131
  315. package/dist/capabilities/volcengine-coding-plan.json +25 -25
  316. package/dist/capabilities/volcengine.json +27 -26
  317. package/dist/capabilities/vultr.json +12 -65
  318. package/dist/capabilities/wafer.ai.json +18 -18
  319. package/dist/capabilities/wallaby.json +4 -4
  320. package/dist/capabilities/wally.json +12 -12
  321. package/dist/capabilities/wandb.json +18 -18
  322. package/dist/capabilities/watt.json +22 -22
  323. package/dist/capabilities/xai.json +6 -6
  324. package/dist/capabilities/xiaomi-token-plan-ams.json +2 -2
  325. package/dist/capabilities/xiaomi-token-plan-cn.json +2 -2
  326. package/dist/capabilities/xiaomi-token-plan-sgp.json +2 -2
  327. package/dist/capabilities/xiaomi.json +2 -2
  328. package/dist/capabilities/xpersona.json +11 -11
  329. package/dist/capabilities/xxapi.json +28 -28
  330. package/dist/capabilities/zai-coding-plan.json +20 -20
  331. package/dist/capabilities/zai.json +39 -30
  332. package/dist/capabilities/zenifra.json +25 -25
  333. package/dist/capabilities/zenmux.json +165 -208
  334. package/dist/capabilities/zerogpu.json +12 -12
  335. package/dist/capabilities/zhipuai-coding-plan.json +5 -16
  336. package/dist/capabilities/zhipuai.json +45 -29
  337. package/dist/capabilities/zro.json +7 -7
  338. package/dist/channels/agent-channels.d.ts +22 -0
  339. package/dist/channels/index.cjs +24 -24
  340. package/dist/channels/index.js +2 -2
  341. package/dist/channels/output-processor.d.ts +12 -0
  342. package/dist/channels/reply-tool.d.ts +5 -1
  343. package/dist/channels/state-adapter.d.ts +3 -1
  344. package/dist/channels/stream-helpers.d.ts +17 -0
  345. package/dist/{channels-0AO7PMJF.js → channels-BUa-51eD.js} +2 -2
  346. package/dist/{channels-BZL9RT2i.cjs → channels-CqwRfJzZ.cjs} +6 -6
  347. package/dist/coding-agent/index.cjs +7 -7
  348. package/dist/coding-agent/index.js +4 -4
  349. package/dist/{constants-B9ZDvXZ4.cjs → constants-B2FVV_2e.cjs} +13 -1
  350. package/dist/{constants-BmdTvEYN.js → constants-Dro9fuhk.js} +13 -1
  351. package/dist/datasets/experiment/scorer.d.ts +16 -5
  352. package/dist/datasets/index.cjs +9 -9
  353. package/dist/datasets/index.js +2 -2
  354. package/dist/docs/SKILL.md +3 -1
  355. package/dist/docs/assets/SOURCE_MAP.json +1289 -1234
  356. package/dist/docs/references/docs-agents-code-mode.md +38 -2
  357. package/dist/docs/references/docs-agents-human-in-the-loop.md +2 -2
  358. package/dist/docs/references/docs-agents-networks.md +2 -2
  359. package/dist/docs/references/docs-agents-overview.md +15 -6
  360. package/dist/docs/references/docs-agents-processors.md +9 -9
  361. package/dist/docs/references/docs-agents-resumable-streams.md +2 -2
  362. package/dist/docs/references/docs-agents-structured-output.md +6 -6
  363. package/dist/docs/references/docs-agents-tools.md +15 -9
  364. package/dist/docs/references/docs-auth-simple-auth.md +8 -8
  365. package/dist/docs/references/docs-browser.md +4 -2
  366. package/dist/docs/references/docs-channels.md +5 -5
  367. package/dist/docs/references/docs-classifier.md +1 -1
  368. package/dist/docs/references/docs-connections-a2a.md +1 -1
  369. package/dist/docs/references/docs-connections-acp.md +2 -2
  370. package/dist/docs/references/docs-connections-overview.md +1 -1
  371. package/dist/docs/references/docs-connections-sdk-agents.md +6 -6
  372. package/dist/docs/references/docs-deployment-workers.md +2 -2
  373. package/dist/docs/references/docs-develop.md +1 -1
  374. package/dist/docs/references/docs-evals-custom-scorers.md +2 -2
  375. package/dist/docs/references/docs-evals-multi-turn.md +2 -2
  376. package/dist/docs/references/docs-guides-build-an-eval-loop.md +2 -2
  377. package/dist/docs/references/docs-guides-context-engineering.md +3 -3
  378. package/dist/docs/references/docs-guides-streaming.md +1 -1
  379. package/dist/docs/references/docs-harness-agent-controller.md +6 -3
  380. package/dist/docs/references/docs-harness-background-tasks.md +48 -7
  381. package/dist/docs/references/docs-harness-durable-agents.md +6 -5
  382. package/dist/docs/references/docs-harness-goals.md +2 -2
  383. package/dist/docs/references/docs-harness-schedules.md +35 -1
  384. package/dist/docs/references/docs-knowledge-agents-and-tools.md +4 -2
  385. package/dist/docs/references/docs-knowledge-importers.md +22 -1
  386. package/dist/docs/references/docs-knowledge-overview.md +1 -1
  387. package/dist/docs/references/docs-knowledge-scopes-and-access.md +1 -1
  388. package/dist/docs/references/docs-knowledge-search.md +1 -1
  389. package/dist/docs/references/docs-mastra-platform-observability-overview.md +3 -189
  390. package/dist/docs/references/docs-memory-memory-processors.md +8 -8
  391. package/dist/docs/references/docs-memory-message-history.md +30 -3
  392. package/dist/docs/references/docs-memory-observational-memory.md +1 -1
  393. package/dist/docs/references/docs-memory-semantic-recall.md +2 -2
  394. package/dist/docs/references/docs-memory-working-memory.md +3 -2
  395. package/dist/docs/references/docs-sandbox-lsp.md +5 -6
  396. package/dist/docs/references/docs-sandbox-overview.md +21 -1
  397. package/dist/docs/references/docs-sandbox-skills.md +3 -1
  398. package/dist/docs/references/docs-server-mastra-client.md +1 -1
  399. package/dist/docs/references/docs-server-mcp.md +23 -0
  400. package/dist/docs/references/docs-server-pubsub.md +22 -2
  401. package/dist/docs/references/docs-server-request-context.md +4 -4
  402. package/dist/docs/references/docs-signals-notifications.md +2 -2
  403. package/dist/docs/references/docs-signals-overview.md +1 -1
  404. package/dist/docs/references/docs-signals-running-across-processes.md +3 -0
  405. package/dist/docs/references/docs-signals-sending-signals.md +20 -7
  406. package/dist/docs/references/docs-signals-signal-providers.md +18 -2
  407. package/dist/docs/references/docs-signals-state-signals.md +1 -0
  408. package/dist/docs/references/docs-signals-thread-streams.md +12 -0
  409. package/dist/docs/references/docs-skills.md +8 -5
  410. package/dist/docs/references/docs-storage.md +12 -12
  411. package/dist/docs/references/docs-studio-editor.md +2 -2
  412. package/dist/docs/references/docs-subagents.md +26 -3
  413. package/dist/docs/references/docs-workflows-overview.md +2 -0
  414. package/dist/docs/references/integrations-agentic-ui-copilotkit.md +1 -1
  415. package/dist/docs/references/integrations-agentic-ui-openui.md +1 -1
  416. package/dist/docs/references/integrations-channels-discord.md +1 -1
  417. package/dist/docs/references/integrations-channels-github.md +1 -1
  418. package/dist/docs/references/integrations-channels-imessage.md +2 -2
  419. package/dist/docs/references/integrations-channels-ring.md +2 -2
  420. package/dist/docs/references/integrations-channels-slack.md +1 -1
  421. package/dist/docs/references/integrations-channels-teams.md +1 -1
  422. package/dist/docs/references/integrations-channels-telegram.md +1 -1
  423. package/dist/docs/references/integrations-channels-whatsapp.md +1 -1
  424. package/dist/docs/references/integrations-tools-firecrawl.md +1 -1
  425. package/dist/docs/references/integrations.md +1 -0
  426. package/dist/docs/references/reference-acp-acp-agent.md +1 -1
  427. package/dist/docs/references/reference-acp-create-acp-tool.md +1 -1
  428. package/dist/docs/references/reference-agent-controller-agent-controller-class.md +3 -1
  429. package/dist/docs/references/reference-agent-controller-session.md +55 -8
  430. package/dist/docs/references/reference-agents-agent.md +40 -14
  431. package/dist/docs/references/reference-agents-channels.md +11 -11
  432. package/dist/docs/references/reference-agents-createSkill.md +20 -1
  433. package/dist/docs/references/reference-agents-durable-agent.md +2 -2
  434. package/dist/docs/references/reference-agents-generate.md +1 -1
  435. package/dist/docs/references/reference-agents-getLLM.md +2 -2
  436. package/dist/docs/references/reference-agents-getMetadata.md +2 -2
  437. package/dist/docs/references/reference-agents-network.md +3 -3
  438. package/dist/docs/references/reference-browser-mastra-browser.md +1 -1
  439. package/dist/docs/references/reference-channels-thread-link.md +1 -1
  440. package/dist/docs/references/reference-classifier-classifier.md +2 -0
  441. package/dist/docs/references/reference-coding-agent-build-base-prompt.md +1 -1
  442. package/dist/docs/references/reference-coding-agent-create-coding-agent.md +7 -7
  443. package/dist/docs/references/reference-configuration.md +15 -14
  444. package/dist/docs/references/reference-core-getAgentById.md +1 -1
  445. package/dist/docs/references/reference-core-getWorkspaceById.md +37 -0
  446. package/dist/docs/references/reference-core-mastra-model-gateway.md +1 -1
  447. package/dist/docs/references/reference-datasets-startExperiment.md +1 -1
  448. package/dist/docs/references/reference-editor-mastra-editor.md +2 -2
  449. package/dist/docs/references/reference-evals-create-scorer.md +5 -5
  450. package/dist/docs/references/reference-evals-run-evals.md +1 -1
  451. package/dist/docs/references/reference-file-based-agents-config.md +3 -3
  452. package/dist/docs/references/reference-file-based-agents-schedules.md +1 -1
  453. package/dist/docs/references/reference-file-based-agents-subagents.md +3 -3
  454. package/dist/docs/references/reference-file-based-agents-workspace.md +1 -1
  455. package/dist/docs/references/reference-knowledge-knowledge-class.md +12 -0
  456. package/dist/docs/references/reference-knowledge-knowledge-tools.md +4 -5
  457. package/dist/docs/references/reference-knowledge-limits.md +16 -16
  458. package/dist/docs/references/reference-manual-install.md +2 -2
  459. package/dist/docs/references/reference-memory-memory-class.md +3 -3
  460. package/dist/docs/references/reference-memory-observational-memory.md +15 -3
  461. package/dist/docs/references/reference-observability-metrics-metrics-context.md +63 -3
  462. package/dist/docs/references/reference-observability-tracing-bridges-datadog.md +12 -11
  463. package/dist/docs/references/reference-observability-tracing-configuration.md +2 -2
  464. package/dist/docs/references/reference-observability-tracing-exporters-datadog.md +14 -12
  465. package/dist/docs/references/reference-observability-tracing-interfaces.md +10 -6
  466. package/dist/docs/references/reference-processors-batch-parts-processor.md +1 -1
  467. package/dist/docs/references/reference-processors-classifier-processor.md +2 -2
  468. package/dist/docs/references/reference-processors-cyber-refusal-handler.md +1 -1
  469. package/dist/docs/references/reference-processors-language-detector.md +1 -1
  470. package/dist/docs/references/reference-processors-message-history-processor.md +1 -1
  471. package/dist/docs/references/reference-processors-model-selection-processor.md +3 -3
  472. package/dist/docs/references/reference-processors-moderation-processor.md +4 -4
  473. package/dist/docs/references/reference-processors-pii-detector.md +2 -2
  474. package/dist/docs/references/reference-processors-prefill-error-handler.md +2 -2
  475. package/dist/docs/references/reference-processors-processor-interface.md +22 -10
  476. package/dist/docs/references/reference-processors-prompt-injection-detector.md +1 -1
  477. package/dist/docs/references/reference-processors-provider-history-compat.md +1 -1
  478. package/dist/docs/references/reference-processors-response-cache.md +1 -1
  479. package/dist/docs/references/reference-processors-semantic-recall-processor.md +1 -1
  480. package/dist/docs/references/reference-processors-skill-search-processor.md +1 -1
  481. package/dist/docs/references/reference-processors-skills-processor.md +1 -1
  482. package/dist/docs/references/reference-processors-stream-error-retry-processor.md +3 -3
  483. package/dist/docs/references/reference-processors-system-prompt-scrubber.md +2 -2
  484. package/dist/docs/references/reference-processors-token-limiter-processor.md +3 -3
  485. package/dist/docs/references/reference-processors-tool-call-filter.md +2 -2
  486. package/dist/docs/references/reference-processors-tool-search-processor.md +6 -6
  487. package/dist/docs/references/reference-processors-unicode-normalizer.md +1 -1
  488. package/dist/docs/references/reference-processors-working-memory-processor.md +1 -1
  489. package/dist/docs/references/reference-pubsub-base.md +6 -4
  490. package/dist/docs/references/reference-pubsub-caching-pubsub.md +3 -1
  491. package/dist/docs/references/reference-pubsub-redis-streams.md +3 -5
  492. package/dist/docs/references/reference-pubsub-valkey-streams.md +2 -2
  493. package/dist/docs/references/reference-rag-chunking-and-embedding.md +1 -1
  494. package/dist/docs/references/reference-rag-graph-rag-guide.md +2 -2
  495. package/dist/docs/references/reference-rag-retrieval.md +13 -13
  496. package/dist/docs/references/reference-signals-create-notification-inbox-tool.md +1 -1
  497. package/dist/docs/references/reference-signals-time-signal-provider.md +137 -0
  498. package/dist/docs/references/reference-storage-composite.md +4 -0
  499. package/dist/docs/references/reference-storage-overview.md +30 -30
  500. package/dist/docs/references/reference-storage-retention.md +20 -20
  501. package/dist/docs/references/reference-templates-overview.md +31 -1
  502. package/dist/docs/references/reference-tools-create-code-mode.md +23 -1
  503. package/dist/docs/references/reference-tools-vector-query-tool.md +11 -3
  504. package/dist/docs/references/reference-voice-overview.md +39 -54
  505. package/dist/docs/references/reference-voice-speech-to-speech.md +11 -11
  506. package/dist/docs/references/reference-voice-speech-to-text.md +1 -1
  507. package/dist/docs/references/reference-voice-text-to-speech.md +1 -1
  508. package/dist/docs/references/reference-voice-voice.addInstructions.md +1 -1
  509. package/dist/docs/references/reference-voice-voice.listen.md +2 -1
  510. package/dist/docs/references/reference-voice-voice.speak.md +1 -3
  511. package/dist/docs/references/reference-workers-overview.md +3 -1
  512. package/dist/docs/references/reference-workflows-run-methods-restart.md +2 -0
  513. package/dist/docs/references/reference-workflows-step.md +1 -1
  514. package/dist/docs/references/reference-workflows-workflow-methods-map.md +1 -1
  515. package/dist/docs/references/reference-workflows-workflow.md +1 -1
  516. package/dist/docs/references/reference-workspace-factory-sandbox.md +8 -6
  517. package/dist/docs/references/reference-workspace-local-filesystem.md +1 -1
  518. package/dist/docs/references/reference-workspace-local-sandbox.md +1 -1
  519. package/dist/docs/references/reference-workspace-sandbox.md +14 -0
  520. package/dist/docs/references/reference.md +3 -0
  521. package/dist/evals/index.cjs +13 -13
  522. package/dist/evals/index.js +2 -2
  523. package/dist/evals/scoreTraces/index.cjs +4 -4
  524. package/dist/evals/scoreTraces/index.js +2 -2
  525. package/dist/events/index.cjs +2 -2
  526. package/dist/events/index.js +2 -2
  527. package/dist/events/pubsub.d.ts +1 -3
  528. package/dist/{run-registry-lLRc7EE6.cjs → execution-fence-DeR5VB54.cjs} +13789 -9619
  529. package/dist/{run-registry-DhOKJtlb.js → execution-fence-Yl_-iJxn.js} +14769 -10677
  530. package/dist/harness/index.cjs +3 -3
  531. package/dist/harness/index.js +3 -3
  532. package/dist/index.cjs +1 -1
  533. package/dist/index.d.ts +1 -0
  534. package/dist/index.js +1 -1
  535. package/dist/integration/index.cjs +1 -1
  536. package/dist/integration/index.js +1 -1
  537. package/dist/knowledge/agent-scopes.d.ts +17 -0
  538. package/dist/knowledge/declarations.d.ts +2 -0
  539. package/dist/knowledge/held-scopes-state-processor.d.ts +50 -0
  540. package/dist/knowledge/importers/overlay.d.ts +170 -0
  541. package/dist/knowledge/importers/sink.d.ts +17 -1
  542. package/dist/knowledge/importers/types.d.ts +16 -0
  543. package/dist/knowledge/index.cjs +2156 -290
  544. package/dist/knowledge/index.d.ts +18 -2
  545. package/dist/knowledge/index.js +2043 -179
  546. package/dist/knowledge/links.d.ts +27 -0
  547. package/dist/knowledge/page-tools.d.ts +25 -0
  548. package/dist/knowledge/pinned-state-processor.d.ts +2 -2
  549. package/dist/knowledge/run.d.ts +5 -0
  550. package/dist/knowledge/scope-runtime.d.ts +6 -0
  551. package/dist/llm/index.cjs +3 -3
  552. package/dist/llm/index.js +3 -3
  553. package/dist/llm/model/base.types.d.ts +3 -1
  554. package/dist/llm/model/gateways/opencode-session-header.d.ts +28 -0
  555. package/dist/llm/model/mastra-gateway-provider-tools.d.ts +9 -6
  556. package/dist/llm/model/model.d.ts +1 -1
  557. package/dist/llm/model/model.loop.d.ts +1 -1
  558. package/dist/llm/model/model.loop.types.d.ts +3 -1
  559. package/dist/llm/model/provider-options.d.ts +4 -3
  560. package/dist/llm/model/provider-types.generated.d.ts +7426 -7631
  561. package/dist/llm/model/resolve-model.d.ts +1 -0
  562. package/dist/llm/model/shared.types.d.ts +1 -0
  563. package/dist/llm/reasoning/anthropic-thinking.d.ts +5 -0
  564. package/dist/llm/reasoning/gemini-thinking.d.ts +24 -0
  565. package/dist/llm/reasoning/index.cjs +389 -0
  566. package/dist/llm/reasoning/index.d.ts +8 -0
  567. package/dist/llm/reasoning/index.js +362 -0
  568. package/dist/llm/reasoning/model-fallback.d.ts +75 -0
  569. package/dist/llm/reasoning/model-ids.d.ts +5 -0
  570. package/dist/llm/reasoning/thinking-provider-options.d.ts +10 -0
  571. package/dist/llm/reasoning/thinking-request.d.ts +14 -0
  572. package/dist/llm/reasoning/thinking.d.ts +37 -0
  573. package/dist/{llm-B46V7Mi7.js → llm-BZQdtNe1.js} +68 -90
  574. package/dist/{llm-B4AeSFvV.cjs → llm-DVQKutUM.cjs} +68 -90
  575. package/dist/loop/index.cjs +15 -15
  576. package/dist/loop/index.js +2 -2
  577. package/dist/loop/loop-runtime.d.ts +1 -1
  578. package/dist/loop/server.cjs +1 -1
  579. package/dist/loop/server.js +1 -1
  580. package/dist/loop/shared/signal-outcome.d.ts +1 -1
  581. package/dist/loop/shared/steps/signal-drain-core.d.ts +9 -3
  582. package/dist/{manager-BwDxA1Nn.cjs → manager-Cr0lJZSV.cjs} +124 -51
  583. package/dist/{manager-BRAvwB9b.js → manager-CxN9r6o4.js} +112 -39
  584. package/dist/mastra/index.cjs +1 -1
  585. package/dist/mastra/index.d.ts +35 -4
  586. package/dist/mastra/index.js +1 -1
  587. package/dist/{mastra-CIx6qEq2.js → mastra-CsuV_iVH.js} +84 -28
  588. package/dist/{mastra-DBhdD172.cjs → mastra-D4Q2NPsZ.cjs} +124 -68
  589. package/dist/memory/index.cjs +25 -25
  590. package/dist/memory/index.js +3 -3
  591. package/dist/memory/mock.d.ts +2 -3
  592. package/dist/memory/om-events/index.cjs +189 -0
  593. package/dist/memory/om-events/index.d.ts +17 -0
  594. package/dist/memory/om-events/index.js +188 -0
  595. package/dist/{message-list-DfN9mWeN.cjs → message-list-C0F2sDNC.cjs} +233 -131
  596. package/dist/{message-list-wI71UGxk.js → message-list-RgFlLrxG.js} +233 -131
  597. package/dist/{model-CJMsDU8w.js → model-CIV_1-kW.js} +5 -4
  598. package/dist/{model-CYhAa5qO.cjs → model-DOqga9dt.cjs} +5 -4
  599. package/dist/{netlify-C9aJA6Cv.js → netlify-CoThk6uD.js} +31257 -20278
  600. package/dist/{netlify-Bw7Vd58y.cjs → netlify-KyTDrIQP.cjs} +41446 -30449
  601. package/dist/notifications/index.cjs +18 -18
  602. package/dist/notifications/index.js +2 -2
  603. package/dist/observability/index.cjs +1 -1
  604. package/dist/observability/index.js +1 -1
  605. package/dist/observability/types/tracing.d.ts +1 -1
  606. package/dist/{observability-D7RNOAPx.js → observability-DPDWibyH.js} +648 -648
  607. package/dist/{output-helpers-DgsH4aTb.cjs → output-helpers-By5FbLpp.cjs} +71 -73
  608. package/dist/{output-helpers-CVzhy1Y0.js → output-helpers-k2-48ssH.js} +72 -74
  609. package/dist/processor-provider/index.cjs +10 -10
  610. package/dist/processor-provider/index.js +1 -1
  611. package/dist/processors/index.cjs +65 -65
  612. package/dist/processors/index.js +2 -2
  613. package/dist/processors/processors/tool-search.d.ts +2 -2
  614. package/dist/processors/runner.d.ts +12 -0
  615. package/dist/{provider-registry-DOfYSEju.js → provider-registry-BIXG21H8.js} +20767 -21397
  616. package/dist/{provider-registry-Bn_7VvZ8.cjs → provider-registry-BsphJbPb.cjs} +20765 -21395
  617. package/dist/provider-registry.json +21391 -22106
  618. package/dist/{registry-generator-BnK5Npgr.cjs → registry-generator-BBmRjrp4.cjs} +1 -1
  619. package/dist/{registry-generator-Cw594Ttt.js → registry-generator-BXZzqm-j.js} +1 -1
  620. package/dist/{rehydrate-Dgqkw7Py.js → rehydrate-BwfL5GuU.js} +2 -2
  621. package/dist/{rehydrate-BWnd_TEx.cjs → rehydrate-tjUWtbB-.cjs} +14 -14
  622. package/dist/relevance/index.cjs +3 -3
  623. package/dist/relevance/index.js +2 -2
  624. package/dist/{scheduler-B-VZUvv_.js → scheduler-0ShtMM1I.js} +71 -21
  625. package/dist/{scheduler-D00X03jQ.cjs → scheduler-CMjK0LoQ.cjs} +82 -20
  626. package/dist/server/types.d.ts +6 -0
  627. package/dist/{signal-provider-BslnAjWG.js → signal-provider-B_mfW-J4.js} +1 -1
  628. package/dist/{signal-provider-BFAvh_AJ.cjs → signal-provider-D9gbevHN.cjs} +1 -1
  629. package/dist/signals/index.cjs +4 -3
  630. package/dist/signals/index.d.ts +1 -0
  631. package/dist/signals/index.js +4 -4
  632. package/dist/signals/time-signal-provider.d.ts +70 -0
  633. package/dist/signals-BwDXGqxc.cjs +358 -0
  634. package/dist/signals-TznxWfM3.js +347 -0
  635. package/dist/skills/create-skill.d.ts +3 -0
  636. package/dist/skills/index.cjs +1 -1
  637. package/dist/skills/index.js +1 -1
  638. package/dist/skills/inline-skill-source.d.ts +5 -1
  639. package/dist/skills/types.d.ts +16 -1
  640. package/dist/{source-fNa6u1kH.js → source-B3He4_mz.js} +7 -0
  641. package/dist/{source-BVOi8Xhp.cjs → source-C_nWbqI0.cjs} +7 -0
  642. package/dist/{state-processor-B9kxpM53.js → state-processor-B_KsS82m.js} +1 -1
  643. package/dist/{state-processor-kRNZ38Nf.cjs → state-processor-DaSmhVUX.cjs} +1 -1
  644. package/dist/storage/constants.cjs +1 -1
  645. package/dist/storage/constants.js +1 -1
  646. package/dist/storage/domains/agents/index.cjs +1 -1
  647. package/dist/storage/domains/agents/index.js +1 -1
  648. package/dist/storage/domains/inmemory-db.d.ts +6 -0
  649. package/dist/storage/domains/knowledge/base.d.ts +155 -5
  650. package/dist/storage/domains/knowledge/importers-inmemory.d.ts +10 -0
  651. package/dist/storage/domains/knowledge/importers.d.ts +39 -0
  652. package/dist/storage/domains/knowledge/inmemory.d.ts +12 -0
  653. package/dist/storage/domains/knowledge/pages-inmemory.d.ts +54 -12
  654. package/dist/storage/domains/knowledge/pages.d.ts +90 -1
  655. package/dist/storage/domains/memory/base.d.ts +117 -0
  656. package/dist/storage/domains/memory/index.d.ts +1 -0
  657. package/dist/storage/domains/memory/inmemory.d.ts +39 -0
  658. package/dist/storage/domains/memory/queue-thread.d.ts +42 -0
  659. package/dist/storage/domains/schedules/base.d.ts +31 -2
  660. package/dist/storage/domains/schedules/inmemory.d.ts +9 -2
  661. package/dist/storage/domains/workflows/base.d.ts +32 -5
  662. package/dist/storage/domains/workflows/inmemory.d.ts +7 -6
  663. package/dist/storage/domains/workflows/journal.d.ts +16 -1
  664. package/dist/storage/index.cjs +192 -186
  665. package/dist/storage/index.js +6 -6
  666. package/dist/storage/types.d.ts +14 -0
  667. package/dist/storage/workflow-snapshot.d.ts +4 -0
  668. package/dist/storage/workflow-step-guard.d.ts +5 -0
  669. package/dist/stream/base/output.d.ts +8 -0
  670. package/dist/stream/index.cjs +2 -2
  671. package/dist/stream/index.js +2 -2
  672. package/dist/{stream-BIDts1fZ.cjs → stream-C4XcOMuS.cjs} +179 -22
  673. package/dist/{stream-C8HKG3qC.js → stream-Dgsrva80.js} +138 -23
  674. package/dist/telemetry/index.cjs +1 -1
  675. package/dist/telemetry/index.js +1 -1
  676. package/dist/test-utils/llm-mock.cjs +1 -1
  677. package/dist/test-utils/llm-mock.js +1 -1
  678. package/dist/{to-prompt-B9eZo2U5.cjs → to-prompt-CG-LyaBY.cjs} +9 -0
  679. package/dist/{to-prompt-BsDtVXrf.js → to-prompt-CMlVGYxC.js} +9 -0
  680. package/dist/{tool-Z3bykc1m.js → tool-DIFduuTw.js} +2 -5
  681. package/dist/{tool-CYlT2UA-.cjs → tool-Dn9WSDVn.cjs} +2 -5
  682. package/dist/tool-loop-agent/index.cjs +1 -1
  683. package/dist/tool-loop-agent/index.js +1 -1
  684. package/dist/{tool-loop-agent-DM5V_0XS.js → tool-loop-agent-DN4C3VpR.js} +4 -4
  685. package/dist/{tool-loop-agent-PEY5a1R6.cjs → tool-loop-agent-Dze-IJOx.cjs} +5 -5
  686. package/dist/{toolchecks-DrsZdc3S.js → toolchecks-CRAfUe9H.js} +1 -1
  687. package/dist/{toolchecks-MFU48cit.cjs → toolchecks-DbBsQGHW.cjs} +1 -1
  688. package/dist/tools/code-mode/index.d.ts +2 -0
  689. package/dist/tools/code-mode/log-collector.d.ts +49 -0
  690. package/dist/tools/code-mode/types.d.ts +71 -0
  691. package/dist/tools/index.cjs +7 -5
  692. package/dist/tools/index.d.ts +1 -0
  693. package/dist/tools/index.js +6 -6
  694. package/dist/tools/is-vercel-tool.cjs +1 -1
  695. package/dist/tools/is-vercel-tool.js +1 -1
  696. package/dist/tools/tool.d.ts +2 -4
  697. package/dist/tools/types.d.ts +1 -0
  698. package/dist/{tools-CGF5Ik6j.cjs → tools-C2q0ougI.cjs} +430 -62
  699. package/dist/{tools-CDfyMpzN.js → tools-ybbz1YKg.js} +419 -63
  700. package/dist/{utils-CxMSu_wc.cjs → utils-AfuTYtPM.cjs} +12 -10
  701. package/dist/{utils-DcnKVK34.js → utils-B-UrrqES.js} +12 -10
  702. package/dist/utils.cjs +3 -3
  703. package/dist/utils.js +3 -3
  704. package/dist/{validate-RVKgazCf.cjs → validate-GzP07CVb.cjs} +1 -1
  705. package/dist/{validate-Dn750ciE.js → validate-zLPo00kk.js} +1 -1
  706. package/dist/vector/index.cjs +9 -9
  707. package/dist/vector/index.js +2 -2
  708. package/dist/worker/index.cjs +1 -1
  709. package/dist/worker/index.js +1 -1
  710. package/dist/worker/workers/orchestration-worker.d.ts +1 -0
  711. package/dist/{worker-SDi9jbP5.js → worker-BYQGN5Lh.js} +12 -7
  712. package/dist/{worker-Dx0ZHMGX.cjs → worker-ChLwyYHR.cjs} +3 -3
  713. package/dist/{worker-DJPAdazC.js → worker-DP_A9d7f.js} +2 -2
  714. package/dist/{worker-CFPu9qwV.cjs → worker-J6-CpZ0n.cjs} +25 -14
  715. package/dist/{workflow-ZFOz_365.cjs → workflow-COgwqQxL.cjs} +30 -38
  716. package/dist/{workflow-DkBqNn7X.js → workflow-DqV0r2P-.js} +26 -34
  717. package/dist/workflows/builder/index.cjs +1 -1
  718. package/dist/workflows/builder/index.js +1 -1
  719. package/dist/workflows/evented/execution-engine.d.ts +3 -1
  720. package/dist/workflows/evented/index.cjs +10 -10
  721. package/dist/workflows/evented/index.js +1 -1
  722. package/dist/workflows/evented/setup-warning.d.ts +11 -0
  723. package/dist/workflows/evented/workflow-event-processor/index.d.ts +10 -4
  724. package/dist/workflows/evented/workflow-event-processor/loop.d.ts +1 -1
  725. package/dist/workflows/evented/workflow-event-processor/parallel.d.ts +2 -2
  726. package/dist/workflows/evented/workflow-event-processor/sleep.d.ts +2 -2
  727. package/dist/workflows/evented/workflow.d.ts +8 -3
  728. package/dist/workflows/handlers/entry.d.ts +8 -0
  729. package/dist/workflows/index.cjs +57 -55
  730. package/dist/workflows/index.js +6 -6
  731. package/dist/workflows/run-storage.d.ts +27 -3
  732. package/dist/workflows/scheduler/claim.d.ts +51 -0
  733. package/dist/workflows/scheduler/index.d.ts +2 -0
  734. package/dist/workflows/step.d.ts +2 -0
  735. package/dist/workflows/types.d.ts +16 -0
  736. package/dist/workflows/workflow.d.ts +90 -11
  737. package/dist/workspace/filesystem/local-filesystem.d.ts +13 -0
  738. package/dist/workspace/index.cjs +3 -1
  739. package/dist/workspace/index.d.ts +1 -1
  740. package/dist/workspace/index.js +2 -2
  741. package/dist/workspace/lsp/manager.d.ts +19 -4
  742. package/dist/workspace/sandbox/local-sandbox.d.ts +11 -0
  743. package/dist/workspace/sandbox/mastra-sandbox.d.ts +17 -0
  744. package/dist/workspace/sandbox/sandbox.d.ts +2 -0
  745. package/dist/workspace/sandbox/teardown-context.d.ts +74 -0
  746. package/dist/workspace/tools/index.d.ts +1 -0
  747. package/dist/workspace/tools/media.d.ts +20 -1
  748. package/dist/workspace/tools/recreate-sandbox.d.ts +24 -0
  749. package/dist/{workspace-X2RHJZU9.cjs → workspace-BQD4tcQi.cjs} +614 -135
  750. package/dist/{workspace-DY2Nxiyi.js → workspace-sqcfdZRR.js} +602 -135
  751. package/llm/reasoning.d.ts +1 -0
  752. package/memory/om-events.d.ts +1 -0
  753. package/package.json +30 -9
  754. package/skills/mastra/SKILL.md +171 -0
  755. package/skills/mastra/references/common-errors.md +557 -0
  756. package/skills/mastra/references/core-concepts.md +21 -0
  757. package/skills/mastra/references/create-mastra.md +233 -0
  758. package/skills/mastra/references/embedded-docs.md +103 -0
  759. package/skills/mastra/references/feedback.md +69 -0
  760. package/skills/mastra/references/gateway.md +66 -0
  761. package/skills/mastra/references/mastra-api.md +222 -0
  762. package/skills/mastra/references/migration-guide.md +185 -0
  763. package/skills/mastra/references/model-selection.md +29 -0
  764. package/skills/mastra/references/platform.md +164 -0
  765. package/skills/mastra/references/remote-docs.md +193 -0
  766. package/skills/mastra/references/trace-query.md +150 -0
  767. package/skills/mastra/scripts/provider-registry.mjs +271 -0
  768. package/src/llm/model/provider-types.generated.d.ts +7426 -7631
  769. package/dist/capabilities/ai21.json +0 -4
  770. package/dist/capabilities/clarifai.json +0 -42
  771. package/dist/capabilities/jad-ai.json +0 -20
  772. package/dist/capabilities/llmtech.json +0 -16
  773. package/dist/signals-B1JSj-Ew.cjs +0 -58
  774. package/dist/signals-De9VnwL2.js +0 -53
  775. package/dist/{observability-B0R_D1PZ.cjs → observability-VaoaeadK.cjs} +647 -647
@@ -1,7 +1,8 @@
1
1
  import { t as MastraBase } from "../base-CKLWBhDo.js";
2
- import { $t as knowledgeDeliveredPins, Ai as MAX_KNOWLEDGE_PAGE_BODY_LINKS, Bi as knowledgeLinkRefKey, Ci as parseKnowledgeWikilinks, Cn as knowledgeRunScopes, Di as KnowledgePageKeyConflictError, Dn as encodeKnowledgeScopeId, Ei as KnowledgePageHasChildrenError, En as decodeKnowledgeScopeId, Fi as MAX_KNOWLEDGE_PAGE_LIST_LIMIT, Gi as parseKnowledgePageRef, Hi as knowledgePinDepth, Ii as MAX_KNOWLEDGE_PIN_LIST_DEPTH, Ki as KnowledgeInvalidCursorError, Li as assertKnowledgeNoteTextWithinBound, Mi as MAX_KNOWLEDGE_PAGE_DESCRIPTION_TOKENS, Ni as MAX_KNOWLEDGE_PAGE_LINKS, Oi as MAX_KNOWLEDGE_MOVE_PAGES, On as buildKnowledgeInstructions, Pi as MAX_KNOWLEDGE_PAGE_LINK_REF_LENGTH, Qt as PINNED_READ_MEMO_KEY, Ri as assertKnowledgePageDescriptionWithinBound, Si as inspectKnowledgeSchema, Sn as knowledgeMemoryScopes, Ti as KnowledgePageDepthError, Tn as strongerKnowledgeRole, Ui as knowledgePositionBetween, Uo as augmentWithInit, Vi as knowledgePagePath, Wi as knowledgeScopeReadable, Wo as getStorageSource, _i as KnowledgeStorage, _n as knowledgeAccessGrants, _r as knowledgeScopeKey, an as removeKnowledgeNote, bi as assertKnowledgeSchemaCompatible, bn as KnowledgeDeclarationError, br as knowledgeVisibleScopeKeys, ci as InMemoryKnowledgeStorage, cn as upsertKnowledgePage, cr as MAX_KNOWLEDGE_SCOPE_TAGS, di as KnowledgeImportersStorage, dn as KnowledgeLinkRefreshIncompleteError, dr as assertKnowledgeRecordTextWithinBound, en as buildKnowledgePageTools, fi as KNOWLEDGE_STORAGE_CONTRACT_VERSION, fn as knowledgeSubtree, fr as assertKnowledgeScopeWithinCeiling, gi as KnowledgeSchemaResetRequiredError, gn as updateKnowledgeLinks, gr as isKnowledgeScopeVisible, hi as KnowledgeNotFoundError, hn as syncKnowledgePageBodyLinks, hr as expandKnowledgeScope, in as moveKnowledgePage, ji as MAX_KNOWLEDGE_PAGE_DEPTH, ki as MAX_KNOWLEDGE_NOTE_TOKENS, li as KnowledgeImporterBindingConflictError, ln as KnowledgeSemanticIndex, lr as assertKnowledgeCeilingRaised, mi as KnowledgeConflictError, mn as reindexKnowledgeLinks, mr as createKnowledgeNodeCursor, nn as knowledgeRunPrincipals, on as removeKnowledgePage, or as MAX_KNOWLEDGE_NODE_DESCRIPTION_LENGTH, pi as KNOWLEDGE_STORAGE_SCHEMA_VERSION, pn as refreshKnowledgeLinksTo, pr as canonicalizeKnowledgeScope, rn as addKnowledgeNote, sn as updateKnowledgeNote, sr as MAX_KNOWLEDGE_RECORD_TEXT_LENGTH, tn as KnowledgeRun, ui as KnowledgeImporterRunStateError, ur as assertKnowledgeDescriptionWithinBound, vi as KnowledgeTransactionDeadlineError, vn as knowledgeReadScopeFor, vr as knowledgeSemanticDocumentId, wi as KnowledgeMoveTooLargeError, wn as knowledgeScopeAddress, xi as createKnowledgeUlid, xn as compileKnowledgeScopes, xr as parseKnowledgeNodeCursor, yi as KnowledgeUnsupportedCapabilityError, yn as knowledgeRoleOn, yr as knowledgeSemanticIdempotencyKey, zi as canonicalKnowledgeName } from "../run-registry-DhOKJtlb.js";
2
+ import { $n as assertKnowledgeCeilingRaised, $r as KnowledgeImporterBindingConflictError, $t as KnowledgeLinkRepairUnsupportedError, Ai as knowledgeLinkRefKey, Bt as KnowledgeRunScopesError, Ci as MAX_KNOWLEDGE_PAGE_LINKS, Di as assertKnowledgeNoteTextWithinBound, Ei as MAX_KNOWLEDGE_PIN_LIST_DEPTH, Fi as parseKnowledgePageRef, Fo as getStorageSource, Ft as PINNED_READ_MEMO_KEY, Gt as moveKnowledgePage, Ht as knowledgeAgentScopes, Ii as KnowledgeInvalidCursorError, It as knowledgeDeliveredPins, Jt as updateKnowledgeNote, Kt as removeKnowledgeNote, Li as knowledgePageKeyProblem, Lt as buildKnowledgePageTools, Mi as knowledgePinDepth, Ni as knowledgePositionBetween, Oi as assertKnowledgePageDescriptionWithinBound, Pi as knowledgeScopeReadable, Po as augmentWithInit, Qn as MAX_KNOWLEDGE_SCOPE_TAGS, Qr as InMemoryKnowledgeStorage, Qt as KnowledgeLinkRefreshIncompleteError, Rt as heldScopes, Si as MAX_KNOWLEDGE_PAGE_DESCRIPTION_TOKENS, Ti as MAX_KNOWLEDGE_PAGE_LIST_LIMIT, Ut as knowledgePersonaScopes, Vt as knowledgeRunPrincipals, Wt as addKnowledgeNote, Xn as MAX_KNOWLEDGE_NODE_DESCRIPTION_LENGTH, Xt as KnowledgeSemanticIndex, Yt as upsertKnowledgePage, Zn as MAX_KNOWLEDGE_RECORD_TEXT_LENGTH, _i as KnowledgePageKeyConflictError, _n as encodeKnowledgeScopeId, ai as KnowledgeNotFoundError, an as syncKnowledgePageBodyLinks, ar as expandKnowledgeScope, bi as MAX_KNOWLEDGE_PAGE_BODY_LINKS, ci as KnowledgeTransactionDeadlineError, cn as knowledgeReadScopeFor, cr as knowledgeSemanticDocumentId, di as createKnowledgeUlid, dn as compileKnowledgeScopes, dr as parseKnowledgeNodeCursor, ei as KnowledgeImporterRunStateError, en as canRepairKnowledgeLinksInBatch, er as assertKnowledgeDescriptionWithinBound, fi as inspectKnowledgeSchema, fn as knowledgeMemoryScopes, gi as KnowledgePageHasChildrenError, gn as decodeKnowledgeScopeId, hi as KnowledgePageDepthError, hn as strongerKnowledgeRole, ii as KnowledgeConflictError, in as repairKnowledgeLinks, ir as createKnowledgeNodeCursor, ji as knowledgePagePath, ki as canonicalKnowledgeName, li as KnowledgeUnsupportedCapabilityError, ln as knowledgeRoleOn, lr as knowledgeSemanticIdempotencyKey, mi as KnowledgeMoveTooLargeError, mn as knowledgeScopeAddress, ni as KNOWLEDGE_STORAGE_CONTRACT_VERSION, nn as refreshKnowledgeLinksTo, nr as assertKnowledgeScopeWithinCeiling, oi as KnowledgeSchemaResetRequiredError, on as updateKnowledgeLinks, or as isKnowledgeScopeVisible, pi as parseKnowledgeWikilinks, pn as knowledgeRunScopes, qt as removeKnowledgePage, ri as KNOWLEDGE_STORAGE_SCHEMA_VERSION, rn as reindexKnowledgeLinks, rr as canonicalizeKnowledgeScope, si as KnowledgeStorage, sn as knowledgeAccessGrants, sr as knowledgeScopeKey, ti as KnowledgeImportersStorage, tn as knowledgeSubtree, tr as assertKnowledgeRecordTextWithinBound, ui as assertKnowledgeSchemaCompatible, un as KnowledgeDeclarationError, ur as knowledgeVisibleScopeKeys, vi as MAX_KNOWLEDGE_MOVE_PAGES, vn as buildKnowledgeInstructions, wi as MAX_KNOWLEDGE_PAGE_LINK_REF_LENGTH, xi as MAX_KNOWLEDGE_PAGE_DEPTH, yi as MAX_KNOWLEDGE_NOTE_TOKENS, zt as KnowledgeRun } from "../execution-fence-Yl_-iJxn.js";
3
3
  import { standardSchemaToJSONSchema, toStandardSchema } from "../schema/index.js";
4
- import { i as createStandardSchemaIssuesError } from "../tool-Z3bykc1m.js";
4
+ import { i as createStandardSchemaIssuesError } from "../tool-DIFduuTw.js";
5
+ import { mt as estimateTokenCount } from "../workspace-sqcfdZRR.js";
5
6
  import { randomUUID } from "crypto";
6
7
  // src/knowledge/changes.ts
7
8
  const page = (op) => (result) => {
@@ -22,6 +23,39 @@ const note = (op) => (result) => {
22
23
  noteId: id
23
24
  };
24
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
+ }
25
59
  /** The page-store writes that emit, and the event each one's result maps to. */
26
60
  const WRITES = {
27
61
  materializeScope: (result) => {
@@ -57,6 +91,7 @@ const WRITES = {
57
91
  fromScopeId
58
92
  };
59
93
  },
94
+ applyPageWrites: (_result, input) => input.writes.map(describePageWrite).filter((change) => change !== null),
60
95
  addNote: note("add"),
61
96
  restampNote: note("restamp"),
62
97
  removeNote: note("remove"),
@@ -142,9 +177,15 @@ function emitKnowledgeChanges(storage, emit, listening, onError, chain) {
142
177
  }
143
178
  const result = await value.call(target, input, ...rest);
144
179
  if (!listening()) return result;
180
+ let changes = [];
145
181
  try {
146
182
  const change = describe(result, input, fromScopeId);
147
- 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);
148
189
  } catch (error) {
149
190
  onError(error);
150
191
  }
@@ -284,7 +325,8 @@ const DECLARATION_FIELDS = {
284
325
  required: true
285
326
  },
286
327
  parent: { kind: "nullableString" },
287
- fallbackParent: { kind: "nonEmpty" }
328
+ fallbackParent: { kind: "nonEmpty" },
329
+ path: { kind: "segments" }
288
330
  };
289
331
  const ITEM_FIELDS = {
290
332
  ...DECLARATION_FIELDS,
@@ -330,6 +372,9 @@ function checkFields(value, fields, where) {
330
372
  case "aliases":
331
373
  out[key] = checkDenseArray(field, at).map((alias, index) => checkString(alias, `${at}[${index}]`, true));
332
374
  break;
375
+ case "segments":
376
+ out[key] = checkDenseArray(field, at).map((segment, index) => checkString(segment, `${at}[${index}]`));
377
+ break;
333
378
  case "links": out[key] = checkDenseArray(field, at).map((link, index) => checkFields(link, {
334
379
  sourceId: {
335
380
  kind: "nonEmpty",
@@ -1032,6 +1077,991 @@ async function finishRun(host, request, lastSeq, unsettledSeq, withRetries) {
1032
1077
  function encodedBytes(value) {
1033
1078
  return new TextEncoder().encode(JSON.stringify(value)).byteLength;
1034
1079
  }
1080
+ // src/knowledge/importers/overlay.ts
1081
+ /**
1082
+ * The working copy a batched importer flush decides over (batched-flush plan v3.1 §1). The sink's
1083
+ * rule code runs unchanged against {@link ImportOverlay.storage} and {@link ImportOverlay.importers}:
1084
+ * reads come from rows gathered in a few set-based queries and locked, writes are applied to the
1085
+ * working copy and kept, in call order, for one batched write after every op is decided.
1086
+ *
1087
+ * A read of something not gathered throws {@link KnowledgeImportNotGatheredError} and names it, so
1088
+ * the caller gathers it and decides again. A call the working copy can't model throws
1089
+ * {@link KnowledgeImportBatchUnsupportedError}, and the flush takes the per-op path instead.
1090
+ *
1091
+ * @internal
1092
+ */
1093
+ /** The overlay was asked for a row it wasn't given. The caller gathers it and decides again. */
1094
+ var KnowledgeImportNotGatheredError = class extends Error {
1095
+ constructor(what) {
1096
+ super(`Not gathered for the batched import flush: ${what}`);
1097
+ this.name = "KnowledgeImportNotGatheredError";
1098
+ }
1099
+ };
1100
+ /** The flush needs a call the overlay doesn't model: it falls back to the per-op path. */
1101
+ /**
1102
+ * The gather read the rows once, its plan writing pages only in place, and the decide pass went to
1103
+ * create, move or delete a page anyway: one more pass reads them again under the lock.
1104
+ */
1105
+ var KnowledgeImportRereadRequiredError = class extends Error {
1106
+ constructor(what) {
1107
+ super(`The batched import flush needs its rows read again under the lock: ${what}`);
1108
+ this.name = "KnowledgeImportRereadRequiredError";
1109
+ }
1110
+ };
1111
+ var KnowledgeImportBatchUnsupportedError = class extends Error {
1112
+ call;
1113
+ constructor(call) {
1114
+ super(`Not supported by the batched import flush: ${call}`);
1115
+ this.call = call;
1116
+ this.name = "KnowledgeImportBatchUnsupportedError";
1117
+ }
1118
+ };
1119
+ const nodeKey = (bindingId, sourceId) => `${bindingId}\u0000${sourceId}`;
1120
+ /** The key {@link ImportOverlayRows.paths} holds a scope path under. */
1121
+ const importPathKey = (scopeId, path) => JSON.stringify([scopeId, ...path]);
1122
+ const pathKey = importPathKey;
1123
+ /**
1124
+ * The key path of each live page whose whole chain to its scope is among `pages`, to that page: a
1125
+ * path a read chain already answers, with no `getPagesByPaths`. One key path has one live page.
1126
+ */
1127
+ function importChainPaths(pages) {
1128
+ const out = /* @__PURE__ */ new Map();
1129
+ for (const page of pages.values()) {
1130
+ if (!page || page.isScope) continue;
1131
+ const path = [];
1132
+ let at = page;
1133
+ while (at && !at.isScope) {
1134
+ if (at.key === void 0 || at.deletedAt || at.mergedInto || path.length >= 10) {
1135
+ at = void 0;
1136
+ break;
1137
+ }
1138
+ path.unshift(at.key);
1139
+ at = at.parentId ? pages.get(at.parentId) : null;
1140
+ }
1141
+ if (at) out.set(pathKey(at.id, path), page.id);
1142
+ }
1143
+ return out;
1144
+ }
1145
+ const childKey = (parentId, key) => `${parentId}\u0000${key}`;
1146
+ 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;
1147
+ /** UTF-8 byte order, as the stores sort source IDs. */
1148
+ const byteOrder = (a, b) => Buffer.compare(Buffer.from(a), Buffer.from(b));
1149
+ const emptyImportOverlayMissing = () => ({
1150
+ pages: /* @__PURE__ */ new Set(),
1151
+ nodes: /* @__PURE__ */ new Set(),
1152
+ nodesByPage: /* @__PURE__ */ new Set(),
1153
+ paths: /* @__PURE__ */ new Map(),
1154
+ notes: /* @__PURE__ */ new Set(),
1155
+ positions: /* @__PURE__ */ new Set(),
1156
+ locks: /* @__PURE__ */ new Set(),
1157
+ subtrees: /* @__PURE__ */ new Set(),
1158
+ linkTargets: /* @__PURE__ */ new Set(),
1159
+ bindings: /* @__PURE__ */ new Set()
1160
+ });
1161
+ const emptyImportOverlayRows = () => ({
1162
+ pages: /* @__PURE__ */ new Map(),
1163
+ nodes: /* @__PURE__ */ new Map(),
1164
+ nodesByPage: /* @__PURE__ */ new Map(),
1165
+ paths: /* @__PURE__ */ new Map(),
1166
+ notes: /* @__PURE__ */ new Map(),
1167
+ positions: /* @__PURE__ */ new Map(),
1168
+ locked: /* @__PURE__ */ new Set(),
1169
+ complete: /* @__PURE__ */ new Set(),
1170
+ tooLarge: /* @__PURE__ */ new Set(),
1171
+ linkTargets: /* @__PURE__ */ new Set(),
1172
+ tooManyLinkers: /* @__PURE__ */ new Set()
1173
+ });
1174
+ /** The binding and targets of a deferred mark, so back-to-back marks for one binding run as one. */
1175
+ const markTargets = /* @__PURE__ */ new WeakMap();
1176
+ const copyRows = (rows) => ({
1177
+ pages: new Map(rows.pages),
1178
+ nodes: new Map(rows.nodes),
1179
+ nodesByPage: new Map(rows.nodesByPage),
1180
+ paths: new Map(rows.paths),
1181
+ notes: new Map(rows.notes),
1182
+ positions: new Map(rows.positions),
1183
+ locked: new Set(rows.locked),
1184
+ complete: new Set(rows.complete),
1185
+ tooLarge: new Set(rows.tooLarge),
1186
+ linkTargets: new Set(rows.linkTargets),
1187
+ tooManyLinkers: new Set(rows.tooManyLinkers),
1188
+ ...rows.bindings ? { bindings: rows.bindings } : {},
1189
+ ...rows.inPlace ? { inPlace: true } : {},
1190
+ ...rows.readOnce ? { readOnce: true } : {}
1191
+ });
1192
+ const copyState = (state) => ({
1193
+ rows: copyRows(state.rows),
1194
+ writes: [...state.writes],
1195
+ touched: new Set(state.touched),
1196
+ marks: [...state.marks],
1197
+ links: [...state.links],
1198
+ moved: new Set(state.moved),
1199
+ freed: new Set(state.freed),
1200
+ stalePositions: new Set(state.stalePositions)
1201
+ });
1202
+ /** Every method the given implementation lacks throws {@link KnowledgeImportBatchUnsupportedError}. */
1203
+ function only(impl, name) {
1204
+ return new Proxy(impl, { get(target, prop, receiver) {
1205
+ if (prop in target) return Reflect.get(target, prop, receiver);
1206
+ if (typeof prop !== "string" || prop === "then") return void 0;
1207
+ return () => {
1208
+ throw new KnowledgeImportBatchUnsupportedError(`${name}.${prop}`);
1209
+ };
1210
+ } });
1211
+ }
1212
+ var ImportOverlay = class {
1213
+ missing = emptyImportOverlayMissing();
1214
+ #state;
1215
+ storage;
1216
+ importers;
1217
+ constructor(base, now = () => /* @__PURE__ */ new Date()) {
1218
+ this.#state = {
1219
+ rows: copyRows(base),
1220
+ writes: [],
1221
+ touched: /* @__PURE__ */ new Set(),
1222
+ marks: [],
1223
+ links: [],
1224
+ moved: /* @__PURE__ */ new Set(),
1225
+ freed: /* @__PURE__ */ new Set(),
1226
+ stalePositions: /* @__PURE__ */ new Set()
1227
+ };
1228
+ this.storage = this.#storage(now);
1229
+ this.importers = this.#importers();
1230
+ }
1231
+ get writes() {
1232
+ return this.#state.writes;
1233
+ }
1234
+ get marks() {
1235
+ return this.#state.marks;
1236
+ }
1237
+ get links() {
1238
+ return this.#state.links;
1239
+ }
1240
+ /** Link-index work the sink would run now; it runs, in one batch, after the batched write instead. */
1241
+ deferLinks(...work) {
1242
+ this.#state.links.push(...work);
1243
+ }
1244
+ /** The node writes decided: each touched node's last record, or a delete when it ends up gone. */
1245
+ nodeWrites(base) {
1246
+ const deletes = [];
1247
+ const saves = [];
1248
+ for (const key of this.#state.touched) {
1249
+ const node = this.#state.rows.nodes.get(key);
1250
+ if (node) {
1251
+ const { updatedAt: _updatedAt, ...record } = node;
1252
+ saves.push(record);
1253
+ } else if (base.nodes.get(key)) {
1254
+ const [bindingId, sourceId] = key.split("\0");
1255
+ deletes.push({
1256
+ bindingId,
1257
+ sourceId
1258
+ });
1259
+ }
1260
+ }
1261
+ return {
1262
+ deletes,
1263
+ saves
1264
+ };
1265
+ }
1266
+ #page(id) {
1267
+ const { pages } = this.#state.rows;
1268
+ if (!pages.has(id)) {
1269
+ this.missing.pages.add(id);
1270
+ throw new KnowledgeImportNotGatheredError(`page ${id}`);
1271
+ }
1272
+ return pages.get(id);
1273
+ }
1274
+ #livePage(id) {
1275
+ const page = this.#page(id);
1276
+ if (!page || page.deletedAt || page.mergedInto) throw new KnowledgeNotFoundError("page", id);
1277
+ return page;
1278
+ }
1279
+ /** Levels below the home scope, from the working copy's chain. */
1280
+ #depth(page) {
1281
+ let depth = 0;
1282
+ let at = page;
1283
+ while (at && !at.isScope) {
1284
+ depth++;
1285
+ at = at.parentId ? this.#page(at.parentId) : null;
1286
+ }
1287
+ return depth;
1288
+ }
1289
+ /** The page's key path from its scope, or null when the chain doesn't reach one. */
1290
+ #keys(page) {
1291
+ const path = [];
1292
+ let at = page;
1293
+ while (at && !at.isScope) {
1294
+ if (at.key === void 0 || at.deletedAt || at.mergedInto) return null;
1295
+ path.unshift(at.key);
1296
+ at = at.parentId ? this.#page(at.parentId) : null;
1297
+ }
1298
+ return at ? {
1299
+ scopeId: at.id,
1300
+ path
1301
+ } : null;
1302
+ }
1303
+ /**
1304
+ * Live ordinary children by parent, sorted by position: built on first use, dropped on each page
1305
+ * write, and keyed by the pages map, which a rolled-back transaction replaces.
1306
+ */
1307
+ #childIndex;
1308
+ #setPage(id, page) {
1309
+ this.#state.rows.pages.set(id, page);
1310
+ this.#childIndex = void 0;
1311
+ this.#chainPaths = void 0;
1312
+ }
1313
+ /** {@link importChainPaths} of the working copy, kept like the child index. */
1314
+ #chainPaths;
1315
+ #pathFromChains(key) {
1316
+ const { pages } = this.#state.rows;
1317
+ if (this.#chainPaths?.pages !== pages) this.#chainPaths = {
1318
+ pages,
1319
+ byPath: importChainPaths(pages)
1320
+ };
1321
+ return this.#chainPaths.byPath.get(key);
1322
+ }
1323
+ /** Live ordinary children by position, once gathered. */
1324
+ #children(parentId) {
1325
+ const { pages, complete } = this.#state.rows;
1326
+ if (!complete.has(parentId)) {
1327
+ this.missing.subtrees.add(parentId);
1328
+ throw new KnowledgeImportNotGatheredError(`children of ${parentId}`);
1329
+ }
1330
+ if (this.#childIndex?.pages !== pages) {
1331
+ const byParent = /* @__PURE__ */ new Map();
1332
+ for (const page of pages.values()) {
1333
+ if (!page || !page.parentId || page.isScope || page.deletedAt) continue;
1334
+ const siblings = byParent.get(page.parentId);
1335
+ if (siblings) siblings.push(page);
1336
+ else byParent.set(page.parentId, [page]);
1337
+ }
1338
+ for (const siblings of byParent.values()) siblings.sort(byPosition);
1339
+ this.#childIndex = {
1340
+ pages,
1341
+ byParent
1342
+ };
1343
+ }
1344
+ return [...this.#childIndex.byParent.get(parentId) ?? []];
1345
+ }
1346
+ /** The next position under a parent, as `createPage` and `movePage` would place a page. */
1347
+ #nextPosition(parentId) {
1348
+ const { positions, complete } = this.#state.rows;
1349
+ if (this.#state.stalePositions.has(parentId)) {
1350
+ if (!complete.has(parentId)) throw new KnowledgeImportBatchUnsupportedError("a position under a parent its last child left");
1351
+ return knowledgePositionBetween(this.#children(parentId).at(-1)?.position);
1352
+ }
1353
+ if (!positions.has(parentId)) {
1354
+ this.missing.positions.add(parentId);
1355
+ throw new KnowledgeImportNotGatheredError(`last child position of ${parentId}`);
1356
+ }
1357
+ return knowledgePositionBetween(positions.get(parentId) ?? void 0);
1358
+ }
1359
+ /** A page left `parentId`: its next position is still the gathered one unless it was the last child. */
1360
+ #left(parentId, position) {
1361
+ if (!parentId) return;
1362
+ const last = this.#state.rows.positions.get(parentId);
1363
+ if (last === void 0 || last === position) this.#state.stalePositions.add(parentId);
1364
+ }
1365
+ /** Points the path map at where `pages` are now; `before` holds their old paths. */
1366
+ #repath(pages, before) {
1367
+ const { paths } = this.#state.rows;
1368
+ const ids = new Set(pages.map((page) => page.id));
1369
+ for (const [key, id] of paths) if (id && ids.has(id)) paths.set(key, null);
1370
+ for (const old of before) if (old) paths.set(pathKey(old.scopeId, old.path), null);
1371
+ for (const page of pages) {
1372
+ const keys = this.#rowKeys(page);
1373
+ if (keys) paths.set(pathKey(keys.scopeId, keys.path), page.id);
1374
+ }
1375
+ }
1376
+ /** {@link #keys} on the working copy's current row. */
1377
+ #rowKeys(page) {
1378
+ return this.#keys(this.#state.rows.pages.get(page.id) ?? page);
1379
+ }
1380
+ #node(key) {
1381
+ const { nodes } = this.#state.rows;
1382
+ if (!nodes.has(key)) {
1383
+ this.missing.nodes.add(key);
1384
+ throw new KnowledgeImportNotGatheredError(`node ${key}`);
1385
+ }
1386
+ return nodes.get(key);
1387
+ }
1388
+ #setNode(key, node) {
1389
+ const { nodes, nodesByPage } = this.#state.rows;
1390
+ const before = nodes.get(key);
1391
+ if (before && nodesByPage.get(before.pageId) === key) nodesByPage.set(before.pageId, null);
1392
+ nodes.set(key, node);
1393
+ if (node) nodesByPage.set(node.pageId, key);
1394
+ this.#state.touched.add(key);
1395
+ }
1396
+ #storage(now) {
1397
+ const rows = () => this.#state.rows;
1398
+ const impl = {
1399
+ transaction: async (fn) => {
1400
+ const saved = copyState(this.#state);
1401
+ try {
1402
+ return await fn(this.storage);
1403
+ } catch (error) {
1404
+ this.#state = saved;
1405
+ throw error;
1406
+ }
1407
+ },
1408
+ getPage: async ({ id }) => this.#page(id),
1409
+ getPageParents: async ({ parentId }) => {
1410
+ const parents = [];
1411
+ let id = parentId;
1412
+ while (id && parents.length <= 10) {
1413
+ const page = this.#page(id);
1414
+ if (!page) break;
1415
+ parents.push(page);
1416
+ id = page.parentId;
1417
+ }
1418
+ return parents;
1419
+ },
1420
+ getPageByPath: async ({ scopeId, path }) => {
1421
+ if (path.length === 0) return null;
1422
+ const key = pathKey(scopeId, path);
1423
+ if (!rows().paths.has(key)) {
1424
+ const id = this.#pathFromChains(key);
1425
+ if (id) return this.#page(id);
1426
+ this.missing.paths.set(key, {
1427
+ scopeId,
1428
+ path
1429
+ });
1430
+ throw new KnowledgeImportNotGatheredError(`path ${key}`);
1431
+ }
1432
+ const id = rows().paths.get(key);
1433
+ return id ? this.#page(id) : null;
1434
+ },
1435
+ lockPages: async (ids) => {
1436
+ const unlocked = ids.filter((id) => !rows().locked.has(id));
1437
+ if (unlocked.length) {
1438
+ for (const id of unlocked) this.missing.locks.add(id);
1439
+ throw new KnowledgeImportNotGatheredError(`locks ${unlocked.join(", ")}`);
1440
+ }
1441
+ return [];
1442
+ },
1443
+ listNotes: async ({ pageId }) => {
1444
+ if (!rows().notes.has(pageId)) {
1445
+ this.missing.notes.add(pageId);
1446
+ throw new KnowledgeImportNotGatheredError(`notes of ${pageId}`);
1447
+ }
1448
+ return { notes: rows().notes.get(pageId).filter((note) => !note.deletedAt) };
1449
+ },
1450
+ createPage: async (input) => {
1451
+ if (rows().readOnce) throw new KnowledgeImportRereadRequiredError("createPage");
1452
+ if (input.id !== void 0 || input.position !== void 0) throw new KnowledgeImportBatchUnsupportedError("createPage with id or position");
1453
+ if (!input.name.trim()) throw new Error("Knowledge page name must not be empty");
1454
+ assertKnowledgePageDescriptionWithinBound(input.description || void 0);
1455
+ const parent = this.#livePage(input.parentId);
1456
+ const scopeId = parent.isScope ? parent.id : parent.scopeId;
1457
+ const id = randomUUID();
1458
+ const depth = this.#depth(parent) + 1;
1459
+ if (depth > 10) throw new KnowledgePageDepthError(id);
1460
+ let path = null;
1461
+ if (input.key !== void 0) {
1462
+ const problem = knowledgePageKeyProblem(input.key);
1463
+ if (problem) throw new Error(problem);
1464
+ const parentKeys = parent.isScope ? {
1465
+ scopeId: parent.id,
1466
+ path: []
1467
+ } : this.#keys(parent);
1468
+ if (!parentKeys) throw new KnowledgeImportBatchUnsupportedError("createPage under a broken chain");
1469
+ path = [...parentKeys.path, input.key];
1470
+ if (await impl.getPageByPath({
1471
+ scopeId,
1472
+ path,
1473
+ read: "all"
1474
+ })) throw new KnowledgePageKeyConflictError(input.key, parent.id);
1475
+ }
1476
+ if (input.key !== void 0 && this.#state.freed.has(childKey(parent.id, input.key))) throw new KnowledgeImportBatchUnsupportedError("createPage at a key a move left");
1477
+ const position = this.#nextPosition(parent.id);
1478
+ const at = now();
1479
+ const page = {
1480
+ id,
1481
+ scopeId,
1482
+ parentId: parent.id,
1483
+ isScope: false,
1484
+ ...input.key !== void 0 ? { key: input.key } : {},
1485
+ position,
1486
+ name: input.name,
1487
+ ...input.description ? { description: input.description } : {},
1488
+ ...input.body !== void 0 ? { body: input.body } : {},
1489
+ version: 1,
1490
+ createdBy: structuredClone(input.provenance),
1491
+ updatedBy: structuredClone(input.provenance),
1492
+ createdAt: at,
1493
+ updatedAt: at
1494
+ };
1495
+ const state = rows();
1496
+ this.#setPage(id, page);
1497
+ state.positions.set(parent.id, position);
1498
+ state.positions.set(id, null);
1499
+ state.notes.set(id, []);
1500
+ state.nodesByPage.set(id, null);
1501
+ state.locked.add(id);
1502
+ state.complete.add(id);
1503
+ if (path) state.paths.set(pathKey(scopeId, path), id);
1504
+ this.#state.writes.push({
1505
+ op: "create",
1506
+ id,
1507
+ scopeId,
1508
+ parentId: parent.id,
1509
+ ...input.key !== void 0 ? { key: input.key } : {},
1510
+ name: input.name,
1511
+ ...input.description !== void 0 ? { description: input.description } : {},
1512
+ ...input.body !== void 0 ? { body: input.body } : {},
1513
+ position,
1514
+ depth,
1515
+ provenance: input.provenance
1516
+ });
1517
+ return structuredClone(page);
1518
+ },
1519
+ updatePage: async (input) => {
1520
+ const page = this.#livePage(input.id);
1521
+ if (page.version !== input.expectedVersion) throw new KnowledgeConflictError(page.id);
1522
+ if (input.name !== void 0 && !input.name.trim()) throw new Error("Knowledge page name must not be empty");
1523
+ assertKnowledgePageDescriptionWithinBound(input.description || void 0);
1524
+ const next = {
1525
+ ...page,
1526
+ version: page.version + 1,
1527
+ updatedBy: structuredClone(input.provenance)
1528
+ };
1529
+ next.updatedAt = now();
1530
+ if (input.name !== void 0) next.name = input.name;
1531
+ if (input.description !== void 0) {
1532
+ if (input.description) next.description = input.description;
1533
+ else delete next.description;
1534
+ }
1535
+ if (input.body !== void 0) next.body = input.body;
1536
+ this.#setPage(page.id, next);
1537
+ this.#state.writes.push({
1538
+ op: "update",
1539
+ id: page.id,
1540
+ scopeId: page.scopeId,
1541
+ expectedVersion: input.expectedVersion,
1542
+ ...input.name !== void 0 ? { name: input.name } : {},
1543
+ ...input.description !== void 0 ? { description: input.description } : {},
1544
+ ...input.body !== void 0 ? { body: input.body } : {},
1545
+ provenance: input.provenance
1546
+ });
1547
+ return structuredClone(next);
1548
+ },
1549
+ listChildPages: async ({ parentId, read, cursor, limit }) => {
1550
+ if (read !== "all") throw new KnowledgeImportBatchUnsupportedError("listChildPages with a read scope");
1551
+ const children = this.#children(parentId);
1552
+ const start = cursor ? Number(cursor) : 0;
1553
+ const end = limit === void 0 ? children.length : start + limit;
1554
+ return {
1555
+ pages: children.slice(start, end).map((page) => structuredClone(page)),
1556
+ ...end < children.length ? { nextCursor: String(end) } : {}
1557
+ };
1558
+ },
1559
+ countChildPages: async ({ parentIds, read }) => {
1560
+ if (read !== "all") throw new KnowledgeImportBatchUnsupportedError("countChildPages with a read scope");
1561
+ return Object.fromEntries(parentIds.map((id) => [id, this.#children(id).length]));
1562
+ },
1563
+ lockSubtree: async (rootId) => {
1564
+ if (rows().tooLarge.has(rootId)) throw new KnowledgeMoveTooLargeError(rootId, 501);
1565
+ const ids = [];
1566
+ const parents = [rootId];
1567
+ while (parents.length) {
1568
+ for (const child of this.#children(parents.shift())) {
1569
+ ids.push(child.id);
1570
+ parents.push(child.id);
1571
+ }
1572
+ if (ids.length >= 500) throw new KnowledgeMoveTooLargeError(rootId, ids.length + 1);
1573
+ }
1574
+ const unlocked = ids.filter((id) => !rows().locked.has(id));
1575
+ if (unlocked.length) {
1576
+ for (const id of unlocked) this.missing.locks.add(id);
1577
+ throw new KnowledgeImportNotGatheredError(`locks ${unlocked.join(", ")}`);
1578
+ }
1579
+ return ids;
1580
+ },
1581
+ movePage: async (input) => {
1582
+ if (rows().readOnce) throw new KnowledgeImportRereadRequiredError("movePage");
1583
+ if (input.position !== void 0) throw new KnowledgeImportBatchUnsupportedError("movePage with a position");
1584
+ const page = this.#livePage(input.id);
1585
+ if (page.isScope) throw new Error(`Knowledge scope page ${page.id} can't be moved`);
1586
+ if (page.version !== input.expectedVersion) throw new KnowledgeConflictError(page.id);
1587
+ const parent = this.#livePage(input.parentId);
1588
+ const subtree = [];
1589
+ const visit = (at, depth) => {
1590
+ subtree.push({
1591
+ page: at,
1592
+ depth
1593
+ });
1594
+ for (const child of this.#children(at.id)) visit(child, depth + 1);
1595
+ };
1596
+ visit(page, 0);
1597
+ 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`);
1598
+ if (subtree.length > 500) throw new KnowledgeMoveTooLargeError(page.id, subtree.length);
1599
+ const parentDepth = parent.isScope ? 0 : this.#depth(parent);
1600
+ if (parentDepth + 1 + Math.max(...subtree.map((entry) => entry.depth)) > 10) throw new KnowledgePageDepthError(page.id);
1601
+ const scopeId = parent.isScope ? parent.id : parent.scopeId;
1602
+ if (scopeId !== page.scopeId) throw new KnowledgeImportBatchUnsupportedError("movePage across scopes");
1603
+ const key = input.key ?? page.key;
1604
+ if (input.key !== void 0) {
1605
+ const problem = knowledgePageKeyProblem(input.key);
1606
+ if (problem) throw new Error(problem);
1607
+ }
1608
+ if (key !== void 0) {
1609
+ const parentKeys = parent.isScope ? {
1610
+ scopeId: parent.id,
1611
+ path: []
1612
+ } : this.#keys(parent);
1613
+ if (!parentKeys) throw new KnowledgeImportBatchUnsupportedError("movePage under a broken chain");
1614
+ const clash = await impl.getPageByPath({
1615
+ scopeId,
1616
+ path: [...parentKeys.path, key],
1617
+ read: "all"
1618
+ });
1619
+ if (clash && clash.id !== page.id) throw new KnowledgePageKeyConflictError(key, parent.id);
1620
+ }
1621
+ if (this.#state.moved.has(page.id)) throw new KnowledgeImportBatchUnsupportedError("a second move of a page");
1622
+ const position = this.#nextPosition(parent.id);
1623
+ const before = subtree.map((entry) => this.#keys(entry.page));
1624
+ const at = now();
1625
+ const moved = {
1626
+ ...page,
1627
+ ...key !== void 0 ? { key } : {},
1628
+ parentId: parent.id,
1629
+ position,
1630
+ version: page.version + 1,
1631
+ updatedBy: structuredClone(input.provenance),
1632
+ updatedAt: at
1633
+ };
1634
+ const state = rows();
1635
+ this.#setPage(page.id, moved);
1636
+ state.positions.set(parent.id, position);
1637
+ this.#left(page.parentId, page.position);
1638
+ if (page.parentId && page.key !== void 0) this.#state.freed.add(childKey(page.parentId, page.key));
1639
+ this.#state.moved.add(page.id);
1640
+ this.#repath(subtree.map((entry) => state.pages.get(entry.page.id)), before);
1641
+ this.#state.writes.push({
1642
+ op: "move",
1643
+ id: page.id,
1644
+ fromScopeId: page.scopeId,
1645
+ expectedVersion: input.expectedVersion,
1646
+ parentId: parent.id,
1647
+ ...input.key !== void 0 ? { key: input.key } : {},
1648
+ scopeId,
1649
+ depth: parentDepth + 1,
1650
+ position,
1651
+ provenance: input.provenance
1652
+ });
1653
+ return structuredClone(moved);
1654
+ },
1655
+ deletePage: async (input) => {
1656
+ if (rows().readOnce) throw new KnowledgeImportRereadRequiredError("deletePage");
1657
+ const page = this.#livePage(input.id);
1658
+ if (page.isScope) throw new Error(`Knowledge scope page ${page.id} can't be deleted`);
1659
+ if (page.version !== input.expectedVersion) throw new KnowledgeConflictError(page.id);
1660
+ if (this.#children(page.id).length) throw new KnowledgePageHasChildrenError(page.id);
1661
+ const at = now();
1662
+ const deleted = {
1663
+ ...page,
1664
+ deletedAt: at,
1665
+ deletedBy: input.deletedBy,
1666
+ version: page.version + 1,
1667
+ updatedAt: at
1668
+ };
1669
+ this.#setPage(page.id, deleted);
1670
+ this.#left(page.parentId, page.position);
1671
+ for (const [key, id] of rows().paths) if (id === page.id) rows().paths.set(key, null);
1672
+ this.#state.writes.push({
1673
+ op: "delete",
1674
+ id: page.id,
1675
+ scopeId: page.scopeId,
1676
+ expectedVersion: input.expectedVersion,
1677
+ deletedBy: input.deletedBy
1678
+ });
1679
+ return structuredClone(deleted);
1680
+ },
1681
+ addNote: async (input) => {
1682
+ const page = this.#livePage(input.pageId);
1683
+ assertKnowledgeNoteTextWithinBound(input.text);
1684
+ if (input.mentions.length) throw new KnowledgeImportBatchUnsupportedError("addNote with mentions");
1685
+ const notes = this.#notesOf(page.id);
1686
+ const id = input.id ?? randomUUID();
1687
+ if (notes.some((note) => note.id === id)) throw new KnowledgeConflictError(id);
1688
+ const at = now();
1689
+ const note = {
1690
+ id,
1691
+ pageId: page.id,
1692
+ text: input.text,
1693
+ ...input.when ? { when: new Date(input.when) } : {},
1694
+ stampScopeIds: [...new Set(input.stampScopeIds)],
1695
+ mentions: [],
1696
+ provenance: structuredClone(input.provenance),
1697
+ version: 1,
1698
+ createdAt: at,
1699
+ updatedAt: at
1700
+ };
1701
+ rows().notes.set(page.id, [...notes, note]);
1702
+ this.#state.writes.push({
1703
+ op: "add-note",
1704
+ id,
1705
+ pageId: page.id,
1706
+ scopeId: page.scopeId,
1707
+ text: input.text,
1708
+ ...input.when ? { when: input.when } : {},
1709
+ stampScopeIds: input.stampScopeIds,
1710
+ mentions: [],
1711
+ provenance: input.provenance
1712
+ });
1713
+ return structuredClone(note);
1714
+ },
1715
+ removeNote: async (input) => {
1716
+ for (const [pageId, notes] of rows().notes) {
1717
+ const note = notes.find((each) => each.id === input.id);
1718
+ if (!note) continue;
1719
+ if (note.deletedAt) throw new KnowledgeNotFoundError("note", input.id);
1720
+ if (this.#state.writes.some((write) => write.op === "add-note" && write.id === input.id)) throw new KnowledgeImportBatchUnsupportedError("removeNote of a note this flush added");
1721
+ const page = this.#livePage(pageId);
1722
+ const at = now();
1723
+ const removed = {
1724
+ ...note,
1725
+ deletedAt: at,
1726
+ deletedBy: input.deletedBy,
1727
+ version: note.version + 1,
1728
+ updatedAt: at
1729
+ };
1730
+ rows().notes.set(pageId, notes.map((each) => each.id === input.id ? removed : each));
1731
+ this.#state.writes.push({
1732
+ op: "remove-note",
1733
+ id: input.id,
1734
+ pageId,
1735
+ scopeId: page.scopeId,
1736
+ deletedBy: input.deletedBy,
1737
+ provenance: input.provenance
1738
+ });
1739
+ return structuredClone(removed);
1740
+ }
1741
+ throw new KnowledgeImportBatchUnsupportedError("removeNote of a note not gathered");
1742
+ }
1743
+ };
1744
+ return only(impl, "storage");
1745
+ }
1746
+ #notesOf(pageId) {
1747
+ const { notes } = this.#state.rows;
1748
+ if (!notes.has(pageId)) {
1749
+ this.missing.notes.add(pageId);
1750
+ throw new KnowledgeImportNotGatheredError(`notes of ${pageId}`);
1751
+ }
1752
+ return notes.get(pageId);
1753
+ }
1754
+ #importers() {
1755
+ const rows = () => this.#state.rows;
1756
+ return only({
1757
+ getNode: async (bindingId, sourceId) => structuredClone(this.#node(nodeKey(bindingId, sourceId))),
1758
+ getNodes: async (bindingId, sourceIds) => {
1759
+ const nodes = [];
1760
+ const unread = [...new Set(sourceIds)].filter((sourceId) => !rows().nodes.has(nodeKey(bindingId, sourceId)));
1761
+ if (unread.length) {
1762
+ for (const sourceId of unread) this.missing.nodes.add(nodeKey(bindingId, sourceId));
1763
+ throw new KnowledgeImportNotGatheredError(`nodes ${unread.join(", ")}`);
1764
+ }
1765
+ for (const sourceId of new Set(sourceIds)) {
1766
+ const node = rows().nodes.get(nodeKey(bindingId, sourceId));
1767
+ if (node) nodes.push(structuredClone(node));
1768
+ }
1769
+ return nodes;
1770
+ },
1771
+ getNodeByPage: async (pageId) => {
1772
+ if (!rows().nodesByPage.has(pageId)) {
1773
+ this.missing.nodesByPage.add(pageId);
1774
+ throw new KnowledgeImportNotGatheredError(`node of page ${pageId}`);
1775
+ }
1776
+ const key = rows().nodesByPage.get(pageId);
1777
+ return key ? structuredClone(this.#node(key)) : null;
1778
+ },
1779
+ getNodesByPages: async (pageIds) => {
1780
+ const unread = [...new Set(pageIds)].filter((pageId) => !rows().nodesByPage.has(pageId));
1781
+ if (unread.length) {
1782
+ for (const pageId of unread) this.missing.nodesByPage.add(pageId);
1783
+ throw new KnowledgeImportNotGatheredError(`nodes of pages ${unread.join(", ")}`);
1784
+ }
1785
+ return [...new Set(pageIds)].flatMap((pageId) => {
1786
+ const node = rows().nodesByPage.get(pageId) ? this.#node(rows().nodesByPage.get(pageId)) : null;
1787
+ return node ? [structuredClone(node)] : [];
1788
+ });
1789
+ },
1790
+ saveNode: async (node) => {
1791
+ const key = nodeKey(node.bindingId, node.sourceId);
1792
+ const mapped = rows().nodesByPage.get(node.pageId);
1793
+ if (mapped === void 0) {
1794
+ this.missing.nodesByPage.add(node.pageId);
1795
+ throw new KnowledgeImportNotGatheredError(`node of page ${node.pageId}`);
1796
+ }
1797
+ if (mapped && mapped !== key) throw new KnowledgeImportBatchUnsupportedError("saveNode onto a mapped page");
1798
+ this.#setNode(key, {
1799
+ ...structuredClone(node),
1800
+ updatedAt: /* @__PURE__ */ new Date()
1801
+ });
1802
+ },
1803
+ deleteNode: async (bindingId, sourceId) => {
1804
+ const key = nodeKey(bindingId, sourceId);
1805
+ this.#node(key);
1806
+ this.#setNode(key, null);
1807
+ },
1808
+ markLinkingNodesUnsettled: async (bindingId, targetSourceIds) => {
1809
+ const targets = new Set(targetSourceIds);
1810
+ for (const [key, node] of rows().nodes) if (node && node.bindingId === bindingId && node.links.some((link) => targets.has(link.sourceId))) rows().nodes.set(key, {
1811
+ ...node,
1812
+ unsettled: true
1813
+ });
1814
+ const marks = this.#state.marks;
1815
+ const last = marks.at(-1);
1816
+ const prior = last && markTargets.get(last);
1817
+ const all = prior?.bindingId === bindingId ? [.../* @__PURE__ */ new Set([...prior.targets, ...targetSourceIds])] : [...targetSourceIds];
1818
+ if (prior?.bindingId === bindingId) marks.pop();
1819
+ const mark = (_, importers) => importers.markLinkingNodesUnsettled(bindingId, all);
1820
+ markTargets.set(mark, {
1821
+ bindingId,
1822
+ targets: all
1823
+ });
1824
+ marks.push(mark);
1825
+ },
1826
+ setState: async (bindingId, state) => {
1827
+ this.#state.marks.push((_, importers) => importers.setState(bindingId, state));
1828
+ },
1829
+ listLinkingNodes: async (bindingId, targetSourceIds, options = {}) => {
1830
+ const keys = [...new Set(targetSourceIds)].map((sourceId) => nodeKey(bindingId, sourceId));
1831
+ if (keys.some((key) => rows().tooManyLinkers.has(key))) throw new KnowledgeImportBatchUnsupportedError("listLinkingNodes past the gathered linking nodes");
1832
+ const unread = keys.filter((key) => !rows().linkTargets.has(key));
1833
+ if (unread.length) {
1834
+ for (const key of unread) this.missing.linkTargets.add(key);
1835
+ throw new KnowledgeImportNotGatheredError(`linking nodes of ${unread.join(", ")}`);
1836
+ }
1837
+ const targets = new Set(targetSourceIds);
1838
+ 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);
1839
+ const limit = options.limit ?? 500;
1840
+ const items = ids.slice(0, limit);
1841
+ return {
1842
+ items,
1843
+ next: ids.length > limit ? items[items.length - 1] : null
1844
+ };
1845
+ },
1846
+ listBindings: async () => {
1847
+ const { bindings } = rows();
1848
+ if (!bindings) {
1849
+ this.missing.bindings.add("bindings");
1850
+ throw new KnowledgeImportNotGatheredError("bindings");
1851
+ }
1852
+ return structuredClone(bindings);
1853
+ }
1854
+ }, "importers");
1855
+ }
1856
+ };
1857
+ /** True when the stores implement every set-based method the batched flush needs. */
1858
+ function canBatchImportFlush(storage, importers) {
1859
+ return !!(storage.getPageChains && storage.getPagesByPaths && storage.getLastChildPositions && storage.listNotesByPages && storage.getPageSubtrees && storage.applyPageWrites && canRepairKnowledgeLinksInBatch(storage) && importers.getNodes && importers.getNodesByPages && importers.writeNodes);
1860
+ }
1861
+ async function readImportRows(input) {
1862
+ const { storage, importers, bindingId, missing } = input;
1863
+ const rows = emptyImportOverlayRows();
1864
+ const sourceIds = new Set(input.sourceIds);
1865
+ for (const key of missing?.nodes ?? []) {
1866
+ const [binding, sourceId] = key.split("\0");
1867
+ if (binding === bindingId) sourceIds.add(sourceId);
1868
+ }
1869
+ const nodes = sourceIds.size ? await importers.getNodes(bindingId, [...sourceIds]) : [];
1870
+ for (const sourceId of sourceIds) rows.nodes.set(nodeKey(bindingId, sourceId), null);
1871
+ for (const node of nodes) {
1872
+ rows.nodes.set(nodeKey(node.bindingId, node.sourceId), node);
1873
+ rows.nodesByPage.set(node.pageId, nodeKey(node.bindingId, node.sourceId));
1874
+ }
1875
+ const addChains = async (ids) => {
1876
+ const wanted = [...ids].filter((id) => !rows.pages.has(id));
1877
+ if (!wanted.length) return;
1878
+ const chains = await storage.getPageChains({
1879
+ ids: wanted,
1880
+ read: "all"
1881
+ });
1882
+ for (const id of wanted) {
1883
+ const chain = chains[id] ?? [];
1884
+ if (!chain.length) rows.pages.set(id, null);
1885
+ for (const page of chain) rows.pages.set(page.id, page);
1886
+ const last = chain.at(-1);
1887
+ if (last?.parentId && chain.length <= 10 && !rows.pages.has(last.parentId)) rows.pages.set(last.parentId, null);
1888
+ }
1889
+ };
1890
+ await addChains(/* @__PURE__ */ new Set([
1891
+ ...input.pageIds,
1892
+ ...nodes.map((node) => node.pageId),
1893
+ ...missing?.pages ?? [],
1894
+ ...missing?.locks ?? []
1895
+ ]));
1896
+ let plan = input.plan(rows);
1897
+ const carried = [];
1898
+ let held = [];
1899
+ let settled = false;
1900
+ for (let stage = 0; stage < GATHER_PLAN_STAGES; stage++) {
1901
+ if (stage) plan = input.plan(rows);
1902
+ const before = rows.pages.size + rows.paths.size + rows.complete.size;
1903
+ const roots = [.../* @__PURE__ */ new Set([...plan.subtrees, ...stage ? [] : missing?.subtrees ?? []])].filter((id) => !rows.complete.has(id) && !rows.tooLarge.has(id));
1904
+ if (roots.length) {
1905
+ const subtrees = await storage.getPageSubtrees({
1906
+ rootIds: roots,
1907
+ limit: 499
1908
+ });
1909
+ for (const root of roots) {
1910
+ const pages = subtrees[root];
1911
+ if (!pages) {
1912
+ rows.tooLarge.add(root);
1913
+ continue;
1914
+ }
1915
+ rows.complete.add(root);
1916
+ for (const page of pages) {
1917
+ rows.pages.set(page.id, page);
1918
+ rows.complete.add(page.id);
1919
+ carried.push(page.id);
1920
+ }
1921
+ }
1922
+ const unmapped = carried.filter((id) => !rows.nodesByPage.has(id));
1923
+ if (unmapped.length) {
1924
+ for (const id of unmapped) rows.nodesByPage.set(id, null);
1925
+ for (const node of await importers.getNodesByPages(unmapped)) {
1926
+ const key = nodeKey(node.bindingId, node.sourceId);
1927
+ rows.nodes.set(key, node);
1928
+ rows.nodesByPage.set(node.pageId, key);
1929
+ }
1930
+ }
1931
+ }
1932
+ const paths = new Map(plan.paths.map((each) => [pathKey(each.scopeId, each.path), each]));
1933
+ if (!stage) for (const [key, each] of missing?.paths ?? []) paths.set(key, each);
1934
+ for (const key of [...paths.keys()]) if (rows.paths.has(key)) paths.delete(key);
1935
+ const byScope = /* @__PURE__ */ new Map();
1936
+ for (const [key, { scopeId, path }] of paths) {
1937
+ if (path.length === 0) continue;
1938
+ byScope.set(scopeId, [...byScope.get(scopeId) ?? [], {
1939
+ key,
1940
+ path
1941
+ }]);
1942
+ }
1943
+ for (const [scopeId, entries] of byScope) {
1944
+ const found = await storage.getPagesByPaths({
1945
+ scopeId,
1946
+ paths: entries.map((each) => each.path),
1947
+ read: "all"
1948
+ });
1949
+ entries.forEach((each, i) => {
1950
+ const page = found[i] ?? null;
1951
+ rows.paths.set(each.key, page?.id ?? null);
1952
+ if (page && !rows.pages.has(page.id)) rows.pages.set(page.id, page);
1953
+ });
1954
+ }
1955
+ held = [...rows.paths.values()].filter((id) => !!id);
1956
+ await addChains(new Set(held.map((id) => rows.pages.get(id)?.parentId).filter((id) => !!id)));
1957
+ const byPage = [...new Set([
1958
+ ...held,
1959
+ ...plan.holders ?? [],
1960
+ ...stage ? [] : missing?.nodesByPage ?? []
1961
+ ].filter((id) => !rows.nodesByPage.has(id)))];
1962
+ if (byPage.length) {
1963
+ for (const id of byPage) rows.nodesByPage.set(id, null);
1964
+ for (const node of await importers.getNodesByPages(byPage)) {
1965
+ const key = nodeKey(node.bindingId, node.sourceId);
1966
+ rows.nodes.set(key, node);
1967
+ rows.nodesByPage.set(node.pageId, key);
1968
+ }
1969
+ }
1970
+ if (rows.pages.size + rows.paths.size + rows.complete.size === before) {
1971
+ settled = true;
1972
+ break;
1973
+ }
1974
+ }
1975
+ const targets = new Set(plan.linkTargets);
1976
+ for (const id of carried) {
1977
+ const key = rows.nodesByPage.get(id);
1978
+ const node = key ? rows.nodes.get(key) : null;
1979
+ if (node?.bindingId === bindingId) targets.add(node.sourceId);
1980
+ }
1981
+ for (const key of missing?.linkTargets ?? []) {
1982
+ const [binding, sourceId] = key.split("\0");
1983
+ if (binding === bindingId) targets.add(sourceId);
1984
+ }
1985
+ const wanted = [...targets].filter((sourceId) => !rows.linkTargets.has(nodeKey(bindingId, sourceId)));
1986
+ if (wanted.length) {
1987
+ const linking = await importers.listLinkingNodes(bindingId, wanted, { limit: LINKING_NODES_READ });
1988
+ for (const sourceId of wanted) (linking.next ? rows.tooManyLinkers : rows.linkTargets).add(nodeKey(bindingId, sourceId));
1989
+ const readNodes = async (sourceIds) => {
1990
+ const unread = [...new Set(sourceIds)].filter((sourceId) => !rows.nodes.has(nodeKey(bindingId, sourceId)));
1991
+ if (!unread.length) return [];
1992
+ for (const sourceId of unread) rows.nodes.set(nodeKey(bindingId, sourceId), null);
1993
+ const read = await importers.getNodes(bindingId, unread);
1994
+ for (const node of read) {
1995
+ rows.nodes.set(nodeKey(node.bindingId, node.sourceId), node);
1996
+ rows.nodesByPage.set(node.pageId, nodeKey(node.bindingId, node.sourceId));
1997
+ }
1998
+ return read;
1999
+ };
2000
+ const linkers = await readNodes(linking.items);
2001
+ 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] : []]));
2002
+ await addChains(new Set([...linkers, ...reached].map((node) => node.pageId)));
2003
+ }
2004
+ if (plan.bindings || missing?.bindings.size) rows.bindings ??= await importers.listBindings();
2005
+ const notes = [.../* @__PURE__ */ new Set([
2006
+ ...plan.notes,
2007
+ ...held,
2008
+ ...missing?.notes ?? []
2009
+ ])];
2010
+ if (notes.length) {
2011
+ const listed = await storage.listNotesByPages({
2012
+ pageIds: notes,
2013
+ read: "all"
2014
+ });
2015
+ for (const id of notes) rows.notes.set(id, listed[id] ?? []);
2016
+ }
2017
+ const positions = [.../* @__PURE__ */ new Set([...plan.positions, ...missing?.positions ?? []])];
2018
+ if (positions.length) {
2019
+ const last = await storage.getLastChildPositions({ parentIds: positions });
2020
+ for (const id of positions) rows.positions.set(id, last[id] ?? null);
2021
+ }
2022
+ rows.inPlace = settled && !!plan.inPlace;
2023
+ return rows;
2024
+ }
2025
+ /** Times one gather plans again from what it read (path folders, then the page at the path, then its children). */
2026
+ const GATHER_PLAN_STAGES = 4;
2027
+ /** Most linking nodes one gather reads; past it, a flush that lists them is saved op by op. */
2028
+ const LINKING_NODES_READ = 500;
2029
+ /** Live, non-scope pages among the rows: the ones a decide pass may lock. */
2030
+ const lockable = (rows) => [...rows.pages.values()].filter((page) => !!page && !page.isScope && !page.deletedAt && !page.mergedInto).map((page) => page.id);
2031
+ /**
2032
+ * Reads every row a decide pass needs in a few set-based queries, locks the live pages among them
2033
+ * in one sorted call, and reads again under the lock: what the second read returns can't change
2034
+ * until commit (a new page at an empty path is refused by the unique key when written). Pages the
2035
+ * second read finds that the first didn't are locked too, and read again, up to `rounds` times.
2036
+ */
2037
+ async function gatherImportRows(input) {
2038
+ const locked = new Set(input.locked ?? []);
2039
+ let rows = await readImportRows(input);
2040
+ if (input.storage.getCapabilities().serializedWriteTransactions && rows.notes.size === 0) {
2041
+ for (const id of lockable(rows)) locked.add(id);
2042
+ rows.locked = locked;
2043
+ return rows;
2044
+ }
2045
+ for (let round = 0; round < (input.rounds ?? 3); round++) {
2046
+ const unlocked = lockable(rows).filter((id) => !locked.has(id));
2047
+ if (!unlocked.length) {
2048
+ rows.locked = locked;
2049
+ return rows;
2050
+ }
2051
+ const versions = await input.storage.lockPages(unlocked.sort());
2052
+ for (const id of unlocked) locked.add(id);
2053
+ if (round === 0 && !input.reread && rows.inPlace && rows.notes.size === 0 && Array.isArray(versions) && versions.length === unlocked.length) {
2054
+ const read = new Map(versions.map((row) => [row.id, row.version]));
2055
+ if (unlocked.every((id) => read.get(id) === rows.pages.get(id)?.version)) {
2056
+ rows.locked = locked;
2057
+ rows.readOnce = true;
2058
+ return rows;
2059
+ }
2060
+ }
2061
+ rows = await readImportRows(input);
2062
+ }
2063
+ return null;
2064
+ }
1035
2065
  // src/knowledge/importers/sink.ts
1036
2066
  /**
1037
2067
  * Applies one flush's ops to pages and the node map, on a transaction view. Pages are found by id
@@ -1088,6 +2118,17 @@ const ownText = (body, section) => {
1088
2118
  if (body === section) return "";
1089
2119
  return body.endsWith(`\n\n${section}`) ? body.slice(0, body.length - section.length - 2) : null;
1090
2120
  };
2121
+ /** Decide passes a batched flush makes before it falls back: each reads what the last one lacked. */
2122
+ const BATCH_DECIDE_PASSES = 4;
2123
+ /** The batched flush can't land this one: its savepoint rolls back and the ops go one by one. */
2124
+ var BatchFallback = class extends Error {
2125
+ reason;
2126
+ constructor(reason) {
2127
+ super(`Batched import flush fell back: ${reason}`);
2128
+ this.reason = reason;
2129
+ this.name = "BatchFallback";
2130
+ }
2131
+ };
1091
2132
  /** A per-item refusal: its savepoint rolls back and the flush goes on. */
1092
2133
  var KnowledgeImportRefusalError = class extends Error {
1093
2134
  reason;
@@ -1117,6 +2158,47 @@ function knowledgeImportKey(sourceId) {
1117
2158
  return sourceId.replace(/[/#%:~]/g, (char) => `~${char.charCodeAt(0).toString(16).toUpperCase()}`);
1118
2159
  }
1119
2160
  const live = (page) => !!page && !page.deletedAt && !page.mergedInto;
2161
+ /** Source IDs the host keeps for the folders it makes on an item's path; importers can't send them. */
2162
+ const KNOWLEDGE_IMPORT_PATH_STUB_PREFIX = "~path:";
2163
+ /**
2164
+ * An item's description cut to the page bound, ending in `…`. Every store refuses a longer one, and
2165
+ * that error would roll back the whole flush, leaving the cursor on this item for every later run.
2166
+ * Cuts between code points, at the last word break when one is in the back half.
2167
+ */
2168
+ function fitKnowledgeImportDescription(description) {
2169
+ if (estimateTokenCount(description) <= 100) return description;
2170
+ const chars = [...description];
2171
+ const cut = (length) => {
2172
+ let text = chars.slice(0, length).join("");
2173
+ const lastBreak = text.search(/\s\S*$/);
2174
+ if (lastBreak > text.length / 2) text = text.slice(0, lastBreak);
2175
+ return `${text.trimEnd()}\u2026`;
2176
+ };
2177
+ let low = 0;
2178
+ let high = chars.length - 1;
2179
+ while (low < high) {
2180
+ const mid = Math.ceil((low + high) / 2);
2181
+ if (estimateTokenCount(cut(mid)) <= 100) low = mid;
2182
+ else high = mid - 1;
2183
+ }
2184
+ return cut(low);
2185
+ }
2186
+ /**
2187
+ * Why an item can never land, whatever the store holds: a reserved `sourceId`, or a `path` the host
2188
+ * can't place (with `parent` or `fallbackParent`, empty, an empty or blank segment, a page key too long to
2189
+ * link to, or deeper than a page can sit under a target `targetDepth` keys deep). Null when it can.
2190
+ */
2191
+ function knowledgeImportItemProblem(item, targetDepth) {
2192
+ if (item.sourceId.startsWith("~path:")) return `sourceId must not start with "${KNOWLEDGE_IMPORT_PATH_STUB_PREFIX}"`;
2193
+ const { path } = item;
2194
+ if (path === void 0) return null;
2195
+ if (item.parent != null || item.fallbackParent !== void 0) return "path is not allowed with parent or fallbackParent";
2196
+ if (path.length === 0) return "path must have at least one segment";
2197
+ if (path.some((segment) => !segment.trim())) return "path segments must not be empty or blank";
2198
+ if (path.some((segment) => knowledgeImportKey(segment).length > 512)) return `path segment keys must be at most 512 characters`;
2199
+ if (targetDepth + path.length > 10) return `path would sit more than 10 levels below the scope`;
2200
+ return null;
2201
+ }
1120
2202
  /** Core errors that mean "this op can't land here", by name: an adapter may carry its own core copy. */
1121
2203
  function refusalFor(error) {
1122
2204
  if (error instanceof KnowledgeImportRefusalError) return error.reason;
@@ -1152,11 +2234,17 @@ function order(ops) {
1152
2234
  const id = op.op === "remove" ? op.sourceId : op.item.sourceId;
1153
2235
  const before = last.get(id);
1154
2236
  if (op.op === "declare" && before?.op === "upsert") {
2237
+ const { parent, fallbackParent, path, ...rest } = before.item;
2238
+ const kept = op.item.path !== void 0 ? rest : op.item.parent !== void 0 || op.item.fallbackParent !== void 0 ? {
2239
+ ...rest,
2240
+ ...parent !== void 0 ? { parent } : {},
2241
+ ...fallbackParent !== void 0 ? { fallbackParent } : {}
2242
+ } : before.item;
1155
2243
  last.delete(id);
1156
2244
  last.set(id, {
1157
2245
  op: "upsert",
1158
2246
  item: {
1159
- ...before.item,
2247
+ ...kept,
1160
2248
  ...op.item
1161
2249
  }
1162
2250
  });
@@ -1183,7 +2271,27 @@ function order(ops) {
1183
2271
  return [...sorted, ...removes];
1184
2272
  }
1185
2273
  async function applyKnowledgeImportFlush(input) {
1186
- const { storage, importers, binding, scope, provenance } = input;
2274
+ const { binding, scope, provenance } = input;
2275
+ let { storage, importers } = input;
2276
+ let overlay = null;
2277
+ /**
2278
+ * Link-index work for a written page: a sync of its body links, then maybe a refresh of the links to
2279
+ * it. Run now, or after the batched write in one repair when deciding over the working copy.
2280
+ */
2281
+ const links = async (sync, refresh) => {
2282
+ if (overlay) {
2283
+ if (sync) overlay.deferLinks({ sync });
2284
+ for (const page of refresh?.pages ?? []) overlay.deferLinks({
2285
+ refresh: page,
2286
+ withDescendants: !!refresh.withDescendants
2287
+ });
2288
+ return;
2289
+ }
2290
+ await syncLinks(async () => {
2291
+ if (sync) await syncKnowledgePageBodyLinks(storage, sync);
2292
+ if (refresh) await refreshKnowledgeLinksTo(storage, refresh.pages, { withDescendants: refresh.withDescendants });
2293
+ });
2294
+ };
1187
2295
  const target = parseKnowledgeImportTarget(binding.target);
1188
2296
  const result = {
1189
2297
  counts: {
@@ -1192,14 +2300,27 @@ async function applyKnowledgeImportFlush(input) {
1192
2300
  unchanged: 0,
1193
2301
  moved: 0,
1194
2302
  removed: 0,
1195
- stubbed: 0
2303
+ stubbed: 0,
2304
+ merged: 0
1196
2305
  },
1197
2306
  refused: [],
1198
2307
  changes: [],
1199
2308
  embeds: [],
1200
2309
  applied: false
1201
2310
  };
1202
- const ops = order(input.ops);
2311
+ const rekey = !!storage.getCapabilities().supportsPageRekey;
2312
+ let ops = order(input.ops).filter((op) => {
2313
+ const sourceId = op.op === "remove" ? op.sourceId : op.item.sourceId;
2314
+ const problem = op.op === "remove" ? sourceId.startsWith(KNOWLEDGE_IMPORT_PATH_STUB_PREFIX) : !!knowledgeImportItemProblem(op.item, 1);
2315
+ const unplaceable = op.op !== "remove" && op.item.path !== void 0 && !rekey;
2316
+ if (!problem && !unplaceable) return true;
2317
+ if (!problem) result.pathsUnsupported = true;
2318
+ result.refused.push({
2319
+ sourceId,
2320
+ reason: "invalid"
2321
+ });
2322
+ return false;
2323
+ });
1203
2324
  if (ops.length === 0 && !(input.settle && binding.anchorPageId)) {
1204
2325
  if (input.settle) result.settle = {
1205
2326
  pending: false,
@@ -1212,20 +2333,28 @@ async function applyKnowledgeImportFlush(input) {
1212
2333
  const keyPath = async (page) => {
1213
2334
  const keys = [];
1214
2335
  const ids = [];
1215
- let at = page;
1216
- while (at && !at.isScope) {
2336
+ const versions = [];
2337
+ if (page.isScope) return page.id === scope.id ? {
2338
+ keys,
2339
+ ids,
2340
+ versions
2341
+ } : null;
2342
+ const parents = page.parentId ? await storage.getPageParents({
2343
+ parentId: page.parentId,
2344
+ read: "all"
2345
+ }) : [];
2346
+ for (const at of [page, ...parents]) {
2347
+ if (at.isScope) return at.id === scope.id ? {
2348
+ keys,
2349
+ ids,
2350
+ versions
2351
+ } : null;
1217
2352
  if (!live(at) || at.key === void 0) return null;
1218
2353
  keys.unshift(at.key);
1219
2354
  ids.unshift(at.id);
1220
- at = at.parentId ? await storage.getPage({
1221
- id: at.parentId,
1222
- read: "all"
1223
- }) : null;
2355
+ versions.unshift(at.version);
1224
2356
  }
1225
- return at?.id === scope.id ? {
1226
- keys,
1227
- ids
1228
- } : null;
2357
+ return null;
1229
2358
  };
1230
2359
  const sameKeys = (a, b) => a.length === b.length && a.every((key, i) => key === b[i]);
1231
2360
  /**
@@ -1256,8 +2385,17 @@ async function applyKnowledgeImportFlush(input) {
1256
2385
  read: "all"
1257
2386
  });
1258
2387
  const path = live(page) ? await keyPath(page) : null;
2388
+ if (page && path && storage.getCapabilities().serializedWriteTransactions) return {
2389
+ page,
2390
+ keys: path.keys
2391
+ };
1259
2392
  if (page && path) {
1260
- await storage.lockPages(path.ids);
2393
+ const read = new Map(path.ids.map((id, i) => [id, path.versions[i]]));
2394
+ const locked = await storage.lockPages(path.ids);
2395
+ if (Array.isArray(locked) && locked.length === read.size && locked.every((row) => read.get(row.id) === row.version)) return {
2396
+ page,
2397
+ keys: path.keys
2398
+ };
1261
2399
  const fresh = await storage.getPage({
1262
2400
  id: page.id,
1263
2401
  read: "all"
@@ -1338,6 +2476,15 @@ async function applyKnowledgeImportFlush(input) {
1338
2476
  return result;
1339
2477
  }
1340
2478
  const anchorPath = anchor?.keys ?? [];
2479
+ ops = ops.filter((op) => {
2480
+ if (op.op === "remove" || !op.item.path) return true;
2481
+ if (anchorPath.length + op.item.path.length <= 10) return true;
2482
+ result.refused.push({
2483
+ sourceId: op.item.sourceId,
2484
+ reason: "invalid"
2485
+ });
2486
+ return false;
2487
+ });
1341
2488
  /**
1342
2489
  * A page this binding owns, checked after locking: live, in the target's scope, mapped back to the
1343
2490
  * node. A person may have moved it out of the anchor, under anyone's pages: it is still the
@@ -1372,12 +2519,13 @@ async function applyKnowledgeImportFlush(input) {
1372
2519
  };
1373
2520
  };
1374
2521
  const nodeOf = async (sourceId) => sourceId ? importers.getNode(binding.id, sourceId) : null;
1375
- const gone = async (node) => {
2522
+ const stateOf = async (node) => {
1376
2523
  const page = await storage.getPage({
1377
2524
  id: node.pageId,
1378
2525
  read: "all"
1379
2526
  });
1380
- return !page || !!page.deletedAt && !page.mergedInto || live(page) && page.scopeId !== scope.id;
2527
+ if (page?.mergedInto) return "merged";
2528
+ return !page || !!page.deletedAt || page.scopeId !== scope.id ? "gone" : "live";
1381
2529
  };
1382
2530
  /**
1383
2531
  * Drops the node of a page that is gone, so its item is written again as new. Pages that linked to
@@ -1429,15 +2577,98 @@ async function applyKnowledgeImportFlush(input) {
1429
2577
  });
1430
2578
  await importers.markLinkingNodesUnsettled(binding.id, [node.sourceId]);
1431
2579
  await importers.deleteNode(binding.id, node.sourceId);
1432
- if (old) await syncLinks(() => refreshKnowledgeLinksTo(storage, [old]));
2580
+ if (old) await links(null, { pages: [old] });
1433
2581
  };
1434
2582
  const liveNodeOf = async (sourceId) => {
1435
2583
  const node = await nodeOf(sourceId);
1436
- return node && !await gone(node) ? node : null;
2584
+ return node && await stateOf(node) === "live" ? node : null;
1437
2585
  };
1438
2586
  const ref = (keys) => `${target.scope}#${keys.join("/")}`;
1439
- const linkLine = async (link) => {
1440
- const node = await importers.getNode(binding.id, link.sourceId);
2587
+ /** The folders an op's path made, counted as created once the op lands. */
2588
+ let madeFolders = [];
2589
+ /**
2590
+ * The page a path item goes under: the anchor, then each segment but the last. A live page at a
2591
+ * segment is used as it is, whoever wrote it; a missing one (a merged page reads as missing, as a
2592
+ * merged parent does for a new child) becomes an empty folder this binding owns, keyed
2593
+ * `~path:<keys>`, that the item sending that path takes over. Returns the node the item is under,
2594
+ * when it is this binding's.
2595
+ */
2596
+ const pathFolders = async (path) => {
2597
+ let at = anchor;
2598
+ let parentSourceId = null;
2599
+ let holderOf = null;
2600
+ const readHolder = async () => {
2601
+ if (!holderOf) return;
2602
+ const holder = await importers.getNodeByPage(holderOf.id);
2603
+ parentSourceId = holder?.bindingId === binding.id ? holder.sourceId : null;
2604
+ holderOf = null;
2605
+ };
2606
+ const relative = [];
2607
+ for (const segment of path.slice(0, -1)) {
2608
+ const key = knowledgeImportKey(segment);
2609
+ relative.push(key);
2610
+ const keys = [...at.keys, key];
2611
+ const found = await storage.getPageByPath({
2612
+ scopeId: scope.id,
2613
+ path: keys,
2614
+ read: "all"
2615
+ });
2616
+ if (found) {
2617
+ await storage.lockPages([found.id]);
2618
+ const fresh = await storage.getPage({
2619
+ id: found.id,
2620
+ read: "all"
2621
+ });
2622
+ if (!live(fresh) || fresh.parentId !== at.page.id || fresh.key !== key) throw new KnowledgeImportRefusalError("conflict");
2623
+ holderOf = fresh;
2624
+ at = {
2625
+ page: fresh,
2626
+ keys
2627
+ };
2628
+ continue;
2629
+ }
2630
+ await readHolder();
2631
+ const sourceId = KNOWLEDGE_IMPORT_PATH_STUB_PREFIX + relative.join("/");
2632
+ const page = await storage.createPage({
2633
+ parentId: at.page.id,
2634
+ key,
2635
+ name: segment,
2636
+ body: "",
2637
+ provenance
2638
+ });
2639
+ await importers.saveNode({
2640
+ bindingId: binding.id,
2641
+ sourceId,
2642
+ pageId: page.id,
2643
+ kind: null,
2644
+ parentSourceId,
2645
+ aliases: [],
2646
+ unresolvedLinks: [],
2647
+ links: [],
2648
+ linkSection: null,
2649
+ stub: false,
2650
+ adopted: false,
2651
+ unsettled: false
2652
+ });
2653
+ await links(page, { pages: [page] });
2654
+ madeFolders.push({
2655
+ sourceId,
2656
+ page,
2657
+ keys
2658
+ });
2659
+ parentSourceId = sourceId;
2660
+ at = {
2661
+ page,
2662
+ keys
2663
+ };
2664
+ }
2665
+ await readHolder();
2666
+ return {
2667
+ destination: at,
2668
+ parentSourceId
2669
+ };
2670
+ };
2671
+ const linkLine = async (link, node) => {
1441
2672
  const page = node ? await storage.getPage({
1442
2673
  id: node.pageId,
1443
2674
  read: "all"
@@ -1448,11 +2679,30 @@ async function applyKnowledgeImportFlush(input) {
1448
2679
  const renderLinks = async (links) => {
1449
2680
  const lines = [];
1450
2681
  const unresolved = [];
2682
+ const getNodes = async (sourceIds) => {
2683
+ if (!sourceIds.length) return [];
2684
+ if (importers.getNodes) return importers.getNodes(binding.id, sourceIds);
2685
+ const nodes = [];
2686
+ for (const sourceId of new Set(sourceIds)) {
2687
+ const node = await importers.getNode(binding.id, sourceId);
2688
+ if (node) nodes.push(node);
2689
+ }
2690
+ return nodes;
2691
+ };
2692
+ const read = async (sourceIds) => new Map((await getNodes(sourceIds)).map((node) => [node.sourceId, node]));
2693
+ const before = await read(links.map((link) => link.sourceId));
2694
+ const rendered = [];
1451
2695
  for (const link of links) {
1452
- const line = await linkLine(link);
1453
- if (line) lines.push(line);
1454
- else unresolved.push(encodeLink(link));
2696
+ const node = before.get(link.sourceId);
2697
+ rendered.push({
2698
+ link,
2699
+ line: await linkLine(link, node),
2700
+ pageId: node?.pageId
2701
+ });
1455
2702
  }
2703
+ const after = await read(rendered.filter((each) => each.line).map((each) => each.link.sourceId));
2704
+ for (const { link, line, pageId } of rendered) if (line && after.get(link.sourceId)?.pageId === pageId) lines.push(line);
2705
+ else unresolved.push(encodeLink(link));
1456
2706
  return {
1457
2707
  section: linkSection(lines),
1458
2708
  unresolved
@@ -1498,7 +2748,7 @@ async function applyKnowledgeImportFlush(input) {
1498
2748
  body,
1499
2749
  provenance
1500
2750
  });
1501
- await syncLinks(() => syncKnowledgePageBodyLinks(storage, page));
2751
+ await links(page);
1502
2752
  return {
1503
2753
  page,
1504
2754
  changed: true,
@@ -1523,7 +2773,7 @@ async function applyKnowledgeImportFlush(input) {
1523
2773
  * and the pages it rewrote; the caller counts them once its op lands.
1524
2774
  */
1525
2775
  let deferredLinkers = false;
1526
- const moveOwned = async (self, page, parent) => {
2776
+ const moveOwned = async (self, page, parent, key) => {
1527
2777
  const targets = [];
1528
2778
  const othersTargets = /* @__PURE__ */ new Map();
1529
2779
  await storage.lockSubtree(page.id);
@@ -1537,6 +2787,7 @@ async function applyKnowledgeImportFlush(input) {
1537
2787
  id: page.id,
1538
2788
  expectedVersion: page.version,
1539
2789
  parentId: parent.page.id,
2790
+ ...key !== void 0 && key !== page.key ? { key } : {},
1540
2791
  provenance
1541
2792
  });
1542
2793
  const keys = [...parent.keys, moved.key];
@@ -1592,24 +2843,131 @@ async function applyKnowledgeImportFlush(input) {
1592
2843
  });
1593
2844
  }
1594
2845
  };
2846
+ /**
2847
+ * Frees `key` under `destination` for a path item's own page to move onto. A folder of this binding's
2848
+ * that holds the path is absorbed: its children move under the item's page in order, their nodes
2849
+ * point at the item, a body a person wrote in it is kept in a note on the item's page, and the empty
2850
+ * folder goes. A folder someone left notes on, or whose body would replace a body the item's page
2851
+ * already keeps, is not absorbed: the item is refused `occupied`, as for any other page at the path.
2852
+ * An item inside the folder, sent at the folder's path, leaves it first under a key no item uses, so
2853
+ * it never moves under itself; the move after this one gives it the folder's key. Returns whether it
2854
+ * kept a body (the item then holds a person's text, so its removal gives that back) and the item's
2855
+ * page as it is now.
2856
+ */
2857
+ const absorbAt = async (self, destination, key, page) => {
2858
+ const held = await storage.getPageByPath({
2859
+ scopeId: scope.id,
2860
+ path: [...destination.keys, key],
2861
+ read: "all"
2862
+ });
2863
+ if (!held || held.id === page.id) return {
2864
+ kept: false,
2865
+ page
2866
+ };
2867
+ await storage.lockPages([held.id]);
2868
+ const stub = await storage.getPage({
2869
+ id: held.id,
2870
+ read: "all"
2871
+ });
2872
+ if (!live(stub) || stub.parentId !== destination.page.id || stub.key !== key) throw new KnowledgeImportRefusalError("occupied");
2873
+ const holder = await importers.getNodeByPage(stub.id);
2874
+ if (holder?.bindingId !== binding.id || !holder.sourceId.startsWith("~path:")) throw new KnowledgeImportRefusalError("occupied");
2875
+ if ((await storage.listNotes({
2876
+ pageId: stub.id,
2877
+ read: "all",
2878
+ limit: 1
2879
+ })).notes.length > 0) throw new KnowledgeImportRefusalError("occupied");
2880
+ if (stub.body && (await keptBodyNotes(page.id)).length > 0) throw new KnowledgeImportRefusalError("occupied");
2881
+ const children = [];
2882
+ let cursor;
2883
+ do {
2884
+ const out = await storage.listChildPages({
2885
+ parentId: stub.id,
2886
+ read: "all",
2887
+ ...cursor ? { cursor } : {}
2888
+ });
2889
+ children.push(...out.pages);
2890
+ cursor = out.nextCursor;
2891
+ } while (cursor);
2892
+ let inside = page.parentId;
2893
+ while (inside && inside !== stub.id) inside = (await storage.getPage({
2894
+ id: inside,
2895
+ read: "all"
2896
+ }))?.parentId ?? null;
2897
+ if (inside) {
2898
+ await storage.lockSubtree(page.id);
2899
+ page = await storage.movePage({
2900
+ id: page.id,
2901
+ expectedVersion: page.version,
2902
+ parentId: destination.page.id,
2903
+ key: `~absorbing-${randomUUID()}`,
2904
+ provenance
2905
+ });
2906
+ }
2907
+ for (const child of children.filter((child) => child.id !== page.id)) {
2908
+ await storage.lockSubtree(child.id);
2909
+ await storage.movePage({
2910
+ id: child.id,
2911
+ expectedVersion: child.version,
2912
+ parentId: page.id,
2913
+ provenance
2914
+ });
2915
+ const node = await importers.getNodeByPage(child.id);
2916
+ if (node?.bindingId === binding.id && node.parentSourceId === holder.sourceId) await importers.saveNode({
2917
+ ...node,
2918
+ parentSourceId: self
2919
+ });
2920
+ }
2921
+ if (stub.body) await keepBody(page.id, stub.body);
2922
+ const emptied = await storage.getPage({
2923
+ id: stub.id,
2924
+ read: "all"
2925
+ });
2926
+ await storage.deletePage({
2927
+ id: stub.id,
2928
+ expectedVersion: emptied.version,
2929
+ deletedBy: provenance.author
2930
+ });
2931
+ await importers.deleteNode(binding.id, holder.sourceId);
2932
+ return {
2933
+ kept: !!stub.body,
2934
+ page
2935
+ };
2936
+ };
1595
2937
  const write = async (item, hasBody) => {
1596
2938
  let existing = await importers.getNode(binding.id, item.sourceId);
1597
- if (existing && await gone(existing)) {
2939
+ const state = existing ? await stateOf(existing) : null;
2940
+ if (state === "merged") return null;
2941
+ if (existing && state === "gone") {
1598
2942
  await forget(existing);
1599
2943
  existing = null;
1600
2944
  }
1601
- const sourceParent = await liveNodeOf(item.parent);
1602
- const misplaced = !!item.parent && !sourceParent;
2945
+ const parentRecord = await nodeOf(item.parent);
2946
+ const parentState = parentRecord ? await stateOf(parentRecord) : null;
2947
+ const sourceParent = parentState === "live" ? parentRecord : null;
2948
+ const parentMerged = parentState === "merged";
2949
+ const misplaced = !!item.parent && !sourceParent && !parentMerged;
1603
2950
  const parentNode = sourceParent ?? await liveNodeOf(item.fallbackParent);
1604
- const destination = parentNode ? await owned(parentNode.pageId, parentNode.sourceId) : anchor;
2951
+ let destination = parentNode ? await owned(parentNode.pageId, parentNode.sourceId) : anchor;
2952
+ let key = knowledgeImportKey(item.sourceId);
2953
+ let parentSourceId = item.parent ?? null;
2954
+ if (item.path) {
2955
+ const current = existing ? await owned(existing.pageId, item.sourceId) : null;
2956
+ if (current?.outside) {
2957
+ key = current.page.key;
2958
+ parentSourceId = existing.parentSourceId;
2959
+ } else {
2960
+ ({destination, parentSourceId} = await pathFolders(item.path));
2961
+ key = knowledgeImportKey(item.path.at(-1));
2962
+ }
2963
+ }
1605
2964
  if (existing && destination.page.id === existing.pageId) throw new KnowledgeImportRefusalError("invalid");
1606
2965
  let rendered = hasBody ? await renderBody(item) : void 0;
1607
2966
  let fields = {
1608
2967
  name: item.title,
1609
- ...item.description !== void 0 ? { description: item.description } : {},
2968
+ ...item.description !== void 0 ? { description: fitKnowledgeImportDescription(item.description) } : {},
1610
2969
  ...rendered ? { body: rendered.body } : {}
1611
2970
  };
1612
- const key = knowledgeImportKey(item.sourceId);
1613
2971
  let page;
1614
2972
  let change;
1615
2973
  let moved = false;
@@ -1629,9 +2987,34 @@ async function applyKnowledgeImportFlush(input) {
1629
2987
  read: "all"
1630
2988
  });
1631
2989
  if (!live(fresh) || fresh.parentId !== destination.page.id || fresh.key !== key) throw new KnowledgeImportRefusalError("occupied");
1632
- const imported = await release(fresh.id);
2990
+ const holder = await importers.getNodeByPage(fresh.id);
1633
2991
  renamed = fields.name !== fresh.name;
1634
- if (!imported) await keepBody(fresh.id, fresh.body ?? "");
2992
+ if (holder?.bindingId === binding.id) {
2993
+ if (!holder.sourceId.startsWith("~path:")) throw new KnowledgeImportRefusalError("occupied");
2994
+ const childIds = [];
2995
+ let cursor;
2996
+ do {
2997
+ const out = await storage.listChildPages({
2998
+ parentId: fresh.id,
2999
+ read: "all",
3000
+ ...cursor ? { cursor } : {}
3001
+ });
3002
+ childIds.push(...out.pages.map((child) => child.id));
3003
+ cursor = out.nextCursor;
3004
+ } while (cursor);
3005
+ const childNodes = importers.getNodesByPages ? await importers.getNodesByPages(childIds) : (await Promise.all(childIds.map((id) => importers.getNodeByPage(id)))).filter((n) => !!n);
3006
+ await importers.deleteNode(binding.id, holder.sourceId);
3007
+ for (const child of childNodes) if (child.bindingId === binding.id && child.parentSourceId === holder.sourceId) await importers.saveNode({
3008
+ ...child,
3009
+ parentSourceId: item.sourceId
3010
+ });
3011
+ if (fresh.body) await keepBody(fresh.id, fresh.body);
3012
+ adopted = !!fresh.body;
3013
+ } else {
3014
+ await release(fresh.id);
3015
+ if (!holder) await keepBody(fresh.id, fresh.body ?? "");
3016
+ adopted = true;
3017
+ }
1635
3018
  page = await storage.updatePage({
1636
3019
  id: fresh.id,
1637
3020
  expectedVersion: fresh.version,
@@ -1639,7 +3022,6 @@ async function applyKnowledgeImportFlush(input) {
1639
3022
  provenance
1640
3023
  });
1641
3024
  change = "updated";
1642
- adopted = true;
1643
3025
  } else if (!existing) {
1644
3026
  page = await storage.createPage({
1645
3027
  parentId: destination.page.id,
@@ -1653,9 +3035,15 @@ async function applyKnowledgeImportFlush(input) {
1653
3035
  const current = await owned(existing.pageId, item.sourceId);
1654
3036
  page = current.page;
1655
3037
  if (existing.stub && existing.adopted && !REMOVED_BODIES.has(page.body ?? "")) await keepBody(page.id, page.body ?? "");
1656
- if (!current.outside && page.parentId !== destination.page.id) {
3038
+ const rekey = !!item.path && !current.outside && page.key !== key;
3039
+ if (!current.outside && !parentMerged && (page.parentId !== destination.page.id || rekey)) {
1657
3040
  if (destination.keys.length > current.keys.length && sameKeys(destination.keys.slice(0, current.keys.length), current.keys)) throw new KnowledgeImportRefusalError("invalid");
1658
- ({page, relinked} = await moveOwned(item.sourceId, page, destination));
3041
+ if (item.path) {
3042
+ const absorbed = await absorbAt(item.sourceId, destination, key, page);
3043
+ page = absorbed.page;
3044
+ if (absorbed.kept) adopted = true;
3045
+ }
3046
+ ({page, relinked} = await moveOwned(item.sourceId, page, destination, item.path ? key : void 0));
1659
3047
  moved = true;
1660
3048
  if (hasBody) {
1661
3049
  rendered = await renderBody(item);
@@ -1692,7 +3080,7 @@ async function applyKnowledgeImportFlush(input) {
1692
3080
  sourceId: item.sourceId,
1693
3081
  pageId: page.id,
1694
3082
  kind: item.kind ?? existing?.kind ?? null,
1695
- parentSourceId: item.parent ?? null,
3083
+ parentSourceId,
1696
3084
  aliases: item.aliases ?? existing?.aliases ?? [],
1697
3085
  unresolvedLinks: rendered ? rendered.unresolved : existing?.unresolvedLinks ?? [],
1698
3086
  links: rendered ? rendered.links : existing?.links ?? [],
@@ -1701,10 +3089,10 @@ async function applyKnowledgeImportFlush(input) {
1701
3089
  adopted,
1702
3090
  unsettled: misplaced || (rendered ? rendered.unresolved : existing?.unresolvedLinks ?? []).length > 0
1703
3091
  });
1704
- if (change !== "unchanged" || existing?.stub) await syncLinks(async () => {
1705
- await syncKnowledgePageBodyLinks(storage, page);
1706
- if (change === "created" || renamed || moved) await refreshKnowledgeLinksTo(storage, [page], { withDescendants: moved });
1707
- });
3092
+ if (change !== "unchanged" || existing?.stub) await links(page, change === "created" || renamed || moved ? {
3093
+ pages: [page],
3094
+ withDescendants: moved
3095
+ } : void 0);
1708
3096
  return {
1709
3097
  page,
1710
3098
  change,
@@ -1712,136 +3100,166 @@ async function applyKnowledgeImportFlush(input) {
1712
3100
  relinked
1713
3101
  };
1714
3102
  };
1715
- const depth = /* @__PURE__ */ new Map();
1716
- for (const op of ops) {
1717
- if (op.op !== "remove") continue;
1718
- const node = await importers.getNode(binding.id, op.sourceId);
1719
- const page = node ? await storage.getPage({
1720
- id: node.pageId,
1721
- read: "all"
1722
- }) : null;
1723
- const path = live(page) ? await keyPath(page) : null;
1724
- depth.set(op.sourceId, path?.keys.length ?? 0);
1725
- }
1726
- const writes = ops.filter((op) => op.op !== "remove");
1727
- const removes = ops.filter((op) => op.op === "remove").sort((a, b) => depth.get(b.sourceId) - depth.get(a.sourceId));
1728
- for (const op of [...writes, ...removes]) {
1729
- const sourceId = op.op === "remove" ? op.sourceId : op.item.sourceId;
1730
- const embeds = [];
1731
- try {
1732
- await storage.transaction(async () => {
1733
- if (op.op === "remove") {
1734
- const node = await importers.getNode(binding.id, sourceId);
1735
- if (!node) return;
1736
- if (await gone(node)) {
1737
- await forget(node);
3103
+ const runOps = async () => {
3104
+ const depth = /* @__PURE__ */ new Map();
3105
+ for (const op of ops) {
3106
+ if (op.op !== "remove") continue;
3107
+ const node = await importers.getNode(binding.id, op.sourceId);
3108
+ const page = node ? await storage.getPage({
3109
+ id: node.pageId,
3110
+ read: "all"
3111
+ }) : null;
3112
+ const path = live(page) ? await keyPath(page) : null;
3113
+ depth.set(op.sourceId, path?.keys.length ?? 0);
3114
+ }
3115
+ const writes = ops.filter((op) => op.op !== "remove");
3116
+ const removes = ops.filter((op) => op.op === "remove").sort((a, b) => depth.get(b.sourceId) - depth.get(a.sourceId));
3117
+ for (const op of [...writes, ...removes]) {
3118
+ const sourceId = op.op === "remove" ? op.sourceId : op.item.sourceId;
3119
+ const embeds = [];
3120
+ madeFolders = [];
3121
+ try {
3122
+ await storage.transaction(async () => {
3123
+ if (op.op === "remove") {
3124
+ const node = await importers.getNode(binding.id, sourceId);
3125
+ if (!node) return;
3126
+ const state = await stateOf(node);
3127
+ if (state === "merged") return;
3128
+ if (state === "gone") {
3129
+ await forget(node);
3130
+ result.applied = true;
3131
+ return;
3132
+ }
3133
+ const current = await owned(node.pageId, sourceId);
3134
+ await storage.lockSubtree(current.page.id);
3135
+ const children = (await storage.countChildPages({
3136
+ parentIds: [current.page.id],
3137
+ read: "all"
3138
+ }))[current.page.id] ?? 0;
3139
+ const folder = (await importers.listBindings()).some((other) => other.id !== binding.id && other.anchorPageId === current.page.id);
3140
+ if (children > 0 || node.adopted || folder) {
3141
+ if (node.stub) return;
3142
+ const note = node.adopted ? (await keptBodyNotes(current.page.id)).at(-1) : void 0;
3143
+ const heading = ORIGINAL_BODY_NOTE_HEADINGS.find((h) => note?.text.startsWith(h));
3144
+ const original = heading ? note.text.slice(heading.length) : note?.text;
3145
+ const page = await storage.updatePage({
3146
+ id: current.page.id,
3147
+ expectedVersion: current.page.version,
3148
+ 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."),
3149
+ provenance
3150
+ });
3151
+ await importers.saveNode({
3152
+ ...node,
3153
+ stub: true
3154
+ });
3155
+ await links(page);
3156
+ embeds.push({
3157
+ kind: "index",
3158
+ pageId: page.id
3159
+ });
3160
+ result.counts.stubbed++;
3161
+ result.changes.push({
3162
+ sourceId,
3163
+ pageId: page.id,
3164
+ change: "stubbed",
3165
+ title: page.name,
3166
+ path: ref(current.keys)
3167
+ });
3168
+ } else {
3169
+ const deleted = await storage.deletePage({
3170
+ id: current.page.id,
3171
+ expectedVersion: current.page.version,
3172
+ deletedBy: provenance.author
3173
+ });
3174
+ await importers.deleteNode(binding.id, sourceId);
3175
+ if ((await importers.listLinkingNodes(binding.id, [sourceId], { limit: 1 })).items.length > 0) {
3176
+ await importers.markLinkingNodesUnsettled(binding.id, [sourceId]);
3177
+ await importers.setState(binding.id, { [KNOWLEDGE_IMPORT_SETTLE_RESTART_KEY]: randomUUID() });
3178
+ deferredLinkers = true;
3179
+ }
3180
+ await links(deleted, { pages: [deleted] });
3181
+ embeds.push({
3182
+ kind: "remove",
3183
+ pageId: deleted.id
3184
+ });
3185
+ result.counts.removed++;
3186
+ result.changes.push({
3187
+ sourceId,
3188
+ pageId: null,
3189
+ change: "removed",
3190
+ title: deleted.name,
3191
+ path: ref(current.keys)
3192
+ });
3193
+ }
1738
3194
  result.applied = true;
1739
3195
  return;
1740
3196
  }
1741
- const current = await owned(node.pageId, sourceId);
1742
- await storage.lockSubtree(current.page.id);
1743
- const children = (await storage.countChildPages({
1744
- parentIds: [current.page.id],
1745
- read: "all"
1746
- }))[current.page.id] ?? 0;
1747
- const folder = (await importers.listBindings()).some((other) => other.id !== binding.id && other.anchorPageId === current.page.id);
1748
- if (children > 0 || node.adopted || folder) {
1749
- if (node.stub) return;
1750
- const note = node.adopted ? (await keptBodyNotes(current.page.id)).at(-1) : void 0;
1751
- const heading = ORIGINAL_BODY_NOTE_HEADINGS.find((h) => note?.text.startsWith(h));
1752
- const original = heading ? note.text.slice(heading.length) : note?.text;
1753
- const page = await storage.updatePage({
1754
- id: current.page.id,
1755
- expectedVersion: current.page.version,
1756
- 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."),
1757
- provenance
1758
- });
1759
- await importers.saveNode({
1760
- ...node,
1761
- stub: true
1762
- });
1763
- await syncLinks(() => syncKnowledgePageBodyLinks(storage, page));
3197
+ const written = await write(op.item, op.op === "upsert");
3198
+ for (const folder of madeFolders) {
3199
+ result.applied = true;
3200
+ result.counts.created++;
1764
3201
  embeds.push({
1765
3202
  kind: "index",
1766
- pageId: page.id
1767
- });
1768
- result.counts.stubbed++;
1769
- result.changes.push({
1770
- sourceId,
1771
- pageId: page.id,
1772
- change: "stubbed",
1773
- title: page.name,
1774
- path: ref(current.keys)
1775
- });
1776
- } else {
1777
- const deleted = await storage.deletePage({
1778
- id: current.page.id,
1779
- expectedVersion: current.page.version,
1780
- deletedBy: provenance.author
1781
- });
1782
- await importers.deleteNode(binding.id, sourceId);
1783
- if ((await importers.listLinkingNodes(binding.id, [sourceId], { limit: 1 })).items.length > 0) {
1784
- await importers.markLinkingNodesUnsettled(binding.id, [sourceId]);
1785
- await importers.setState(binding.id, { [KNOWLEDGE_IMPORT_SETTLE_RESTART_KEY]: randomUUID() });
1786
- deferredLinkers = true;
1787
- }
1788
- await syncLinks(async () => {
1789
- await syncKnowledgePageBodyLinks(storage, deleted);
1790
- await refreshKnowledgeLinksTo(storage, [deleted]);
3203
+ pageId: folder.page.id
1791
3204
  });
1792
- embeds.push({
1793
- kind: "remove",
1794
- pageId: deleted.id
1795
- });
1796
- result.counts.removed++;
1797
3205
  result.changes.push({
1798
- sourceId,
1799
- pageId: null,
1800
- change: "removed",
1801
- title: deleted.name,
1802
- path: ref(current.keys)
3206
+ sourceId: folder.sourceId,
3207
+ pageId: folder.page.id,
3208
+ change: "created",
3209
+ title: folder.page.name,
3210
+ path: ref(folder.keys)
1803
3211
  });
1804
3212
  }
3213
+ if (!written) {
3214
+ result.counts.merged++;
3215
+ return;
3216
+ }
3217
+ const { page, change, moved, relinked } = written;
3218
+ recordRelinked(relinked, embeds);
3219
+ if (change === "unchanged") {
3220
+ result.counts.unchanged++;
3221
+ return;
3222
+ }
1805
3223
  result.applied = true;
1806
- return;
1807
- }
1808
- const { page, change, moved, relinked } = await write(op.item, op.op === "upsert");
1809
- recordRelinked(relinked, embeds);
1810
- if (change === "unchanged") {
1811
- result.counts.unchanged++;
1812
- return;
1813
- }
1814
- result.applied = true;
1815
- if (change !== "moved") embeds.push({
1816
- kind: "index",
1817
- pageId: page.id
3224
+ if (change !== "moved") embeds.push({
3225
+ kind: "index",
3226
+ pageId: page.id
3227
+ });
3228
+ if (change === "created") result.counts.created++;
3229
+ else if (change === "updated") result.counts.updated++;
3230
+ if (moved) result.counts.moved++;
3231
+ const path = await keyPath(page);
3232
+ result.changes.push({
3233
+ sourceId,
3234
+ pageId: page.id,
3235
+ change,
3236
+ title: page.name,
3237
+ path: path ? ref(path.keys) : ""
3238
+ });
1818
3239
  });
1819
- if (change === "created") result.counts.created++;
1820
- else if (change === "updated") result.counts.updated++;
1821
- if (moved) result.counts.moved++;
1822
- const path = await keyPath(page);
1823
- result.changes.push({
3240
+ result.embeds.push(...embeds);
3241
+ } catch (error) {
3242
+ const reason = refusalFor(error);
3243
+ if (!reason) throw error;
3244
+ result.refused.push({
1824
3245
  sourceId,
1825
- pageId: page.id,
1826
- change,
1827
- title: page.name,
1828
- path: path ? ref(path.keys) : ""
3246
+ reason
1829
3247
  });
1830
- });
1831
- result.embeds.push(...embeds);
1832
- } catch (error) {
1833
- const reason = refusalFor(error);
1834
- if (!reason) throw error;
1835
- result.refused.push({
1836
- sourceId,
1837
- reason
1838
- });
3248
+ }
3249
+ }
3250
+ };
3251
+ if (!canBatchImportFlush(input.storage, input.importers)) await runOps();
3252
+ else if (ops.length) {
3253
+ const fallback = await applyBatched(anchor?.page ?? null);
3254
+ if (fallback) {
3255
+ result.fallback = fallback;
3256
+ await runOps();
1839
3257
  }
1840
3258
  }
1841
3259
  if (input.settle) {
1842
3260
  if (anchor) {
1843
3261
  input.settle.onStart?.();
1844
- result.settle = await settle(input.settle);
3262
+ result.settle = await settle(input.settle, anchor.page);
1845
3263
  } else result.settle = {
1846
3264
  pending: false,
1847
3265
  cursor: null,
@@ -1851,13 +3269,369 @@ async function applyKnowledgeImportFlush(input) {
1851
3269
  }
1852
3270
  return result;
1853
3271
  /**
3272
+ * Decides every op over a working copy (overlay.ts) and writes what they decided in a few
3273
+ * set-based statements, all in one savepoint (batched-flush plan v3.1). Returns why it fell back,
3274
+ * with the savepoint rolled back and the result as before, or null once the ops landed.
3275
+ */
3276
+ async function applyBatched(folder) {
3277
+ const writeOps = new Map(ops.flatMap((op) => op.op === "remove" ? [] : [[op.item.sourceId, op]]));
3278
+ const removed = ops.flatMap((op) => op.op === "remove" ? [op.sourceId] : []);
3279
+ const sourceIds = new Set(removed);
3280
+ for (const op of writeOps.values()) {
3281
+ sourceIds.add(op.item.sourceId);
3282
+ if (op.item.parent) sourceIds.add(op.item.parent);
3283
+ if (op.item.fallbackParent) sourceIds.add(op.item.fallbackParent);
3284
+ for (const link of ("links" in op.item ? op.item.links : void 0) ?? []) sourceIds.add(link.sourceId);
3285
+ }
3286
+ const plan = (rows) => {
3287
+ const keysOf = (page) => {
3288
+ const keys = [];
3289
+ for (let at = page; at && !at.isScope; at = at.parentId ? rows.pages.get(at.parentId) : null) {
3290
+ if (!live(at) || at.key === void 0) return null;
3291
+ keys.unshift(at.key);
3292
+ if (keys.length > 10) return null;
3293
+ }
3294
+ return keys;
3295
+ };
3296
+ const chains = importChainPaths(rows.pages);
3297
+ const pageAt = (keys) => {
3298
+ const key = importPathKey(scope.id, keys);
3299
+ return rows.paths.has(key) ? rows.paths.get(key) : chains.get(key);
3300
+ };
3301
+ const at = (sourceId, seen) => {
3302
+ if (!sourceId) return null;
3303
+ const node = rows.nodes.get(`${binding.id}\u0000${sourceId}`);
3304
+ const page = node ? rows.pages.get(node.pageId) : null;
3305
+ if (live(page ?? null) && page.scopeId === scope.id) {
3306
+ const keys = keysOf(page);
3307
+ if (keys) return {
3308
+ id: page.id,
3309
+ keys
3310
+ };
3311
+ }
3312
+ const op = writeOps.get(sourceId);
3313
+ if (!op || seen.has(sourceId)) return null;
3314
+ return {
3315
+ id: null,
3316
+ keys: [...destinationOf(op, /* @__PURE__ */ new Set([...seen, sourceId])).keys, leafOf(op)]
3317
+ };
3318
+ };
3319
+ const leafOf = (op) => knowledgeImportKey(op.item.path?.at(-1) ?? op.item.sourceId);
3320
+ const destinationOf = (op, seen) => {
3321
+ if (op.item.path) {
3322
+ const keys = [...anchorPath, ...op.item.path.slice(0, -1).map(knowledgeImportKey)];
3323
+ return {
3324
+ id: op.item.path.length === 1 ? folder.id : pageAt(keys),
3325
+ keys
3326
+ };
3327
+ }
3328
+ return at(op.item.parent, seen) ?? at(op.item.fallbackParent, seen) ?? {
3329
+ id: folder.id,
3330
+ keys: anchorPath
3331
+ };
3332
+ };
3333
+ const out = {
3334
+ paths: [],
3335
+ positions: [],
3336
+ notes: [],
3337
+ holders: [],
3338
+ subtrees: [],
3339
+ linkTargets: removed,
3340
+ bindings: removed.length > 0,
3341
+ inPlace: removed.length === 0
3342
+ };
3343
+ const nodeAt = (sourceId) => rows.nodes.get(`${binding.id}\u0000${sourceId}`);
3344
+ const left = /* @__PURE__ */ new Set();
3345
+ for (const op of writeOps.values()) {
3346
+ const destination = destinationOf(op, /* @__PURE__ */ new Set([op.item.sourceId]));
3347
+ const leaf = [...destination.keys, leafOf(op)];
3348
+ const page = rows.pages.get(nodeAt(op.item.sourceId)?.pageId ?? "");
3349
+ if (destination.id && live(page ?? null) && page.parentId === destination.id && (!op.item.path || page.key === leafOf(op))) {
3350
+ if (op.item.path && op.item.path.length > 1) out.holders.push(destination.id);
3351
+ continue;
3352
+ }
3353
+ out.inPlace = false;
3354
+ out.paths.push({
3355
+ scopeId: scope.id,
3356
+ path: leaf
3357
+ });
3358
+ if (destination.id) out.positions.push(destination.id);
3359
+ if (destination.id !== void 0 && live(page ?? null) && (page.parentId !== destination.id || op.item.path && page.key !== leafOf(op))) {
3360
+ out.subtrees.push(page.id);
3361
+ if (page.parentId) left.add(page.parentId);
3362
+ }
3363
+ if (!op.item.path) continue;
3364
+ out.positions.push(folder.id);
3365
+ for (let i = anchorPath.length + 1; i < leaf.length; i++) {
3366
+ out.paths.push({
3367
+ scopeId: scope.id,
3368
+ path: leaf.slice(0, i)
3369
+ });
3370
+ const prefix = pageAt(leaf.slice(0, i));
3371
+ if (prefix) out.positions.push(prefix);
3372
+ }
3373
+ const held = pageAt(leaf);
3374
+ if (held && held !== page?.id) {
3375
+ out.subtrees.push(held);
3376
+ out.notes.push(held);
3377
+ if (page) {
3378
+ out.notes.push(page.id);
3379
+ out.positions.push(page.id);
3380
+ const keys = keysOf(page);
3381
+ if (keys) {
3382
+ for (const child of rows.pages.values()) if (child?.parentId === held && live(child) && child.key !== void 0) out.paths.push({
3383
+ scopeId: scope.id,
3384
+ path: [...keys, child.key]
3385
+ });
3386
+ }
3387
+ }
3388
+ }
3389
+ }
3390
+ for (const id of out.positions) if (left.has(id)) out.subtrees.push(id);
3391
+ for (const sourceId of removed) {
3392
+ const node = nodeAt(sourceId);
3393
+ if (!node) continue;
3394
+ out.subtrees.push(node.pageId);
3395
+ if (node.adopted) out.notes.push(node.pageId);
3396
+ }
3397
+ for (const node of rows.nodes.values()) if (node?.stub && node.adopted) out.notes.push(node.pageId);
3398
+ return out;
3399
+ };
3400
+ return batchedOver(folder, sourceIds, plan, runOps);
3401
+ }
3402
+ /**
3403
+ * Runs `decide` over a working copy of the rows `plan` names, then writes what it decided in a few
3404
+ * set-based statements, all in one savepoint. Returns why it fell back, with the savepoint rolled
3405
+ * back and the result as before, or null once the writes landed.
3406
+ */
3407
+ async function batchedOver(folder, sourceIds, plan, decide) {
3408
+ const real = {
3409
+ storage: input.storage,
3410
+ importers: input.importers
3411
+ };
3412
+ const before = structuredClone(result);
3413
+ const deferredBefore = deferredLinkers;
3414
+ const reset = () => {
3415
+ const copy = structuredClone(before);
3416
+ Object.assign(result, copy);
3417
+ deferredLinkers = deferredBefore;
3418
+ };
3419
+ const missing = emptyImportOverlayMissing();
3420
+ let locked = /* @__PURE__ */ new Set();
3421
+ let reread = false;
3422
+ try {
3423
+ return await real.storage.transaction(async () => {
3424
+ for (let pass = 0; pass < BATCH_DECIDE_PASSES; pass++) {
3425
+ const rows = await gatherImportRows({
3426
+ storage: real.storage,
3427
+ importers: real.importers,
3428
+ bindingId: binding.id,
3429
+ sourceIds,
3430
+ pageIds: folder ? [folder.id] : [],
3431
+ plan,
3432
+ missing,
3433
+ locked,
3434
+ reread
3435
+ });
3436
+ if (!rows) throw new BatchFallback("lock-churn");
3437
+ locked = rows.locked;
3438
+ const working = new ImportOverlay(rows);
3439
+ reset();
3440
+ overlay = working;
3441
+ storage = working.storage;
3442
+ importers = working.importers;
3443
+ try {
3444
+ await decide();
3445
+ } catch (error) {
3446
+ if (error instanceof KnowledgeImportNotGatheredError) {
3447
+ for (const [name, set] of Object.entries(working.missing)) {
3448
+ const into = missing[name];
3449
+ if (into instanceof Map) for (const [k, v] of set) into.set(k, v);
3450
+ else for (const k of set) into.add(k);
3451
+ }
3452
+ continue;
3453
+ }
3454
+ if (error instanceof KnowledgeImportRereadRequiredError) {
3455
+ reread = true;
3456
+ continue;
3457
+ }
3458
+ if (error instanceof KnowledgeImportBatchUnsupportedError) throw new BatchFallback(error.call);
3459
+ throw error;
3460
+ } finally {
3461
+ overlay = null;
3462
+ storage = real.storage;
3463
+ importers = real.importers;
3464
+ }
3465
+ try {
3466
+ if (working.writes.length) await real.storage.applyPageWrites({ writes: working.writes });
3467
+ } catch (error) {
3468
+ if (!refusalFor(error)) throw error;
3469
+ throw new BatchFallback(`page writes: ${error.name}`);
3470
+ }
3471
+ for (const work of working.marks) await work(real.storage, real.importers);
3472
+ const nodes = working.nodeWrites(rows);
3473
+ try {
3474
+ if (nodes.deletes.length || nodes.saves.length) await real.importers.writeNodes(nodes);
3475
+ } catch (error) {
3476
+ if (!refusalFor(error)) throw error;
3477
+ throw new BatchFallback(`node writes: ${error.name}`);
3478
+ }
3479
+ try {
3480
+ await repairKnowledgeLinks(real.storage, {
3481
+ synced: working.links.flatMap((work) => "sync" in work ? [work.sync] : []),
3482
+ refreshed: working.links.flatMap((work) => "refresh" in work ? [{
3483
+ page: work.refresh,
3484
+ withDescendants: work.withDescendants
3485
+ }] : [])
3486
+ });
3487
+ } catch (error) {
3488
+ if (error instanceof KnowledgeLinkRepairUnsupportedError) throw new BatchFallback(error.reason);
3489
+ if (error instanceof KnowledgeUnsupportedCapabilityError) throw new BatchFallback(`link repair: ${error.name}`);
3490
+ throw error;
3491
+ }
3492
+ return null;
3493
+ }
3494
+ throw new BatchFallback("gather passes");
3495
+ });
3496
+ } catch (error) {
3497
+ if (!(error instanceof BatchFallback)) throw error;
3498
+ reset();
3499
+ return error.reason;
3500
+ }
3501
+ }
3502
+ /**
1854
3503
  * One settle slice (O3 §C, §C′): visits the binding's unsettled nodes after `budget.after`, each
1855
3504
  * in its own savepoint, moving a page under a source parent that has arrived since and writing
1856
3505
  * links whose targets now resolve. Stops at the candidate, move or time cap and leaves the rest
1857
3506
  * for the next slice. A node it can't settle (refused, or still waiting) is skipped and stays
1858
3507
  * unsettled; the pass ends when it reaches the last unsettled node.
1859
3508
  */
1860
- async function settle(budget) {
3509
+ async function settle(budget, folder) {
3510
+ if (!canBatchImportFlush(input.storage, input.importers)) return settleNodeByNode(budget);
3511
+ const fromStart = (budget.after ?? void 0) === void 0;
3512
+ const window = [];
3513
+ let cursor = budget.after ?? void 0;
3514
+ let end = false;
3515
+ while (window.length < budget.candidates) {
3516
+ const page = await input.importers.listNodes(binding.id, {
3517
+ unsettled: true,
3518
+ ...cursor !== void 0 ? { after: cursor } : {},
3519
+ limit: budget.candidates - window.length
3520
+ });
3521
+ window.push(...page.items);
3522
+ cursor = page.items.at(-1)?.sourceId ?? cursor;
3523
+ if (!page.next) {
3524
+ end = true;
3525
+ break;
3526
+ }
3527
+ }
3528
+ if (!window.length) return settleNodeByNode(budget);
3529
+ const parents = new Map((await input.importers.getNodes(binding.id, [...new Set(window.flatMap((node) => node.parentSourceId ? [node.parentSourceId] : []))])).map((node) => [node.sourceId, node]));
3530
+ const pages = new Map((await input.storage.getPages({
3531
+ ids: window.map((node) => node.pageId),
3532
+ read: "all"
3533
+ })).map((page) => [page.id, page]));
3534
+ const visit = [];
3535
+ const movers = [];
3536
+ for (const node of window) {
3537
+ visit.push(node);
3538
+ const parent = node.parentSourceId ? parents.get(node.parentSourceId) : void 0;
3539
+ const page = pages.get(node.pageId);
3540
+ if (parent && page && page.parentId !== parent.pageId) {
3541
+ movers.push({
3542
+ sourceId: node.sourceId,
3543
+ page,
3544
+ destination: parent.pageId
3545
+ });
3546
+ if (movers.length >= budget.moves) break;
3547
+ }
3548
+ }
3549
+ if (visit.length < window.length) end = false;
3550
+ const sourceIds = /* @__PURE__ */ new Set();
3551
+ for (const node of visit) {
3552
+ sourceIds.add(node.sourceId);
3553
+ if (node.parentSourceId) sourceIds.add(node.parentSourceId);
3554
+ for (const link of node.links) sourceIds.add(link.sourceId);
3555
+ }
3556
+ let outcome = null;
3557
+ const fallback = await batchedOver(folder, sourceIds, (rows) => ({
3558
+ paths: movers.flatMap((mover) => {
3559
+ const keys = [];
3560
+ for (let at = rows.pages.get(mover.destination); at && !at.isScope;) {
3561
+ if (at.key === void 0) return [];
3562
+ keys.unshift(at.key);
3563
+ at = at.parentId ? rows.pages.get(at.parentId) : null;
3564
+ }
3565
+ return mover.page.key === void 0 ? [] : [{
3566
+ scopeId: scope.id,
3567
+ path: [...keys, mover.page.key]
3568
+ }];
3569
+ }),
3570
+ positions: movers.map((mover) => mover.destination),
3571
+ notes: [],
3572
+ subtrees: movers.map((mover) => mover.page.id),
3573
+ linkTargets: movers.map((mover) => mover.sourceId),
3574
+ bindings: false
3575
+ }), async () => {
3576
+ outcome = await settleWindow(budget, visit, end, fromStart);
3577
+ });
3578
+ if (fallback === null && outcome) {
3579
+ const settledSlice = outcome;
3580
+ if (!settledSlice.pending && deferredLinkers) {
3581
+ if ((await input.importers.listNodes(binding.id, {
3582
+ unsettled: true,
3583
+ limit: 1
3584
+ })).items.length > 0) return {
3585
+ ...settledSlice,
3586
+ pending: true
3587
+ };
3588
+ }
3589
+ return settledSlice;
3590
+ }
3591
+ result.fallback = result.fallback ? `${result.fallback}; settle: ${fallback}` : `settle: ${fallback}`;
3592
+ return settleNodeByNode(budget);
3593
+ }
3594
+ /**
3595
+ * The node-by-node loop over a window read ahead, for the batched slice: the same caps, the same
3596
+ * savepoint per node, over the working copy.
3597
+ */
3598
+ async function settleWindow(budget, visit, end, fromStart) {
3599
+ let after = budget.after ?? void 0;
3600
+ let moves = 0;
3601
+ let settled = 0;
3602
+ const resumeAt = () => deferredLinkers ? null : after ?? null;
3603
+ for (const node of visit) {
3604
+ if (moves >= budget.moves || Date.now() >= budget.until) return {
3605
+ pending: true,
3606
+ cursor: resumeAt(),
3607
+ settled,
3608
+ fromStart
3609
+ };
3610
+ after = node.sourceId;
3611
+ const embeds = [];
3612
+ try {
3613
+ const outcome = await storage.transaction(() => settleNode(node.sourceId, embeds, moves < budget.moves));
3614
+ if (outcome.moved) moves++;
3615
+ if (outcome.moved || outcome.relinked) settled++;
3616
+ result.embeds.push(...embeds);
3617
+ } catch (error) {
3618
+ if (!refusalFor(error)) throw error;
3619
+ }
3620
+ }
3621
+ if (!end) return {
3622
+ pending: true,
3623
+ cursor: resumeAt(),
3624
+ settled,
3625
+ fromStart
3626
+ };
3627
+ return {
3628
+ pending: false,
3629
+ cursor: null,
3630
+ settled,
3631
+ fromStart
3632
+ };
3633
+ }
3634
+ async function settleNodeByNode(budget) {
1861
3635
  let after = budget.after ?? void 0;
1862
3636
  const fromStart = after === void 0;
1863
3637
  let examined = 0;
@@ -1924,12 +3698,24 @@ async function applyKnowledgeImportFlush(input) {
1924
3698
  moved: false,
1925
3699
  relinked: false
1926
3700
  };
3701
+ if (await stateOf(node) === "merged") {
3702
+ await importers.saveNode({
3703
+ ...node,
3704
+ unsettled: false
3705
+ });
3706
+ return {
3707
+ moved: false,
3708
+ relinked: false
3709
+ };
3710
+ }
1927
3711
  const current = await owned(node.pageId, sourceId);
1928
3712
  let { page, keys } = current;
1929
3713
  let moved = false;
1930
3714
  let relinked = false;
1931
- const parent = current.outside ? null : await nodeOf(node.parentSourceId);
1932
- let misplaced = !current.outside && !!node.parentSourceId && !parent;
3715
+ const sourceParent = current.outside ? null : await nodeOf(node.parentSourceId);
3716
+ const parentMerged = !!sourceParent && await stateOf(sourceParent) === "merged";
3717
+ const parent = parentMerged ? null : sourceParent;
3718
+ let misplaced = !current.outside && !!node.parentSourceId && !parent && !parentMerged;
1933
3719
  if (parent && canMove) {
1934
3720
  const destination = await owned(parent.pageId, parent.sourceId);
1935
3721
  if (page.parentId !== destination.page.id) {
@@ -1938,7 +3724,10 @@ async function applyKnowledgeImportFlush(input) {
1938
3724
  ({page, keys, relinked: rewrote} = await moveOwned(sourceId, page, destination));
1939
3725
  recordRelinked(rewrote, embeds);
1940
3726
  moved = true;
1941
- await syncLinks(() => refreshKnowledgeLinksTo(storage, [page], { withDescendants: true }));
3727
+ await links(null, {
3728
+ pages: [page],
3729
+ withDescendants: true
3730
+ });
1942
3731
  }
1943
3732
  } else if (parent) misplaced = true;
1944
3733
  const out = await relink(node, page);
@@ -2330,6 +4119,14 @@ function hostError(error) {
2330
4119
  failure.cause = error;
2331
4120
  return failure;
2332
4121
  }
4122
+ /** A committed receipt as replayed; receipts written before the `merged` count existed read it as 0. */
4123
+ const storedReceipt = (receipt) => {
4124
+ const stored = receipt;
4125
+ return {
4126
+ ...stored,
4127
+ merged: stored.merged ?? 0
4128
+ };
4129
+ };
2333
4130
  const receiptCounts = (counts) => ({
2334
4131
  created: counts.created ?? 0,
2335
4132
  updated: counts.updated ?? 0,
@@ -2337,6 +4134,7 @@ const receiptCounts = (counts) => ({
2337
4134
  moved: counts.moved ?? 0,
2338
4135
  removed: counts.removed ?? 0,
2339
4136
  stubbed: counts.stubbed ?? 0,
4137
+ merged: counts.merged ?? 0,
2340
4138
  refused: counts.refused ?? 0
2341
4139
  });
2342
4140
  const runReceipt = (run) => {
@@ -2399,6 +4197,7 @@ function createLocalKnowledgeImporterHost(writer, options) {
2399
4197
  /** Store time (epoch ms) at which a running run stops being live under `leaseMs`. */
2400
4198
  const liveUntil = (run) => Math.min((run.heartbeatAt ?? run.startedAt).getTime() + (leaseMs ?? Infinity), run.deadlineAt?.getTime() ?? Infinity);
2401
4199
  const listBindings = async () => typeof options.bindings === "function" ? await options.bindings() : options.bindings;
4200
+ const pathWarned = /* @__PURE__ */ new Set();
2402
4201
  const storageAndImporters = async () => {
2403
4202
  const storage = await writer.getStorage();
2404
4203
  const importers = storage.importers;
@@ -2442,7 +4241,10 @@ function createLocalKnowledgeImporterHost(writer, options) {
2442
4241
  * flushes and finish are refused as `run_not_active`; exact replays still return receipts.
2443
4242
  */
2444
4243
  const staleAfter = leaseMs ?? options.staleRunAfterMs ?? DEFAULT_STALE_RUN_AFTER_MS;
2445
- /** Ends `run` if it isn't live; the caller holds the guard and the run's lock. */
4244
+ /**
4245
+ * Ends `run` if it isn't live; the caller holds the guard and the run's lock. The caller clears the
4246
+ * run's path-warning marker once its transaction commits: a rollback brings the run back.
4247
+ */
2446
4248
  const expireLocked = async (importers, run) => {
2447
4249
  const why = lapsed(run, await clock(importers), staleAfter);
2448
4250
  if (!why) return false;
@@ -2454,13 +4256,16 @@ function createLocalKnowledgeImporterHost(writer, options) {
2454
4256
  });
2455
4257
  return true;
2456
4258
  };
4259
+ /** Ends the binding's runs that aren't live, returning the ones it ended. */
2457
4260
  const reclaimStaleRuns = async (importers, bindingId) => {
4261
+ const ended = [];
2458
4262
  for (const candidate of await importers.listRuns(bindingId)) {
2459
4263
  if (candidate.status !== "running") continue;
2460
4264
  const run = await importers.lockRun(candidate.id);
2461
4265
  if (!run || run.status !== "running") continue;
2462
- await expireLocked(importers, run);
4266
+ if (await expireLocked(importers, run)) ended.push(run.id);
2463
4267
  }
4268
+ return ended;
2464
4269
  };
2465
4270
  /**
2466
4271
  * Counts a settle flush that timed out, outside its rolled-back transaction. Best effort, and
@@ -2517,7 +4322,7 @@ function createLocalKnowledgeImporterHost(writer, options) {
2517
4322
  importer: binding.importer,
2518
4323
  target: binding.target
2519
4324
  });
2520
- await reclaimStaleRuns(importers, binding.id);
4325
+ const ended = await reclaimStaleRuns(importers, binding.id);
2521
4326
  if (start?.admit) try {
2522
4327
  await start.admit(unwrapKnowledgeStorage(tx));
2523
4328
  } catch (error) {
@@ -2539,7 +4344,8 @@ function createLocalKnowledgeImporterHost(writer, options) {
2539
4344
  const saved = run.status === "started" ? await importers.getState(binding.id) : {};
2540
4345
  return {
2541
4346
  run,
2542
- state: Object.fromEntries(Object.entries(saved).filter(([key]) => !key.startsWith(RESERVED_STATE_PREFIX)))
4347
+ state: Object.fromEntries(Object.entries(saved).filter(([key]) => !key.startsWith(RESERVED_STATE_PREFIX))),
4348
+ ended
2543
4349
  };
2544
4350
  });
2545
4351
  let result;
@@ -2550,6 +4356,7 @@ function createLocalKnowledgeImporterHost(writer, options) {
2550
4356
  exclusive = true;
2551
4357
  result = await attempt();
2552
4358
  }
4359
+ for (const runId of result.ended) pathWarned.delete(runId);
2553
4360
  if (result.run.status !== "started") return {
2554
4361
  status: "skipped",
2555
4362
  runId: result.run.run.id
@@ -2591,7 +4398,7 @@ function createLocalKnowledgeImporterHost(writer, options) {
2591
4398
  });
2592
4399
  if (replayed) {
2593
4400
  if (replayed.digest !== digest) throw conflict("digest_mismatch", "This seq was committed with other content.");
2594
- return replayed.receipt;
4401
+ return storedReceipt(replayed.receipt);
2595
4402
  }
2596
4403
  const [peek, peekRun] = await Promise.all([rootImporters.readWriterGuard(), rootImporters.getRun(flush.runId)]).catch((error) => {
2597
4404
  throw hostError(error);
@@ -2608,15 +4415,19 @@ function createLocalKnowledgeImporterHost(writer, options) {
2608
4415
  }
2609
4416
  let embeds = [];
2610
4417
  let settling = false;
4418
+ let fallbackWarning;
4419
+ let pathsUnsupported = false;
2611
4420
  try {
2612
4421
  const write = (deadlineAt) => storage.transaction(async (tx) => {
4422
+ fallbackWarning = void 0;
4423
+ pathsUnsupported = false;
2613
4424
  const importers = tx.importers;
2614
4425
  const guard = await importers.lockWriterGuard(peek.firstWriteAt ? "share" : "update");
2615
4426
  const run = await importers.lockRun(flush.runId);
2616
4427
  const stored = await importers.getFlush(flush.runId, flush.generation, flush.seq);
2617
4428
  if (stored) {
2618
4429
  if (stored.digest !== digest) throw conflict("digest_mismatch", "This seq was committed with other content.");
2619
- return stored.receipt;
4430
+ return storedReceipt(stored.receipt);
2620
4431
  }
2621
4432
  if (!run || run.status !== "running") throw conflict("run_not_active", "The run is not running.");
2622
4433
  if (run.generation !== flush.generation || guard.generation !== flush.generation) throw conflict("stale_generation", "The run belongs to an older writer generation.");
@@ -2654,6 +4465,8 @@ function createLocalKnowledgeImporterHost(writer, options) {
2654
4465
  }
2655
4466
  } } : {}
2656
4467
  });
4468
+ if (applied.fallback) fallbackWarning = `Knowledge importer: flush ${flush.seq} of run ${run.id} saved op by op instead of batched (${applied.fallback})`;
4469
+ pathsUnsupported = !!applied.pathsUnsupported;
2657
4470
  const settled = applied.settle;
2658
4471
  const hostUpdates = {};
2659
4472
  if (settled && (settled.cursor ?? "") !== (hostState[SETTLE_CURSOR_KEY] ?? "")) hostUpdates[SETTLE_CURSOR_KEY] = settled.cursor ?? "";
@@ -2664,15 +4477,18 @@ function createLocalKnowledgeImporterHost(writer, options) {
2664
4477
  ...hostUpdates
2665
4478
  };
2666
4479
  if (Object.keys(state).length) await importers.setState(binding.id, state);
2667
- for (const change of applied.changes) await importers.recordRunChange({
4480
+ const changes = applied.changes.map((change) => ({
2668
4481
  runId: run.id,
2669
4482
  ...change
2670
- });
4483
+ }));
4484
+ if (importers.recordRunChanges) await importers.recordRunChanges(changes);
4485
+ else for (const change of changes) await importers.recordRunChange(change);
2671
4486
  const receipt = {
2672
4487
  seq: flush.seq,
2673
4488
  ...applied.counts,
2674
4489
  refused: applied.refused,
2675
- pending: settled?.pending ?? false
4490
+ pending: settled?.pending ?? false,
4491
+ ...applied.fallback ? { fallback: applied.fallback } : {}
2676
4492
  };
2677
4493
  await importers.recordFlush({
2678
4494
  runId: run.id,
@@ -2683,7 +4499,8 @@ function createLocalKnowledgeImporterHost(writer, options) {
2683
4499
  counts: {
2684
4500
  ...applied.counts,
2685
4501
  refused: applied.refused.length,
2686
- settled: settled?.settled ?? 0
4502
+ settled: settled?.settled ?? 0,
4503
+ ...applied.fallback ? { fallbacks: 1 } : {}
2687
4504
  }
2688
4505
  });
2689
4506
  if (applied.applied && !guard.firstWriteAt) await importers.markFirstWrite();
@@ -2698,6 +4515,11 @@ function createLocalKnowledgeImporterHost(writer, options) {
2698
4515
  if (attempt >= MAX_LEASE_BOUND_ATTEMPTS) throw new KnowledgeImporterHostError("The flush could not be bounded by its run lease; resend it.", 503);
2699
4516
  deadlineAt = Math.min(budgetAt, error.cutoff - LEASE_CUTOFF_MARGIN_MS);
2700
4517
  }
4518
+ if (fallbackWarning) writer.warn(fallbackWarning);
4519
+ if (pathsUnsupported && !pathWarned.has(flush.runId)) {
4520
+ pathWarned.add(flush.runId);
4521
+ writer.warn(`Knowledge importer: run ${flush.runId} refused items placed by path: path placement needs a store that supports page re-key; ${Object.getPrototypeOf(storage).constructor.name} does not`);
4522
+ }
2701
4523
  await runEmbeds(storage, embeds);
2702
4524
  return receipt;
2703
4525
  } catch (error) {
@@ -2765,7 +4587,10 @@ function createLocalKnowledgeImporterHost(writer, options) {
2765
4587
  await importers.lockWriterGuard("share");
2766
4588
  const run = await importers.lockRun(runId);
2767
4589
  return !!run && run.status === "running" && await expireLocked(importers, run);
2768
- })) expired.push(runId);
4590
+ })) {
4591
+ expired.push(runId);
4592
+ pathWarned.delete(runId);
4593
+ }
2769
4594
  return { expired };
2770
4595
  } catch (error) {
2771
4596
  throw hostError(error);
@@ -2789,7 +4614,7 @@ function createLocalKnowledgeImporterHost(writer, options) {
2789
4614
  }
2790
4615
  const { storage } = await storageAndImporters();
2791
4616
  try {
2792
- return await storage.transaction(async (tx) => {
4617
+ const receipt = await storage.transaction(async (tx) => {
2793
4618
  const importers = tx.importers;
2794
4619
  const guard = await importers.lockWriterGuard("share");
2795
4620
  const run = await importers.lockRun(request.runId);
@@ -2833,6 +4658,8 @@ function createLocalKnowledgeImporterHost(writer, options) {
2833
4658
  });
2834
4659
  return runReceipt(finished);
2835
4660
  });
4661
+ pathWarned.delete(request.runId);
4662
+ return receipt;
2836
4663
  } catch (error) {
2837
4664
  throw hostError(error);
2838
4665
  }
@@ -3399,6 +5226,19 @@ var KnowledgeScopeRuntime = class {
3399
5226
  };
3400
5227
  for (const address of addresses) await this.#materialize(address, principals, provenance, [], run);
3401
5228
  }
5229
+ /**
5230
+ * The parent address a first write would place a not-yet-created scope under, as `#materialize`
5231
+ * chooses it: a template child's own parent, or the one held `belongsTo` candidate. Undefined when
5232
+ * the scope would stay unlinked.
5233
+ */
5234
+ firstWriteParentAddress(address, principals) {
5235
+ const match = this.compiled.match(address);
5236
+ if (!match) return void 0;
5237
+ if (match.compiled.child) return address.slice(0, address.lastIndexOf("/"));
5238
+ if (!match.compiled.belongsTo) return void 0;
5239
+ const candidates = this.#belongsToCandidates(match, this.#held(principals));
5240
+ return candidates.length === 1 && candidates[0] !== address ? candidates[0] : void 0;
5241
+ }
3402
5242
  /** The run's distinct principals grouped by declaration key, matched once. */
3403
5243
  #held(principals) {
3404
5244
  const held = /* @__PURE__ */ new Map();
@@ -4197,7 +6037,8 @@ var Knowledge = class extends MastraBase {
4197
6037
  warn: (message) => this.logger.warn(message),
4198
6038
  maxTokens: this.#tools.maxTokens,
4199
6039
  ...principals ? { principals } : {},
4200
- ...options?.author ? { author: options.author } : {}
6040
+ ...options?.author ? { author: options.author } : {},
6041
+ ...options?.requireExpectedVersion ? { requireExpectedVersion: true } : {}
4201
6042
  }, this.#groups(options), (context) => context?.requestContext?.delete?.(PINNED_READ_MEMO_KEY));
4202
6043
  }
4203
6044
  /**
@@ -4344,9 +6185,24 @@ var Knowledge = class extends MastraBase {
4344
6185
  write
4345
6186
  };
4346
6187
  }
4347
- /** The run's principals as a stable key; throws when the run has none or holds an undeclared scope. @internal */
4348
- __principalsKey(context) {
4349
- return knowledgeRunPrincipals(this.#runtime, context).sort().join("\n");
6188
+ /** Whether the resolved mint declarations need metadata.persona. @internal */
6189
+ async __needsAgentPersona() {
6190
+ await this.#runtime.resolve();
6191
+ return [...this.#runtime.compiled.declarations.values()].some((declaration) => declaration.declaration.mint === "run-identity" && declaration.pattern.params.some((param) => param === "role" || param === "teamId"));
6192
+ }
6193
+ /**
6194
+ * The run's principals as a stable key, or `undefined` when the run has no Knowledge view (no scopes,
6195
+ * or an undeclared scope). Loads the store's declarations first, so a scope only the store declares
6196
+ * counts; a failure loading them rejects. @internal
6197
+ */
6198
+ async __principalsKey(context) {
6199
+ await this.#runtime.resolve();
6200
+ try {
6201
+ return knowledgeRunPrincipals(this.#runtime, context).sort().join("\n");
6202
+ } catch (error) {
6203
+ if (error instanceof KnowledgeRunScopesError || error instanceof KnowledgeDeclarationError) return void 0;
6204
+ throw error;
6205
+ }
4350
6206
  }
4351
6207
  /**
4352
6208
  * The pinned pages a host-run caller with these principals receives, rendered as an agent run
@@ -4373,6 +6229,14 @@ var Knowledge = class extends MastraBase {
4373
6229
  const run = await KnowledgeRun.start(this.#runtime, await this.getStorage(), context);
4374
6230
  return knowledgeDeliveredPins(run, budget, this.#groups().read);
4375
6231
  }
6232
+ /** The scopes a run holds a role on this turn, with that role. @internal */
6233
+ async __heldScopes(context) {
6234
+ const run = await KnowledgeRun.start(this.#runtime, await this.getStorage(), context);
6235
+ return (await heldScopes(run)).flatMap(({ address, role }) => role ? [{
6236
+ address,
6237
+ role
6238
+ }] : []);
6239
+ }
4376
6240
  /** @internal */
4377
6241
  __registerMastra(_mastra) {}
4378
6242
  /** @internal */
@@ -4489,4 +6353,4 @@ var Knowledge = class extends MastraBase {
4489
6353
  function createKnowledgeImporterHost(knowledge, options) {
4490
6354
  return createLocalKnowledgeImporterHost(hostWriterOf(knowledge), options);
4491
6355
  }
4492
- export { DEFAULT_KNOWLEDGE_PAGE_GRAPH_LIMITS, InMemoryKnowledgeStorage, KNOWLEDGE_IMPORTER_ERROR_CODES, REMOVED_PARENT_BODY as KNOWLEDGE_IMPORT_REMOVED_PARENT_BODY, KNOWLEDGE_STORAGE_CONTRACT_VERSION, KNOWLEDGE_STORAGE_SCHEMA_VERSION, Knowledge, KnowledgeConflictError, KnowledgeDeclarationError, KnowledgeImporter, KnowledgeImporterBase, KnowledgeImporterBindingConflictError, KnowledgeImporterCredentialsError, KnowledgeImporterDefinitionError, KnowledgeImporterHostConflictError, KnowledgeImporterHostError, KnowledgeImporterRunStateError, KnowledgeImporterSettingsError, KnowledgeImporterSourceError, KnowledgeImportersStorage, KnowledgeInvalidCursorError, KnowledgeMoveTooLargeError, KnowledgeNotFoundError, KnowledgePageDepthError, KnowledgePageHasChildrenError, KnowledgePageKeyConflictError, KnowledgeSchemaResetRequiredError, KnowledgeStorage, KnowledgeTransactionDeadlineError, KnowledgeUnsupportedCapabilityError, MAX_KNOWLEDGE_EXPLORER_PAGE_LINKS, MAX_KNOWLEDGE_LINK_COUNT_PAGES, MAX_KNOWLEDGE_MOVE_PAGES, MAX_KNOWLEDGE_NODE_DESCRIPTION_LENGTH, MAX_KNOWLEDGE_NOTE_TOKENS, MAX_KNOWLEDGE_PAGE_BODY_LINKS, MAX_KNOWLEDGE_PAGE_DEPTH, MAX_KNOWLEDGE_PAGE_DESCRIPTION_TOKENS, MAX_KNOWLEDGE_PAGE_LINKS, MAX_KNOWLEDGE_PAGE_LINK_REF_LENGTH, MAX_KNOWLEDGE_PAGE_LIST_LIMIT, MAX_KNOWLEDGE_PIN_LIST_DEPTH, MAX_KNOWLEDGE_RECORD_TEXT_LENGTH, MAX_KNOWLEDGE_SCOPE_TAGS, assertKnowledgeCeilingRaised, assertKnowledgeDescriptionWithinBound, assertKnowledgeNoteTextWithinBound, assertKnowledgePageDescriptionWithinBound, assertKnowledgeRecordTextWithinBound, assertKnowledgeSchemaCompatible, assertKnowledgeScopeWithinCeiling, canonicalJson, canonicalKnowledgeName, canonicalizeKnowledgeScope, createKnowledgeImporterHost, createKnowledgeNodeCursor, createKnowledgeUlid, decodeKnowledgeScopeId, encodeKnowledgeScopeId, expandKnowledgeScope, importerHostConformance, inspectKnowledgeSchema, isKnowledgeScopeVisible, knowledgeImportKey, knowledgeImporterFlushDigest, knowledgeImporterRegistry, knowledgeLinkRefKey, knowledgeMemoryScopes, knowledgePagePath, knowledgePinDepth, knowledgePositionBetween, knowledgeScopeAddress, knowledgeScopeKey, knowledgeScopeReadable, knowledgeSemanticDocumentId, knowledgeSemanticIdempotencyKey, knowledgeVisibleScopeKeys, listKnowledgeTreeChildren, normalizeKnowledgeImporterFinish, parseKnowledgeImporterFlushBody, parseKnowledgeNodeCursor, parseKnowledgePageRef, parseKnowledgeWikilinks, readKnowledgePage, readKnowledgePageActivity, readKnowledgePageGraph, readKnowledgePageLinkCounts, readKnowledgePageLinks, readKnowledgeScopeGrants, runKnowledgeImport, searchKnowledgeExplorerPages };
6356
+ export { DEFAULT_KNOWLEDGE_PAGE_GRAPH_LIMITS, InMemoryKnowledgeStorage, KNOWLEDGE_IMPORTER_ERROR_CODES, REMOVED_PARENT_BODY as KNOWLEDGE_IMPORT_REMOVED_PARENT_BODY, KNOWLEDGE_STORAGE_CONTRACT_VERSION, KNOWLEDGE_STORAGE_SCHEMA_VERSION, Knowledge, KnowledgeConflictError, KnowledgeDeclarationError, KnowledgeImporter, KnowledgeImporterBase, KnowledgeImporterBindingConflictError, KnowledgeImporterCredentialsError, KnowledgeImporterDefinitionError, KnowledgeImporterHostConflictError, KnowledgeImporterHostError, KnowledgeImporterRunStateError, KnowledgeImporterSettingsError, KnowledgeImporterSourceError, KnowledgeImportersStorage, KnowledgeInvalidCursorError, KnowledgeMoveTooLargeError, KnowledgeNotFoundError, KnowledgePageDepthError, KnowledgePageHasChildrenError, KnowledgePageKeyConflictError, KnowledgeSchemaResetRequiredError, KnowledgeStorage, KnowledgeTransactionDeadlineError, KnowledgeUnsupportedCapabilityError, MAX_KNOWLEDGE_EXPLORER_PAGE_LINKS, MAX_KNOWLEDGE_LINK_COUNT_PAGES, MAX_KNOWLEDGE_MOVE_PAGES, MAX_KNOWLEDGE_NODE_DESCRIPTION_LENGTH, MAX_KNOWLEDGE_NOTE_TOKENS, MAX_KNOWLEDGE_PAGE_BODY_LINKS, MAX_KNOWLEDGE_PAGE_DEPTH, MAX_KNOWLEDGE_PAGE_DESCRIPTION_TOKENS, MAX_KNOWLEDGE_PAGE_LINKS, MAX_KNOWLEDGE_PAGE_LINK_REF_LENGTH, MAX_KNOWLEDGE_PAGE_LIST_LIMIT, MAX_KNOWLEDGE_PIN_LIST_DEPTH, MAX_KNOWLEDGE_RECORD_TEXT_LENGTH, MAX_KNOWLEDGE_SCOPE_TAGS, assertKnowledgeCeilingRaised, assertKnowledgeDescriptionWithinBound, assertKnowledgeNoteTextWithinBound, assertKnowledgePageDescriptionWithinBound, assertKnowledgeRecordTextWithinBound, assertKnowledgeSchemaCompatible, assertKnowledgeScopeWithinCeiling, canonicalJson, canonicalKnowledgeName, canonicalizeKnowledgeScope, createKnowledgeImporterHost, createKnowledgeNodeCursor, createKnowledgeUlid, decodeKnowledgeScopeId, encodeKnowledgeScopeId, expandKnowledgeScope, importerHostConformance, inspectKnowledgeSchema, isKnowledgeScopeVisible, knowledgeAgentScopes, knowledgeImportKey, knowledgeImporterFlushDigest, knowledgeImporterRegistry, knowledgeLinkRefKey, knowledgeMemoryScopes, knowledgePagePath, knowledgePersonaScopes, knowledgePinDepth, knowledgePositionBetween, knowledgeScopeAddress, knowledgeScopeKey, knowledgeScopeReadable, knowledgeSemanticDocumentId, knowledgeSemanticIdempotencyKey, knowledgeVisibleScopeKeys, listKnowledgeTreeChildren, normalizeKnowledgeImporterFinish, parseKnowledgeImporterFlushBody, parseKnowledgeNodeCursor, parseKnowledgePageRef, parseKnowledgeWikilinks, readKnowledgePage, readKnowledgePageActivity, readKnowledgePageGraph, readKnowledgePageLinkCounts, readKnowledgePageLinks, readKnowledgeScopeGrants, runKnowledgeImport, searchKnowledgeExplorerPages };