@mastra/core 1.87.0-alpha.1 → 1.87.0-alpha.11
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/_types/@ai-sdk_openai@4.0.106/dist/index.d.ts +2034 -0
- package/dist/_types/@ai-sdk_openai@4.0.106/package.json +1 -0
- 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/agent.d.ts +3 -1
- package/dist/agent/durable/index.cjs +1 -1
- package/dist/agent/durable/index.js +1 -1
- package/dist/agent/durable/run-message-refs.d.ts +3 -2
- package/dist/agent/index.cjs +5 -4
- package/dist/agent/index.d.ts +2 -0
- package/dist/agent/index.js +5 -5
- package/dist/agent/merge-persona.d.ts +15 -0
- package/dist/agent/message-list/adapters/AIV5Adapter.d.ts +15 -1
- package/dist/agent/message-list/index.cjs +2 -2
- package/dist/agent/message-list/index.js +2 -2
- package/dist/agent/message-list/state/types.d.ts +5 -1
- package/dist/agent/message-list/types.d.ts +1 -1
- package/dist/agent/message-list/utils/provider-compat.d.ts +9 -1
- package/dist/agent-builder/ee/index.cjs +1 -1
- package/dist/agent-builder/ee/index.js +1 -1
- package/dist/agent-controller/agent-controller.d.ts +6 -0
- package/dist/agent-controller/index.cjs +2 -2
- package/dist/agent-controller/index.js +2 -2
- package/dist/agent-controller/session.d.ts +11 -1
- package/dist/agent-controller/worker-run-binding.d.ts +15 -0
- package/dist/{agent-controller-C1bK0CXm.js → agent-controller-BrRzZy4-.js} +66 -15
- package/dist/{agent-controller-BTIxiD1u.cjs → agent-controller-DKI-d-np.cjs} +66 -15
- package/dist/background-tasks/index.cjs +2 -1
- package/dist/background-tasks/index.d.ts +1 -1
- package/dist/background-tasks/index.js +1 -1
- package/dist/background-tasks/resolve-config.d.ts +30 -1
- package/dist/background-tasks/system-prompt.d.ts +8 -2
- package/dist/background-tasks/types.d.ts +47 -1
- package/dist/{background-tasks-BbVsBghi.js → background-tasks-CDP3Pgeu.js} +156 -33
- package/dist/{background-tasks-CVl6e0Jo.cjs → background-tasks-CDgdfRmB.cjs} +167 -32
- package/dist/browser/index.cjs +2 -2
- package/dist/browser/index.js +2 -2
- package/dist/{builder-BRJPSTig.cjs → builder-Bs4CtyqT.cjs} +2 -2
- package/dist/{builder-C8XzrtBQ.js → builder-DuT0Iqb5.js} +2 -2
- package/dist/capabilities/302ai.json +199 -199
- package/dist/capabilities/abliteratedllm.json +43 -34
- package/dist/capabilities/abliteration-ai.json +7 -7
- package/dist/capabilities/above.json +19 -19
- package/dist/capabilities/adaption.json +15 -15
- package/dist/capabilities/adzuki.json +27 -27
- package/dist/capabilities/agentrouter.json +13 -13
- package/dist/capabilities/agnes.json +3 -3
- package/dist/capabilities/ai-router.json +6 -6
- package/dist/capabilities/aiand.json +21 -21
- package/dist/capabilities/aigrow.json +12 -12
- package/dist/capabilities/aimlapi.json +143 -146
- package/dist/capabilities/aipg.json +2 -2
- package/dist/capabilities/aixy.json +22 -22
- package/dist/capabilities/aki-io.json +16 -16
- package/dist/capabilities/alibaba-cn.json +108 -102
- 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 +52 -52
- package/dist/capabilities/alibaba-token-plan.json +53 -53
- package/dist/capabilities/alibaba.json +98 -64
- package/dist/capabilities/ambient.json +17 -10
- package/dist/capabilities/amd.json +9 -9
- package/dist/capabilities/anthropic.json +45 -45
- package/dist/capabilities/anyapi.json +47 -47
- package/dist/capabilities/apiko.json +2 -2
- package/dist/capabilities/arcee.json +11 -11
- package/dist/capabilities/augure.json +6 -6
- package/dist/capabilities/auriko.json +20 -20
- package/dist/capabilities/bailing.json +4 -4
- package/dist/capabilities/baseten.json +33 -33
- package/dist/capabilities/bee.json +5 -5
- package/dist/capabilities/berget.json +20 -7
- package/dist/capabilities/bothub.json +14 -14
- package/dist/capabilities/boundless.json +37 -37
- package/dist/capabilities/bumo.json +42 -42
- package/dist/capabilities/byteplus.json +28 -28
- package/dist/capabilities/cerebras.json +4 -4
- package/dist/capabilities/cheapaimodel.json +7 -7
- package/dist/capabilities/cheapest-token.json +30 -30
- package/dist/capabilities/chutes.json +4 -4
- package/dist/capabilities/clarifai.json +2 -2
- package/dist/capabilities/claudinio.json +10 -1
- package/dist/capabilities/cline-pass.json +42 -42
- package/dist/capabilities/cloudcode.json +9 -16
- package/dist/capabilities/cloudferro-sherlock.json +4 -4
- package/dist/capabilities/cloudflare-workers-ai.json +14 -14
- package/dist/capabilities/commandcode.json +140 -140
- package/dist/capabilities/concentrate.json +289 -298
- package/dist/capabilities/cortecs.json +105 -105
- package/dist/capabilities/crossmodel.json +197 -197
- package/dist/capabilities/crusoe.json +38 -9
- package/dist/capabilities/daoxe.json +8 -8
- package/dist/capabilities/databricks.json +125 -125
- package/dist/capabilities/deepinfra.json +109 -94
- package/dist/capabilities/deepseek.json +4 -4
- package/dist/capabilities/digitalocean.json +112 -112
- package/dist/capabilities/dothoosh.json +34 -34
- package/dist/capabilities/doubleword.json +24 -24
- package/dist/capabilities/edenai.json +280 -292
- package/dist/capabilities/empiriolabs.json +168 -168
- package/dist/capabilities/engy.json +21 -21
- package/dist/capabilities/entrim.json +8 -8
- package/dist/capabilities/evroc.json +12 -12
- package/dist/capabilities/ezkielyna.json +8 -8
- package/dist/capabilities/fastrouter.json +87 -87
- package/dist/capabilities/fireworks-ai.json +130 -69
- package/dist/capabilities/fortytwo.json +9 -3
- package/dist/capabilities/freemodel.json +14 -14
- package/dist/capabilities/friendli.json +2 -2
- package/dist/capabilities/frogbot.json +96 -96
- package/dist/capabilities/gisoo.json +17 -17
- package/dist/capabilities/gmicloud.json +24 -24
- package/dist/capabilities/google.json +54 -54
- package/dist/capabilities/graphn.json +16 -16
- package/dist/capabilities/greenpt.json +35 -35
- package/dist/capabilities/groq.json +2 -2
- package/dist/capabilities/helicone.json +94 -94
- package/dist/capabilities/hetzner.json +35 -3
- package/dist/capabilities/hostinger-router.json +14 -14
- package/dist/capabilities/hpc-ai.json +11 -11
- package/dist/capabilities/huawei-maas.json +14 -14
- package/dist/capabilities/hubris.json +30 -30
- package/dist/capabilities/huggingface.json +113 -155
- package/dist/capabilities/humain.json +2 -2
- package/dist/capabilities/hyper.json +25 -33
- package/dist/capabilities/impossibl.json +155 -155
- package/dist/capabilities/inception.json +2 -2
- package/dist/capabilities/inceptron.json +8 -8
- package/dist/capabilities/inco.json +5 -5
- package/dist/capabilities/infer.json +20 -20
- package/dist/capabilities/inferall.json +14 -14
- package/dist/capabilities/inference-coop.json +9 -9
- package/dist/capabilities/inferenceapis.json +20 -20
- package/dist/capabilities/inferris.json +4 -4
- package/dist/capabilities/infersia.json +11 -11
- package/dist/capabilities/infomaniak.json +4 -4
- package/dist/capabilities/io-net.json +4 -4
- package/dist/capabilities/isoquant.json +4 -4
- package/dist/capabilities/iteracompute.json +59 -59
- package/dist/capabilities/jad-ai.json +3 -3
- package/dist/capabilities/jalapeno.json +10 -10
- package/dist/capabilities/jiekou.json +60 -60
- package/dist/capabilities/joingonka.json +4 -4
- package/dist/capabilities/jzstoken.json +58 -59
- package/dist/capabilities/keln.json +18 -18
- package/dist/capabilities/kenari.json +119 -127
- package/dist/capabilities/kilo.json +609 -613
- package/dist/capabilities/kimi-code-plan-cn.json +5 -5
- package/dist/capabilities/kimi-code-plan-global.json +5 -5
- package/dist/capabilities/kitani.json +6 -6
- package/dist/capabilities/klavo.json +20 -20
- package/dist/capabilities/korouter.json +32 -32
- package/dist/capabilities/kunavo.json +8 -8
- package/dist/capabilities/liquid.json +12 -12
- package/dist/capabilities/lithosai.json +2 -2
- package/dist/capabilities/llmgateway-providers.json +947 -878
- package/dist/capabilities/llmgateway.json +336 -335
- package/dist/capabilities/llmtr.json +26 -26
- package/dist/capabilities/logits.json +2 -2
- package/dist/capabilities/longcat.json +2 -2
- package/dist/capabilities/lowrouter.json +65 -65
- package/dist/capabilities/lyceum.json +19 -11
- package/dist/capabilities/melious.json +14 -14
- package/dist/capabilities/merge-gateway.json +264 -263
- package/dist/capabilities/meta.json +13 -13
- package/dist/capabilities/minimax-cn-coding-plan.json +2 -2
- package/dist/capabilities/minimax-cn.json +5 -5
- package/dist/capabilities/minimax-coding-plan.json +2 -2
- package/dist/capabilities/minimax.json +5 -5
- package/dist/capabilities/mistral.json +21 -21
- package/dist/capabilities/mixlayer.json +3 -3
- package/dist/capabilities/modal.json +10 -10
- package/dist/capabilities/model-oracle-ai.json +26 -26
- package/dist/capabilities/modelis.json +17 -17
- package/dist/capabilities/modelscope.json +2 -2
- package/dist/capabilities/modular.json +30 -8
- package/dist/capabilities/moneo.json +12 -12
- package/dist/capabilities/moonshotai-cn.json +2 -2
- package/dist/capabilities/moonshotai.json +2 -2
- package/dist/capabilities/morph.json +17 -17
- package/dist/capabilities/munito-eu.json +6 -6
- package/dist/capabilities/munito.json +6 -6
- package/dist/capabilities/nan.json +29 -29
- package/dist/capabilities/nano-gpt.json +606 -593
- package/dist/capabilities/nearai.json +112 -112
- package/dist/capabilities/nebius.json +30 -30
- package/dist/capabilities/neon.json +136 -136
- package/dist/capabilities/neuralwatt.json +43 -43
- package/dist/capabilities/nokeep.json +4 -4
- package/dist/capabilities/novita-ai.json +136 -136
- package/dist/capabilities/nvidia.json +52 -35
- package/dist/capabilities/oathbreaker.json +24 -1
- package/dist/capabilities/obscurify.json +29 -29
- package/dist/capabilities/oci.json +7 -7
- package/dist/capabilities/ofox.json +315 -315
- package/dist/capabilities/ollama-cloud.json +53 -53
- package/dist/capabilities/openai.json +53 -53
- package/dist/capabilities/opencode-go.json +88 -88
- package/dist/capabilities/openreason.json +5 -5
- package/dist/capabilities/openrouter.json +528 -519
- package/dist/capabilities/opper.json +29 -29
- package/dist/capabilities/orcarouter.json +214 -214
- package/dist/capabilities/outerlabs.json +33 -33
- package/dist/capabilities/ovhcloud.json +20 -20
- package/dist/capabilities/pareto.json +6 -6
- package/dist/capabilities/pendra.json +4 -4
- package/dist/capabilities/perplexity-agent.json +55 -55
- package/dist/capabilities/perplexity.json +2 -2
- package/dist/capabilities/phala.json +26 -26
- package/dist/capabilities/pioneer.json +31 -31
- package/dist/capabilities/poe.json +136 -136
- package/dist/capabilities/poolside.json +2 -2
- package/dist/capabilities/powerspring.json +12 -12
- package/dist/capabilities/primalabs.json +9 -9
- package/dist/capabilities/prime.json +121 -111
- package/dist/capabilities/privatemode-ai.json +5 -5
- package/dist/capabilities/proxystacks.json +7 -7
- package/dist/capabilities/qiniu-ai.json +16 -16
- package/dist/capabilities/refuseless.json +9 -9
- package/dist/capabilities/regolo-ai.json +11 -11
- package/dist/capabilities/requesty.json +451 -177
- package/dist/capabilities/ruapi.json +35 -19
- package/dist/capabilities/runcrate.json +13 -13
- package/dist/capabilities/runinfra.json +18 -18
- package/dist/capabilities/sakana.json +7 -7
- package/dist/capabilities/sambanova.json +6 -6
- package/dist/capabilities/sandbase.json +25 -25
- package/dist/capabilities/sarvam.json +7 -7
- package/dist/capabilities/scaleway.json +19 -19
- package/dist/capabilities/scnet-token-plan.json +10 -10
- package/dist/capabilities/scx-ai.json +30 -30
- package/dist/capabilities/sensenova.json +12 -12
- package/dist/capabilities/siliconflow-cn.json +60 -60
- package/dist/capabilities/siliconflow.json +62 -62
- package/dist/capabilities/snowflake-cortex.json +21 -21
- package/dist/capabilities/sokkan.json +7 -7
- package/dist/capabilities/sparrowcodes.json +19 -19
- package/dist/capabilities/standardcompute.json +106 -106
- package/dist/capabilities/steadyrouter.json +37 -37
- package/dist/capabilities/stepfun-ai-step-plan.json +6 -6
- package/dist/capabilities/stepfun-ai.json +6 -6
- package/dist/capabilities/stepfun-step-plan.json +6 -6
- package/dist/capabilities/stepfun.json +6 -6
- package/dist/capabilities/stepping-stone.json +17 -17
- package/dist/capabilities/superbot-gg.json +4 -4
- package/dist/capabilities/synthetic.json +13 -13
- package/dist/capabilities/synthorai.json +24 -24
- package/dist/capabilities/teamorouter.json +23 -23
- package/dist/capabilities/teapot-router.json +11 -11
- package/dist/capabilities/tencent-token-plan-intl.json +126 -0
- package/dist/capabilities/tencent-token-plan.json +44 -44
- package/dist/capabilities/tencent-tokenhub.json +58 -43
- package/dist/capabilities/tensorx.json +40 -40
- package/dist/capabilities/tenstorrent.json +8 -8
- package/dist/capabilities/the-grid-ai.json +35 -35
- package/dist/capabilities/thinkingmachines.json +76 -76
- package/dist/capabilities/tinfoil.json +13 -13
- package/dist/capabilities/toapis.json +3 -3
- package/dist/capabilities/togetherai.json +54 -54
- package/dist/capabilities/tokengo.json +25 -25
- package/dist/capabilities/tokenify.json +9 -9
- package/dist/capabilities/tokenwatt.json +10 -2
- package/dist/capabilities/trustedrouter.json +7 -7
- package/dist/capabilities/trustedtokens.json +18 -18
- package/dist/capabilities/umans-ai-coding-plan.json +13 -13
- package/dist/capabilities/umans-ai.json +14 -14
- package/dist/capabilities/uncensuredai.json +5 -5
- 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 +23 -23
- package/dist/capabilities/vercel.json +543 -540
- package/dist/capabilities/vivgrid.json +88 -79
- package/dist/capabilities/volcengine-coding-plan.json +26 -26
- package/dist/capabilities/volcengine.json +26 -25
- package/dist/capabilities/vultr.json +32 -32
- package/dist/capabilities/wafer.ai.json +16 -16
- package/dist/capabilities/wallaby.json +2 -2
- package/dist/capabilities/wally.json +11 -11
- package/dist/capabilities/wandb.json +17 -17
- package/dist/capabilities/watt.json +25 -25
- package/dist/capabilities/xai.json +6 -6
- package/dist/capabilities/xiaomi.json +2 -2
- package/dist/capabilities/xpersona.json +13 -13
- package/dist/capabilities/xxapi.json +26 -26
- package/dist/capabilities/zai-coding-plan.json +15 -15
- package/dist/capabilities/zai.json +32 -32
- package/dist/capabilities/zenifra.json +26 -26
- package/dist/capabilities/zenmux.json +208 -208
- package/dist/capabilities/zerogpu.json +13 -13
- package/dist/capabilities/zhipuai-coding-plan.json +4 -4
- package/dist/capabilities/zhipuai.json +31 -31
- package/dist/capabilities/zro.json +7 -7
- package/dist/channels/agent-channels.d.ts +22 -0
- package/dist/channels/index.cjs +2 -2
- package/dist/channels/index.js +2 -2
- package/dist/channels/output-processor.d.ts +12 -0
- package/dist/channels/state-adapter.d.ts +3 -1
- package/dist/channels/stream-helpers.d.ts +17 -0
- package/dist/{channels-Cl-pRrWB.cjs → channels-Bkd_v8M1.cjs} +1 -1
- package/dist/{channels-DegTNzaq.js → channels-CkRMEIQ6.js} +1 -1
- package/dist/coding-agent/index.cjs +2 -2
- package/dist/coding-agent/index.js +2 -2
- package/dist/{constants-B9ZDvXZ4.cjs → constants-Bou0hEgY.cjs} +4 -0
- package/dist/{constants-BmdTvEYN.js → constants-CFWgIaqA.js} +4 -0
- package/dist/datasets/experiment/scorer.d.ts +16 -5
- package/dist/datasets/index.cjs +2 -2
- package/dist/datasets/index.js +2 -2
- package/dist/docs/SKILL.md +2 -1
- package/dist/docs/assets/SOURCE_MAP.json +1070 -1055
- package/dist/docs/references/docs-agents-code-mode.md +36 -0
- package/dist/docs/references/docs-agents-networks.md +1 -1
- package/dist/docs/references/docs-agents-tools.md +6 -0
- package/dist/docs/references/docs-auth-simple-auth.md +8 -8
- package/dist/docs/references/docs-browser.md +3 -1
- package/dist/docs/references/docs-evals-custom-scorers.md +1 -1
- package/dist/docs/references/docs-harness-background-tasks.md +38 -0
- package/dist/docs/references/docs-knowledge-agents-and-tools.md +2 -0
- package/dist/docs/references/docs-mastra-platform-observability-overview.md +3 -189
- package/dist/docs/references/docs-memory-message-history.md +25 -0
- package/dist/docs/references/docs-sandbox-lsp.md +5 -6
- package/dist/docs/references/docs-sandbox-overview.md +20 -0
- package/dist/docs/references/docs-sandbox-skills.md +2 -0
- package/dist/docs/references/docs-signals-sending-signals.md +1 -1
- package/dist/docs/references/integrations.md +1 -0
- package/dist/docs/references/reference-agent-controller-session.md +30 -2
- package/dist/docs/references/reference-agents-generate.md +1 -1
- package/dist/docs/references/reference-agents-network.md +1 -1
- package/dist/docs/references/reference-configuration.md +8 -8
- package/dist/docs/references/reference-core-getWorkspaceById.md +37 -0
- package/dist/docs/references/reference-evals-create-scorer.md +5 -5
- package/dist/docs/references/reference-evals-run-evals.md +1 -1
- package/dist/docs/references/reference-knowledge-knowledge-tools.md +3 -3
- package/dist/docs/references/reference-manual-install.md +1 -1
- package/dist/docs/references/reference-memory-observational-memory.md +8 -0
- package/dist/docs/references/reference-observability-tracing-interfaces.md +10 -6
- package/dist/docs/references/reference-processors-processor-interface.md +3 -2
- package/dist/docs/references/reference-processors-system-prompt-scrubber.md +1 -1
- package/dist/docs/references/reference-processors-tool-search-processor.md +3 -3
- package/dist/docs/references/reference-pubsub-base.md +5 -3
- package/dist/docs/references/reference-pubsub-caching-pubsub.md +3 -1
- package/dist/docs/references/reference-storage-overview.md +1 -1
- package/dist/docs/references/reference-storage-retention.md +20 -20
- package/dist/docs/references/reference-tools-create-code-mode.md +22 -0
- package/dist/docs/references/reference-tools-vector-query-tool.md +8 -0
- package/dist/docs/references/reference-voice-overview.md +11 -26
- package/dist/docs/references/reference-voice-speech-to-speech.md +1 -1
- package/dist/docs/references/reference-voice-voice.listen.md +1 -0
- package/dist/docs/references/reference-voice-voice.speak.md +1 -3
- package/dist/docs/references/reference-workspace-factory-sandbox.md +6 -6
- package/dist/docs/references/reference-workspace-sandbox.md +14 -0
- package/dist/docs/references/reference.md +1 -0
- package/dist/evals/index.cjs +2 -2
- package/dist/evals/index.js +2 -2
- package/dist/evals/scoreTraces/index.cjs +2 -2
- package/dist/evals/scoreTraces/index.js +2 -2
- package/dist/events/index.cjs +1 -1
- package/dist/events/index.js +1 -1
- package/dist/harness/index.cjs +2 -2
- package/dist/harness/index.js +2 -2
- package/dist/index.cjs +1 -1
- package/dist/index.js +1 -1
- package/dist/knowledge/agent-scopes.d.ts +17 -0
- package/dist/knowledge/declarations.d.ts +2 -0
- package/dist/knowledge/held-scopes-state-processor.d.ts +50 -0
- package/dist/knowledge/importers/host.d.ts +7 -1
- package/dist/knowledge/importers/overlay.d.ts +138 -0
- package/dist/knowledge/importers/runner.d.ts +12 -0
- package/dist/knowledge/importers/sink.d.ts +6 -0
- package/dist/knowledge/importers/types.d.ts +9 -0
- package/dist/knowledge/index.cjs +1611 -167
- package/dist/knowledge/index.d.ts +12 -2
- package/dist/knowledge/index.js +1610 -168
- package/dist/knowledge/links.d.ts +27 -0
- package/dist/knowledge/page-tools.d.ts +23 -0
- package/dist/knowledge/pinned-state-processor.d.ts +2 -2
- package/dist/knowledge/run.d.ts +5 -0
- package/dist/knowledge/scope-runtime.d.ts +6 -0
- package/dist/llm/index.cjs +3 -3
- package/dist/llm/index.js +3 -3
- package/dist/llm/model/base.types.d.ts +3 -1
- package/dist/llm/model/mastra-gateway-provider-tools.d.ts +9 -6
- package/dist/llm/model/model.d.ts +1 -1
- package/dist/llm/model/model.loop.d.ts +1 -1
- package/dist/llm/model/model.loop.types.d.ts +3 -1
- package/dist/llm/model/provider-options.d.ts +4 -3
- package/dist/llm/model/provider-types.generated.d.ts +8161 -8082
- package/dist/{llm-BKxlS9Kk.cjs → llm-DAw2eouV.cjs} +38 -78
- package/dist/{llm-CMkzIFAk.js → llm-DFT5EKp4.js} +38 -78
- package/dist/loop/index.cjs +2 -2
- package/dist/loop/index.js +2 -2
- package/dist/{manager-C-eQXmRq.js → manager-DiDnvKLM.js} +106 -35
- package/dist/{manager-CasaT35Q.cjs → manager-hxzEe4U5.cjs} +106 -35
- package/dist/mastra/index.cjs +1 -1
- package/dist/mastra/index.js +1 -1
- package/dist/{mastra-C7Tj4U8c.cjs → mastra-1diaq68N.cjs} +17 -17
- package/dist/{mastra-5EEmN3Ok.js → mastra-BPaPxG5t.js} +17 -17
- package/dist/memory/index.cjs +3 -3
- package/dist/memory/index.js +3 -3
- package/dist/{message-list-wI71UGxk.js → message-list-BGm1DCiG.js} +230 -129
- package/dist/{message-list-DfN9mWeN.cjs → message-list-vR3uLAHL.cjs} +230 -129
- package/dist/{model-DCLUL-8a.js → model-CUBZjm0T.js} +4 -3
- package/dist/{model-9HA-W0tg.cjs → model-DSMHJM3c.cjs} +4 -3
- package/dist/{netlify-Cq3H-A9I.cjs → netlify-C21T9ozJ.cjs} +41364 -30461
- package/dist/{netlify-DaWURNSU.js → netlify-D1BKjns0.js} +41361 -30464
- package/dist/notifications/index.cjs +1 -1
- package/dist/notifications/index.js +1 -1
- package/dist/observability/types/tracing.d.ts +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/processors/processors/tool-search.d.ts +2 -2
- package/dist/processors/runner.d.ts +12 -0
- package/dist/{provider-registry-DWixjFX7.js → provider-registry-BAlFFX5o.js} +21911 -21671
- package/dist/{provider-registry-a649fS5r.cjs → provider-registry-ChojUVJa.cjs} +21910 -21670
- package/dist/provider-registry.json +21947 -21767
- package/dist/{registry-generator-BYJC7p8M.js → registry-generator-BbWSH6W4.js} +1 -1
- package/dist/{registry-generator-BuKC7UKd.cjs → registry-generator-CAUL9Hek.cjs} +1 -1
- package/dist/{rehydrate-DR2_WAz2.cjs → rehydrate-0xSq47n9.cjs} +2 -2
- package/dist/{rehydrate-DPhmASM6.js → rehydrate-CzUnNFU6.js} +2 -2
- package/dist/relevance/index.cjs +2 -2
- package/dist/relevance/index.js +2 -2
- package/dist/{run-registry-oUNF6szW.cjs → run-registry-CrTsH9iL.cjs} +1158 -125
- package/dist/{run-registry-D3X7XvUL.js → run-registry-DJT02z_9.js} +1092 -125
- package/dist/storage/constants.cjs +1 -1
- package/dist/storage/constants.js +1 -1
- package/dist/storage/domains/knowledge/base.d.ts +101 -1
- package/dist/storage/domains/knowledge/importers-inmemory.d.ts +10 -0
- package/dist/storage/domains/knowledge/importers.d.ts +39 -0
- package/dist/storage/domains/knowledge/inmemory.d.ts +8 -0
- package/dist/storage/domains/knowledge/pages-inmemory.d.ts +35 -1
- package/dist/storage/domains/knowledge/pages.d.ts +74 -0
- package/dist/storage/index.cjs +3 -3
- package/dist/storage/index.js +3 -3
- package/dist/storage/types.d.ts +14 -0
- package/dist/stream/index.cjs +2 -2
- package/dist/stream/index.js +2 -2
- package/dist/{stream-DoZ6F41o.js → stream-CG9OooRx.js} +37 -14
- package/dist/{stream-DQC1vpvl.cjs → stream-CMKRczs4.cjs} +37 -14
- package/dist/test-utils/llm-mock.cjs +1 -1
- package/dist/test-utils/llm-mock.js +1 -1
- package/dist/{to-prompt-B9eZo2U5.cjs → to-prompt-CG-LyaBY.cjs} +9 -0
- package/dist/{to-prompt-BsDtVXrf.js → to-prompt-CMlVGYxC.js} +9 -0
- package/dist/tool-loop-agent/index.cjs +1 -1
- package/dist/tool-loop-agent/index.js +1 -1
- package/dist/{tool-loop-agent-Cy4NDOMS.cjs → tool-loop-agent-14o3Z1qo.cjs} +4 -4
- package/dist/{tool-loop-agent-C9YkvDRd.js → tool-loop-agent-Bi6z_q7o.js} +4 -4
- package/dist/tools/code-mode/index.d.ts +2 -0
- package/dist/tools/code-mode/log-collector.d.ts +49 -0
- package/dist/tools/code-mode/types.d.ts +71 -0
- package/dist/tools/index.cjs +3 -1
- package/dist/tools/index.js +2 -2
- package/dist/{tools-CGF5Ik6j.cjs → tools-BEYxowf0.cjs} +429 -61
- package/dist/{tools-CDfyMpzN.js → tools-tPy2FwMI.js} +418 -62
- package/dist/{utils-Bs2IYyOb.cjs → utils-DkvbP8EA.cjs} +7 -6
- package/dist/{utils-9JyiKu5r.js → utils-Fag7YDBU.js} +7 -6
- package/dist/utils.cjs +1 -1
- package/dist/utils.js +1 -1
- package/dist/{validate-BE3mVxVy.cjs → validate-Bhrlve2E.cjs} +1 -1
- package/dist/{validate-8j0phWFV.js → validate-DLER0nlQ.js} +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/workers/orchestration-worker.d.ts +1 -0
- package/dist/{worker-DwdgU6E9.cjs → worker-0gczpztM.cjs} +2 -2
- package/dist/{worker-BiK1kfMa.cjs → worker-BwJyrFQN.cjs} +10 -4
- package/dist/{worker-BfWFqSH2.js → worker-D-em3hyS.js} +5 -5
- package/dist/{worker-DIRdEwih.js → worker-leYV1Y91.js} +2 -2
- package/dist/{workflow-CxQMcTbT.cjs → workflow-DWdcEcxw.cjs} +3 -3
- package/dist/{workflow-ni-keg2i.js → workflow-FikHVwog.js} +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/workflows/step.d.ts +2 -0
- package/dist/workflows/workflow.d.ts +2 -0
- package/dist/workspace/index.cjs +3 -1
- package/dist/workspace/index.d.ts +1 -1
- package/dist/workspace/index.js +2 -2
- package/dist/workspace/lsp/manager.d.ts +19 -4
- package/dist/workspace/sandbox/mastra-sandbox.d.ts +17 -0
- package/dist/workspace/sandbox/teardown-context.d.ts +74 -0
- package/dist/workspace/tools/index.d.ts +1 -0
- package/dist/workspace/tools/media.d.ts +20 -1
- package/dist/workspace/tools/recreate-sandbox.d.ts +24 -0
- package/dist/{workspace-X2RHJZU9.cjs → workspace-C8Zo5_qK.cjs} +387 -109
- package/dist/{workspace-DY2Nxiyi.js → workspace-DOAil8mG.js} +376 -110
- package/package.json +6 -6
- package/src/llm/model/provider-types.generated.d.ts +8161 -8082
package/dist/knowledge/index.cjs
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
2
2
|
const require_base = require("../base-BIzR1D3_.cjs");
|
|
3
|
-
const require_run_registry = require("../run-registry-
|
|
3
|
+
const require_run_registry = require("../run-registry-CrTsH9iL.cjs");
|
|
4
4
|
const require_tool = require("../tool-CYlT2UA-.cjs");
|
|
5
5
|
let crypto = require("crypto");
|
|
6
6
|
let _mastra_schema_compat_schema = require("@mastra/schema-compat/schema");
|
|
@@ -23,6 +23,39 @@ const note = (op) => (result) => {
|
|
|
23
23
|
noteId: id
|
|
24
24
|
};
|
|
25
25
|
};
|
|
26
|
+
/** The event each single write would emit for `write`, so a batch emits what its single writes would. */
|
|
27
|
+
function describePageWrite(write) {
|
|
28
|
+
switch (write.op) {
|
|
29
|
+
case "create":
|
|
30
|
+
case "update":
|
|
31
|
+
case "delete": return {
|
|
32
|
+
kind: "page",
|
|
33
|
+
op: write.op,
|
|
34
|
+
pageId: write.id,
|
|
35
|
+
scopeId: write.scopeId
|
|
36
|
+
};
|
|
37
|
+
case "move": return {
|
|
38
|
+
kind: "page",
|
|
39
|
+
op: "move",
|
|
40
|
+
pageId: write.id,
|
|
41
|
+
scopeId: write.scopeId,
|
|
42
|
+
fromScopeId: write.fromScopeId
|
|
43
|
+
};
|
|
44
|
+
case "add-note": return {
|
|
45
|
+
kind: "note",
|
|
46
|
+
op: "add",
|
|
47
|
+
pageId: write.pageId,
|
|
48
|
+
noteId: write.id
|
|
49
|
+
};
|
|
50
|
+
case "remove-note": return {
|
|
51
|
+
kind: "note",
|
|
52
|
+
op: "remove",
|
|
53
|
+
pageId: write.pageId,
|
|
54
|
+
noteId: write.id
|
|
55
|
+
};
|
|
56
|
+
case "replace-links": return null;
|
|
57
|
+
}
|
|
58
|
+
}
|
|
26
59
|
/** The page-store writes that emit, and the event each one's result maps to. */
|
|
27
60
|
const WRITES = {
|
|
28
61
|
materializeScope: (result) => {
|
|
@@ -58,6 +91,7 @@ const WRITES = {
|
|
|
58
91
|
fromScopeId
|
|
59
92
|
};
|
|
60
93
|
},
|
|
94
|
+
applyPageWrites: (_result, input) => input.writes.map(describePageWrite).filter((change) => change !== null),
|
|
61
95
|
addNote: note("add"),
|
|
62
96
|
restampNote: note("restamp"),
|
|
63
97
|
removeNote: note("remove"),
|
|
@@ -143,9 +177,15 @@ function emitKnowledgeChanges(storage, emit, listening, onError, chain) {
|
|
|
143
177
|
}
|
|
144
178
|
const result = await value.call(target, input, ...rest);
|
|
145
179
|
if (!listening()) return result;
|
|
180
|
+
let changes = [];
|
|
146
181
|
try {
|
|
147
182
|
const change = describe(result, input, fromScopeId);
|
|
148
|
-
|
|
183
|
+
changes = Array.isArray(change) ? change : change ? [change] : [];
|
|
184
|
+
} catch (error) {
|
|
185
|
+
onError(error);
|
|
186
|
+
}
|
|
187
|
+
for (const one of changes) try {
|
|
188
|
+
report(one);
|
|
149
189
|
} catch (error) {
|
|
150
190
|
onError(error);
|
|
151
191
|
}
|
|
@@ -174,6 +214,7 @@ const KNOWLEDGE_IMPORTER_ERROR_CODES = [
|
|
|
174
214
|
"credential_missing",
|
|
175
215
|
"importer_missing_from_deploy",
|
|
176
216
|
"importer_error",
|
|
217
|
+
"flush_too_large",
|
|
177
218
|
"stopped",
|
|
178
219
|
"lease_expired",
|
|
179
220
|
"deadline_exceeded"
|
|
@@ -671,17 +712,22 @@ function sourceError(error) {
|
|
|
671
712
|
* @experimental
|
|
672
713
|
*/
|
|
673
714
|
async function runKnowledgeImport(options) {
|
|
674
|
-
const { host, budgetMs = 15e5, graceMs = 18e4, maxPasses = 200, bufferSize = 200, flushAfterMs = 3e4, heartbeatMs = 3e4, maxRetries = 8, hostCallTimeoutMs = 6e4, retryDelayMs = (attempt) => Math.min(250 * 2 ** attempt, 1e4) } = options;
|
|
715
|
+
const { host, budgetMs = 15e5, graceMs = 18e4, maxPasses = 200, bufferSize = 200, maxFlushBytes: ownMaxFlushBytes = Infinity, flushAfterMs = 3e4, heartbeatMs = 3e4, maxRetries = 8, hostCallTimeoutMs = 6e4, retryDelayMs = (attempt) => Math.min(250 * 2 ** attempt, 1e4) } = options;
|
|
675
716
|
if (!Number.isFinite(flushAfterMs) || flushAfterMs <= 0 || flushAfterMs > 2 ** 31 - 1) throw new TypeError(`flushAfterMs must be a positive number of milliseconds up to 2147483647, got ${flushAfterMs}`);
|
|
717
|
+
if (ownMaxFlushBytes !== Infinity && !(Number.isInteger(ownMaxFlushBytes) && ownMaxFlushBytes > 0)) throw new TypeError(`maxFlushBytes must be a positive whole number of bytes, got ${ownMaxFlushBytes}`);
|
|
676
718
|
const started = await within(host.startRun(options.bindingId, options.start), hostCallTimeoutMs, () => new KnowledgeImporterHostError("host call timed out"));
|
|
677
719
|
if (started.status === "skipped") return started;
|
|
678
720
|
const { runId, generation } = started;
|
|
721
|
+
const hostMaxFlushBytes = started.maxFlushBytes;
|
|
722
|
+
const maxFlushBytes = typeof hostMaxFlushBytes === "number" && Number.isInteger(hostMaxFlushBytes) && hostMaxFlushBytes > 0 ? Math.min(ownMaxFlushBytes, hostMaxFlushBytes) : ownMaxFlushBytes;
|
|
679
723
|
const startedAt = Date.now();
|
|
680
724
|
let lastSeq = started.lastSeq;
|
|
681
725
|
/** A flush sent but never acknowledged: it may have committed. */
|
|
682
726
|
let unsettledSeq;
|
|
683
727
|
let state = { ...started.state };
|
|
684
728
|
let buffer = [];
|
|
729
|
+
/** Encoded bytes of the ops in `buffer`, without the commas between them. */
|
|
730
|
+
let bufferBytes = 0;
|
|
685
731
|
let stop;
|
|
686
732
|
/** Armed while the buffer holds ops; sends them once the oldest has waited `flushAfterMs`. */
|
|
687
733
|
let flushTimer;
|
|
@@ -732,6 +778,7 @@ async function runKnowledgeImport(options) {
|
|
|
732
778
|
disarm();
|
|
733
779
|
const ops = buffer;
|
|
734
780
|
buffer = [];
|
|
781
|
+
bufferBytes = 0;
|
|
735
782
|
const next = flushing.then(async () => {
|
|
736
783
|
if (stop) throw stop;
|
|
737
784
|
if (ops.length === 0 && !staged && !settle) return;
|
|
@@ -756,6 +803,11 @@ async function runKnowledgeImport(options) {
|
|
|
756
803
|
digest,
|
|
757
804
|
...body
|
|
758
805
|
};
|
|
806
|
+
if (maxFlushBytes !== Infinity && encodedBytes(request) > maxFlushBytes) {
|
|
807
|
+
flushFailure = { code: "flush_too_large" };
|
|
808
|
+
halt("flush");
|
|
809
|
+
throw stop;
|
|
810
|
+
}
|
|
759
811
|
unsettledSeq = seq;
|
|
760
812
|
try {
|
|
761
813
|
const receipt = await withRetries(() => host.flush(request), "mutation");
|
|
@@ -780,14 +832,70 @@ async function runKnowledgeImport(options) {
|
|
|
780
832
|
flushing = next.catch(() => {});
|
|
781
833
|
return next;
|
|
782
834
|
}
|
|
783
|
-
|
|
835
|
+
/** The request around the ops, at the longest `seq` it can have; `ops` empty, no `state`. */
|
|
836
|
+
const envelopeBytes = encodedBytes({
|
|
837
|
+
runId,
|
|
838
|
+
generation,
|
|
839
|
+
seq: Number.MAX_SAFE_INTEGER,
|
|
840
|
+
digest: "0".repeat(64),
|
|
841
|
+
ops: []
|
|
842
|
+
});
|
|
843
|
+
/**
|
|
844
|
+
* The envelope at the shortest `seq` the next request can have. A request's `seq` is only known
|
|
845
|
+
* when it is sent, so splitting plans for the longest; refusing what can never fit uses the
|
|
846
|
+
* shortest, and the request as sent is measured again before it goes.
|
|
847
|
+
*/
|
|
848
|
+
const shortestEnvelopeBytes = () => envelopeBytes - String(Number.MAX_SAFE_INTEGER).length + String(lastSeq + 1).length;
|
|
849
|
+
/** Bytes of a request holding the buffer plus `extra` more ops' bytes over `more` ops, and a state. */
|
|
850
|
+
const requestBytes = (extra, more, stateBytes) => {
|
|
851
|
+
const count = buffer.length + more;
|
|
852
|
+
const commas = Math.max(count - 1, 0);
|
|
853
|
+
const state = stateBytes === void 0 ? 0 : 9 + stateBytes;
|
|
854
|
+
return envelopeBytes + bufferBytes + extra + commas + state;
|
|
855
|
+
};
|
|
856
|
+
/**
|
|
857
|
+
* Measures what the importer hands over and returns a copy decoded from that encoding, so a value
|
|
858
|
+
* the importer changes after handing it over can't outgrow its measured size. Anything
|
|
859
|
+
* unencodable or too big ends the run here.
|
|
860
|
+
*/
|
|
861
|
+
const measure = (value, alone) => {
|
|
862
|
+
let json;
|
|
863
|
+
let bytes;
|
|
864
|
+
try {
|
|
865
|
+
json = JSON.stringify(value);
|
|
866
|
+
bytes = new TextEncoder().encode(json).byteLength;
|
|
867
|
+
} catch (error) {
|
|
868
|
+
flushFailure = { code: "importer_error" };
|
|
869
|
+
halt("flush");
|
|
870
|
+
throw error;
|
|
871
|
+
}
|
|
872
|
+
if (alone(bytes) > maxFlushBytes) {
|
|
873
|
+
flushFailure = { code: "flush_too_large" };
|
|
874
|
+
halt("flush");
|
|
875
|
+
throw stop;
|
|
876
|
+
}
|
|
877
|
+
return {
|
|
878
|
+
bytes,
|
|
879
|
+
copy: JSON.parse(json)
|
|
880
|
+
};
|
|
881
|
+
};
|
|
882
|
+
const push = async (handed) => {
|
|
784
883
|
if (stop) throw stop;
|
|
884
|
+
let op = handed;
|
|
885
|
+
let sending;
|
|
886
|
+
if (maxFlushBytes !== Infinity) {
|
|
887
|
+
const { bytes, copy } = measure(handed, (opBytes) => shortestEnvelopeBytes() + opBytes);
|
|
888
|
+
op = copy;
|
|
889
|
+
if (buffer.length > 0 && requestBytes(bytes, 1) > maxFlushBytes) sending = flush();
|
|
890
|
+
bufferBytes += bytes;
|
|
891
|
+
}
|
|
785
892
|
buffer.push(op);
|
|
786
|
-
if (buffer.length
|
|
787
|
-
else if (!flushTimer) {
|
|
893
|
+
if (!flushTimer && buffer.length < bufferSize) {
|
|
788
894
|
flushTimer = setTimeout(() => flush().catch(() => {}), flushAfterMs);
|
|
789
895
|
flushTimer.unref?.();
|
|
790
896
|
}
|
|
897
|
+
if (sending) await sending;
|
|
898
|
+
if (buffer.length >= bufferSize) await flush();
|
|
791
899
|
};
|
|
792
900
|
const finish = async (request) => {
|
|
793
901
|
const result = await finishRun(host, {
|
|
@@ -851,7 +959,12 @@ async function runKnowledgeImport(options) {
|
|
|
851
959
|
get: async (key) => state[key],
|
|
852
960
|
set: async (key, value) => {
|
|
853
961
|
if (stop) throw stop;
|
|
854
|
-
|
|
962
|
+
const staged = { [key]: value };
|
|
963
|
+
if (maxFlushBytes !== Infinity) {
|
|
964
|
+
const { bytes } = measure(staged, (stateBytes) => shortestEnvelopeBytes() + 9 + stateBytes);
|
|
965
|
+
if (requestBytes(0, 0, bytes) > maxFlushBytes) flush().catch(() => {});
|
|
966
|
+
}
|
|
967
|
+
await flush(staged);
|
|
855
968
|
}
|
|
856
969
|
},
|
|
857
970
|
items: {
|
|
@@ -957,6 +1070,892 @@ async function finishRun(host, request, lastSeq, unsettledSeq, withRetries) {
|
|
|
957
1070
|
lastSeq
|
|
958
1071
|
};
|
|
959
1072
|
}
|
|
1073
|
+
function encodedBytes(value) {
|
|
1074
|
+
return new TextEncoder().encode(JSON.stringify(value)).byteLength;
|
|
1075
|
+
}
|
|
1076
|
+
// src/knowledge/importers/overlay.ts
|
|
1077
|
+
/**
|
|
1078
|
+
* The working copy a batched importer flush decides over (batched-flush plan v3.1 §1). The sink's
|
|
1079
|
+
* rule code runs unchanged against {@link ImportOverlay.storage} and {@link ImportOverlay.importers}:
|
|
1080
|
+
* reads come from rows gathered in a few set-based queries and locked, writes are applied to the
|
|
1081
|
+
* working copy and kept, in call order, for one batched write after every op is decided.
|
|
1082
|
+
*
|
|
1083
|
+
* A read of something not gathered throws {@link KnowledgeImportNotGatheredError} and names it, so
|
|
1084
|
+
* the caller gathers it and decides again. A call the working copy can't model throws
|
|
1085
|
+
* {@link KnowledgeImportBatchUnsupportedError}, and the flush takes the per-op path instead.
|
|
1086
|
+
*
|
|
1087
|
+
* @internal
|
|
1088
|
+
*/
|
|
1089
|
+
/** The overlay was asked for a row it wasn't given. The caller gathers it and decides again. */
|
|
1090
|
+
var KnowledgeImportNotGatheredError = class extends Error {
|
|
1091
|
+
constructor(what) {
|
|
1092
|
+
super(`Not gathered for the batched import flush: ${what}`);
|
|
1093
|
+
this.name = "KnowledgeImportNotGatheredError";
|
|
1094
|
+
}
|
|
1095
|
+
};
|
|
1096
|
+
/** The flush needs a call the overlay doesn't model: it falls back to the per-op path. */
|
|
1097
|
+
var KnowledgeImportBatchUnsupportedError = class extends Error {
|
|
1098
|
+
call;
|
|
1099
|
+
constructor(call) {
|
|
1100
|
+
super(`Not supported by the batched import flush: ${call}`);
|
|
1101
|
+
this.call = call;
|
|
1102
|
+
this.name = "KnowledgeImportBatchUnsupportedError";
|
|
1103
|
+
}
|
|
1104
|
+
};
|
|
1105
|
+
const nodeKey = (bindingId, sourceId) => `${bindingId}\u0000${sourceId}`;
|
|
1106
|
+
const pathKey = (scopeId, path) => JSON.stringify([scopeId, ...path]);
|
|
1107
|
+
const childKey = (parentId, key) => `${parentId}\u0000${key}`;
|
|
1108
|
+
const byPosition = (a, b) => a.position < b.position ? -1 : a.position > b.position ? 1 : a.id < b.id ? -1 : a.id > b.id ? 1 : 0;
|
|
1109
|
+
/** UTF-8 byte order, as the stores sort source IDs. */
|
|
1110
|
+
const byteOrder = (a, b) => Buffer.compare(Buffer.from(a), Buffer.from(b));
|
|
1111
|
+
const emptyImportOverlayMissing = () => ({
|
|
1112
|
+
pages: /* @__PURE__ */ new Set(),
|
|
1113
|
+
nodes: /* @__PURE__ */ new Set(),
|
|
1114
|
+
nodesByPage: /* @__PURE__ */ new Set(),
|
|
1115
|
+
paths: /* @__PURE__ */ new Map(),
|
|
1116
|
+
notes: /* @__PURE__ */ new Set(),
|
|
1117
|
+
positions: /* @__PURE__ */ new Set(),
|
|
1118
|
+
locks: /* @__PURE__ */ new Set(),
|
|
1119
|
+
subtrees: /* @__PURE__ */ new Set(),
|
|
1120
|
+
linkTargets: /* @__PURE__ */ new Set(),
|
|
1121
|
+
bindings: /* @__PURE__ */ new Set()
|
|
1122
|
+
});
|
|
1123
|
+
const emptyImportOverlayRows = () => ({
|
|
1124
|
+
pages: /* @__PURE__ */ new Map(),
|
|
1125
|
+
nodes: /* @__PURE__ */ new Map(),
|
|
1126
|
+
nodesByPage: /* @__PURE__ */ new Map(),
|
|
1127
|
+
paths: /* @__PURE__ */ new Map(),
|
|
1128
|
+
notes: /* @__PURE__ */ new Map(),
|
|
1129
|
+
positions: /* @__PURE__ */ new Map(),
|
|
1130
|
+
locked: /* @__PURE__ */ new Set(),
|
|
1131
|
+
complete: /* @__PURE__ */ new Set(),
|
|
1132
|
+
tooLarge: /* @__PURE__ */ new Set(),
|
|
1133
|
+
linkTargets: /* @__PURE__ */ new Set(),
|
|
1134
|
+
tooManyLinkers: /* @__PURE__ */ new Set()
|
|
1135
|
+
});
|
|
1136
|
+
/** The binding and targets of a deferred mark, so back-to-back marks for one binding run as one. */
|
|
1137
|
+
const markTargets = /* @__PURE__ */ new WeakMap();
|
|
1138
|
+
const copyRows = (rows) => ({
|
|
1139
|
+
pages: new Map(rows.pages),
|
|
1140
|
+
nodes: new Map(rows.nodes),
|
|
1141
|
+
nodesByPage: new Map(rows.nodesByPage),
|
|
1142
|
+
paths: new Map(rows.paths),
|
|
1143
|
+
notes: new Map(rows.notes),
|
|
1144
|
+
positions: new Map(rows.positions),
|
|
1145
|
+
locked: new Set(rows.locked),
|
|
1146
|
+
complete: new Set(rows.complete),
|
|
1147
|
+
tooLarge: new Set(rows.tooLarge),
|
|
1148
|
+
linkTargets: new Set(rows.linkTargets),
|
|
1149
|
+
tooManyLinkers: new Set(rows.tooManyLinkers),
|
|
1150
|
+
...rows.bindings ? { bindings: rows.bindings } : {}
|
|
1151
|
+
});
|
|
1152
|
+
const copyState = (state) => ({
|
|
1153
|
+
rows: copyRows(state.rows),
|
|
1154
|
+
writes: [...state.writes],
|
|
1155
|
+
touched: new Set(state.touched),
|
|
1156
|
+
marks: [...state.marks],
|
|
1157
|
+
links: [...state.links],
|
|
1158
|
+
moved: new Set(state.moved),
|
|
1159
|
+
freed: new Set(state.freed),
|
|
1160
|
+
stalePositions: new Set(state.stalePositions)
|
|
1161
|
+
});
|
|
1162
|
+
/** Every method the given implementation lacks throws {@link KnowledgeImportBatchUnsupportedError}. */
|
|
1163
|
+
function only(impl, name) {
|
|
1164
|
+
return new Proxy(impl, { get(target, prop, receiver) {
|
|
1165
|
+
if (prop in target) return Reflect.get(target, prop, receiver);
|
|
1166
|
+
if (typeof prop !== "string" || prop === "then") return void 0;
|
|
1167
|
+
return () => {
|
|
1168
|
+
throw new KnowledgeImportBatchUnsupportedError(`${name}.${prop}`);
|
|
1169
|
+
};
|
|
1170
|
+
} });
|
|
1171
|
+
}
|
|
1172
|
+
var ImportOverlay = class {
|
|
1173
|
+
missing = emptyImportOverlayMissing();
|
|
1174
|
+
#state;
|
|
1175
|
+
storage;
|
|
1176
|
+
importers;
|
|
1177
|
+
constructor(base, now = () => /* @__PURE__ */ new Date()) {
|
|
1178
|
+
this.#state = {
|
|
1179
|
+
rows: copyRows(base),
|
|
1180
|
+
writes: [],
|
|
1181
|
+
touched: /* @__PURE__ */ new Set(),
|
|
1182
|
+
marks: [],
|
|
1183
|
+
links: [],
|
|
1184
|
+
moved: /* @__PURE__ */ new Set(),
|
|
1185
|
+
freed: /* @__PURE__ */ new Set(),
|
|
1186
|
+
stalePositions: /* @__PURE__ */ new Set()
|
|
1187
|
+
};
|
|
1188
|
+
this.storage = this.#storage(now);
|
|
1189
|
+
this.importers = this.#importers();
|
|
1190
|
+
}
|
|
1191
|
+
get writes() {
|
|
1192
|
+
return this.#state.writes;
|
|
1193
|
+
}
|
|
1194
|
+
get marks() {
|
|
1195
|
+
return this.#state.marks;
|
|
1196
|
+
}
|
|
1197
|
+
get links() {
|
|
1198
|
+
return this.#state.links;
|
|
1199
|
+
}
|
|
1200
|
+
/** Link-index work the sink would run now; it runs, in one batch, after the batched write instead. */
|
|
1201
|
+
deferLinks(...work) {
|
|
1202
|
+
this.#state.links.push(...work);
|
|
1203
|
+
}
|
|
1204
|
+
/** The node writes decided: each touched node's last record, or a delete when it ends up gone. */
|
|
1205
|
+
nodeWrites(base) {
|
|
1206
|
+
const deletes = [];
|
|
1207
|
+
const saves = [];
|
|
1208
|
+
for (const key of this.#state.touched) {
|
|
1209
|
+
const node = this.#state.rows.nodes.get(key);
|
|
1210
|
+
if (node) {
|
|
1211
|
+
const { updatedAt: _updatedAt, ...record } = node;
|
|
1212
|
+
saves.push(record);
|
|
1213
|
+
} else if (base.nodes.get(key)) {
|
|
1214
|
+
const [bindingId, sourceId] = key.split("\0");
|
|
1215
|
+
deletes.push({
|
|
1216
|
+
bindingId,
|
|
1217
|
+
sourceId
|
|
1218
|
+
});
|
|
1219
|
+
}
|
|
1220
|
+
}
|
|
1221
|
+
return {
|
|
1222
|
+
deletes,
|
|
1223
|
+
saves
|
|
1224
|
+
};
|
|
1225
|
+
}
|
|
1226
|
+
#page(id) {
|
|
1227
|
+
const { pages } = this.#state.rows;
|
|
1228
|
+
if (!pages.has(id)) {
|
|
1229
|
+
this.missing.pages.add(id);
|
|
1230
|
+
throw new KnowledgeImportNotGatheredError(`page ${id}`);
|
|
1231
|
+
}
|
|
1232
|
+
return pages.get(id);
|
|
1233
|
+
}
|
|
1234
|
+
#livePage(id) {
|
|
1235
|
+
const page = this.#page(id);
|
|
1236
|
+
if (!page || page.deletedAt || page.mergedInto) throw new require_run_registry.KnowledgeNotFoundError("page", id);
|
|
1237
|
+
return page;
|
|
1238
|
+
}
|
|
1239
|
+
/** Levels below the home scope, from the working copy's chain. */
|
|
1240
|
+
#depth(page) {
|
|
1241
|
+
let depth = 0;
|
|
1242
|
+
let at = page;
|
|
1243
|
+
while (at && !at.isScope) {
|
|
1244
|
+
depth++;
|
|
1245
|
+
at = at.parentId ? this.#page(at.parentId) : null;
|
|
1246
|
+
}
|
|
1247
|
+
return depth;
|
|
1248
|
+
}
|
|
1249
|
+
/** The page's key path from its scope, or null when the chain doesn't reach one. */
|
|
1250
|
+
#keys(page) {
|
|
1251
|
+
const path = [];
|
|
1252
|
+
let at = page;
|
|
1253
|
+
while (at && !at.isScope) {
|
|
1254
|
+
if (at.key === void 0 || at.deletedAt || at.mergedInto) return null;
|
|
1255
|
+
path.unshift(at.key);
|
|
1256
|
+
at = at.parentId ? this.#page(at.parentId) : null;
|
|
1257
|
+
}
|
|
1258
|
+
return at ? {
|
|
1259
|
+
scopeId: at.id,
|
|
1260
|
+
path
|
|
1261
|
+
} : null;
|
|
1262
|
+
}
|
|
1263
|
+
/**
|
|
1264
|
+
* Live ordinary children by parent, sorted by position: built on first use, dropped on each page
|
|
1265
|
+
* write, and keyed by the pages map, which a rolled-back transaction replaces.
|
|
1266
|
+
*/
|
|
1267
|
+
#childIndex;
|
|
1268
|
+
#setPage(id, page) {
|
|
1269
|
+
this.#state.rows.pages.set(id, page);
|
|
1270
|
+
this.#childIndex = void 0;
|
|
1271
|
+
}
|
|
1272
|
+
/** Live ordinary children by position, once gathered. */
|
|
1273
|
+
#children(parentId) {
|
|
1274
|
+
const { pages, complete } = this.#state.rows;
|
|
1275
|
+
if (!complete.has(parentId)) {
|
|
1276
|
+
this.missing.subtrees.add(parentId);
|
|
1277
|
+
throw new KnowledgeImportNotGatheredError(`children of ${parentId}`);
|
|
1278
|
+
}
|
|
1279
|
+
if (this.#childIndex?.pages !== pages) {
|
|
1280
|
+
const byParent = /* @__PURE__ */ new Map();
|
|
1281
|
+
for (const page of pages.values()) {
|
|
1282
|
+
if (!page || !page.parentId || page.isScope || page.deletedAt) continue;
|
|
1283
|
+
const siblings = byParent.get(page.parentId);
|
|
1284
|
+
if (siblings) siblings.push(page);
|
|
1285
|
+
else byParent.set(page.parentId, [page]);
|
|
1286
|
+
}
|
|
1287
|
+
for (const siblings of byParent.values()) siblings.sort(byPosition);
|
|
1288
|
+
this.#childIndex = {
|
|
1289
|
+
pages,
|
|
1290
|
+
byParent
|
|
1291
|
+
};
|
|
1292
|
+
}
|
|
1293
|
+
return [...this.#childIndex.byParent.get(parentId) ?? []];
|
|
1294
|
+
}
|
|
1295
|
+
/** The next position under a parent, as `createPage` and `movePage` would place a page. */
|
|
1296
|
+
#nextPosition(parentId) {
|
|
1297
|
+
const { positions, complete } = this.#state.rows;
|
|
1298
|
+
if (this.#state.stalePositions.has(parentId)) {
|
|
1299
|
+
if (!complete.has(parentId)) throw new KnowledgeImportBatchUnsupportedError("a position under a parent its last child left");
|
|
1300
|
+
return require_run_registry.knowledgePositionBetween(this.#children(parentId).at(-1)?.position);
|
|
1301
|
+
}
|
|
1302
|
+
if (!positions.has(parentId)) {
|
|
1303
|
+
this.missing.positions.add(parentId);
|
|
1304
|
+
throw new KnowledgeImportNotGatheredError(`last child position of ${parentId}`);
|
|
1305
|
+
}
|
|
1306
|
+
return require_run_registry.knowledgePositionBetween(positions.get(parentId) ?? void 0);
|
|
1307
|
+
}
|
|
1308
|
+
/** A page left `parentId`: its next position is still the gathered one unless it was the last child. */
|
|
1309
|
+
#left(parentId, position) {
|
|
1310
|
+
if (!parentId) return;
|
|
1311
|
+
const last = this.#state.rows.positions.get(parentId);
|
|
1312
|
+
if (last === void 0 || last === position) this.#state.stalePositions.add(parentId);
|
|
1313
|
+
}
|
|
1314
|
+
/** Points the path map at where `pages` are now; `before` holds their old paths. */
|
|
1315
|
+
#repath(pages, before) {
|
|
1316
|
+
const { paths } = this.#state.rows;
|
|
1317
|
+
const ids = new Set(pages.map((page) => page.id));
|
|
1318
|
+
for (const [key, id] of paths) if (id && ids.has(id)) paths.set(key, null);
|
|
1319
|
+
for (const old of before) if (old) paths.set(pathKey(old.scopeId, old.path), null);
|
|
1320
|
+
for (const page of pages) {
|
|
1321
|
+
const keys = this.#rowKeys(page);
|
|
1322
|
+
if (keys) paths.set(pathKey(keys.scopeId, keys.path), page.id);
|
|
1323
|
+
}
|
|
1324
|
+
}
|
|
1325
|
+
/** {@link #keys} on the working copy's current row. */
|
|
1326
|
+
#rowKeys(page) {
|
|
1327
|
+
return this.#keys(this.#state.rows.pages.get(page.id) ?? page);
|
|
1328
|
+
}
|
|
1329
|
+
#node(key) {
|
|
1330
|
+
const { nodes } = this.#state.rows;
|
|
1331
|
+
if (!nodes.has(key)) {
|
|
1332
|
+
this.missing.nodes.add(key);
|
|
1333
|
+
throw new KnowledgeImportNotGatheredError(`node ${key}`);
|
|
1334
|
+
}
|
|
1335
|
+
return nodes.get(key);
|
|
1336
|
+
}
|
|
1337
|
+
#setNode(key, node) {
|
|
1338
|
+
const { nodes, nodesByPage } = this.#state.rows;
|
|
1339
|
+
const before = nodes.get(key);
|
|
1340
|
+
if (before && nodesByPage.get(before.pageId) === key) nodesByPage.set(before.pageId, null);
|
|
1341
|
+
nodes.set(key, node);
|
|
1342
|
+
if (node) nodesByPage.set(node.pageId, key);
|
|
1343
|
+
this.#state.touched.add(key);
|
|
1344
|
+
}
|
|
1345
|
+
#storage(now) {
|
|
1346
|
+
const rows = () => this.#state.rows;
|
|
1347
|
+
const impl = {
|
|
1348
|
+
transaction: async (fn) => {
|
|
1349
|
+
const saved = copyState(this.#state);
|
|
1350
|
+
try {
|
|
1351
|
+
return await fn(this.storage);
|
|
1352
|
+
} catch (error) {
|
|
1353
|
+
this.#state = saved;
|
|
1354
|
+
throw error;
|
|
1355
|
+
}
|
|
1356
|
+
},
|
|
1357
|
+
getPage: async ({ id }) => this.#page(id),
|
|
1358
|
+
getPageParents: async ({ parentId }) => {
|
|
1359
|
+
const parents = [];
|
|
1360
|
+
let id = parentId;
|
|
1361
|
+
while (id && parents.length <= 10) {
|
|
1362
|
+
const page = this.#page(id);
|
|
1363
|
+
if (!page) break;
|
|
1364
|
+
parents.push(page);
|
|
1365
|
+
id = page.parentId;
|
|
1366
|
+
}
|
|
1367
|
+
return parents;
|
|
1368
|
+
},
|
|
1369
|
+
getPageByPath: async ({ scopeId, path }) => {
|
|
1370
|
+
if (path.length === 0) return null;
|
|
1371
|
+
const key = pathKey(scopeId, path);
|
|
1372
|
+
if (!rows().paths.has(key)) {
|
|
1373
|
+
this.missing.paths.set(key, {
|
|
1374
|
+
scopeId,
|
|
1375
|
+
path
|
|
1376
|
+
});
|
|
1377
|
+
throw new KnowledgeImportNotGatheredError(`path ${key}`);
|
|
1378
|
+
}
|
|
1379
|
+
const id = rows().paths.get(key);
|
|
1380
|
+
return id ? this.#page(id) : null;
|
|
1381
|
+
},
|
|
1382
|
+
lockPages: async (ids) => {
|
|
1383
|
+
const unlocked = ids.filter((id) => !rows().locked.has(id));
|
|
1384
|
+
if (unlocked.length) {
|
|
1385
|
+
for (const id of unlocked) this.missing.locks.add(id);
|
|
1386
|
+
throw new KnowledgeImportNotGatheredError(`locks ${unlocked.join(", ")}`);
|
|
1387
|
+
}
|
|
1388
|
+
},
|
|
1389
|
+
listNotes: async ({ pageId }) => {
|
|
1390
|
+
if (!rows().notes.has(pageId)) {
|
|
1391
|
+
this.missing.notes.add(pageId);
|
|
1392
|
+
throw new KnowledgeImportNotGatheredError(`notes of ${pageId}`);
|
|
1393
|
+
}
|
|
1394
|
+
return { notes: rows().notes.get(pageId).filter((note) => !note.deletedAt) };
|
|
1395
|
+
},
|
|
1396
|
+
createPage: async (input) => {
|
|
1397
|
+
if (input.id !== void 0 || input.position !== void 0) throw new KnowledgeImportBatchUnsupportedError("createPage with id or position");
|
|
1398
|
+
if (!input.name.trim()) throw new Error("Knowledge page name must not be empty");
|
|
1399
|
+
require_run_registry.assertKnowledgePageDescriptionWithinBound(input.description || void 0);
|
|
1400
|
+
const parent = this.#livePage(input.parentId);
|
|
1401
|
+
const scopeId = parent.isScope ? parent.id : parent.scopeId;
|
|
1402
|
+
const id = (0, crypto.randomUUID)();
|
|
1403
|
+
const depth = this.#depth(parent) + 1;
|
|
1404
|
+
if (depth > 10) throw new require_run_registry.KnowledgePageDepthError(id);
|
|
1405
|
+
let path = null;
|
|
1406
|
+
if (input.key !== void 0) {
|
|
1407
|
+
const problem = require_run_registry.knowledgePageKeyProblem(input.key);
|
|
1408
|
+
if (problem) throw new Error(problem);
|
|
1409
|
+
const parentKeys = parent.isScope ? {
|
|
1410
|
+
scopeId: parent.id,
|
|
1411
|
+
path: []
|
|
1412
|
+
} : this.#keys(parent);
|
|
1413
|
+
if (!parentKeys) throw new KnowledgeImportBatchUnsupportedError("createPage under a broken chain");
|
|
1414
|
+
path = [...parentKeys.path, input.key];
|
|
1415
|
+
if (await impl.getPageByPath({
|
|
1416
|
+
scopeId,
|
|
1417
|
+
path,
|
|
1418
|
+
read: "all"
|
|
1419
|
+
})) throw new require_run_registry.KnowledgePageKeyConflictError(input.key, parent.id);
|
|
1420
|
+
}
|
|
1421
|
+
if (input.key !== void 0 && this.#state.freed.has(childKey(parent.id, input.key))) throw new KnowledgeImportBatchUnsupportedError("createPage at a key a move left");
|
|
1422
|
+
const position = this.#nextPosition(parent.id);
|
|
1423
|
+
const at = now();
|
|
1424
|
+
const page = {
|
|
1425
|
+
id,
|
|
1426
|
+
scopeId,
|
|
1427
|
+
parentId: parent.id,
|
|
1428
|
+
isScope: false,
|
|
1429
|
+
...input.key !== void 0 ? { key: input.key } : {},
|
|
1430
|
+
position,
|
|
1431
|
+
name: input.name,
|
|
1432
|
+
...input.description ? { description: input.description } : {},
|
|
1433
|
+
...input.body !== void 0 ? { body: input.body } : {},
|
|
1434
|
+
version: 1,
|
|
1435
|
+
createdBy: structuredClone(input.provenance),
|
|
1436
|
+
updatedBy: structuredClone(input.provenance),
|
|
1437
|
+
createdAt: at,
|
|
1438
|
+
updatedAt: at
|
|
1439
|
+
};
|
|
1440
|
+
const state = rows();
|
|
1441
|
+
this.#setPage(id, page);
|
|
1442
|
+
state.positions.set(parent.id, position);
|
|
1443
|
+
state.positions.set(id, null);
|
|
1444
|
+
state.notes.set(id, []);
|
|
1445
|
+
state.nodesByPage.set(id, null);
|
|
1446
|
+
state.locked.add(id);
|
|
1447
|
+
state.complete.add(id);
|
|
1448
|
+
if (path) state.paths.set(pathKey(scopeId, path), id);
|
|
1449
|
+
this.#state.writes.push({
|
|
1450
|
+
op: "create",
|
|
1451
|
+
id,
|
|
1452
|
+
scopeId,
|
|
1453
|
+
parentId: parent.id,
|
|
1454
|
+
...input.key !== void 0 ? { key: input.key } : {},
|
|
1455
|
+
name: input.name,
|
|
1456
|
+
...input.description !== void 0 ? { description: input.description } : {},
|
|
1457
|
+
...input.body !== void 0 ? { body: input.body } : {},
|
|
1458
|
+
position,
|
|
1459
|
+
depth,
|
|
1460
|
+
provenance: input.provenance
|
|
1461
|
+
});
|
|
1462
|
+
return structuredClone(page);
|
|
1463
|
+
},
|
|
1464
|
+
updatePage: async (input) => {
|
|
1465
|
+
const page = this.#livePage(input.id);
|
|
1466
|
+
if (page.version !== input.expectedVersion) throw new require_run_registry.KnowledgeConflictError(page.id);
|
|
1467
|
+
if (input.name !== void 0 && !input.name.trim()) throw new Error("Knowledge page name must not be empty");
|
|
1468
|
+
require_run_registry.assertKnowledgePageDescriptionWithinBound(input.description || void 0);
|
|
1469
|
+
const next = {
|
|
1470
|
+
...page,
|
|
1471
|
+
version: page.version + 1,
|
|
1472
|
+
updatedBy: structuredClone(input.provenance)
|
|
1473
|
+
};
|
|
1474
|
+
next.updatedAt = now();
|
|
1475
|
+
if (input.name !== void 0) next.name = input.name;
|
|
1476
|
+
if (input.description !== void 0) {
|
|
1477
|
+
if (input.description) next.description = input.description;
|
|
1478
|
+
else delete next.description;
|
|
1479
|
+
}
|
|
1480
|
+
if (input.body !== void 0) next.body = input.body;
|
|
1481
|
+
this.#setPage(page.id, next);
|
|
1482
|
+
this.#state.writes.push({
|
|
1483
|
+
op: "update",
|
|
1484
|
+
id: page.id,
|
|
1485
|
+
scopeId: page.scopeId,
|
|
1486
|
+
expectedVersion: input.expectedVersion,
|
|
1487
|
+
...input.name !== void 0 ? { name: input.name } : {},
|
|
1488
|
+
...input.description !== void 0 ? { description: input.description } : {},
|
|
1489
|
+
...input.body !== void 0 ? { body: input.body } : {},
|
|
1490
|
+
provenance: input.provenance
|
|
1491
|
+
});
|
|
1492
|
+
return structuredClone(next);
|
|
1493
|
+
},
|
|
1494
|
+
listChildPages: async ({ parentId, read, cursor, limit }) => {
|
|
1495
|
+
if (read !== "all") throw new KnowledgeImportBatchUnsupportedError("listChildPages with a read scope");
|
|
1496
|
+
const children = this.#children(parentId);
|
|
1497
|
+
const start = cursor ? Number(cursor) : 0;
|
|
1498
|
+
const end = limit === void 0 ? children.length : start + limit;
|
|
1499
|
+
return {
|
|
1500
|
+
pages: children.slice(start, end).map((page) => structuredClone(page)),
|
|
1501
|
+
...end < children.length ? { nextCursor: String(end) } : {}
|
|
1502
|
+
};
|
|
1503
|
+
},
|
|
1504
|
+
countChildPages: async ({ parentIds, read }) => {
|
|
1505
|
+
if (read !== "all") throw new KnowledgeImportBatchUnsupportedError("countChildPages with a read scope");
|
|
1506
|
+
return Object.fromEntries(parentIds.map((id) => [id, this.#children(id).length]));
|
|
1507
|
+
},
|
|
1508
|
+
lockSubtree: async (rootId) => {
|
|
1509
|
+
if (rows().tooLarge.has(rootId)) throw new require_run_registry.KnowledgeMoveTooLargeError(rootId, 501);
|
|
1510
|
+
const ids = [];
|
|
1511
|
+
const parents = [rootId];
|
|
1512
|
+
while (parents.length) {
|
|
1513
|
+
for (const child of this.#children(parents.shift())) {
|
|
1514
|
+
ids.push(child.id);
|
|
1515
|
+
parents.push(child.id);
|
|
1516
|
+
}
|
|
1517
|
+
if (ids.length >= 500) throw new require_run_registry.KnowledgeMoveTooLargeError(rootId, ids.length + 1);
|
|
1518
|
+
}
|
|
1519
|
+
const unlocked = ids.filter((id) => !rows().locked.has(id));
|
|
1520
|
+
if (unlocked.length) {
|
|
1521
|
+
for (const id of unlocked) this.missing.locks.add(id);
|
|
1522
|
+
throw new KnowledgeImportNotGatheredError(`locks ${unlocked.join(", ")}`);
|
|
1523
|
+
}
|
|
1524
|
+
return ids;
|
|
1525
|
+
},
|
|
1526
|
+
movePage: async (input) => {
|
|
1527
|
+
if (input.position !== void 0) throw new KnowledgeImportBatchUnsupportedError("movePage with a position");
|
|
1528
|
+
const page = this.#livePage(input.id);
|
|
1529
|
+
if (page.isScope) throw new Error(`Knowledge scope page ${page.id} can't be moved`);
|
|
1530
|
+
if (page.version !== input.expectedVersion) throw new require_run_registry.KnowledgeConflictError(page.id);
|
|
1531
|
+
const parent = this.#livePage(input.parentId);
|
|
1532
|
+
const subtree = [];
|
|
1533
|
+
const visit = (at, depth) => {
|
|
1534
|
+
subtree.push({
|
|
1535
|
+
page: at,
|
|
1536
|
+
depth
|
|
1537
|
+
});
|
|
1538
|
+
for (const child of this.#children(at.id)) visit(child, depth + 1);
|
|
1539
|
+
};
|
|
1540
|
+
visit(page, 0);
|
|
1541
|
+
if (subtree.some((entry) => entry.page.id === parent.id)) throw new Error(`Knowledge page ${page.id} can't move under itself or its own subtree`);
|
|
1542
|
+
if (subtree.length > 500) throw new require_run_registry.KnowledgeMoveTooLargeError(page.id, subtree.length);
|
|
1543
|
+
const parentDepth = parent.isScope ? 0 : this.#depth(parent);
|
|
1544
|
+
if (parentDepth + 1 + Math.max(...subtree.map((entry) => entry.depth)) > 10) throw new require_run_registry.KnowledgePageDepthError(page.id);
|
|
1545
|
+
const scopeId = parent.isScope ? parent.id : parent.scopeId;
|
|
1546
|
+
if (scopeId !== page.scopeId) throw new KnowledgeImportBatchUnsupportedError("movePage across scopes");
|
|
1547
|
+
if (page.key !== void 0) {
|
|
1548
|
+
const parentKeys = parent.isScope ? {
|
|
1549
|
+
scopeId: parent.id,
|
|
1550
|
+
path: []
|
|
1551
|
+
} : this.#keys(parent);
|
|
1552
|
+
if (!parentKeys) throw new KnowledgeImportBatchUnsupportedError("movePage under a broken chain");
|
|
1553
|
+
const clash = await impl.getPageByPath({
|
|
1554
|
+
scopeId,
|
|
1555
|
+
path: [...parentKeys.path, page.key],
|
|
1556
|
+
read: "all"
|
|
1557
|
+
});
|
|
1558
|
+
if (clash && clash.id !== page.id) throw new require_run_registry.KnowledgePageKeyConflictError(page.key, parent.id);
|
|
1559
|
+
}
|
|
1560
|
+
if (this.#state.moved.has(page.id)) throw new KnowledgeImportBatchUnsupportedError("a second move of a page");
|
|
1561
|
+
const position = this.#nextPosition(parent.id);
|
|
1562
|
+
const before = subtree.map((entry) => this.#keys(entry.page));
|
|
1563
|
+
const at = now();
|
|
1564
|
+
const moved = {
|
|
1565
|
+
...page,
|
|
1566
|
+
parentId: parent.id,
|
|
1567
|
+
position,
|
|
1568
|
+
version: page.version + 1,
|
|
1569
|
+
updatedBy: structuredClone(input.provenance),
|
|
1570
|
+
updatedAt: at
|
|
1571
|
+
};
|
|
1572
|
+
const state = rows();
|
|
1573
|
+
this.#setPage(page.id, moved);
|
|
1574
|
+
state.positions.set(parent.id, position);
|
|
1575
|
+
this.#left(page.parentId, page.position);
|
|
1576
|
+
if (page.parentId && page.key !== void 0) this.#state.freed.add(childKey(page.parentId, page.key));
|
|
1577
|
+
this.#state.moved.add(page.id);
|
|
1578
|
+
this.#repath(subtree.map((entry) => state.pages.get(entry.page.id)), before);
|
|
1579
|
+
this.#state.writes.push({
|
|
1580
|
+
op: "move",
|
|
1581
|
+
id: page.id,
|
|
1582
|
+
fromScopeId: page.scopeId,
|
|
1583
|
+
expectedVersion: input.expectedVersion,
|
|
1584
|
+
parentId: parent.id,
|
|
1585
|
+
scopeId,
|
|
1586
|
+
depth: parentDepth + 1,
|
|
1587
|
+
position,
|
|
1588
|
+
provenance: input.provenance
|
|
1589
|
+
});
|
|
1590
|
+
return structuredClone(moved);
|
|
1591
|
+
},
|
|
1592
|
+
deletePage: async (input) => {
|
|
1593
|
+
const page = this.#livePage(input.id);
|
|
1594
|
+
if (page.isScope) throw new Error(`Knowledge scope page ${page.id} can't be deleted`);
|
|
1595
|
+
if (page.version !== input.expectedVersion) throw new require_run_registry.KnowledgeConflictError(page.id);
|
|
1596
|
+
if (this.#children(page.id).length) throw new require_run_registry.KnowledgePageHasChildrenError(page.id);
|
|
1597
|
+
const at = now();
|
|
1598
|
+
const deleted = {
|
|
1599
|
+
...page,
|
|
1600
|
+
deletedAt: at,
|
|
1601
|
+
deletedBy: input.deletedBy,
|
|
1602
|
+
version: page.version + 1,
|
|
1603
|
+
updatedAt: at
|
|
1604
|
+
};
|
|
1605
|
+
this.#setPage(page.id, deleted);
|
|
1606
|
+
this.#left(page.parentId, page.position);
|
|
1607
|
+
for (const [key, id] of rows().paths) if (id === page.id) rows().paths.set(key, null);
|
|
1608
|
+
this.#state.writes.push({
|
|
1609
|
+
op: "delete",
|
|
1610
|
+
id: page.id,
|
|
1611
|
+
scopeId: page.scopeId,
|
|
1612
|
+
expectedVersion: input.expectedVersion,
|
|
1613
|
+
deletedBy: input.deletedBy
|
|
1614
|
+
});
|
|
1615
|
+
return structuredClone(deleted);
|
|
1616
|
+
},
|
|
1617
|
+
addNote: async (input) => {
|
|
1618
|
+
const page = this.#livePage(input.pageId);
|
|
1619
|
+
require_run_registry.assertKnowledgeNoteTextWithinBound(input.text);
|
|
1620
|
+
if (input.mentions.length) throw new KnowledgeImportBatchUnsupportedError("addNote with mentions");
|
|
1621
|
+
const notes = this.#notesOf(page.id);
|
|
1622
|
+
const id = input.id ?? (0, crypto.randomUUID)();
|
|
1623
|
+
if (notes.some((note) => note.id === id)) throw new require_run_registry.KnowledgeConflictError(id);
|
|
1624
|
+
const at = now();
|
|
1625
|
+
const note = {
|
|
1626
|
+
id,
|
|
1627
|
+
pageId: page.id,
|
|
1628
|
+
text: input.text,
|
|
1629
|
+
...input.when ? { when: new Date(input.when) } : {},
|
|
1630
|
+
stampScopeIds: [...new Set(input.stampScopeIds)],
|
|
1631
|
+
mentions: [],
|
|
1632
|
+
provenance: structuredClone(input.provenance),
|
|
1633
|
+
version: 1,
|
|
1634
|
+
createdAt: at,
|
|
1635
|
+
updatedAt: at
|
|
1636
|
+
};
|
|
1637
|
+
rows().notes.set(page.id, [...notes, note]);
|
|
1638
|
+
this.#state.writes.push({
|
|
1639
|
+
op: "add-note",
|
|
1640
|
+
id,
|
|
1641
|
+
pageId: page.id,
|
|
1642
|
+
scopeId: page.scopeId,
|
|
1643
|
+
text: input.text,
|
|
1644
|
+
...input.when ? { when: input.when } : {},
|
|
1645
|
+
stampScopeIds: input.stampScopeIds,
|
|
1646
|
+
mentions: [],
|
|
1647
|
+
provenance: input.provenance
|
|
1648
|
+
});
|
|
1649
|
+
return structuredClone(note);
|
|
1650
|
+
},
|
|
1651
|
+
removeNote: async (input) => {
|
|
1652
|
+
for (const [pageId, notes] of rows().notes) {
|
|
1653
|
+
const note = notes.find((each) => each.id === input.id);
|
|
1654
|
+
if (!note) continue;
|
|
1655
|
+
if (note.deletedAt) throw new require_run_registry.KnowledgeNotFoundError("note", input.id);
|
|
1656
|
+
if (this.#state.writes.some((write) => write.op === "add-note" && write.id === input.id)) throw new KnowledgeImportBatchUnsupportedError("removeNote of a note this flush added");
|
|
1657
|
+
const page = this.#livePage(pageId);
|
|
1658
|
+
const at = now();
|
|
1659
|
+
const removed = {
|
|
1660
|
+
...note,
|
|
1661
|
+
deletedAt: at,
|
|
1662
|
+
deletedBy: input.deletedBy,
|
|
1663
|
+
version: note.version + 1,
|
|
1664
|
+
updatedAt: at
|
|
1665
|
+
};
|
|
1666
|
+
rows().notes.set(pageId, notes.map((each) => each.id === input.id ? removed : each));
|
|
1667
|
+
this.#state.writes.push({
|
|
1668
|
+
op: "remove-note",
|
|
1669
|
+
id: input.id,
|
|
1670
|
+
pageId,
|
|
1671
|
+
scopeId: page.scopeId,
|
|
1672
|
+
deletedBy: input.deletedBy,
|
|
1673
|
+
provenance: input.provenance
|
|
1674
|
+
});
|
|
1675
|
+
return structuredClone(removed);
|
|
1676
|
+
}
|
|
1677
|
+
throw new KnowledgeImportBatchUnsupportedError("removeNote of a note not gathered");
|
|
1678
|
+
}
|
|
1679
|
+
};
|
|
1680
|
+
return only(impl, "storage");
|
|
1681
|
+
}
|
|
1682
|
+
#notesOf(pageId) {
|
|
1683
|
+
const { notes } = this.#state.rows;
|
|
1684
|
+
if (!notes.has(pageId)) {
|
|
1685
|
+
this.missing.notes.add(pageId);
|
|
1686
|
+
throw new KnowledgeImportNotGatheredError(`notes of ${pageId}`);
|
|
1687
|
+
}
|
|
1688
|
+
return notes.get(pageId);
|
|
1689
|
+
}
|
|
1690
|
+
#importers() {
|
|
1691
|
+
const rows = () => this.#state.rows;
|
|
1692
|
+
return only({
|
|
1693
|
+
getNode: async (bindingId, sourceId) => structuredClone(this.#node(nodeKey(bindingId, sourceId))),
|
|
1694
|
+
getNodes: async (bindingId, sourceIds) => {
|
|
1695
|
+
const nodes = [];
|
|
1696
|
+
const unread = [...new Set(sourceIds)].filter((sourceId) => !rows().nodes.has(nodeKey(bindingId, sourceId)));
|
|
1697
|
+
if (unread.length) {
|
|
1698
|
+
for (const sourceId of unread) this.missing.nodes.add(nodeKey(bindingId, sourceId));
|
|
1699
|
+
throw new KnowledgeImportNotGatheredError(`nodes ${unread.join(", ")}`);
|
|
1700
|
+
}
|
|
1701
|
+
for (const sourceId of new Set(sourceIds)) {
|
|
1702
|
+
const node = rows().nodes.get(nodeKey(bindingId, sourceId));
|
|
1703
|
+
if (node) nodes.push(structuredClone(node));
|
|
1704
|
+
}
|
|
1705
|
+
return nodes;
|
|
1706
|
+
},
|
|
1707
|
+
getNodeByPage: async (pageId) => {
|
|
1708
|
+
if (!rows().nodesByPage.has(pageId)) {
|
|
1709
|
+
this.missing.nodesByPage.add(pageId);
|
|
1710
|
+
throw new KnowledgeImportNotGatheredError(`node of page ${pageId}`);
|
|
1711
|
+
}
|
|
1712
|
+
const key = rows().nodesByPage.get(pageId);
|
|
1713
|
+
return key ? structuredClone(this.#node(key)) : null;
|
|
1714
|
+
},
|
|
1715
|
+
saveNode: async (node) => {
|
|
1716
|
+
const key = nodeKey(node.bindingId, node.sourceId);
|
|
1717
|
+
const mapped = rows().nodesByPage.get(node.pageId);
|
|
1718
|
+
if (mapped === void 0) {
|
|
1719
|
+
this.missing.nodesByPage.add(node.pageId);
|
|
1720
|
+
throw new KnowledgeImportNotGatheredError(`node of page ${node.pageId}`);
|
|
1721
|
+
}
|
|
1722
|
+
if (mapped && mapped !== key) throw new KnowledgeImportBatchUnsupportedError("saveNode onto a mapped page");
|
|
1723
|
+
this.#setNode(key, {
|
|
1724
|
+
...structuredClone(node),
|
|
1725
|
+
updatedAt: /* @__PURE__ */ new Date()
|
|
1726
|
+
});
|
|
1727
|
+
},
|
|
1728
|
+
deleteNode: async (bindingId, sourceId) => {
|
|
1729
|
+
const key = nodeKey(bindingId, sourceId);
|
|
1730
|
+
this.#node(key);
|
|
1731
|
+
this.#setNode(key, null);
|
|
1732
|
+
},
|
|
1733
|
+
markLinkingNodesUnsettled: async (bindingId, targetSourceIds) => {
|
|
1734
|
+
const targets = new Set(targetSourceIds);
|
|
1735
|
+
for (const [key, node] of rows().nodes) if (node && node.bindingId === bindingId && node.links.some((link) => targets.has(link.sourceId))) rows().nodes.set(key, {
|
|
1736
|
+
...node,
|
|
1737
|
+
unsettled: true
|
|
1738
|
+
});
|
|
1739
|
+
const marks = this.#state.marks;
|
|
1740
|
+
const last = marks.at(-1);
|
|
1741
|
+
const prior = last && markTargets.get(last);
|
|
1742
|
+
const all = prior?.bindingId === bindingId ? [.../* @__PURE__ */ new Set([...prior.targets, ...targetSourceIds])] : [...targetSourceIds];
|
|
1743
|
+
if (prior?.bindingId === bindingId) marks.pop();
|
|
1744
|
+
const mark = (_, importers) => importers.markLinkingNodesUnsettled(bindingId, all);
|
|
1745
|
+
markTargets.set(mark, {
|
|
1746
|
+
bindingId,
|
|
1747
|
+
targets: all
|
|
1748
|
+
});
|
|
1749
|
+
marks.push(mark);
|
|
1750
|
+
},
|
|
1751
|
+
setState: async (bindingId, state) => {
|
|
1752
|
+
this.#state.marks.push((_, importers) => importers.setState(bindingId, state));
|
|
1753
|
+
},
|
|
1754
|
+
listLinkingNodes: async (bindingId, targetSourceIds, options = {}) => {
|
|
1755
|
+
const keys = [...new Set(targetSourceIds)].map((sourceId) => nodeKey(bindingId, sourceId));
|
|
1756
|
+
if (keys.some((key) => rows().tooManyLinkers.has(key))) throw new KnowledgeImportBatchUnsupportedError("listLinkingNodes past the gathered linking nodes");
|
|
1757
|
+
const unread = keys.filter((key) => !rows().linkTargets.has(key));
|
|
1758
|
+
if (unread.length) {
|
|
1759
|
+
for (const key of unread) this.missing.linkTargets.add(key);
|
|
1760
|
+
throw new KnowledgeImportNotGatheredError(`linking nodes of ${unread.join(", ")}`);
|
|
1761
|
+
}
|
|
1762
|
+
const targets = new Set(targetSourceIds);
|
|
1763
|
+
const ids = [...rows().nodes.values()].filter((node) => !!node && node.bindingId === bindingId && node.links.some((link) => targets.has(link.sourceId))).map((node) => node.sourceId).filter((id) => options.after === void 0 || byteOrder(id, options.after) > 0).sort(byteOrder);
|
|
1764
|
+
const limit = options.limit ?? 500;
|
|
1765
|
+
const items = ids.slice(0, limit);
|
|
1766
|
+
return {
|
|
1767
|
+
items,
|
|
1768
|
+
next: ids.length > limit ? items[items.length - 1] : null
|
|
1769
|
+
};
|
|
1770
|
+
},
|
|
1771
|
+
listBindings: async () => {
|
|
1772
|
+
const { bindings } = rows();
|
|
1773
|
+
if (!bindings) {
|
|
1774
|
+
this.missing.bindings.add("bindings");
|
|
1775
|
+
throw new KnowledgeImportNotGatheredError("bindings");
|
|
1776
|
+
}
|
|
1777
|
+
return structuredClone(bindings);
|
|
1778
|
+
}
|
|
1779
|
+
}, "importers");
|
|
1780
|
+
}
|
|
1781
|
+
};
|
|
1782
|
+
/** True when the stores implement every set-based method the batched flush needs. */
|
|
1783
|
+
function canBatchImportFlush(storage, importers) {
|
|
1784
|
+
return !!(storage.getPageChains && storage.getPagesByPaths && storage.getLastChildPositions && storage.listNotesByPages && storage.getPageSubtrees && storage.applyPageWrites && require_run_registry.canRepairKnowledgeLinksInBatch(storage) && importers.getNodes && importers.getNodesByPages && importers.writeNodes);
|
|
1785
|
+
}
|
|
1786
|
+
async function readImportRows(input) {
|
|
1787
|
+
const { storage, importers, bindingId, missing } = input;
|
|
1788
|
+
const rows = emptyImportOverlayRows();
|
|
1789
|
+
const sourceIds = new Set(input.sourceIds);
|
|
1790
|
+
for (const key of missing?.nodes ?? []) {
|
|
1791
|
+
const [binding, sourceId] = key.split("\0");
|
|
1792
|
+
if (binding === bindingId) sourceIds.add(sourceId);
|
|
1793
|
+
}
|
|
1794
|
+
const nodes = sourceIds.size ? await importers.getNodes(bindingId, [...sourceIds]) : [];
|
|
1795
|
+
for (const sourceId of sourceIds) rows.nodes.set(nodeKey(bindingId, sourceId), null);
|
|
1796
|
+
for (const node of nodes) {
|
|
1797
|
+
rows.nodes.set(nodeKey(node.bindingId, node.sourceId), node);
|
|
1798
|
+
rows.nodesByPage.set(node.pageId, nodeKey(node.bindingId, node.sourceId));
|
|
1799
|
+
}
|
|
1800
|
+
const addChains = async (ids) => {
|
|
1801
|
+
const wanted = [...ids].filter((id) => !rows.pages.has(id));
|
|
1802
|
+
if (!wanted.length) return;
|
|
1803
|
+
const chains = await storage.getPageChains({
|
|
1804
|
+
ids: wanted,
|
|
1805
|
+
read: "all"
|
|
1806
|
+
});
|
|
1807
|
+
for (const id of wanted) {
|
|
1808
|
+
const chain = chains[id] ?? [];
|
|
1809
|
+
if (!chain.length) rows.pages.set(id, null);
|
|
1810
|
+
for (const page of chain) rows.pages.set(page.id, page);
|
|
1811
|
+
const last = chain.at(-1);
|
|
1812
|
+
if (last?.parentId && chain.length <= 10 && !rows.pages.has(last.parentId)) rows.pages.set(last.parentId, null);
|
|
1813
|
+
}
|
|
1814
|
+
};
|
|
1815
|
+
await addChains(/* @__PURE__ */ new Set([
|
|
1816
|
+
...input.pageIds,
|
|
1817
|
+
...nodes.map((node) => node.pageId),
|
|
1818
|
+
...missing?.pages ?? [],
|
|
1819
|
+
...missing?.locks ?? []
|
|
1820
|
+
]));
|
|
1821
|
+
const plan = input.plan(rows);
|
|
1822
|
+
const roots = [.../* @__PURE__ */ new Set([...plan.subtrees, ...missing?.subtrees ?? []])].filter((id) => !rows.complete.has(id));
|
|
1823
|
+
const carried = [];
|
|
1824
|
+
if (roots.length) {
|
|
1825
|
+
const subtrees = await storage.getPageSubtrees({
|
|
1826
|
+
rootIds: roots,
|
|
1827
|
+
limit: 499
|
|
1828
|
+
});
|
|
1829
|
+
for (const root of roots) {
|
|
1830
|
+
const pages = subtrees[root];
|
|
1831
|
+
if (!pages) {
|
|
1832
|
+
rows.tooLarge.add(root);
|
|
1833
|
+
continue;
|
|
1834
|
+
}
|
|
1835
|
+
rows.complete.add(root);
|
|
1836
|
+
for (const page of pages) {
|
|
1837
|
+
rows.pages.set(page.id, page);
|
|
1838
|
+
rows.complete.add(page.id);
|
|
1839
|
+
carried.push(page.id);
|
|
1840
|
+
}
|
|
1841
|
+
}
|
|
1842
|
+
const unmapped = carried.filter((id) => !rows.nodesByPage.has(id));
|
|
1843
|
+
if (unmapped.length) {
|
|
1844
|
+
for (const id of unmapped) rows.nodesByPage.set(id, null);
|
|
1845
|
+
for (const node of await importers.getNodesByPages(unmapped)) {
|
|
1846
|
+
const key = nodeKey(node.bindingId, node.sourceId);
|
|
1847
|
+
rows.nodes.set(key, node);
|
|
1848
|
+
rows.nodesByPage.set(node.pageId, key);
|
|
1849
|
+
}
|
|
1850
|
+
}
|
|
1851
|
+
}
|
|
1852
|
+
const targets = new Set(plan.linkTargets);
|
|
1853
|
+
for (const id of carried) {
|
|
1854
|
+
const key = rows.nodesByPage.get(id);
|
|
1855
|
+
const node = key ? rows.nodes.get(key) : null;
|
|
1856
|
+
if (node?.bindingId === bindingId) targets.add(node.sourceId);
|
|
1857
|
+
}
|
|
1858
|
+
for (const key of missing?.linkTargets ?? []) {
|
|
1859
|
+
const [binding, sourceId] = key.split("\0");
|
|
1860
|
+
if (binding === bindingId) targets.add(sourceId);
|
|
1861
|
+
}
|
|
1862
|
+
const wanted = [...targets].filter((sourceId) => !rows.linkTargets.has(nodeKey(bindingId, sourceId)));
|
|
1863
|
+
if (wanted.length) {
|
|
1864
|
+
const linking = await importers.listLinkingNodes(bindingId, wanted, { limit: LINKING_NODES_READ });
|
|
1865
|
+
for (const sourceId of wanted) (linking.next ? rows.tooManyLinkers : rows.linkTargets).add(nodeKey(bindingId, sourceId));
|
|
1866
|
+
const readNodes = async (sourceIds) => {
|
|
1867
|
+
const unread = [...new Set(sourceIds)].filter((sourceId) => !rows.nodes.has(nodeKey(bindingId, sourceId)));
|
|
1868
|
+
if (!unread.length) return [];
|
|
1869
|
+
for (const sourceId of unread) rows.nodes.set(nodeKey(bindingId, sourceId), null);
|
|
1870
|
+
const read = await importers.getNodes(bindingId, unread);
|
|
1871
|
+
for (const node of read) {
|
|
1872
|
+
rows.nodes.set(nodeKey(node.bindingId, node.sourceId), node);
|
|
1873
|
+
rows.nodesByPage.set(node.pageId, nodeKey(node.bindingId, node.sourceId));
|
|
1874
|
+
}
|
|
1875
|
+
return read;
|
|
1876
|
+
};
|
|
1877
|
+
const linkers = await readNodes(linking.items);
|
|
1878
|
+
const reached = await readNodes(linking.items.map((sourceId) => rows.nodes.get(nodeKey(bindingId, sourceId))).filter((n) => !!n).flatMap((node) => [...node.links.map((link) => link.sourceId), ...node.parentSourceId ? [node.parentSourceId] : []]));
|
|
1879
|
+
await addChains(new Set([...linkers, ...reached].map((node) => node.pageId)));
|
|
1880
|
+
}
|
|
1881
|
+
if (plan.bindings || missing?.bindings.size) rows.bindings ??= await importers.listBindings();
|
|
1882
|
+
const paths = new Map(plan.paths.map((each) => [pathKey(each.scopeId, each.path), each]));
|
|
1883
|
+
for (const [key, each] of missing?.paths ?? []) paths.set(key, each);
|
|
1884
|
+
const byScope = /* @__PURE__ */ new Map();
|
|
1885
|
+
for (const [key, { scopeId, path }] of paths) {
|
|
1886
|
+
if (path.length === 0) continue;
|
|
1887
|
+
byScope.set(scopeId, [...byScope.get(scopeId) ?? [], {
|
|
1888
|
+
key,
|
|
1889
|
+
path
|
|
1890
|
+
}]);
|
|
1891
|
+
}
|
|
1892
|
+
for (const [scopeId, entries] of byScope) {
|
|
1893
|
+
const found = await storage.getPagesByPaths({
|
|
1894
|
+
scopeId,
|
|
1895
|
+
paths: entries.map((each) => each.path),
|
|
1896
|
+
read: "all"
|
|
1897
|
+
});
|
|
1898
|
+
entries.forEach((each, i) => {
|
|
1899
|
+
const page = found[i] ?? null;
|
|
1900
|
+
rows.paths.set(each.key, page?.id ?? null);
|
|
1901
|
+
if (page && !rows.pages.has(page.id)) rows.pages.set(page.id, page);
|
|
1902
|
+
});
|
|
1903
|
+
}
|
|
1904
|
+
const held = [...rows.paths.values()].filter((id) => !!id);
|
|
1905
|
+
await addChains(new Set(held.map((id) => rows.pages.get(id)?.parentId).filter((id) => !!id)));
|
|
1906
|
+
const byPage = [...new Set([...held, ...missing?.nodesByPage ?? []].filter((id) => !rows.nodesByPage.has(id)))];
|
|
1907
|
+
if (byPage.length) {
|
|
1908
|
+
for (const id of byPage) rows.nodesByPage.set(id, null);
|
|
1909
|
+
for (const node of await importers.getNodesByPages(byPage)) {
|
|
1910
|
+
const key = nodeKey(node.bindingId, node.sourceId);
|
|
1911
|
+
rows.nodes.set(key, node);
|
|
1912
|
+
rows.nodesByPage.set(node.pageId, key);
|
|
1913
|
+
}
|
|
1914
|
+
}
|
|
1915
|
+
const notes = [.../* @__PURE__ */ new Set([
|
|
1916
|
+
...plan.notes,
|
|
1917
|
+
...held,
|
|
1918
|
+
...missing?.notes ?? []
|
|
1919
|
+
])];
|
|
1920
|
+
if (notes.length) {
|
|
1921
|
+
const listed = await storage.listNotesByPages({
|
|
1922
|
+
pageIds: notes,
|
|
1923
|
+
read: "all"
|
|
1924
|
+
});
|
|
1925
|
+
for (const id of notes) rows.notes.set(id, listed[id] ?? []);
|
|
1926
|
+
}
|
|
1927
|
+
const positions = [.../* @__PURE__ */ new Set([...plan.positions, ...missing?.positions ?? []])];
|
|
1928
|
+
if (positions.length) {
|
|
1929
|
+
const last = await storage.getLastChildPositions({ parentIds: positions });
|
|
1930
|
+
for (const id of positions) rows.positions.set(id, last[id] ?? null);
|
|
1931
|
+
}
|
|
1932
|
+
return rows;
|
|
1933
|
+
}
|
|
1934
|
+
/** Most linking nodes one gather reads; past it, a flush that lists them is saved op by op. */
|
|
1935
|
+
const LINKING_NODES_READ = 500;
|
|
1936
|
+
/** Live, non-scope pages among the rows: the ones a decide pass may lock. */
|
|
1937
|
+
const lockable = (rows) => [...rows.pages.values()].filter((page) => !!page && !page.isScope && !page.deletedAt && !page.mergedInto).map((page) => page.id);
|
|
1938
|
+
/**
|
|
1939
|
+
* Reads every row a decide pass needs in a few set-based queries, locks the live pages among them
|
|
1940
|
+
* in one sorted call, and reads again under the lock: what the second read returns can't change
|
|
1941
|
+
* until commit (a new page at an empty path is refused by the unique key when written). Pages the
|
|
1942
|
+
* second read finds that the first didn't are locked too, and read again, up to `rounds` times.
|
|
1943
|
+
*/
|
|
1944
|
+
async function gatherImportRows(input) {
|
|
1945
|
+
const locked = new Set(input.locked ?? []);
|
|
1946
|
+
let rows = await readImportRows(input);
|
|
1947
|
+
for (let round = 0; round < (input.rounds ?? 3); round++) {
|
|
1948
|
+
const unlocked = lockable(rows).filter((id) => !locked.has(id));
|
|
1949
|
+
if (!unlocked.length) {
|
|
1950
|
+
rows.locked = locked;
|
|
1951
|
+
return rows;
|
|
1952
|
+
}
|
|
1953
|
+
await input.storage.lockPages(unlocked.sort());
|
|
1954
|
+
for (const id of unlocked) locked.add(id);
|
|
1955
|
+
rows = await readImportRows(input);
|
|
1956
|
+
}
|
|
1957
|
+
return null;
|
|
1958
|
+
}
|
|
960
1959
|
// src/knowledge/importers/sink.ts
|
|
961
1960
|
/**
|
|
962
1961
|
* Applies one flush's ops to pages and the node map, on a transaction view. Pages are found by id
|
|
@@ -1013,6 +2012,17 @@ const ownText = (body, section) => {
|
|
|
1013
2012
|
if (body === section) return "";
|
|
1014
2013
|
return body.endsWith(`\n\n${section}`) ? body.slice(0, body.length - section.length - 2) : null;
|
|
1015
2014
|
};
|
|
2015
|
+
/** Decide passes a batched flush makes before it falls back: each reads what the last one lacked. */
|
|
2016
|
+
const BATCH_DECIDE_PASSES = 4;
|
|
2017
|
+
/** The batched flush can't land this one: its savepoint rolls back and the ops go one by one. */
|
|
2018
|
+
var BatchFallback = class extends Error {
|
|
2019
|
+
reason;
|
|
2020
|
+
constructor(reason) {
|
|
2021
|
+
super(`Batched import flush fell back: ${reason}`);
|
|
2022
|
+
this.reason = reason;
|
|
2023
|
+
this.name = "BatchFallback";
|
|
2024
|
+
}
|
|
2025
|
+
};
|
|
1016
2026
|
/** A per-item refusal: its savepoint rolls back and the flush goes on. */
|
|
1017
2027
|
var KnowledgeImportRefusalError = class extends Error {
|
|
1018
2028
|
reason;
|
|
@@ -1108,7 +2118,27 @@ function order(ops) {
|
|
|
1108
2118
|
return [...sorted, ...removes];
|
|
1109
2119
|
}
|
|
1110
2120
|
async function applyKnowledgeImportFlush(input) {
|
|
1111
|
-
const {
|
|
2121
|
+
const { binding, scope, provenance } = input;
|
|
2122
|
+
let { storage, importers } = input;
|
|
2123
|
+
let overlay = null;
|
|
2124
|
+
/**
|
|
2125
|
+
* Link-index work for a written page: a sync of its body links, then maybe a refresh of the links to
|
|
2126
|
+
* it. Run now, or after the batched write in one repair when deciding over the working copy.
|
|
2127
|
+
*/
|
|
2128
|
+
const links = async (sync, refresh) => {
|
|
2129
|
+
if (overlay) {
|
|
2130
|
+
if (sync) overlay.deferLinks({ sync });
|
|
2131
|
+
for (const page of refresh?.pages ?? []) overlay.deferLinks({
|
|
2132
|
+
refresh: page,
|
|
2133
|
+
withDescendants: !!refresh.withDescendants
|
|
2134
|
+
});
|
|
2135
|
+
return;
|
|
2136
|
+
}
|
|
2137
|
+
await syncLinks(async () => {
|
|
2138
|
+
if (sync) await require_run_registry.syncKnowledgePageBodyLinks(storage, sync);
|
|
2139
|
+
if (refresh) await require_run_registry.refreshKnowledgeLinksTo(storage, refresh.pages, { withDescendants: refresh.withDescendants });
|
|
2140
|
+
});
|
|
2141
|
+
};
|
|
1112
2142
|
const target = parseKnowledgeImportTarget(binding.target);
|
|
1113
2143
|
const result = {
|
|
1114
2144
|
counts: {
|
|
@@ -1117,7 +2147,8 @@ async function applyKnowledgeImportFlush(input) {
|
|
|
1117
2147
|
unchanged: 0,
|
|
1118
2148
|
moved: 0,
|
|
1119
2149
|
removed: 0,
|
|
1120
|
-
stubbed: 0
|
|
2150
|
+
stubbed: 0,
|
|
2151
|
+
merged: 0
|
|
1121
2152
|
},
|
|
1122
2153
|
refused: [],
|
|
1123
2154
|
changes: [],
|
|
@@ -1137,20 +2168,24 @@ async function applyKnowledgeImportFlush(input) {
|
|
|
1137
2168
|
const keyPath = async (page) => {
|
|
1138
2169
|
const keys = [];
|
|
1139
2170
|
const ids = [];
|
|
1140
|
-
|
|
1141
|
-
|
|
2171
|
+
if (page.isScope) return page.id === scope.id ? {
|
|
2172
|
+
keys,
|
|
2173
|
+
ids
|
|
2174
|
+
} : null;
|
|
2175
|
+
const parents = page.parentId ? await storage.getPageParents({
|
|
2176
|
+
parentId: page.parentId,
|
|
2177
|
+
read: "all"
|
|
2178
|
+
}) : [];
|
|
2179
|
+
for (const at of [page, ...parents]) {
|
|
2180
|
+
if (at.isScope) return at.id === scope.id ? {
|
|
2181
|
+
keys,
|
|
2182
|
+
ids
|
|
2183
|
+
} : null;
|
|
1142
2184
|
if (!live(at) || at.key === void 0) return null;
|
|
1143
2185
|
keys.unshift(at.key);
|
|
1144
2186
|
ids.unshift(at.id);
|
|
1145
|
-
at = at.parentId ? await storage.getPage({
|
|
1146
|
-
id: at.parentId,
|
|
1147
|
-
read: "all"
|
|
1148
|
-
}) : null;
|
|
1149
2187
|
}
|
|
1150
|
-
return
|
|
1151
|
-
keys,
|
|
1152
|
-
ids
|
|
1153
|
-
} : null;
|
|
2188
|
+
return null;
|
|
1154
2189
|
};
|
|
1155
2190
|
const sameKeys = (a, b) => a.length === b.length && a.every((key, i) => key === b[i]);
|
|
1156
2191
|
/**
|
|
@@ -1297,12 +2332,13 @@ async function applyKnowledgeImportFlush(input) {
|
|
|
1297
2332
|
};
|
|
1298
2333
|
};
|
|
1299
2334
|
const nodeOf = async (sourceId) => sourceId ? importers.getNode(binding.id, sourceId) : null;
|
|
1300
|
-
const
|
|
2335
|
+
const stateOf = async (node) => {
|
|
1301
2336
|
const page = await storage.getPage({
|
|
1302
2337
|
id: node.pageId,
|
|
1303
2338
|
read: "all"
|
|
1304
2339
|
});
|
|
1305
|
-
|
|
2340
|
+
if (page?.mergedInto) return "merged";
|
|
2341
|
+
return !page || !!page.deletedAt || page.scopeId !== scope.id ? "gone" : "live";
|
|
1306
2342
|
};
|
|
1307
2343
|
/**
|
|
1308
2344
|
* Drops the node of a page that is gone, so its item is written again as new. Pages that linked to
|
|
@@ -1354,15 +2390,14 @@ async function applyKnowledgeImportFlush(input) {
|
|
|
1354
2390
|
});
|
|
1355
2391
|
await importers.markLinkingNodesUnsettled(binding.id, [node.sourceId]);
|
|
1356
2392
|
await importers.deleteNode(binding.id, node.sourceId);
|
|
1357
|
-
if (old) await
|
|
2393
|
+
if (old) await links(null, { pages: [old] });
|
|
1358
2394
|
};
|
|
1359
2395
|
const liveNodeOf = async (sourceId) => {
|
|
1360
2396
|
const node = await nodeOf(sourceId);
|
|
1361
|
-
return node &&
|
|
2397
|
+
return node && await stateOf(node) === "live" ? node : null;
|
|
1362
2398
|
};
|
|
1363
2399
|
const ref = (keys) => `${target.scope}#${keys.join("/")}`;
|
|
1364
|
-
const linkLine = async (link) => {
|
|
1365
|
-
const node = await importers.getNode(binding.id, link.sourceId);
|
|
2400
|
+
const linkLine = async (link, node) => {
|
|
1366
2401
|
const page = node ? await storage.getPage({
|
|
1367
2402
|
id: node.pageId,
|
|
1368
2403
|
read: "all"
|
|
@@ -1373,11 +2408,30 @@ async function applyKnowledgeImportFlush(input) {
|
|
|
1373
2408
|
const renderLinks = async (links) => {
|
|
1374
2409
|
const lines = [];
|
|
1375
2410
|
const unresolved = [];
|
|
2411
|
+
const getNodes = async (sourceIds) => {
|
|
2412
|
+
if (!sourceIds.length) return [];
|
|
2413
|
+
if (importers.getNodes) return importers.getNodes(binding.id, sourceIds);
|
|
2414
|
+
const nodes = [];
|
|
2415
|
+
for (const sourceId of new Set(sourceIds)) {
|
|
2416
|
+
const node = await importers.getNode(binding.id, sourceId);
|
|
2417
|
+
if (node) nodes.push(node);
|
|
2418
|
+
}
|
|
2419
|
+
return nodes;
|
|
2420
|
+
};
|
|
2421
|
+
const read = async (sourceIds) => new Map((await getNodes(sourceIds)).map((node) => [node.sourceId, node]));
|
|
2422
|
+
const before = await read(links.map((link) => link.sourceId));
|
|
2423
|
+
const rendered = [];
|
|
1376
2424
|
for (const link of links) {
|
|
1377
|
-
const
|
|
1378
|
-
|
|
1379
|
-
|
|
2425
|
+
const node = before.get(link.sourceId);
|
|
2426
|
+
rendered.push({
|
|
2427
|
+
link,
|
|
2428
|
+
line: await linkLine(link, node),
|
|
2429
|
+
pageId: node?.pageId
|
|
2430
|
+
});
|
|
1380
2431
|
}
|
|
2432
|
+
const after = await read(rendered.filter((each) => each.line).map((each) => each.link.sourceId));
|
|
2433
|
+
for (const { link, line, pageId } of rendered) if (line && after.get(link.sourceId)?.pageId === pageId) lines.push(line);
|
|
2434
|
+
else unresolved.push(encodeLink(link));
|
|
1381
2435
|
return {
|
|
1382
2436
|
section: linkSection(lines),
|
|
1383
2437
|
unresolved
|
|
@@ -1423,7 +2477,7 @@ async function applyKnowledgeImportFlush(input) {
|
|
|
1423
2477
|
body,
|
|
1424
2478
|
provenance
|
|
1425
2479
|
});
|
|
1426
|
-
await
|
|
2480
|
+
await links(page);
|
|
1427
2481
|
return {
|
|
1428
2482
|
page,
|
|
1429
2483
|
changed: true,
|
|
@@ -1519,12 +2573,17 @@ async function applyKnowledgeImportFlush(input) {
|
|
|
1519
2573
|
};
|
|
1520
2574
|
const write = async (item, hasBody) => {
|
|
1521
2575
|
let existing = await importers.getNode(binding.id, item.sourceId);
|
|
1522
|
-
|
|
2576
|
+
const state = existing ? await stateOf(existing) : null;
|
|
2577
|
+
if (state === "merged") return null;
|
|
2578
|
+
if (existing && state === "gone") {
|
|
1523
2579
|
await forget(existing);
|
|
1524
2580
|
existing = null;
|
|
1525
2581
|
}
|
|
1526
|
-
const
|
|
1527
|
-
const
|
|
2582
|
+
const parentRecord = await nodeOf(item.parent);
|
|
2583
|
+
const parentState = parentRecord ? await stateOf(parentRecord) : null;
|
|
2584
|
+
const sourceParent = parentState === "live" ? parentRecord : null;
|
|
2585
|
+
const parentMerged = parentState === "merged";
|
|
2586
|
+
const misplaced = !!item.parent && !sourceParent && !parentMerged;
|
|
1528
2587
|
const parentNode = sourceParent ?? await liveNodeOf(item.fallbackParent);
|
|
1529
2588
|
const destination = parentNode ? await owned(parentNode.pageId, parentNode.sourceId) : anchor;
|
|
1530
2589
|
if (existing && destination.page.id === existing.pageId) throw new KnowledgeImportRefusalError("invalid");
|
|
@@ -1578,7 +2637,7 @@ async function applyKnowledgeImportFlush(input) {
|
|
|
1578
2637
|
const current = await owned(existing.pageId, item.sourceId);
|
|
1579
2638
|
page = current.page;
|
|
1580
2639
|
if (existing.stub && existing.adopted && !REMOVED_BODIES.has(page.body ?? "")) await keepBody(page.id, page.body ?? "");
|
|
1581
|
-
if (!current.outside && page.parentId !== destination.page.id) {
|
|
2640
|
+
if (!current.outside && !parentMerged && page.parentId !== destination.page.id) {
|
|
1582
2641
|
if (destination.keys.length > current.keys.length && sameKeys(destination.keys.slice(0, current.keys.length), current.keys)) throw new KnowledgeImportRefusalError("invalid");
|
|
1583
2642
|
({page, relinked} = await moveOwned(item.sourceId, page, destination));
|
|
1584
2643
|
moved = true;
|
|
@@ -1626,10 +2685,10 @@ async function applyKnowledgeImportFlush(input) {
|
|
|
1626
2685
|
adopted,
|
|
1627
2686
|
unsettled: misplaced || (rendered ? rendered.unresolved : existing?.unresolvedLinks ?? []).length > 0
|
|
1628
2687
|
});
|
|
1629
|
-
if (change !== "unchanged" || existing?.stub) await
|
|
1630
|
-
|
|
1631
|
-
|
|
1632
|
-
});
|
|
2688
|
+
if (change !== "unchanged" || existing?.stub) await links(page, change === "created" || renamed || moved ? {
|
|
2689
|
+
pages: [page],
|
|
2690
|
+
withDescendants: moved
|
|
2691
|
+
} : void 0);
|
|
1633
2692
|
return {
|
|
1634
2693
|
page,
|
|
1635
2694
|
change,
|
|
@@ -1637,136 +2696,150 @@ async function applyKnowledgeImportFlush(input) {
|
|
|
1637
2696
|
relinked
|
|
1638
2697
|
};
|
|
1639
2698
|
};
|
|
1640
|
-
const
|
|
1641
|
-
|
|
1642
|
-
|
|
1643
|
-
|
|
1644
|
-
|
|
1645
|
-
|
|
1646
|
-
|
|
1647
|
-
|
|
1648
|
-
|
|
1649
|
-
|
|
1650
|
-
|
|
1651
|
-
|
|
1652
|
-
|
|
1653
|
-
|
|
1654
|
-
const
|
|
1655
|
-
|
|
1656
|
-
|
|
1657
|
-
|
|
1658
|
-
|
|
1659
|
-
|
|
1660
|
-
|
|
1661
|
-
|
|
1662
|
-
await
|
|
2699
|
+
const runOps = async () => {
|
|
2700
|
+
const depth = /* @__PURE__ */ new Map();
|
|
2701
|
+
for (const op of ops) {
|
|
2702
|
+
if (op.op !== "remove") continue;
|
|
2703
|
+
const node = await importers.getNode(binding.id, op.sourceId);
|
|
2704
|
+
const page = node ? await storage.getPage({
|
|
2705
|
+
id: node.pageId,
|
|
2706
|
+
read: "all"
|
|
2707
|
+
}) : null;
|
|
2708
|
+
const path = live(page) ? await keyPath(page) : null;
|
|
2709
|
+
depth.set(op.sourceId, path?.keys.length ?? 0);
|
|
2710
|
+
}
|
|
2711
|
+
const writes = ops.filter((op) => op.op !== "remove");
|
|
2712
|
+
const removes = ops.filter((op) => op.op === "remove").sort((a, b) => depth.get(b.sourceId) - depth.get(a.sourceId));
|
|
2713
|
+
for (const op of [...writes, ...removes]) {
|
|
2714
|
+
const sourceId = op.op === "remove" ? op.sourceId : op.item.sourceId;
|
|
2715
|
+
const embeds = [];
|
|
2716
|
+
try {
|
|
2717
|
+
await storage.transaction(async () => {
|
|
2718
|
+
if (op.op === "remove") {
|
|
2719
|
+
const node = await importers.getNode(binding.id, sourceId);
|
|
2720
|
+
if (!node) return;
|
|
2721
|
+
const state = await stateOf(node);
|
|
2722
|
+
if (state === "merged") return;
|
|
2723
|
+
if (state === "gone") {
|
|
2724
|
+
await forget(node);
|
|
2725
|
+
result.applied = true;
|
|
2726
|
+
return;
|
|
2727
|
+
}
|
|
2728
|
+
const current = await owned(node.pageId, sourceId);
|
|
2729
|
+
await storage.lockSubtree(current.page.id);
|
|
2730
|
+
const children = (await storage.countChildPages({
|
|
2731
|
+
parentIds: [current.page.id],
|
|
2732
|
+
read: "all"
|
|
2733
|
+
}))[current.page.id] ?? 0;
|
|
2734
|
+
const folder = (await importers.listBindings()).some((other) => other.id !== binding.id && other.anchorPageId === current.page.id);
|
|
2735
|
+
if (children > 0 || node.adopted || folder) {
|
|
2736
|
+
if (node.stub) return;
|
|
2737
|
+
const note = node.adopted ? (await keptBodyNotes(current.page.id)).at(-1) : void 0;
|
|
2738
|
+
const heading = ORIGINAL_BODY_NOTE_HEADINGS.find((h) => note?.text.startsWith(h));
|
|
2739
|
+
const original = heading ? note.text.slice(heading.length) : note?.text;
|
|
2740
|
+
const page = await storage.updatePage({
|
|
2741
|
+
id: current.page.id,
|
|
2742
|
+
expectedVersion: current.page.version,
|
|
2743
|
+
body: original || (children > 0 ? "Removed from the source. Kept because pages are still nested under it." : folder ? "Removed from the source. Kept because another importer writes under it." : "Removed from the source. Kept because the page was here before the import."),
|
|
2744
|
+
provenance
|
|
2745
|
+
});
|
|
2746
|
+
await importers.saveNode({
|
|
2747
|
+
...node,
|
|
2748
|
+
stub: true
|
|
2749
|
+
});
|
|
2750
|
+
await links(page);
|
|
2751
|
+
embeds.push({
|
|
2752
|
+
kind: "index",
|
|
2753
|
+
pageId: page.id
|
|
2754
|
+
});
|
|
2755
|
+
result.counts.stubbed++;
|
|
2756
|
+
result.changes.push({
|
|
2757
|
+
sourceId,
|
|
2758
|
+
pageId: page.id,
|
|
2759
|
+
change: "stubbed",
|
|
2760
|
+
title: page.name,
|
|
2761
|
+
path: ref(current.keys)
|
|
2762
|
+
});
|
|
2763
|
+
} else {
|
|
2764
|
+
const deleted = await storage.deletePage({
|
|
2765
|
+
id: current.page.id,
|
|
2766
|
+
expectedVersion: current.page.version,
|
|
2767
|
+
deletedBy: provenance.author
|
|
2768
|
+
});
|
|
2769
|
+
await importers.deleteNode(binding.id, sourceId);
|
|
2770
|
+
if ((await importers.listLinkingNodes(binding.id, [sourceId], { limit: 1 })).items.length > 0) {
|
|
2771
|
+
await importers.markLinkingNodesUnsettled(binding.id, [sourceId]);
|
|
2772
|
+
await importers.setState(binding.id, { [KNOWLEDGE_IMPORT_SETTLE_RESTART_KEY]: (0, crypto.randomUUID)() });
|
|
2773
|
+
deferredLinkers = true;
|
|
2774
|
+
}
|
|
2775
|
+
await links(deleted, { pages: [deleted] });
|
|
2776
|
+
embeds.push({
|
|
2777
|
+
kind: "remove",
|
|
2778
|
+
pageId: deleted.id
|
|
2779
|
+
});
|
|
2780
|
+
result.counts.removed++;
|
|
2781
|
+
result.changes.push({
|
|
2782
|
+
sourceId,
|
|
2783
|
+
pageId: null,
|
|
2784
|
+
change: "removed",
|
|
2785
|
+
title: deleted.name,
|
|
2786
|
+
path: ref(current.keys)
|
|
2787
|
+
});
|
|
2788
|
+
}
|
|
1663
2789
|
result.applied = true;
|
|
1664
2790
|
return;
|
|
1665
2791
|
}
|
|
1666
|
-
const
|
|
1667
|
-
|
|
1668
|
-
|
|
1669
|
-
|
|
1670
|
-
|
|
1671
|
-
|
|
1672
|
-
|
|
1673
|
-
if (
|
|
1674
|
-
|
|
1675
|
-
|
|
1676
|
-
const heading = ORIGINAL_BODY_NOTE_HEADINGS.find((h) => note?.text.startsWith(h));
|
|
1677
|
-
const original = heading ? note.text.slice(heading.length) : note?.text;
|
|
1678
|
-
const page = await storage.updatePage({
|
|
1679
|
-
id: current.page.id,
|
|
1680
|
-
expectedVersion: current.page.version,
|
|
1681
|
-
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."),
|
|
1682
|
-
provenance
|
|
1683
|
-
});
|
|
1684
|
-
await importers.saveNode({
|
|
1685
|
-
...node,
|
|
1686
|
-
stub: true
|
|
1687
|
-
});
|
|
1688
|
-
await syncLinks(() => require_run_registry.syncKnowledgePageBodyLinks(storage, page));
|
|
1689
|
-
embeds.push({
|
|
1690
|
-
kind: "index",
|
|
1691
|
-
pageId: page.id
|
|
1692
|
-
});
|
|
1693
|
-
result.counts.stubbed++;
|
|
1694
|
-
result.changes.push({
|
|
1695
|
-
sourceId,
|
|
1696
|
-
pageId: page.id,
|
|
1697
|
-
change: "stubbed",
|
|
1698
|
-
title: page.name,
|
|
1699
|
-
path: ref(current.keys)
|
|
1700
|
-
});
|
|
1701
|
-
} else {
|
|
1702
|
-
const deleted = await storage.deletePage({
|
|
1703
|
-
id: current.page.id,
|
|
1704
|
-
expectedVersion: current.page.version,
|
|
1705
|
-
deletedBy: provenance.author
|
|
1706
|
-
});
|
|
1707
|
-
await importers.deleteNode(binding.id, sourceId);
|
|
1708
|
-
if ((await importers.listLinkingNodes(binding.id, [sourceId], { limit: 1 })).items.length > 0) {
|
|
1709
|
-
await importers.markLinkingNodesUnsettled(binding.id, [sourceId]);
|
|
1710
|
-
await importers.setState(binding.id, { [KNOWLEDGE_IMPORT_SETTLE_RESTART_KEY]: (0, crypto.randomUUID)() });
|
|
1711
|
-
deferredLinkers = true;
|
|
1712
|
-
}
|
|
1713
|
-
await syncLinks(async () => {
|
|
1714
|
-
await require_run_registry.syncKnowledgePageBodyLinks(storage, deleted);
|
|
1715
|
-
await require_run_registry.refreshKnowledgeLinksTo(storage, [deleted]);
|
|
1716
|
-
});
|
|
1717
|
-
embeds.push({
|
|
1718
|
-
kind: "remove",
|
|
1719
|
-
pageId: deleted.id
|
|
1720
|
-
});
|
|
1721
|
-
result.counts.removed++;
|
|
1722
|
-
result.changes.push({
|
|
1723
|
-
sourceId,
|
|
1724
|
-
pageId: null,
|
|
1725
|
-
change: "removed",
|
|
1726
|
-
title: deleted.name,
|
|
1727
|
-
path: ref(current.keys)
|
|
1728
|
-
});
|
|
2792
|
+
const written = await write(op.item, op.op === "upsert");
|
|
2793
|
+
if (!written) {
|
|
2794
|
+
result.counts.merged++;
|
|
2795
|
+
return;
|
|
2796
|
+
}
|
|
2797
|
+
const { page, change, moved, relinked } = written;
|
|
2798
|
+
recordRelinked(relinked, embeds);
|
|
2799
|
+
if (change === "unchanged") {
|
|
2800
|
+
result.counts.unchanged++;
|
|
2801
|
+
return;
|
|
1729
2802
|
}
|
|
1730
2803
|
result.applied = true;
|
|
1731
|
-
|
|
1732
|
-
|
|
1733
|
-
|
|
1734
|
-
|
|
1735
|
-
|
|
1736
|
-
result.counts.
|
|
1737
|
-
|
|
1738
|
-
|
|
1739
|
-
|
|
1740
|
-
|
|
1741
|
-
|
|
1742
|
-
|
|
2804
|
+
if (change !== "moved") embeds.push({
|
|
2805
|
+
kind: "index",
|
|
2806
|
+
pageId: page.id
|
|
2807
|
+
});
|
|
2808
|
+
if (change === "created") result.counts.created++;
|
|
2809
|
+
else if (change === "updated") result.counts.updated++;
|
|
2810
|
+
if (moved) result.counts.moved++;
|
|
2811
|
+
const path = await keyPath(page);
|
|
2812
|
+
result.changes.push({
|
|
2813
|
+
sourceId,
|
|
2814
|
+
pageId: page.id,
|
|
2815
|
+
change,
|
|
2816
|
+
title: page.name,
|
|
2817
|
+
path: path ? ref(path.keys) : ""
|
|
2818
|
+
});
|
|
1743
2819
|
});
|
|
1744
|
-
|
|
1745
|
-
|
|
1746
|
-
|
|
1747
|
-
|
|
1748
|
-
result.
|
|
2820
|
+
result.embeds.push(...embeds);
|
|
2821
|
+
} catch (error) {
|
|
2822
|
+
const reason = refusalFor(error);
|
|
2823
|
+
if (!reason) throw error;
|
|
2824
|
+
result.refused.push({
|
|
1749
2825
|
sourceId,
|
|
1750
|
-
|
|
1751
|
-
change,
|
|
1752
|
-
title: page.name,
|
|
1753
|
-
path: path ? ref(path.keys) : ""
|
|
2826
|
+
reason
|
|
1754
2827
|
});
|
|
1755
|
-
}
|
|
1756
|
-
|
|
1757
|
-
|
|
1758
|
-
|
|
1759
|
-
|
|
1760
|
-
|
|
1761
|
-
|
|
1762
|
-
|
|
1763
|
-
|
|
2828
|
+
}
|
|
2829
|
+
}
|
|
2830
|
+
};
|
|
2831
|
+
if (!canBatchImportFlush(input.storage, input.importers)) await runOps();
|
|
2832
|
+
else if (ops.length) {
|
|
2833
|
+
const fallback = await applyBatched(anchor?.page ?? null);
|
|
2834
|
+
if (fallback) {
|
|
2835
|
+
result.fallback = fallback;
|
|
2836
|
+
await runOps();
|
|
1764
2837
|
}
|
|
1765
2838
|
}
|
|
1766
2839
|
if (input.settle) {
|
|
1767
2840
|
if (anchor) {
|
|
1768
2841
|
input.settle.onStart?.();
|
|
1769
|
-
result.settle = await settle(input.settle);
|
|
2842
|
+
result.settle = await settle(input.settle, anchor.page);
|
|
1770
2843
|
} else result.settle = {
|
|
1771
2844
|
pending: false,
|
|
1772
2845
|
cursor: null,
|
|
@@ -1776,13 +2849,314 @@ async function applyKnowledgeImportFlush(input) {
|
|
|
1776
2849
|
}
|
|
1777
2850
|
return result;
|
|
1778
2851
|
/**
|
|
2852
|
+
* Decides every op over a working copy (overlay.ts) and writes what they decided in a few
|
|
2853
|
+
* set-based statements, all in one savepoint (batched-flush plan v3.1). Returns why it fell back,
|
|
2854
|
+
* with the savepoint rolled back and the result as before, or null once the ops landed.
|
|
2855
|
+
*/
|
|
2856
|
+
async function applyBatched(folder) {
|
|
2857
|
+
const writeOps = new Map(ops.flatMap((op) => op.op === "remove" ? [] : [[op.item.sourceId, op]]));
|
|
2858
|
+
const removed = ops.flatMap((op) => op.op === "remove" ? [op.sourceId] : []);
|
|
2859
|
+
const sourceIds = new Set(removed);
|
|
2860
|
+
for (const op of writeOps.values()) {
|
|
2861
|
+
sourceIds.add(op.item.sourceId);
|
|
2862
|
+
if (op.item.parent) sourceIds.add(op.item.parent);
|
|
2863
|
+
if (op.item.fallbackParent) sourceIds.add(op.item.fallbackParent);
|
|
2864
|
+
for (const link of ("links" in op.item ? op.item.links : void 0) ?? []) sourceIds.add(link.sourceId);
|
|
2865
|
+
}
|
|
2866
|
+
const plan = (rows) => {
|
|
2867
|
+
const keysOf = (page) => {
|
|
2868
|
+
const keys = [];
|
|
2869
|
+
for (let at = page; at && !at.isScope; at = at.parentId ? rows.pages.get(at.parentId) : null) {
|
|
2870
|
+
if (!live(at) || at.key === void 0) return null;
|
|
2871
|
+
keys.unshift(at.key);
|
|
2872
|
+
if (keys.length > 10) return null;
|
|
2873
|
+
}
|
|
2874
|
+
return keys;
|
|
2875
|
+
};
|
|
2876
|
+
const at = (sourceId, seen) => {
|
|
2877
|
+
if (!sourceId) return null;
|
|
2878
|
+
const node = rows.nodes.get(`${binding.id}\u0000${sourceId}`);
|
|
2879
|
+
const page = node ? rows.pages.get(node.pageId) : null;
|
|
2880
|
+
if (live(page ?? null) && page.scopeId === scope.id) {
|
|
2881
|
+
const keys = keysOf(page);
|
|
2882
|
+
if (keys) return {
|
|
2883
|
+
id: page.id,
|
|
2884
|
+
keys
|
|
2885
|
+
};
|
|
2886
|
+
}
|
|
2887
|
+
const op = writeOps.get(sourceId);
|
|
2888
|
+
if (!op || seen.has(sourceId)) return null;
|
|
2889
|
+
return {
|
|
2890
|
+
id: null,
|
|
2891
|
+
keys: [...destinationOf(op, /* @__PURE__ */ new Set([...seen, sourceId])).keys, knowledgeImportKey(sourceId)]
|
|
2892
|
+
};
|
|
2893
|
+
};
|
|
2894
|
+
const destinationOf = (op, seen) => at(op.item.parent, seen) ?? at(op.item.fallbackParent, seen) ?? {
|
|
2895
|
+
id: folder.id,
|
|
2896
|
+
keys: anchorPath
|
|
2897
|
+
};
|
|
2898
|
+
const out = {
|
|
2899
|
+
paths: [],
|
|
2900
|
+
positions: [],
|
|
2901
|
+
notes: [],
|
|
2902
|
+
subtrees: [],
|
|
2903
|
+
linkTargets: removed,
|
|
2904
|
+
bindings: removed.length > 0
|
|
2905
|
+
};
|
|
2906
|
+
const nodeAt = (sourceId) => rows.nodes.get(`${binding.id}\u0000${sourceId}`);
|
|
2907
|
+
const left = /* @__PURE__ */ new Set();
|
|
2908
|
+
for (const op of writeOps.values()) {
|
|
2909
|
+
const destination = destinationOf(op, /* @__PURE__ */ new Set([op.item.sourceId]));
|
|
2910
|
+
out.paths.push({
|
|
2911
|
+
scopeId: scope.id,
|
|
2912
|
+
path: [...destination.keys, knowledgeImportKey(op.item.sourceId)]
|
|
2913
|
+
});
|
|
2914
|
+
if (destination.id) out.positions.push(destination.id);
|
|
2915
|
+
const page = rows.pages.get(nodeAt(op.item.sourceId)?.pageId ?? "");
|
|
2916
|
+
if (live(page ?? null) && page.parentId !== destination.id) {
|
|
2917
|
+
out.subtrees.push(page.id);
|
|
2918
|
+
if (page.parentId) left.add(page.parentId);
|
|
2919
|
+
}
|
|
2920
|
+
}
|
|
2921
|
+
for (const id of out.positions) if (left.has(id)) out.subtrees.push(id);
|
|
2922
|
+
for (const sourceId of removed) {
|
|
2923
|
+
const node = nodeAt(sourceId);
|
|
2924
|
+
if (!node) continue;
|
|
2925
|
+
out.subtrees.push(node.pageId);
|
|
2926
|
+
if (node.adopted) out.notes.push(node.pageId);
|
|
2927
|
+
}
|
|
2928
|
+
for (const node of rows.nodes.values()) if (node?.stub && node.adopted) out.notes.push(node.pageId);
|
|
2929
|
+
return out;
|
|
2930
|
+
};
|
|
2931
|
+
return batchedOver(folder, sourceIds, plan, runOps);
|
|
2932
|
+
}
|
|
2933
|
+
/**
|
|
2934
|
+
* Runs `decide` over a working copy of the rows `plan` names, then writes what it decided in a few
|
|
2935
|
+
* set-based statements, all in one savepoint. Returns why it fell back, with the savepoint rolled
|
|
2936
|
+
* back and the result as before, or null once the writes landed.
|
|
2937
|
+
*/
|
|
2938
|
+
async function batchedOver(folder, sourceIds, plan, decide) {
|
|
2939
|
+
const real = {
|
|
2940
|
+
storage: input.storage,
|
|
2941
|
+
importers: input.importers
|
|
2942
|
+
};
|
|
2943
|
+
const before = structuredClone(result);
|
|
2944
|
+
const deferredBefore = deferredLinkers;
|
|
2945
|
+
const reset = () => {
|
|
2946
|
+
const copy = structuredClone(before);
|
|
2947
|
+
Object.assign(result, copy);
|
|
2948
|
+
deferredLinkers = deferredBefore;
|
|
2949
|
+
};
|
|
2950
|
+
const missing = emptyImportOverlayMissing();
|
|
2951
|
+
let locked = /* @__PURE__ */ new Set();
|
|
2952
|
+
try {
|
|
2953
|
+
return await real.storage.transaction(async () => {
|
|
2954
|
+
for (let pass = 0; pass < BATCH_DECIDE_PASSES; pass++) {
|
|
2955
|
+
const rows = await gatherImportRows({
|
|
2956
|
+
storage: real.storage,
|
|
2957
|
+
importers: real.importers,
|
|
2958
|
+
bindingId: binding.id,
|
|
2959
|
+
sourceIds,
|
|
2960
|
+
pageIds: folder ? [folder.id] : [],
|
|
2961
|
+
plan,
|
|
2962
|
+
missing,
|
|
2963
|
+
locked
|
|
2964
|
+
});
|
|
2965
|
+
if (!rows) throw new BatchFallback("lock-churn");
|
|
2966
|
+
locked = rows.locked;
|
|
2967
|
+
const working = new ImportOverlay(rows);
|
|
2968
|
+
reset();
|
|
2969
|
+
overlay = working;
|
|
2970
|
+
storage = working.storage;
|
|
2971
|
+
importers = working.importers;
|
|
2972
|
+
try {
|
|
2973
|
+
await decide();
|
|
2974
|
+
} catch (error) {
|
|
2975
|
+
if (error instanceof KnowledgeImportNotGatheredError) {
|
|
2976
|
+
for (const [name, set] of Object.entries(working.missing)) {
|
|
2977
|
+
const into = missing[name];
|
|
2978
|
+
if (into instanceof Map) for (const [k, v] of set) into.set(k, v);
|
|
2979
|
+
else for (const k of set) into.add(k);
|
|
2980
|
+
}
|
|
2981
|
+
continue;
|
|
2982
|
+
}
|
|
2983
|
+
if (error instanceof KnowledgeImportBatchUnsupportedError) throw new BatchFallback(error.call);
|
|
2984
|
+
throw error;
|
|
2985
|
+
} finally {
|
|
2986
|
+
overlay = null;
|
|
2987
|
+
storage = real.storage;
|
|
2988
|
+
importers = real.importers;
|
|
2989
|
+
}
|
|
2990
|
+
try {
|
|
2991
|
+
if (working.writes.length) await real.storage.applyPageWrites({ writes: working.writes });
|
|
2992
|
+
} catch (error) {
|
|
2993
|
+
if (!refusalFor(error)) throw error;
|
|
2994
|
+
throw new BatchFallback(`page writes: ${error.name}`);
|
|
2995
|
+
}
|
|
2996
|
+
for (const work of working.marks) await work(real.storage, real.importers);
|
|
2997
|
+
const nodes = working.nodeWrites(rows);
|
|
2998
|
+
try {
|
|
2999
|
+
if (nodes.deletes.length || nodes.saves.length) await real.importers.writeNodes(nodes);
|
|
3000
|
+
} catch (error) {
|
|
3001
|
+
if (!refusalFor(error)) throw error;
|
|
3002
|
+
throw new BatchFallback(`node writes: ${error.name}`);
|
|
3003
|
+
}
|
|
3004
|
+
try {
|
|
3005
|
+
await require_run_registry.repairKnowledgeLinks(real.storage, {
|
|
3006
|
+
synced: working.links.flatMap((work) => "sync" in work ? [work.sync] : []),
|
|
3007
|
+
refreshed: working.links.flatMap((work) => "refresh" in work ? [{
|
|
3008
|
+
page: work.refresh,
|
|
3009
|
+
withDescendants: work.withDescendants
|
|
3010
|
+
}] : [])
|
|
3011
|
+
});
|
|
3012
|
+
} catch (error) {
|
|
3013
|
+
if (error instanceof require_run_registry.KnowledgeLinkRepairUnsupportedError) throw new BatchFallback(error.reason);
|
|
3014
|
+
if (error instanceof require_run_registry.KnowledgeUnsupportedCapabilityError) throw new BatchFallback(`link repair: ${error.name}`);
|
|
3015
|
+
throw error;
|
|
3016
|
+
}
|
|
3017
|
+
return null;
|
|
3018
|
+
}
|
|
3019
|
+
throw new BatchFallback("gather passes");
|
|
3020
|
+
});
|
|
3021
|
+
} catch (error) {
|
|
3022
|
+
if (!(error instanceof BatchFallback)) throw error;
|
|
3023
|
+
reset();
|
|
3024
|
+
return error.reason;
|
|
3025
|
+
}
|
|
3026
|
+
}
|
|
3027
|
+
/**
|
|
1779
3028
|
* One settle slice (O3 §C, §C′): visits the binding's unsettled nodes after `budget.after`, each
|
|
1780
3029
|
* in its own savepoint, moving a page under a source parent that has arrived since and writing
|
|
1781
3030
|
* links whose targets now resolve. Stops at the candidate, move or time cap and leaves the rest
|
|
1782
3031
|
* for the next slice. A node it can't settle (refused, or still waiting) is skipped and stays
|
|
1783
3032
|
* unsettled; the pass ends when it reaches the last unsettled node.
|
|
1784
3033
|
*/
|
|
1785
|
-
async function settle(budget) {
|
|
3034
|
+
async function settle(budget, folder) {
|
|
3035
|
+
if (!canBatchImportFlush(input.storage, input.importers)) return settleNodeByNode(budget);
|
|
3036
|
+
const fromStart = (budget.after ?? void 0) === void 0;
|
|
3037
|
+
const window = [];
|
|
3038
|
+
let cursor = budget.after ?? void 0;
|
|
3039
|
+
let end = false;
|
|
3040
|
+
while (window.length < budget.candidates) {
|
|
3041
|
+
const page = await input.importers.listNodes(binding.id, {
|
|
3042
|
+
unsettled: true,
|
|
3043
|
+
...cursor !== void 0 ? { after: cursor } : {},
|
|
3044
|
+
limit: budget.candidates - window.length
|
|
3045
|
+
});
|
|
3046
|
+
window.push(...page.items);
|
|
3047
|
+
cursor = page.items.at(-1)?.sourceId ?? cursor;
|
|
3048
|
+
if (!page.next) {
|
|
3049
|
+
end = true;
|
|
3050
|
+
break;
|
|
3051
|
+
}
|
|
3052
|
+
}
|
|
3053
|
+
if (!window.length) return settleNodeByNode(budget);
|
|
3054
|
+
const parents = new Map((await input.importers.getNodes(binding.id, [...new Set(window.flatMap((node) => node.parentSourceId ? [node.parentSourceId] : []))])).map((node) => [node.sourceId, node]));
|
|
3055
|
+
const pages = new Map((await input.storage.getPages({
|
|
3056
|
+
ids: window.map((node) => node.pageId),
|
|
3057
|
+
read: "all"
|
|
3058
|
+
})).map((page) => [page.id, page]));
|
|
3059
|
+
const visit = [];
|
|
3060
|
+
const movers = [];
|
|
3061
|
+
for (const node of window) {
|
|
3062
|
+
visit.push(node);
|
|
3063
|
+
const parent = node.parentSourceId ? parents.get(node.parentSourceId) : void 0;
|
|
3064
|
+
const page = pages.get(node.pageId);
|
|
3065
|
+
if (parent && page && page.parentId !== parent.pageId) {
|
|
3066
|
+
movers.push({
|
|
3067
|
+
sourceId: node.sourceId,
|
|
3068
|
+
page,
|
|
3069
|
+
destination: parent.pageId
|
|
3070
|
+
});
|
|
3071
|
+
if (movers.length >= budget.moves) break;
|
|
3072
|
+
}
|
|
3073
|
+
}
|
|
3074
|
+
if (visit.length < window.length) end = false;
|
|
3075
|
+
const sourceIds = /* @__PURE__ */ new Set();
|
|
3076
|
+
for (const node of visit) {
|
|
3077
|
+
sourceIds.add(node.sourceId);
|
|
3078
|
+
if (node.parentSourceId) sourceIds.add(node.parentSourceId);
|
|
3079
|
+
for (const link of node.links) sourceIds.add(link.sourceId);
|
|
3080
|
+
}
|
|
3081
|
+
let outcome = null;
|
|
3082
|
+
const fallback = await batchedOver(folder, sourceIds, (rows) => ({
|
|
3083
|
+
paths: movers.flatMap((mover) => {
|
|
3084
|
+
const keys = [];
|
|
3085
|
+
for (let at = rows.pages.get(mover.destination); at && !at.isScope;) {
|
|
3086
|
+
if (at.key === void 0) return [];
|
|
3087
|
+
keys.unshift(at.key);
|
|
3088
|
+
at = at.parentId ? rows.pages.get(at.parentId) : null;
|
|
3089
|
+
}
|
|
3090
|
+
return mover.page.key === void 0 ? [] : [{
|
|
3091
|
+
scopeId: scope.id,
|
|
3092
|
+
path: [...keys, mover.page.key]
|
|
3093
|
+
}];
|
|
3094
|
+
}),
|
|
3095
|
+
positions: movers.map((mover) => mover.destination),
|
|
3096
|
+
notes: [],
|
|
3097
|
+
subtrees: movers.map((mover) => mover.page.id),
|
|
3098
|
+
linkTargets: movers.map((mover) => mover.sourceId),
|
|
3099
|
+
bindings: false
|
|
3100
|
+
}), async () => {
|
|
3101
|
+
outcome = await settleWindow(budget, visit, end, fromStart);
|
|
3102
|
+
});
|
|
3103
|
+
if (fallback === null && outcome) {
|
|
3104
|
+
const settledSlice = outcome;
|
|
3105
|
+
if (!settledSlice.pending && deferredLinkers) {
|
|
3106
|
+
if ((await input.importers.listNodes(binding.id, {
|
|
3107
|
+
unsettled: true,
|
|
3108
|
+
limit: 1
|
|
3109
|
+
})).items.length > 0) return {
|
|
3110
|
+
...settledSlice,
|
|
3111
|
+
pending: true
|
|
3112
|
+
};
|
|
3113
|
+
}
|
|
3114
|
+
return settledSlice;
|
|
3115
|
+
}
|
|
3116
|
+
result.fallback = result.fallback ? `${result.fallback}; settle: ${fallback}` : `settle: ${fallback}`;
|
|
3117
|
+
return settleNodeByNode(budget);
|
|
3118
|
+
}
|
|
3119
|
+
/**
|
|
3120
|
+
* The node-by-node loop over a window read ahead, for the batched slice: the same caps, the same
|
|
3121
|
+
* savepoint per node, over the working copy.
|
|
3122
|
+
*/
|
|
3123
|
+
async function settleWindow(budget, visit, end, fromStart) {
|
|
3124
|
+
let after = budget.after ?? void 0;
|
|
3125
|
+
let moves = 0;
|
|
3126
|
+
let settled = 0;
|
|
3127
|
+
const resumeAt = () => deferredLinkers ? null : after ?? null;
|
|
3128
|
+
for (const node of visit) {
|
|
3129
|
+
if (moves >= budget.moves || Date.now() >= budget.until) return {
|
|
3130
|
+
pending: true,
|
|
3131
|
+
cursor: resumeAt(),
|
|
3132
|
+
settled,
|
|
3133
|
+
fromStart
|
|
3134
|
+
};
|
|
3135
|
+
after = node.sourceId;
|
|
3136
|
+
const embeds = [];
|
|
3137
|
+
try {
|
|
3138
|
+
const outcome = await storage.transaction(() => settleNode(node.sourceId, embeds, moves < budget.moves));
|
|
3139
|
+
if (outcome.moved) moves++;
|
|
3140
|
+
if (outcome.moved || outcome.relinked) settled++;
|
|
3141
|
+
result.embeds.push(...embeds);
|
|
3142
|
+
} catch (error) {
|
|
3143
|
+
if (!refusalFor(error)) throw error;
|
|
3144
|
+
}
|
|
3145
|
+
}
|
|
3146
|
+
if (!end) return {
|
|
3147
|
+
pending: true,
|
|
3148
|
+
cursor: resumeAt(),
|
|
3149
|
+
settled,
|
|
3150
|
+
fromStart
|
|
3151
|
+
};
|
|
3152
|
+
return {
|
|
3153
|
+
pending: false,
|
|
3154
|
+
cursor: null,
|
|
3155
|
+
settled,
|
|
3156
|
+
fromStart
|
|
3157
|
+
};
|
|
3158
|
+
}
|
|
3159
|
+
async function settleNodeByNode(budget) {
|
|
1786
3160
|
let after = budget.after ?? void 0;
|
|
1787
3161
|
const fromStart = after === void 0;
|
|
1788
3162
|
let examined = 0;
|
|
@@ -1849,12 +3223,24 @@ async function applyKnowledgeImportFlush(input) {
|
|
|
1849
3223
|
moved: false,
|
|
1850
3224
|
relinked: false
|
|
1851
3225
|
};
|
|
3226
|
+
if (await stateOf(node) === "merged") {
|
|
3227
|
+
await importers.saveNode({
|
|
3228
|
+
...node,
|
|
3229
|
+
unsettled: false
|
|
3230
|
+
});
|
|
3231
|
+
return {
|
|
3232
|
+
moved: false,
|
|
3233
|
+
relinked: false
|
|
3234
|
+
};
|
|
3235
|
+
}
|
|
1852
3236
|
const current = await owned(node.pageId, sourceId);
|
|
1853
3237
|
let { page, keys } = current;
|
|
1854
3238
|
let moved = false;
|
|
1855
3239
|
let relinked = false;
|
|
1856
|
-
const
|
|
1857
|
-
|
|
3240
|
+
const sourceParent = current.outside ? null : await nodeOf(node.parentSourceId);
|
|
3241
|
+
const parentMerged = !!sourceParent && await stateOf(sourceParent) === "merged";
|
|
3242
|
+
const parent = parentMerged ? null : sourceParent;
|
|
3243
|
+
let misplaced = !current.outside && !!node.parentSourceId && !parent && !parentMerged;
|
|
1858
3244
|
if (parent && canMove) {
|
|
1859
3245
|
const destination = await owned(parent.pageId, parent.sourceId);
|
|
1860
3246
|
if (page.parentId !== destination.page.id) {
|
|
@@ -1863,7 +3249,10 @@ async function applyKnowledgeImportFlush(input) {
|
|
|
1863
3249
|
({page, keys, relinked: rewrote} = await moveOwned(sourceId, page, destination));
|
|
1864
3250
|
recordRelinked(rewrote, embeds);
|
|
1865
3251
|
moved = true;
|
|
1866
|
-
await
|
|
3252
|
+
await links(null, {
|
|
3253
|
+
pages: [page],
|
|
3254
|
+
withDescendants: true
|
|
3255
|
+
});
|
|
1867
3256
|
}
|
|
1868
3257
|
} else if (parent) misplaced = true;
|
|
1869
3258
|
const out = await relink(node, page);
|
|
@@ -2255,6 +3644,14 @@ function hostError(error) {
|
|
|
2255
3644
|
failure.cause = error;
|
|
2256
3645
|
return failure;
|
|
2257
3646
|
}
|
|
3647
|
+
/** A committed receipt as replayed; receipts written before the `merged` count existed read it as 0. */
|
|
3648
|
+
const storedReceipt = (receipt) => {
|
|
3649
|
+
const stored = receipt;
|
|
3650
|
+
return {
|
|
3651
|
+
...stored,
|
|
3652
|
+
merged: stored.merged ?? 0
|
|
3653
|
+
};
|
|
3654
|
+
};
|
|
2258
3655
|
const receiptCounts = (counts) => ({
|
|
2259
3656
|
created: counts.created ?? 0,
|
|
2260
3657
|
updated: counts.updated ?? 0,
|
|
@@ -2262,6 +3659,7 @@ const receiptCounts = (counts) => ({
|
|
|
2262
3659
|
moved: counts.moved ?? 0,
|
|
2263
3660
|
removed: counts.removed ?? 0,
|
|
2264
3661
|
stubbed: counts.stubbed ?? 0,
|
|
3662
|
+
merged: counts.merged ?? 0,
|
|
2265
3663
|
refused: counts.refused ?? 0
|
|
2266
3664
|
});
|
|
2267
3665
|
const runReceipt = (run) => {
|
|
@@ -2516,7 +3914,7 @@ function createLocalKnowledgeImporterHost(writer, options) {
|
|
|
2516
3914
|
});
|
|
2517
3915
|
if (replayed) {
|
|
2518
3916
|
if (replayed.digest !== digest) throw conflict("digest_mismatch", "This seq was committed with other content.");
|
|
2519
|
-
return replayed.receipt;
|
|
3917
|
+
return storedReceipt(replayed.receipt);
|
|
2520
3918
|
}
|
|
2521
3919
|
const [peek, peekRun] = await Promise.all([rootImporters.readWriterGuard(), rootImporters.getRun(flush.runId)]).catch((error) => {
|
|
2522
3920
|
throw hostError(error);
|
|
@@ -2533,15 +3931,17 @@ function createLocalKnowledgeImporterHost(writer, options) {
|
|
|
2533
3931
|
}
|
|
2534
3932
|
let embeds = [];
|
|
2535
3933
|
let settling = false;
|
|
3934
|
+
let fallbackWarning;
|
|
2536
3935
|
try {
|
|
2537
3936
|
const write = (deadlineAt) => storage.transaction(async (tx) => {
|
|
3937
|
+
fallbackWarning = void 0;
|
|
2538
3938
|
const importers = tx.importers;
|
|
2539
3939
|
const guard = await importers.lockWriterGuard(peek.firstWriteAt ? "share" : "update");
|
|
2540
3940
|
const run = await importers.lockRun(flush.runId);
|
|
2541
3941
|
const stored = await importers.getFlush(flush.runId, flush.generation, flush.seq);
|
|
2542
3942
|
if (stored) {
|
|
2543
3943
|
if (stored.digest !== digest) throw conflict("digest_mismatch", "This seq was committed with other content.");
|
|
2544
|
-
return stored.receipt;
|
|
3944
|
+
return storedReceipt(stored.receipt);
|
|
2545
3945
|
}
|
|
2546
3946
|
if (!run || run.status !== "running") throw conflict("run_not_active", "The run is not running.");
|
|
2547
3947
|
if (run.generation !== flush.generation || guard.generation !== flush.generation) throw conflict("stale_generation", "The run belongs to an older writer generation.");
|
|
@@ -2579,6 +3979,7 @@ function createLocalKnowledgeImporterHost(writer, options) {
|
|
|
2579
3979
|
}
|
|
2580
3980
|
} } : {}
|
|
2581
3981
|
});
|
|
3982
|
+
if (applied.fallback) fallbackWarning = `Knowledge importer: flush ${flush.seq} of run ${run.id} saved op by op instead of batched (${applied.fallback})`;
|
|
2582
3983
|
const settled = applied.settle;
|
|
2583
3984
|
const hostUpdates = {};
|
|
2584
3985
|
if (settled && (settled.cursor ?? "") !== (hostState[SETTLE_CURSOR_KEY] ?? "")) hostUpdates[SETTLE_CURSOR_KEY] = settled.cursor ?? "";
|
|
@@ -2589,15 +3990,18 @@ function createLocalKnowledgeImporterHost(writer, options) {
|
|
|
2589
3990
|
...hostUpdates
|
|
2590
3991
|
};
|
|
2591
3992
|
if (Object.keys(state).length) await importers.setState(binding.id, state);
|
|
2592
|
-
|
|
3993
|
+
const changes = applied.changes.map((change) => ({
|
|
2593
3994
|
runId: run.id,
|
|
2594
3995
|
...change
|
|
2595
|
-
});
|
|
3996
|
+
}));
|
|
3997
|
+
if (importers.recordRunChanges) await importers.recordRunChanges(changes);
|
|
3998
|
+
else for (const change of changes) await importers.recordRunChange(change);
|
|
2596
3999
|
const receipt = {
|
|
2597
4000
|
seq: flush.seq,
|
|
2598
4001
|
...applied.counts,
|
|
2599
4002
|
refused: applied.refused,
|
|
2600
|
-
pending: settled?.pending ?? false
|
|
4003
|
+
pending: settled?.pending ?? false,
|
|
4004
|
+
...applied.fallback ? { fallback: applied.fallback } : {}
|
|
2601
4005
|
};
|
|
2602
4006
|
await importers.recordFlush({
|
|
2603
4007
|
runId: run.id,
|
|
@@ -2608,7 +4012,8 @@ function createLocalKnowledgeImporterHost(writer, options) {
|
|
|
2608
4012
|
counts: {
|
|
2609
4013
|
...applied.counts,
|
|
2610
4014
|
refused: applied.refused.length,
|
|
2611
|
-
settled: settled?.settled ?? 0
|
|
4015
|
+
settled: settled?.settled ?? 0,
|
|
4016
|
+
...applied.fallback ? { fallbacks: 1 } : {}
|
|
2612
4017
|
}
|
|
2613
4018
|
});
|
|
2614
4019
|
if (applied.applied && !guard.firstWriteAt) await importers.markFirstWrite();
|
|
@@ -2623,6 +4028,7 @@ function createLocalKnowledgeImporterHost(writer, options) {
|
|
|
2623
4028
|
if (attempt >= MAX_LEASE_BOUND_ATTEMPTS) throw new KnowledgeImporterHostError("The flush could not be bounded by its run lease; resend it.", 503);
|
|
2624
4029
|
deadlineAt = Math.min(budgetAt, error.cutoff - LEASE_CUTOFF_MARGIN_MS);
|
|
2625
4030
|
}
|
|
4031
|
+
if (fallbackWarning) writer.warn(fallbackWarning);
|
|
2626
4032
|
await runEmbeds(storage, embeds);
|
|
2627
4033
|
return receipt;
|
|
2628
4034
|
} catch (error) {
|
|
@@ -3324,6 +4730,19 @@ var KnowledgeScopeRuntime = class {
|
|
|
3324
4730
|
};
|
|
3325
4731
|
for (const address of addresses) await this.#materialize(address, principals, provenance, [], run);
|
|
3326
4732
|
}
|
|
4733
|
+
/**
|
|
4734
|
+
* The parent address a first write would place a not-yet-created scope under, as `#materialize`
|
|
4735
|
+
* chooses it: a template child's own parent, or the one held `belongsTo` candidate. Undefined when
|
|
4736
|
+
* the scope would stay unlinked.
|
|
4737
|
+
*/
|
|
4738
|
+
firstWriteParentAddress(address, principals) {
|
|
4739
|
+
const match = this.compiled.match(address);
|
|
4740
|
+
if (!match) return void 0;
|
|
4741
|
+
if (match.compiled.child) return address.slice(0, address.lastIndexOf("/"));
|
|
4742
|
+
if (!match.compiled.belongsTo) return void 0;
|
|
4743
|
+
const candidates = this.#belongsToCandidates(match, this.#held(principals));
|
|
4744
|
+
return candidates.length === 1 && candidates[0] !== address ? candidates[0] : void 0;
|
|
4745
|
+
}
|
|
3327
4746
|
/** The run's distinct principals grouped by declaration key, matched once. */
|
|
3328
4747
|
#held(principals) {
|
|
3329
4748
|
const held = /* @__PURE__ */ new Map();
|
|
@@ -4269,9 +5688,24 @@ var Knowledge = class extends require_base.MastraBase {
|
|
|
4269
5688
|
write
|
|
4270
5689
|
};
|
|
4271
5690
|
}
|
|
4272
|
-
/**
|
|
4273
|
-
|
|
4274
|
-
|
|
5691
|
+
/** Whether the resolved mint declarations need metadata.persona. @internal */
|
|
5692
|
+
async __needsAgentPersona() {
|
|
5693
|
+
await this.#runtime.resolve();
|
|
5694
|
+
return [...this.#runtime.compiled.declarations.values()].some((declaration) => declaration.declaration.mint === "run-identity" && declaration.pattern.params.some((param) => param === "role" || param === "teamId"));
|
|
5695
|
+
}
|
|
5696
|
+
/**
|
|
5697
|
+
* The run's principals as a stable key, or `undefined` when the run has no Knowledge view (no scopes,
|
|
5698
|
+
* or an undeclared scope). Loads the store's declarations first, so a scope only the store declares
|
|
5699
|
+
* counts; a failure loading them rejects. @internal
|
|
5700
|
+
*/
|
|
5701
|
+
async __principalsKey(context) {
|
|
5702
|
+
await this.#runtime.resolve();
|
|
5703
|
+
try {
|
|
5704
|
+
return require_run_registry.knowledgeRunPrincipals(this.#runtime, context).sort().join("\n");
|
|
5705
|
+
} catch (error) {
|
|
5706
|
+
if (error instanceof require_run_registry.KnowledgeRunScopesError || error instanceof require_run_registry.KnowledgeDeclarationError) return void 0;
|
|
5707
|
+
throw error;
|
|
5708
|
+
}
|
|
4275
5709
|
}
|
|
4276
5710
|
/**
|
|
4277
5711
|
* The pinned pages a host-run caller with these principals receives, rendered as an agent run
|
|
@@ -4298,6 +5732,14 @@ var Knowledge = class extends require_base.MastraBase {
|
|
|
4298
5732
|
const run = await require_run_registry.KnowledgeRun.start(this.#runtime, await this.getStorage(), context);
|
|
4299
5733
|
return require_run_registry.knowledgeDeliveredPins(run, budget, this.#groups().read);
|
|
4300
5734
|
}
|
|
5735
|
+
/** The scopes a run holds a role on this turn, with that role. @internal */
|
|
5736
|
+
async __heldScopes(context) {
|
|
5737
|
+
const run = await require_run_registry.KnowledgeRun.start(this.#runtime, await this.getStorage(), context);
|
|
5738
|
+
return (await require_run_registry.heldScopes(run)).flatMap(({ address, role }) => role ? [{
|
|
5739
|
+
address,
|
|
5740
|
+
role
|
|
5741
|
+
}] : []);
|
|
5742
|
+
}
|
|
4301
5743
|
/** @internal */
|
|
4302
5744
|
__registerMastra(_mastra) {}
|
|
4303
5745
|
/** @internal */
|
|
@@ -4477,12 +5919,14 @@ exports.expandKnowledgeScope = require_run_registry.expandKnowledgeScope;
|
|
|
4477
5919
|
exports.importerHostConformance = importerHostConformance;
|
|
4478
5920
|
exports.inspectKnowledgeSchema = require_run_registry.inspectKnowledgeSchema;
|
|
4479
5921
|
exports.isKnowledgeScopeVisible = require_run_registry.isKnowledgeScopeVisible;
|
|
5922
|
+
exports.knowledgeAgentScopes = require_run_registry.knowledgeAgentScopes;
|
|
4480
5923
|
exports.knowledgeImportKey = knowledgeImportKey;
|
|
4481
5924
|
exports.knowledgeImporterFlushDigest = knowledgeImporterFlushDigest;
|
|
4482
5925
|
exports.knowledgeImporterRegistry = knowledgeImporterRegistry;
|
|
4483
5926
|
exports.knowledgeLinkRefKey = require_run_registry.knowledgeLinkRefKey;
|
|
4484
5927
|
exports.knowledgeMemoryScopes = require_run_registry.knowledgeMemoryScopes;
|
|
4485
5928
|
exports.knowledgePagePath = require_run_registry.knowledgePagePath;
|
|
5929
|
+
exports.knowledgePersonaScopes = require_run_registry.knowledgePersonaScopes;
|
|
4486
5930
|
exports.knowledgePinDepth = require_run_registry.knowledgePinDepth;
|
|
4487
5931
|
exports.knowledgePositionBetween = require_run_registry.knowledgePositionBetween;
|
|
4488
5932
|
exports.knowledgeScopeAddress = require_run_registry.knowledgeScopeAddress;
|