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