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

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