dsh-memu-memory 1.4.2 → 1.4.4
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/AGENTS.md +108 -110
- package/CHANGELOG.md +173 -868
- package/LICENSE +21 -21
- package/README.md +368 -374
- package/README.zh.md +354 -360
- package/assets/icon.svg +7 -7
- package/cordis.patch.yml +8 -8
- package/docs/active-memory-ab.md +279 -385
- package/docs/binding-lifecycle.md +99 -99
- package/docs/client-conventions.md +75 -75
- package/docs/contributing.md +217 -217
- package/docs/emotion-model-spec.md +247 -281
- package/docs/env-and-commands.md +149 -152
- package/docs/host-adaptation.md +339 -360
- package/docs/host-api.md +131 -137
- package/docs/host-versions.md +117 -120
- package/docs/mcp-porting.md +146 -146
- package/docs/memory-semantics.md +271 -259
- package/docs/pending-work.md +44 -51
- package/docs/troubleshooting.md +909 -854
- package/lib/active-memory.js +160 -165
- package/lib/activity-log.js +207 -207
- package/lib/auto-link/apply.js +248 -249
- package/lib/auto-link/candidates.js +163 -163
- package/lib/auto-link/decide.js +300 -300
- package/lib/auto-link/normalize.js +99 -99
- package/lib/auto-link/policy.js +42 -42
- package/lib/auto-link/suppression.js +101 -101
- package/lib/auto-link/terminology.js +311 -311
- package/lib/backup.js +1254 -1254
- package/lib/binding-diagnostics.js +634 -634
- package/lib/budget.js +118 -118
- package/lib/client.js +9820 -9751
- package/lib/commitment.js +178 -138
- package/lib/consolidation-ledger.js +434 -438
- package/lib/consolidation-receipt.js +386 -387
- package/lib/consolidation-snapshot.js +420 -405
- package/lib/consolidation-worker.js +240 -241
- package/lib/context.js +33 -33
- package/lib/curator-evidence.js +131 -131
- package/lib/curator-policy.js +198 -202
- package/lib/curator.js +1813 -1811
- package/lib/cycle.js +524 -513
- package/lib/diagnostics.js +524 -524
- package/lib/embedding-catalog.js +1051 -1055
- package/lib/embedding-download.js +637 -607
- package/lib/embedding-runtime.js +946 -946
- package/lib/engine.js +1103 -1103
- package/lib/entity-repair.js +285 -285
- package/lib/environment-check.js +394 -394
- package/lib/fork-model.js +312 -312
- package/lib/freshness.js +128 -121
- package/lib/global-graph.js +389 -389
- package/lib/graph.js +1193 -1193
- package/lib/host-surface.js +30 -30
- package/lib/inbound.js +284 -281
- package/lib/index.js +506 -511
- package/lib/inject.js +2639 -2619
- package/lib/lexicon-scope.js +143 -143
- package/lib/lexicon.js +1183 -1192
- package/lib/lifecycle-audit.js +37 -0
- package/lib/local-embedding-entry.js +145 -145
- package/lib/local-embedding-manager.js +306 -306
- package/lib/local-embedding-protocol.js +210 -210
- package/lib/local-embedding-worker.js +682 -682
- package/lib/local-vector-service.js +506 -453
- package/lib/maintenance-ledger.js +138 -0
- package/lib/maintenance-review.js +103 -0
- package/lib/maintenance-runner.js +267 -0
- package/lib/managed-runtime.js +118 -118
- package/lib/media.js +607 -513
- package/lib/memory.js +5035 -4941
- package/lib/memu-config.js +213 -213
- package/lib/memu.js +565 -565
- package/lib/migrate.js +200 -200
- package/lib/mood.js +300 -300
- package/lib/paths.js +453 -457
- package/lib/port-surface.js +82 -82
- package/lib/preset-mount.js +85 -0
- package/lib/preset-scope.js +126 -126
- package/lib/private-links.js +567 -567
- package/lib/private.js +2198 -2209
- package/lib/prompts/global-curator.md +135 -135
- package/lib/prompts/image-caption.md +1 -1
- package/lib/prompts/private-consolidation.coding.md +39 -39
- package/lib/prompts/private-consolidation.md +32 -32
- package/lib/prompts/private-consolidation.mixed.md +37 -37
- package/lib/prompts/private-consolidation.rp.md +47 -47
- package/lib/prompts/private-policy.coding.md +35 -35
- package/lib/prompts/private-policy.md +36 -36
- package/lib/prompts/private-policy.mixed.md +29 -29
- package/lib/prompts/private-policy.rp.md +43 -43
- package/lib/prompts/system-guide.coding.md +20 -20
- package/lib/prompts/system-guide.md +25 -25
- package/lib/prompts/system-guide.mixed.md +22 -22
- package/lib/prompts/system-guide.rp.md +23 -23
- package/lib/prompts.js +331 -331
- package/lib/recall-cache.js +212 -212
- package/lib/remote-summary.js +123 -123
- package/lib/rpc.js +2531 -2532
- package/lib/salient-wake.js +438 -438
- package/lib/snippet.js +125 -125
- package/lib/state.js +1948 -1928
- package/lib/stats.js +236 -236
- package/lib/temporal.js +345 -348
- package/lib/text-retrieval.js +992 -1001
- package/lib/text-similarity.js +305 -305
- package/lib/tokenizer-v2.js +271 -271
- package/lib/tools.js +1098 -1091
- package/lib/turn-log.js +545 -545
- package/lib/vector-migration.js +928 -930
- package/lib/vector-profile.js +1353 -1359
- package/lib/visibility.js +59 -59
- package/lib/webui/graph-LICENSE.txt +1 -1
- package/lib/webui/graph-view.bundle.js +2 -2
- package/lib/webui/graph-view.js +1171 -1175
- package/lib/webui/mark.svg +7 -7
- package/lib/webui/standalone.css +1178 -1178
- package/lib/webui/standalone.js +238 -238
- package/lib/webui.js +136 -136
- package/lib/worker-pool.js +1020 -979
- package/package.json +153 -153
- package/requirements.lock +34 -34
- package/scripts/acceptance-local.mjs +946 -946
- package/scripts/active-memory-ab-live.mjs +653 -655
- package/scripts/active-memory-ab.mjs +1302 -1302
- package/scripts/audit-memory-lifecycle.mjs +55 -0
- package/scripts/bench-recall.mjs +142 -142
- package/scripts/build-graph.mjs +44 -45
- package/scripts/chain-matrix.mjs +541 -541
- package/scripts/check-all.mjs +68 -74
- package/scripts/check-doc-drift.mjs +547 -547
- package/scripts/check-graph-browser.mjs +261 -261
- package/scripts/check-i18n.mjs +81 -83
- package/scripts/check-idle-compositing.mjs +61 -61
- package/scripts/check-seed-compat.mjs +115 -118
- package/scripts/check-text-format.mjs +55 -0
- package/scripts/curator-pair-calibrate.mjs +259 -259
- package/scripts/diagnose-bindings.mjs +176 -176
- package/scripts/drive-session.mjs +863 -864
- package/scripts/engine-smoke.mjs +69 -69
- package/scripts/entity-dedupe.mjs +110 -110
- package/scripts/lexicon-calibrate.mjs +230 -230
- package/scripts/lexicon-dedupe.mjs +318 -318
- package/scripts/local-runtime-install.mjs +142 -142
- package/scripts/local-runtime-verify.mjs +56 -56
- package/scripts/local-vector-verify.mjs +93 -93
- package/scripts/make-readme-shots.mjs +59 -59
- package/scripts/migrate-visibility.mjs +94 -94
- package/scripts/mock-llm.mjs +938 -903
- package/scripts/preview.mjs +58 -58
- package/scripts/prune-sessions.mjs +31 -34
- package/scripts/prune-turnlogs.mjs +29 -30
- package/scripts/prune-vectors.mjs +24 -24
- package/scripts/rebuild-auto-links.mjs +252 -252
- package/scripts/recall-bench.mjs +820 -820
- package/scripts/repetition-ab-scenarios.mjs +93 -93
- package/scripts/repetition-detector-snapshot.mjs +314 -314
- package/scripts/repetition-eval-live.mjs +360 -360
- package/scripts/repetition-eval.mjs +702 -702
- package/scripts/replay.mjs +705 -575
- package/scripts/setup.mjs +46 -46
- package/scripts/simulate-injection.mjs +299 -301
- package/tests/absorb-review.test.mjs +354 -354
- package/tests/activation.test.mjs +89 -89
- package/tests/active-memory-ab.test.mjs +745 -745
- package/tests/active-memory.test.mjs +129 -129
- package/tests/activity-log.test.mjs +126 -126
- package/tests/activity-wiring.test.mjs +155 -155
- package/tests/appendix-b.test.mjs +217 -217
- package/tests/appendix-b2.test.mjs +166 -166
- package/tests/audit-batch3.test.mjs +247 -247
- package/tests/audit-regression.test.mjs +275 -275
- package/tests/audit-safety.test.mjs +227 -227
- package/tests/auto-link-candidates.test.mjs +245 -245
- package/tests/auto-link-decide.test.mjs +512 -512
- package/tests/auto-link-migration.test.mjs +133 -133
- package/tests/backend-compensation.test.mjs +272 -272
- package/tests/backup.test.mjs +793 -793
- package/tests/binding-diagnostics.test.mjs +720 -720
- package/tests/browser.test.mjs +476 -476
- package/tests/client-export.test.mjs +521 -521
- package/tests/client-render.test.mjs +2008 -1728
- package/tests/coalesce.test.mjs +113 -113
- package/tests/commitment.test.mjs +243 -144
- package/tests/config.test.mjs +159 -159
- package/tests/consolidation-credential.test.mjs +330 -330
- package/tests/consolidation-feed.test.mjs +122 -122
- package/tests/consolidation-fork.test.mjs +1587 -1539
- package/tests/consolidation-ledger.test.mjs +389 -389
- package/tests/consolidation-snapshot.test.mjs +567 -505
- package/tests/consolidation-value.test.mjs +89 -89
- package/tests/context-scope.test.mjs +40 -40
- package/tests/cross-library-recall.test.mjs +269 -269
- package/tests/cue.test.mjs +58 -58
- package/tests/curator-absorb.test.mjs +444 -444
- package/tests/curator-calibrate.test.mjs +173 -173
- package/tests/curator-clusters.test.mjs +306 -306
- package/tests/curator-commit.test.mjs +325 -325
- package/tests/curator-contract.test.mjs +191 -191
- package/tests/curator-evidence.test.mjs +102 -102
- package/tests/curator-link.test.mjs +317 -317
- package/tests/curator-pairing.test.mjs +339 -339
- package/tests/curator-probe.test.mjs +490 -490
- package/tests/curator-review-mode.test.mjs +315 -315
- package/tests/curator.test.mjs +152 -152
- package/tests/cycle.test.mjs +567 -568
- package/tests/diagnostics.test.mjs +278 -278
- package/tests/disclosure.test.mjs +249 -249
- package/tests/doc-drift.test.mjs +342 -342
- package/tests/drive-session.test.mjs +152 -152
- package/tests/dynamic-rrf.test.mjs +182 -182
- package/tests/dynamic-threshold.test.mjs +52 -52
- package/tests/embedding-catalog.test.mjs +374 -374
- package/tests/embedding-download.test.mjs +529 -486
- package/tests/embedding-runtime.test.mjs +449 -449
- package/tests/emotion-chain.test.mjs +84 -84
- package/tests/emotion-contract.test.mjs +445 -445
- package/tests/engine.test.mjs +108 -108
- package/tests/entity-merge.test.mjs +278 -278
- package/tests/environment-check.test.mjs +187 -187
- package/tests/fact-version.test.mjs +146 -146
- package/tests/fixtures/active-memory-ab/README.md +56 -56
- package/tests/fixtures/active-memory-ab/cases/01-clean-dense-turn.json +351 -351
- package/tests/fixtures/active-memory-ab/cases/02-clean-thin-turn.json +122 -122
- package/tests/fixtures/active-memory-ab/cases/03-clean-starved-small.json +125 -125
- package/tests/fixtures/active-memory-ab/cases/04-clean-large-thin.json +137 -137
- package/tests/fixtures/active-memory-ab/cases/05-clean-half-step.json +166 -166
- package/tests/fixtures/active-memory-ab/cases/06-clean-duplicate-reread.json +197 -197
- package/tests/fixtures/active-memory-ab/cases/07-clean-recent-recall.json +125 -125
- package/tests/fixtures/active-memory-ab/cases/08-global-relevant.json +111 -111
- package/tests/fixtures/active-memory-ab/cases/09-global-irrelevant-conflict.json +158 -158
- package/tests/fixtures/active-memory-ab/cases/10-no-human-turn.json +97 -97
- package/tests/fixtures/active-memory-ab/cases/11-clean-scale-100.json +137 -137
- package/tests/fixtures/active-memory-ab/cases/12-clean-scale-1000.json +137 -137
- package/tests/fixtures/active-memory-ab/cases/13-clean-scale-5000.json +137 -137
- package/tests/fixtures/active-memory-ab/cases/14-clean-scale-20000.json +137 -137
- package/tests/fixtures/active-memory-ab/lead-ai-reviewed-reference.json +191 -191
- package/tests/fixtures/active-memory-ab/manifest.json +199 -199
- package/tests/fixtures/curator-pairs/labeled.v1.jsonl +90 -90
- package/tests/fixtures/lexicon-stub-hooks.mjs +15 -15
- package/tests/fixtures/lexicon-stub.mjs +284 -284
- package/tests/fixtures/mock-llm/reply.txt +1 -1
- package/tests/fixtures/recall-bench/01-paraphrase.json +183 -183
- package/tests/fixtures/recall-bench/02-exact.json +152 -152
- package/tests/fixtures/recall-bench/03-negation.json +172 -172
- package/tests/fixtures/recall-bench/04-no-answer.json +161 -161
- package/tests/fixtures/recall-bench/05-conflict.json +193 -193
- package/tests/fixtures/recall-bench/06-boundary.json +272 -272
- package/tests/fixtures/recall-bench/07-secret.json +190 -190
- package/tests/fixtures/recall-bench/08-coding.json +163 -163
- package/tests/fixtures/recall-bench-gold-candidates/01-paraphrase.json +193 -193
- package/tests/fixtures/recall-bench-gold-candidates/02-exact.json +197 -197
- package/tests/fixtures/recall-bench-gold-candidates/03-negation.json +244 -244
- package/tests/fixtures/recall-bench-gold-candidates/04-no-answer.json +189 -189
- package/tests/fixtures/recall-bench-gold-candidates/05-conflict.json +245 -245
- package/tests/fixtures/recall-bench-gold-candidates/06-boundary.json +279 -279
- package/tests/fixtures/recall-bench-gold-candidates/07-secret.json +224 -224
- package/tests/fixtures/recall-bench-gold-candidates/08-coding.json +218 -218
- package/tests/fixtures/repetition-eval/01-zh-rp.json +92 -92
- package/tests/fixtures/repetition-eval/02-en.json +96 -96
- package/tests/fixtures/repetition-eval/03-code.json +90 -90
- package/tests/fixtures/repetition-eval/04-names.json +115 -115
- package/tests/fixtures/repetition-eval/05-user-quote.json +95 -95
- package/tests/fixtures/repetition-eval/06-agreement.json +85 -85
- package/tests/fixtures/tokenizer-cases.mjs +27 -27
- package/tests/fork-model.test.mjs +345 -345
- package/tests/freshness.test.mjs +140 -140
- package/tests/global-graph.test.mjs +106 -106
- package/tests/global-lifecycle.test.mjs +149 -149
- package/tests/graph-cascade.test.mjs +363 -363
- package/tests/graph-view.test.mjs +414 -414
- package/tests/graph.test.mjs +371 -371
- package/tests/help-page.test.mjs +416 -416
- package/tests/hook-order.test.mjs +72 -72
- package/tests/humanlike.test.mjs +232 -232
- package/tests/hybrid-recall.test.mjs +610 -610
- package/tests/inbound.test.mjs +441 -441
- package/tests/inject-conflict.test.mjs +173 -173
- package/tests/inject-guide.test.mjs +513 -513
- package/tests/inject.test.mjs +384 -384
- package/tests/injection-budget-settings.test.mjs +35 -35
- package/tests/injection-budget.test.mjs +165 -165
- package/tests/injection-chain.test.mjs +442 -442
- package/tests/injection-intent-budget.test.mjs +92 -92
- package/tests/injection-rollback.test.mjs +428 -428
- package/tests/issue2-chain.test.mjs +169 -169
- package/tests/lexical-bm25.test.mjs +171 -171
- package/tests/lexicon-calibrate.test.mjs +48 -48
- package/tests/lexicon-dedupe.test.mjs +171 -171
- package/tests/lexicon-frequency.test.mjs +195 -195
- package/tests/lexicon-inject.test.mjs +459 -459
- package/tests/lexicon-perf.test.mjs +464 -464
- package/tests/lexicon-scope.test.mjs +256 -256
- package/tests/lexicon-ui.test.mjs +667 -667
- package/tests/lexicon.test.mjs +922 -922
- package/tests/lifecycle-audit.test.mjs +56 -0
- package/tests/loader-register.mjs +3 -3
- package/tests/loader.mjs +17 -17
- package/tests/local-embedding-entry.test.mjs +95 -95
- package/tests/local-embedding-env.test.mjs +51 -51
- package/tests/local-embedding-manager.test.mjs +494 -494
- package/tests/local-embedding-protocol.test.mjs +121 -121
- package/tests/local-embedding-worker.test.mjs +440 -440
- package/tests/local-vector-service.test.mjs +41 -0
- package/tests/maintenance-status.test.mjs +77 -0
- package/tests/maintenance.test.mjs +438 -0
- package/tests/managed-memory.test.mjs +1234 -1234
- package/tests/managed-runtime.test.mjs +72 -72
- package/tests/media-injection.test.mjs +225 -0
- package/tests/media.test.mjs +135 -135
- package/tests/memory-chain.test.mjs +169 -169
- package/tests/memory-fields.test.mjs +134 -134
- package/tests/memu-resident-route.test.mjs +130 -130
- package/tests/memu-resident.test.mjs +33 -33
- package/tests/migration-payload.test.mjs +40 -42
- package/tests/mock-llm.test.mjs +263 -225
- package/tests/mood.test.mjs +109 -109
- package/tests/multiprocess.test.mjs +29 -29
- package/tests/negation-polarity.test.mjs +135 -135
- package/tests/new-session-gate.test.mjs +617 -617
- package/tests/open-loop-date.test.mjs +416 -416
- package/tests/ops-hardening.test.mjs +209 -209
- package/tests/package-shipping.test.mjs +88 -88
- package/tests/pending-injection.test.mjs +107 -107
- package/tests/port-surface.test.mjs +138 -138
- package/tests/preset-mount.test.mjs +132 -0
- package/tests/preset-scope.test.mjs +212 -212
- package/tests/private-links.test.mjs +493 -493
- package/tests/prompt-semantics.test.mjs +51 -51
- package/tests/prompts.test.mjs +315 -315
- package/tests/query-decompose.test.mjs +62 -62
- package/tests/react-snapshot.test.mjs +24 -24
- package/tests/recall-bench.test.mjs +317 -317
- package/tests/recall-cache.test.mjs +292 -292
- package/tests/recall-corpus-eligibility.test.mjs +51 -51
- package/tests/recall-dedup.test.mjs +446 -446
- package/tests/recall-intent.test.mjs +172 -172
- package/tests/regression-sweep.test.mjs +311 -311
- package/tests/reminder-fairness.test.mjs +55 -0
- package/tests/remote.test.mjs +140 -140
- package/tests/rename.test.mjs +30 -30
- package/tests/repetition-detector-snapshot.test.mjs +231 -231
- package/tests/repetition-eval-live.test.mjs +177 -177
- package/tests/repetition-eval.test.mjs +373 -373
- package/tests/salience-domain.test.mjs +173 -173
- package/tests/salient-date.test.mjs +142 -142
- package/tests/salient-wake.test.mjs +389 -389
- package/tests/settings-beat.test.mjs +222 -222
- package/tests/settings-coverage.test.mjs +97 -97
- package/tests/settings-plumbing.test.mjs +79 -79
- package/tests/short-term.test.mjs +182 -166
- package/tests/sidebar-beat.test.mjs +213 -213
- package/tests/sidebar-refresh.test.mjs +123 -123
- package/tests/sidebar.test.mjs +102 -74
- package/tests/simulate-injection.test.mjs +76 -76
- package/tests/slot-similarity.test.mjs +153 -153
- package/tests/snippet.test.mjs +79 -79
- package/tests/source-kind.test.mjs +52 -52
- package/tests/speaker-provenance.test.mjs +120 -120
- package/tests/stale-maintenance.test.mjs +206 -131
- package/tests/state-gc.test.mjs +34 -34
- package/tests/state.test.mjs +155 -155
- package/tests/stats.test.mjs +112 -112
- package/tests/storage.test.mjs +125 -125
- package/tests/stubs/child-process-spy.mjs +14 -14
- package/tests/stubs/dsh-llm-pi-ai.js +13 -13
- package/tests/stubs/dsh-llm.js +5 -5
- package/tests/stubs/dsh-schedule.js +140 -140
- package/tests/stubs/dsh-session-query.js +26 -26
- package/tests/stubs/dsh-session.js +7 -7
- package/tests/stubs/dsh-tools.js +101 -101
- package/tests/temporal-repair.test.mjs +78 -0
- package/tests/temporal.test.mjs +124 -124
- package/tests/text-format.test.mjs +24 -0
- package/tests/tokenizer-v2.test.mjs +142 -142
- package/tests/tool-schema.test.mjs +126 -126
- package/tests/tools.test.mjs +810 -810
- package/tests/turn-log.test.mjs +487 -487
- package/tests/ui-defaults.test.mjs +57 -57
- package/tests/update-fields.test.mjs +138 -138
- package/tests/vector-gc.test.mjs +37 -37
- package/tests/vector-migration.test.mjs +810 -810
- package/tests/vector-profile.test.mjs +449 -449
- package/tests/visibility-migration.test.mjs +152 -152
- package/tests/webui-auth.test.mjs +963 -963
- package/tests/webui.test.mjs +421 -421
- package/tests/windows-env.test.mjs +89 -89
- package/tests/worker-lifecycle.test.mjs +1522 -1429
package/lib/vector-profile.js
CHANGED
|
@@ -1,1359 +1,1353 @@
|
|
|
1
|
-
import fs from 'node:fs'
|
|
2
|
-
import path from 'node:path'
|
|
3
|
-
import crypto from 'node:crypto'
|
|
4
|
-
import {
|
|
5
|
-
dataDir, librariesDir, indexDir, ensureDir, downloadsDir,
|
|
6
|
-
readJsonStrict, writeJson, withFileLock, stamp, isSafeId, warn,
|
|
7
|
-
} from './paths.js'
|
|
8
|
-
import {
|
|
9
|
-
PROVIDER_ORDER, getEmbeddingModel, profileFingerprint, validateEmbeddingManifest,
|
|
10
|
-
} from './embedding-catalog.js'
|
|
11
|
-
|
|
12
|
-
// §14.8 向量空间身份、代际选择与写入护栏。
|
|
13
|
-
//
|
|
14
|
-
// 本模块只回答四件事:
|
|
15
|
-
// 1. 一个 profile 的身份是什么(fingerprint 直接复用 embedding-catalog 的协议,不另立一套);
|
|
16
|
-
// 2. 当前 active 代际是哪一个(单个 index/vector-active.json 原子选择 profile + DB 集合);
|
|
17
|
-
// 3. 用户"想要"的 profile(requested)与真正生效的 profile 分离;
|
|
18
|
-
// 4. 此刻允不允许写向量(护栏:未验证/未就绪/pending/撕裂一律拒绝,且拒绝必须可退词法,
|
|
19
|
-
// 绝不能悄悄回落成 legacy 远端嵌入)。
|
|
20
|
-
//
|
|
21
|
-
// 硬约束(来自 §14.8):
|
|
22
|
-
// * profile 只依赖 paths/catalog,不依赖 state.json;本模块不读 state。
|
|
23
|
-
// * 文件锁只在最后短窗口内做同步 compare + 原子写指针;整个模块没有 await 跨锁。
|
|
24
|
-
// * 所有 DB 路径都从 active manifest 的 database-set 一次性取得,避免逐个库换导致混空间。
|
|
25
|
-
// * 全局库影子也放 librariesDir():backupDatabases 只扫 libraries/*.sqlite3 与 index/*.json,
|
|
26
|
-
// 放 data 根目录会被备份漏掉(§14.9 第 6 条要求备份包含 vector active profile manifest)。
|
|
27
|
-
|
|
28
|
-
export const VECTOR_ACTIVE_FILE = 'vector-active.json'
|
|
29
|
-
export const VECTOR_ACTIVE_SCHEMA = 1
|
|
30
|
-
|
|
31
|
-
export const VECTOR_ERROR_CODES = Object.freeze({
|
|
32
|
-
PROFILE_MISSING: 'VECTOR_PROFILE_MISSING',
|
|
33
|
-
PROFILE_UNKNOWN: 'VECTOR_PROFILE_UNKNOWN',
|
|
34
|
-
PROFILE_PENDING: 'VECTOR_PROFILE_PENDING',
|
|
35
|
-
PROFILE_UNVERIFIED: 'VECTOR_PROFILE_UNVERIFIED',
|
|
36
|
-
PROFILE_FINGERPRINT_MISMATCH: 'VECTOR_PROFILE_FINGERPRINT_MISMATCH',
|
|
37
|
-
PROFILE_MANIFEST_CHANGED: 'VECTOR_PROFILE_MANIFEST_CHANGED',
|
|
38
|
-
ACTIVE_CORRUPT: 'VECTOR_ACTIVE_CORRUPT',
|
|
39
|
-
ACTIVE_UNREADABLE: 'VECTOR_ACTIVE_UNREADABLE',
|
|
40
|
-
NOT_ACTIVE: 'VECTOR_NOT_ACTIVE',
|
|
41
|
-
TORN_STATE: 'VECTOR_TORN_STATE',
|
|
42
|
-
STALE_GENERATION: 'VECTOR_STALE_GENERATION',
|
|
43
|
-
NO_GENERATION: 'VECTOR_NO_GENERATION',
|
|
44
|
-
SHADOW_PATH_TAKEN: 'VECTOR_SHADOW_PATH_TAKEN',
|
|
45
|
-
PATH_ESCAPE: 'VECTOR_PATH_ESCAPE',
|
|
46
|
-
BAD_UPDATE: 'VECTOR_BAD_UPDATE',
|
|
47
|
-
})
|
|
48
|
-
|
|
49
|
-
/**
|
|
50
|
-
* 向量状态错误:带 code + fallback='lexical' + forbidLegacyRemote。
|
|
51
|
-
* 调用方一旦看到 isVectorStateError(e) 为真,就只能退化成词法召回,
|
|
52
|
-
* 不允许把同一批查询发去 legacy/远端嵌入(那会把两种向量空间混在一个库里)。
|
|
53
|
-
*/
|
|
54
|
-
export class VectorStateError extends Error {
|
|
55
|
-
constructor(code, message, extra = {}) {
|
|
56
|
-
super(message)
|
|
57
|
-
this.name = 'VectorStateError'
|
|
58
|
-
this.code = code
|
|
59
|
-
this.fallback = 'lexical'
|
|
60
|
-
this.forbidLegacyRemote = true
|
|
61
|
-
for (const [key, value] of Object.entries(extra)) if (value !== undefined) this[key] = value
|
|
62
|
-
}
|
|
63
|
-
}
|
|
64
|
-
|
|
65
|
-
export function vectorError(code, message, extra) {
|
|
66
|
-
return new VectorStateError(code, message, extra)
|
|
67
|
-
}
|
|
68
|
-
|
|
69
|
-
export function isVectorStateError(value) {
|
|
70
|
-
if (value instanceof VectorStateError) return true
|
|
71
|
-
return typeof value?.code === 'string' && value.code.startsWith('VECTOR_')
|
|
72
|
-
}
|
|
73
|
-
|
|
74
|
-
// ---------------------------------------------------------------- 规范化哈希
|
|
75
|
-
|
|
76
|
-
/**
|
|
77
|
-
* 规范化 JSON 序列化:键排序、undefined 省略。与 embedding-catalog 内部 canonical()
|
|
78
|
-
* 同一协议(那里没有导出),保证"同一个 manifest 在任何模块里哈希都相同"。
|
|
79
|
-
*/
|
|
80
|
-
export function stableStringify(value) {
|
|
81
|
-
if (Array.isArray(value)) return '[' + value.map(stableStringify).join(',') + ']'
|
|
82
|
-
if (value && typeof value === 'object') {
|
|
83
|
-
return '{' + Object.keys(value).sort()
|
|
84
|
-
.filter(key => value[key] !== undefined)
|
|
85
|
-
.map(key => JSON.stringify(key) + ':' + stableStringify(value[key]))
|
|
86
|
-
.join(',') + '}'
|
|
87
|
-
}
|
|
88
|
-
return JSON.stringify(value === undefined ? null : value)
|
|
89
|
-
}
|
|
90
|
-
|
|
91
|
-
export function sha256Hex(value) {
|
|
92
|
-
return crypto.createHash('sha256').update(value).digest('hex')
|
|
93
|
-
}
|
|
94
|
-
|
|
95
|
-
/**
|
|
96
|
-
*
|
|
97
|
-
*
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
//
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
//
|
|
107
|
-
//
|
|
108
|
-
//
|
|
109
|
-
|
|
110
|
-
//
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
const
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
return
|
|
140
|
-
}
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
return
|
|
156
|
-
}
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
return
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
return
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
}
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
*
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
const
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
export function
|
|
253
|
-
catalogEntryResolver =
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
export function
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
}
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
const
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
:
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
: null
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
})
|
|
394
|
-
}
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
return assertProfileVerified(
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
}
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
if (
|
|
440
|
-
|
|
441
|
-
}
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
}
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
if (path.
|
|
457
|
-
throw vectorError(VECTOR_ERROR_CODES.PATH_ESCAPE, 'vector storage
|
|
458
|
-
}
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
export function
|
|
468
|
-
return
|
|
469
|
-
}
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
&&
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
|
|
510
|
-
|
|
511
|
-
|
|
512
|
-
|
|
513
|
-
*
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
|
|
519
|
-
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
|
|
547
|
-
|
|
548
|
-
|
|
549
|
-
|
|
550
|
-
|
|
551
|
-
throw vectorError(VECTOR_ERROR_CODES.TORN_STATE, '
|
|
552
|
-
|
|
553
|
-
|
|
554
|
-
|
|
555
|
-
|
|
556
|
-
|
|
557
|
-
|
|
558
|
-
|
|
559
|
-
|
|
560
|
-
|
|
561
|
-
|
|
562
|
-
|
|
563
|
-
|
|
564
|
-
|
|
565
|
-
|
|
566
|
-
|
|
567
|
-
|
|
568
|
-
|
|
569
|
-
|
|
570
|
-
|
|
571
|
-
|
|
572
|
-
|
|
573
|
-
|
|
574
|
-
}
|
|
575
|
-
}
|
|
576
|
-
|
|
577
|
-
/**
|
|
578
|
-
|
|
579
|
-
|
|
580
|
-
|
|
581
|
-
|
|
582
|
-
|
|
583
|
-
|
|
584
|
-
|
|
585
|
-
|
|
586
|
-
|
|
587
|
-
|
|
588
|
-
|
|
589
|
-
|
|
590
|
-
|
|
591
|
-
|
|
592
|
-
|
|
593
|
-
if (result.
|
|
594
|
-
|
|
595
|
-
|
|
596
|
-
}
|
|
597
|
-
|
|
598
|
-
|
|
599
|
-
|
|
600
|
-
|
|
601
|
-
|
|
602
|
-
|
|
603
|
-
|
|
604
|
-
|
|
605
|
-
const
|
|
606
|
-
|
|
607
|
-
|
|
608
|
-
|
|
609
|
-
|
|
610
|
-
|
|
611
|
-
|
|
612
|
-
|
|
613
|
-
|
|
614
|
-
|
|
615
|
-
|
|
616
|
-
|
|
617
|
-
|
|
618
|
-
|
|
619
|
-
|
|
620
|
-
|
|
621
|
-
|
|
622
|
-
|
|
623
|
-
|
|
624
|
-
|
|
625
|
-
|
|
626
|
-
|
|
627
|
-
|
|
628
|
-
|
|
629
|
-
|
|
630
|
-
}))
|
|
631
|
-
return next.requested
|
|
632
|
-
}
|
|
633
|
-
|
|
634
|
-
|
|
635
|
-
|
|
636
|
-
|
|
637
|
-
|
|
638
|
-
|
|
639
|
-
|
|
640
|
-
|
|
641
|
-
|
|
642
|
-
|
|
643
|
-
|
|
644
|
-
return state
|
|
645
|
-
}
|
|
646
|
-
|
|
647
|
-
|
|
648
|
-
|
|
649
|
-
|
|
650
|
-
|
|
651
|
-
|
|
652
|
-
|
|
653
|
-
|
|
654
|
-
|
|
655
|
-
*
|
|
656
|
-
|
|
657
|
-
|
|
658
|
-
|
|
659
|
-
|
|
660
|
-
|
|
661
|
-
|
|
662
|
-
|
|
663
|
-
|
|
664
|
-
|
|
665
|
-
|
|
666
|
-
|
|
667
|
-
|
|
668
|
-
|
|
669
|
-
|
|
670
|
-
|
|
671
|
-
|
|
672
|
-
|
|
673
|
-
|
|
674
|
-
|
|
675
|
-
|
|
676
|
-
|
|
677
|
-
|
|
678
|
-
|
|
679
|
-
|
|
680
|
-
|
|
681
|
-
|
|
682
|
-
|
|
683
|
-
|
|
684
|
-
|
|
685
|
-
|
|
686
|
-
|
|
687
|
-
|
|
688
|
-
|
|
689
|
-
|
|
690
|
-
|
|
691
|
-
|
|
692
|
-
|
|
693
|
-
|
|
694
|
-
|
|
695
|
-
|
|
696
|
-
|
|
697
|
-
}
|
|
698
|
-
|
|
699
|
-
|
|
700
|
-
|
|
701
|
-
|
|
702
|
-
|
|
703
|
-
|
|
704
|
-
|
|
705
|
-
|
|
706
|
-
const
|
|
707
|
-
|
|
708
|
-
|
|
709
|
-
|
|
710
|
-
|
|
711
|
-
|
|
712
|
-
|
|
713
|
-
|
|
714
|
-
|
|
715
|
-
|
|
716
|
-
|
|
717
|
-
|
|
718
|
-
|
|
719
|
-
|
|
720
|
-
|
|
721
|
-
|
|
722
|
-
|
|
723
|
-
|
|
724
|
-
return
|
|
725
|
-
}
|
|
726
|
-
|
|
727
|
-
|
|
728
|
-
|
|
729
|
-
|
|
730
|
-
|
|
731
|
-
|
|
732
|
-
|
|
733
|
-
|
|
734
|
-
|
|
735
|
-
|
|
736
|
-
|
|
737
|
-
|
|
738
|
-
|
|
739
|
-
|
|
740
|
-
|
|
741
|
-
|
|
742
|
-
|
|
743
|
-
|
|
744
|
-
|
|
745
|
-
|
|
746
|
-
|
|
747
|
-
|
|
748
|
-
|
|
749
|
-
} catch {}
|
|
750
|
-
|
|
751
|
-
|
|
752
|
-
|
|
753
|
-
|
|
754
|
-
|
|
755
|
-
|
|
756
|
-
|
|
757
|
-
|
|
758
|
-
|
|
759
|
-
|
|
760
|
-
|
|
761
|
-
|
|
762
|
-
|
|
763
|
-
|
|
764
|
-
|
|
765
|
-
|
|
766
|
-
|
|
767
|
-
|
|
768
|
-
|
|
769
|
-
|
|
770
|
-
|
|
771
|
-
|
|
772
|
-
|
|
773
|
-
|
|
774
|
-
|
|
775
|
-
|
|
776
|
-
|
|
777
|
-
|
|
778
|
-
|
|
779
|
-
|
|
780
|
-
|
|
781
|
-
|
|
782
|
-
|
|
783
|
-
|
|
784
|
-
|
|
785
|
-
|
|
786
|
-
|
|
787
|
-
|
|
788
|
-
}
|
|
789
|
-
|
|
790
|
-
|
|
791
|
-
|
|
792
|
-
|
|
793
|
-
|
|
794
|
-
|
|
795
|
-
|
|
796
|
-
|
|
797
|
-
|
|
798
|
-
|
|
799
|
-
|
|
800
|
-
|
|
801
|
-
|
|
802
|
-
|
|
803
|
-
|
|
804
|
-
|
|
805
|
-
|
|
806
|
-
|
|
807
|
-
|
|
808
|
-
|
|
809
|
-
|
|
810
|
-
|
|
811
|
-
|
|
812
|
-
|
|
813
|
-
|
|
814
|
-
|
|
815
|
-
|
|
816
|
-
|
|
817
|
-
|
|
818
|
-
|
|
819
|
-
|
|
820
|
-
|
|
821
|
-
|
|
822
|
-
|
|
823
|
-
|
|
824
|
-
|
|
825
|
-
|
|
826
|
-
|
|
827
|
-
|
|
828
|
-
|
|
829
|
-
|
|
830
|
-
|
|
831
|
-
|
|
832
|
-
|
|
833
|
-
|
|
834
|
-
|
|
835
|
-
|
|
836
|
-
|
|
837
|
-
|
|
838
|
-
|
|
839
|
-
|
|
840
|
-
|
|
841
|
-
|
|
842
|
-
|
|
843
|
-
|
|
844
|
-
|
|
845
|
-
|
|
846
|
-
|
|
847
|
-
|
|
848
|
-
|
|
849
|
-
|
|
850
|
-
|
|
851
|
-
|
|
852
|
-
|
|
853
|
-
|
|
854
|
-
|
|
855
|
-
|
|
856
|
-
|
|
857
|
-
|
|
858
|
-
|
|
859
|
-
|
|
860
|
-
|
|
861
|
-
|
|
862
|
-
|
|
863
|
-
|
|
864
|
-
|
|
865
|
-
|
|
866
|
-
|
|
867
|
-
|
|
868
|
-
|
|
869
|
-
|
|
870
|
-
|
|
871
|
-
|
|
872
|
-
|
|
873
|
-
/**
|
|
874
|
-
*
|
|
875
|
-
*
|
|
876
|
-
*
|
|
877
|
-
|
|
878
|
-
|
|
879
|
-
|
|
880
|
-
|
|
881
|
-
|
|
882
|
-
|
|
883
|
-
|
|
884
|
-
|
|
885
|
-
|
|
886
|
-
|
|
887
|
-
|
|
888
|
-
|
|
889
|
-
|
|
890
|
-
|
|
891
|
-
|
|
892
|
-
|
|
893
|
-
|
|
894
|
-
|
|
895
|
-
|
|
896
|
-
|
|
897
|
-
|
|
898
|
-
|
|
899
|
-
|
|
900
|
-
|
|
901
|
-
|
|
902
|
-
|
|
903
|
-
|
|
904
|
-
}
|
|
905
|
-
|
|
906
|
-
|
|
907
|
-
|
|
908
|
-
|
|
909
|
-
|
|
910
|
-
if (
|
|
911
|
-
const
|
|
912
|
-
|
|
913
|
-
|
|
914
|
-
|
|
915
|
-
|
|
916
|
-
|
|
917
|
-
|
|
918
|
-
|
|
919
|
-
|
|
920
|
-
|
|
921
|
-
|
|
922
|
-
|
|
923
|
-
|
|
924
|
-
|
|
925
|
-
|
|
926
|
-
}
|
|
927
|
-
|
|
928
|
-
|
|
929
|
-
|
|
930
|
-
|
|
931
|
-
|
|
932
|
-
|
|
933
|
-
|
|
934
|
-
|
|
935
|
-
|
|
936
|
-
|
|
937
|
-
|
|
938
|
-
|
|
939
|
-
|
|
940
|
-
|
|
941
|
-
|
|
942
|
-
|
|
943
|
-
|
|
944
|
-
|
|
945
|
-
|
|
946
|
-
|
|
947
|
-
|
|
948
|
-
|
|
949
|
-
}
|
|
950
|
-
|
|
951
|
-
|
|
952
|
-
|
|
953
|
-
|
|
954
|
-
|
|
955
|
-
|
|
956
|
-
|
|
957
|
-
|
|
958
|
-
|
|
959
|
-
|
|
960
|
-
|
|
961
|
-
|
|
962
|
-
|
|
963
|
-
|
|
964
|
-
|
|
965
|
-
|
|
966
|
-
|
|
967
|
-
|
|
968
|
-
|
|
969
|
-
|
|
970
|
-
|
|
971
|
-
|
|
972
|
-
|
|
973
|
-
|
|
974
|
-
const
|
|
975
|
-
|
|
976
|
-
|
|
977
|
-
}
|
|
978
|
-
|
|
979
|
-
|
|
980
|
-
|
|
981
|
-
|
|
982
|
-
|
|
983
|
-
|
|
984
|
-
|
|
985
|
-
|
|
986
|
-
|
|
987
|
-
|
|
988
|
-
|
|
989
|
-
|
|
990
|
-
|
|
991
|
-
|
|
992
|
-
|
|
993
|
-
|
|
994
|
-
|
|
995
|
-
|
|
996
|
-
|
|
997
|
-
|
|
998
|
-
|
|
999
|
-
|
|
1000
|
-
|
|
1001
|
-
|
|
1002
|
-
|
|
1003
|
-
|
|
1004
|
-
|
|
1005
|
-
|
|
1006
|
-
|
|
1007
|
-
|
|
1008
|
-
|
|
1009
|
-
|
|
1010
|
-
|
|
1011
|
-
|
|
1012
|
-
|
|
1013
|
-
|
|
1014
|
-
|
|
1015
|
-
|
|
1016
|
-
|
|
1017
|
-
|
|
1018
|
-
|
|
1019
|
-
|
|
1020
|
-
|
|
1021
|
-
|
|
1022
|
-
|
|
1023
|
-
|
|
1024
|
-
|
|
1025
|
-
|
|
1026
|
-
return
|
|
1027
|
-
}
|
|
1028
|
-
|
|
1029
|
-
|
|
1030
|
-
|
|
1031
|
-
|
|
1032
|
-
|
|
1033
|
-
}
|
|
1034
|
-
|
|
1035
|
-
|
|
1036
|
-
|
|
1037
|
-
|
|
1038
|
-
|
|
1039
|
-
|
|
1040
|
-
|
|
1041
|
-
|
|
1042
|
-
|
|
1043
|
-
|
|
1044
|
-
|
|
1045
|
-
|
|
1046
|
-
|
|
1047
|
-
|
|
1048
|
-
|
|
1049
|
-
|
|
1050
|
-
}
|
|
1051
|
-
|
|
1052
|
-
|
|
1053
|
-
|
|
1054
|
-
|
|
1055
|
-
|
|
1056
|
-
|
|
1057
|
-
|
|
1058
|
-
}
|
|
1059
|
-
|
|
1060
|
-
|
|
1061
|
-
|
|
1062
|
-
|
|
1063
|
-
|
|
1064
|
-
|
|
1065
|
-
|
|
1066
|
-
|
|
1067
|
-
|
|
1068
|
-
|
|
1069
|
-
if (
|
|
1070
|
-
|
|
1071
|
-
|
|
1072
|
-
|
|
1073
|
-
|
|
1074
|
-
|
|
1075
|
-
|
|
1076
|
-
|
|
1077
|
-
}
|
|
1078
|
-
|
|
1079
|
-
|
|
1080
|
-
|
|
1081
|
-
|
|
1082
|
-
|
|
1083
|
-
|
|
1084
|
-
|
|
1085
|
-
|
|
1086
|
-
|
|
1087
|
-
|
|
1088
|
-
|
|
1089
|
-
|
|
1090
|
-
|
|
1091
|
-
|
|
1092
|
-
|
|
1093
|
-
|
|
1094
|
-
}
|
|
1095
|
-
|
|
1096
|
-
|
|
1097
|
-
|
|
1098
|
-
|
|
1099
|
-
|
|
1100
|
-
|
|
1101
|
-
|
|
1102
|
-
|
|
1103
|
-
|
|
1104
|
-
|
|
1105
|
-
|
|
1106
|
-
|
|
1107
|
-
|
|
1108
|
-
|
|
1109
|
-
|
|
1110
|
-
|
|
1111
|
-
|
|
1112
|
-
|
|
1113
|
-
|
|
1114
|
-
|
|
1115
|
-
|
|
1116
|
-
|
|
1117
|
-
|
|
1118
|
-
|
|
1119
|
-
|
|
1120
|
-
|
|
1121
|
-
|
|
1122
|
-
|
|
1123
|
-
|
|
1124
|
-
|
|
1125
|
-
|
|
1126
|
-
|
|
1127
|
-
|
|
1128
|
-
|
|
1129
|
-
|
|
1130
|
-
|
|
1131
|
-
|
|
1132
|
-
|
|
1133
|
-
|
|
1134
|
-
|
|
1135
|
-
|
|
1136
|
-
|
|
1137
|
-
|
|
1138
|
-
|
|
1139
|
-
|
|
1140
|
-
|
|
1141
|
-
|
|
1142
|
-
|
|
1143
|
-
|
|
1144
|
-
|
|
1145
|
-
}
|
|
1146
|
-
|
|
1147
|
-
|
|
1148
|
-
|
|
1149
|
-
|
|
1150
|
-
|
|
1151
|
-
|
|
1152
|
-
|
|
1153
|
-
|
|
1154
|
-
|
|
1155
|
-
|
|
1156
|
-
|
|
1157
|
-
|
|
1158
|
-
|
|
1159
|
-
|
|
1160
|
-
|
|
1161
|
-
|
|
1162
|
-
|
|
1163
|
-
|
|
1164
|
-
|
|
1165
|
-
|
|
1166
|
-
|
|
1167
|
-
|
|
1168
|
-
|
|
1169
|
-
|
|
1170
|
-
|
|
1171
|
-
|
|
1172
|
-
|
|
1173
|
-
|
|
1174
|
-
|
|
1175
|
-
|
|
1176
|
-
|
|
1177
|
-
|
|
1178
|
-
|
|
1179
|
-
|
|
1180
|
-
|
|
1181
|
-
|
|
1182
|
-
|
|
1183
|
-
if (
|
|
1184
|
-
|
|
1185
|
-
|
|
1186
|
-
|
|
1187
|
-
|
|
1188
|
-
|
|
1189
|
-
|
|
1190
|
-
|
|
1191
|
-
|
|
1192
|
-
|
|
1193
|
-
|
|
1194
|
-
|
|
1195
|
-
|
|
1196
|
-
|
|
1197
|
-
|
|
1198
|
-
|
|
1199
|
-
|
|
1200
|
-
|
|
1201
|
-
|
|
1202
|
-
|
|
1203
|
-
|
|
1204
|
-
|
|
1205
|
-
|
|
1206
|
-
|
|
1207
|
-
|
|
1208
|
-
|
|
1209
|
-
|
|
1210
|
-
|
|
1211
|
-
|
|
1212
|
-
|
|
1213
|
-
|
|
1214
|
-
|
|
1215
|
-
|
|
1216
|
-
|
|
1217
|
-
|
|
1218
|
-
|
|
1219
|
-
|
|
1220
|
-
|
|
1221
|
-
|
|
1222
|
-
|
|
1223
|
-
|
|
1224
|
-
|
|
1225
|
-
}
|
|
1226
|
-
|
|
1227
|
-
|
|
1228
|
-
|
|
1229
|
-
|
|
1230
|
-
|
|
1231
|
-
|
|
1232
|
-
}
|
|
1233
|
-
function
|
|
1234
|
-
|
|
1235
|
-
|
|
1236
|
-
|
|
1237
|
-
|
|
1238
|
-
|
|
1239
|
-
|
|
1240
|
-
|
|
1241
|
-
|
|
1242
|
-
|
|
1243
|
-
|
|
1244
|
-
|
|
1245
|
-
|
|
1246
|
-
|
|
1247
|
-
|
|
1248
|
-
|
|
1249
|
-
|
|
1250
|
-
|
|
1251
|
-
|
|
1252
|
-
|
|
1253
|
-
|
|
1254
|
-
|
|
1255
|
-
|
|
1256
|
-
|
|
1257
|
-
|
|
1258
|
-
|
|
1259
|
-
|
|
1260
|
-
|
|
1261
|
-
|
|
1262
|
-
|
|
1263
|
-
|
|
1264
|
-
|
|
1265
|
-
|
|
1266
|
-
|
|
1267
|
-
|
|
1268
|
-
|
|
1269
|
-
|
|
1270
|
-
|
|
1271
|
-
|
|
1272
|
-
|
|
1273
|
-
|
|
1274
|
-
|
|
1275
|
-
|
|
1276
|
-
|
|
1277
|
-
|
|
1278
|
-
|
|
1279
|
-
|
|
1280
|
-
|
|
1281
|
-
|
|
1282
|
-
|
|
1283
|
-
|
|
1284
|
-
|
|
1285
|
-
|
|
1286
|
-
const
|
|
1287
|
-
|
|
1288
|
-
|
|
1289
|
-
|
|
1290
|
-
|
|
1291
|
-
|
|
1292
|
-
|
|
1293
|
-
|
|
1294
|
-
|
|
1295
|
-
|
|
1296
|
-
|
|
1297
|
-
|
|
1298
|
-
|
|
1299
|
-
|
|
1300
|
-
|
|
1301
|
-
|
|
1302
|
-
|
|
1303
|
-
|
|
1304
|
-
|
|
1305
|
-
|
|
1306
|
-
|
|
1307
|
-
|
|
1308
|
-
|
|
1309
|
-
|
|
1310
|
-
|
|
1311
|
-
|
|
1312
|
-
|
|
1313
|
-
|
|
1314
|
-
|
|
1315
|
-
|
|
1316
|
-
|
|
1317
|
-
|
|
1318
|
-
|
|
1319
|
-
|
|
1320
|
-
|
|
1321
|
-
|
|
1322
|
-
|
|
1323
|
-
|
|
1324
|
-
|
|
1325
|
-
|
|
1326
|
-
|
|
1327
|
-
|
|
1328
|
-
|
|
1329
|
-
|
|
1330
|
-
|
|
1331
|
-
|
|
1332
|
-
|
|
1333
|
-
|
|
1334
|
-
|
|
1335
|
-
|
|
1336
|
-
|
|
1337
|
-
|
|
1338
|
-
|
|
1339
|
-
|
|
1340
|
-
|
|
1341
|
-
|
|
1342
|
-
|
|
1343
|
-
|
|
1344
|
-
}
|
|
1345
|
-
|
|
1346
|
-
|
|
1347
|
-
|
|
1348
|
-
|
|
1349
|
-
|
|
1350
|
-
|
|
1351
|
-
|
|
1352
|
-
|
|
1353
|
-
|
|
1354
|
-
keepGenerations,
|
|
1355
|
-
olderThanDays,
|
|
1356
|
-
candidates: candidates.map((item) => ({ file: item.file, generation: item.generation, bytes: item.bytes })),
|
|
1357
|
-
removed,
|
|
1358
|
-
}
|
|
1359
|
-
}
|
|
1
|
+
import fs from 'node:fs'
|
|
2
|
+
import path from 'node:path'
|
|
3
|
+
import crypto from 'node:crypto'
|
|
4
|
+
import {
|
|
5
|
+
dataDir, librariesDir, indexDir, ensureDir, downloadsDir,
|
|
6
|
+
readJsonStrict, writeJson, withFileLock, stamp, isSafeId, warn,
|
|
7
|
+
} from './paths.js'
|
|
8
|
+
import {
|
|
9
|
+
PROVIDER_ORDER, getEmbeddingModel, profileFingerprint, validateEmbeddingManifest,
|
|
10
|
+
} from './embedding-catalog.js'
|
|
11
|
+
|
|
12
|
+
// §14.8 向量空间身份、代际选择与写入护栏。
|
|
13
|
+
//
|
|
14
|
+
// 本模块只回答四件事:
|
|
15
|
+
// 1. 一个 profile 的身份是什么(fingerprint 直接复用 embedding-catalog 的协议,不另立一套);
|
|
16
|
+
// 2. 当前 active 代际是哪一个(单个 index/vector-active.json 原子选择 profile + DB 集合);
|
|
17
|
+
// 3. 用户"想要"的 profile(requested)与真正生效的 profile 分离;
|
|
18
|
+
// 4. 此刻允不允许写向量(护栏:未验证/未就绪/pending/撕裂一律拒绝,且拒绝必须可退词法,
|
|
19
|
+
// 绝不能悄悄回落成 legacy 远端嵌入)。
|
|
20
|
+
//
|
|
21
|
+
// 硬约束(来自 §14.8):
|
|
22
|
+
// * profile 只依赖 paths/catalog,不依赖 state.json;本模块不读 state。
|
|
23
|
+
// * 文件锁只在最后短窗口内做同步 compare + 原子写指针;整个模块没有 await 跨锁。
|
|
24
|
+
// * 所有 DB 路径都从 active manifest 的 database-set 一次性取得,避免逐个库换导致混空间。
|
|
25
|
+
// * 全局库影子也放 librariesDir():backupDatabases 只扫 libraries/*.sqlite3 与 index/*.json,
|
|
26
|
+
// 放 data 根目录会被备份漏掉(§14.9 第 6 条要求备份包含 vector active profile manifest)。
|
|
27
|
+
|
|
28
|
+
export const VECTOR_ACTIVE_FILE = 'vector-active.json'
|
|
29
|
+
export const VECTOR_ACTIVE_SCHEMA = 1
|
|
30
|
+
|
|
31
|
+
export const VECTOR_ERROR_CODES = Object.freeze({
|
|
32
|
+
PROFILE_MISSING: 'VECTOR_PROFILE_MISSING',
|
|
33
|
+
PROFILE_UNKNOWN: 'VECTOR_PROFILE_UNKNOWN',
|
|
34
|
+
PROFILE_PENDING: 'VECTOR_PROFILE_PENDING',
|
|
35
|
+
PROFILE_UNVERIFIED: 'VECTOR_PROFILE_UNVERIFIED',
|
|
36
|
+
PROFILE_FINGERPRINT_MISMATCH: 'VECTOR_PROFILE_FINGERPRINT_MISMATCH',
|
|
37
|
+
PROFILE_MANIFEST_CHANGED: 'VECTOR_PROFILE_MANIFEST_CHANGED',
|
|
38
|
+
ACTIVE_CORRUPT: 'VECTOR_ACTIVE_CORRUPT',
|
|
39
|
+
ACTIVE_UNREADABLE: 'VECTOR_ACTIVE_UNREADABLE',
|
|
40
|
+
NOT_ACTIVE: 'VECTOR_NOT_ACTIVE',
|
|
41
|
+
TORN_STATE: 'VECTOR_TORN_STATE',
|
|
42
|
+
STALE_GENERATION: 'VECTOR_STALE_GENERATION',
|
|
43
|
+
NO_GENERATION: 'VECTOR_NO_GENERATION',
|
|
44
|
+
SHADOW_PATH_TAKEN: 'VECTOR_SHADOW_PATH_TAKEN',
|
|
45
|
+
PATH_ESCAPE: 'VECTOR_PATH_ESCAPE',
|
|
46
|
+
BAD_UPDATE: 'VECTOR_BAD_UPDATE',
|
|
47
|
+
})
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* 向量状态错误:带 code + fallback='lexical' + forbidLegacyRemote。
|
|
51
|
+
* 调用方一旦看到 isVectorStateError(e) 为真,就只能退化成词法召回,
|
|
52
|
+
* 不允许把同一批查询发去 legacy/远端嵌入(那会把两种向量空间混在一个库里)。
|
|
53
|
+
*/
|
|
54
|
+
export class VectorStateError extends Error {
|
|
55
|
+
constructor(code, message, extra = {}) {
|
|
56
|
+
super(message)
|
|
57
|
+
this.name = 'VectorStateError'
|
|
58
|
+
this.code = code
|
|
59
|
+
this.fallback = 'lexical'
|
|
60
|
+
this.forbidLegacyRemote = true
|
|
61
|
+
for (const [key, value] of Object.entries(extra)) if (value !== undefined) this[key] = value
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
export function vectorError(code, message, extra) {
|
|
66
|
+
return new VectorStateError(code, message, extra)
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
export function isVectorStateError(value) {
|
|
70
|
+
if (value instanceof VectorStateError) return true
|
|
71
|
+
return typeof value?.code === 'string' && value.code.startsWith('VECTOR_')
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
// ---------------------------------------------------------------- 规范化哈希
|
|
75
|
+
|
|
76
|
+
/**
|
|
77
|
+
* 规范化 JSON 序列化:键排序、undefined 省略。与 embedding-catalog 内部 canonical()
|
|
78
|
+
* 同一协议(那里没有导出),保证"同一个 manifest 在任何模块里哈希都相同"。
|
|
79
|
+
*/
|
|
80
|
+
export function stableStringify(value) {
|
|
81
|
+
if (Array.isArray(value)) return '[' + value.map(stableStringify).join(',') + ']'
|
|
82
|
+
if (value && typeof value === 'object') {
|
|
83
|
+
return '{' + Object.keys(value).sort()
|
|
84
|
+
.filter(key => value[key] !== undefined)
|
|
85
|
+
.map(key => JSON.stringify(key) + ':' + stableStringify(value[key]))
|
|
86
|
+
.join(',') + '}'
|
|
87
|
+
}
|
|
88
|
+
return JSON.stringify(value === undefined ? null : value)
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
export function sha256Hex(value) {
|
|
92
|
+
return crypto.createHash('sha256').update(value).digest('hex')
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/**
|
|
96
|
+
* manifest 哈希覆盖制品身份字段;profileFingerprint 描述向量空间。
|
|
97
|
+
* 两者共同检查当前代际所使用的模型与制品身份。
|
|
98
|
+
*/
|
|
99
|
+
// 摘要只覆盖会改变向量空间或制品的字段;displayName、summary 与参数说明
|
|
100
|
+
// 不属于制品身份,修改这些文案不应使已激活的 profile 失效。
|
|
101
|
+
const DIGEST_FIELDS = ['id', 'dimension', 'maxTokens', 'pooling', 'normalization', 'prefixes', 'quantization',
|
|
102
|
+
'runtime', 'sources', 'files', 'graph', 'protocol', 'preprocessing', 'windowing', 'aggregation', 'tokenizer']
|
|
103
|
+
|
|
104
|
+
// 制品清单里只有这些子字段属于"身份":镜像源、镜像标签、下载地址都回答"从哪拿",
|
|
105
|
+
// 不回答"拿到什么"。
|
|
106
|
+
//
|
|
107
|
+
// runtime/sources 的镜像配置与说明不参与身份;保留名称、版本、大小、
|
|
108
|
+
// sha256、integrity 等制品字段,避免仅更换镜像就要求重建向量。
|
|
109
|
+
const RUNTIME_IDENTITY_FIELDS = ['engine', 'abi', 'version', 'os', 'arch']
|
|
110
|
+
// 这些键只描述"从哪个镜像下载",不参与身份。
|
|
111
|
+
const MIRROR_KEYS = new Set(['sources', 'mirrors', 'mirror', 'label', 'displayName', 'summary', 'note', 'url', 'gated'])
|
|
112
|
+
|
|
113
|
+
function identityArtifact(item) {
|
|
114
|
+
if (!item || typeof item !== 'object' || Array.isArray(item)) return item
|
|
115
|
+
const out = {}
|
|
116
|
+
for (const key of Object.keys(item)) {
|
|
117
|
+
if (MIRROR_KEYS.has(key)) continue
|
|
118
|
+
out[key] = item[key]
|
|
119
|
+
}
|
|
120
|
+
return out
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
// runtime 里还可能是"平台 → 制品"的字典(artifacts: { 'win32-x64': {...} })或制品数组
|
|
124
|
+
// (artifacts: [{...}])。两种都要剥镜像层,否则字典形态会把 sources 原样算进身份。
|
|
125
|
+
function identityNested(value) {
|
|
126
|
+
if (Array.isArray(value)) return value.map(item => identityNested(item))
|
|
127
|
+
if (!value || typeof value !== 'object') return value
|
|
128
|
+
const out = {}
|
|
129
|
+
for (const key of Object.keys(value)) {
|
|
130
|
+
if (MIRROR_KEYS.has(key)) continue
|
|
131
|
+
const inner = value[key]
|
|
132
|
+
out[key] = inner && typeof inner === 'object' ? identityNested(inner) : inner
|
|
133
|
+
}
|
|
134
|
+
return out
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
function identityRuntime(runtime) {
|
|
138
|
+
if (runtime === undefined) return undefined
|
|
139
|
+
if (!runtime || typeof runtime !== 'object' || Array.isArray(runtime)) return runtime
|
|
140
|
+
const out = {}
|
|
141
|
+
for (const key of RUNTIME_IDENTITY_FIELDS) if (runtime[key] !== undefined) out[key] = runtime[key]
|
|
142
|
+
for (const key of Object.keys(runtime)) {
|
|
143
|
+
if (RUNTIME_IDENTITY_FIELDS.includes(key)) continue
|
|
144
|
+
const value = runtime[key]
|
|
145
|
+
if (MIRROR_KEYS.has(key)) continue
|
|
146
|
+
if (Array.isArray(value)) out[key] = value.map(identityArtifact)
|
|
147
|
+
else if (value && typeof value === 'object') out[key] = identityNested(value)
|
|
148
|
+
else out[key] = value
|
|
149
|
+
}
|
|
150
|
+
return out
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
function identitySources(sources) {
|
|
154
|
+
if (sources === undefined) return undefined
|
|
155
|
+
if (!sources || typeof sources !== 'object' || Array.isArray(sources)) return sources
|
|
156
|
+
const out = {}
|
|
157
|
+
for (const provider of Object.keys(sources)) {
|
|
158
|
+
const value = sources[provider]
|
|
159
|
+
out[provider] = value && typeof value === 'object' && !Array.isArray(value) ? identityArtifact(value) : value
|
|
160
|
+
}
|
|
161
|
+
return out
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
/** 单个摘要字段的"身份视图":runtime/sources 去掉镜像层,其余字段原样。 */
|
|
165
|
+
function identityOf(field, value) {
|
|
166
|
+
if (field === 'runtime') return identityRuntime(value)
|
|
167
|
+
if (field === 'sources') return identitySources(value)
|
|
168
|
+
return value
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
function digestSubset(manifest, normalize) {
|
|
172
|
+
const subset = {}
|
|
173
|
+
for (const key of DIGEST_FIELDS) {
|
|
174
|
+
if (manifest[key] === undefined) continue
|
|
175
|
+
subset[key] = normalize ? identityOf(key, manifest[key]) : manifest[key]
|
|
176
|
+
}
|
|
177
|
+
return subset
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
/** 当前算法:摘要只覆盖身份视图里的制品字段。 */
|
|
181
|
+
export function manifestDigest(manifest) {
|
|
182
|
+
if (!manifest || typeof manifest !== 'object' || Array.isArray(manifest)) return null
|
|
183
|
+
return sha256Hex(stableStringify(digestSubset(manifest, true)))
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
/** 1.3.x 算法(DIGEST_FIELDS 原样):只用于兼容已经落盘的 profile。 */
|
|
187
|
+
export function rawManifestDigest(manifest) {
|
|
188
|
+
if (!manifest || typeof manifest !== 'object' || Array.isArray(manifest)) return null
|
|
189
|
+
return sha256Hex(stableStringify(digestSubset(manifest, false)))
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
/** 旧算法(全字段,除了它自己)。只用于兼容已经落盘的 profile。 */
|
|
193
|
+
export function legacyManifestDigest(manifest) {
|
|
194
|
+
if (!manifest || typeof manifest !== 'object' || Array.isArray(manifest)) return null
|
|
195
|
+
const copy = {}
|
|
196
|
+
for (const key of Object.keys(manifest)) {
|
|
197
|
+
if (key === 'profileFingerprint') continue
|
|
198
|
+
copy[key] = manifest[key]
|
|
199
|
+
}
|
|
200
|
+
return sha256Hex(stableStringify(copy))
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
/** 已落盘摘要三种都认:当前算法 + 1.3.x 算法 + 更早的全字段算法。 */
|
|
204
|
+
export function manifestDigestAccepted(stored, manifest) {
|
|
205
|
+
if (typeof stored !== 'string' || !stored) return true
|
|
206
|
+
return stored === manifestDigest(manifest)
|
|
207
|
+
|| stored === rawManifestDigest(manifest)
|
|
208
|
+
|| stored === legacyManifestDigest(manifest)
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
/**
|
|
212
|
+
* 已落盘的 profile manifest 与 catalog 现在的条目差在哪。
|
|
213
|
+
*
|
|
214
|
+
* 返回值把这个差异分成两类,这是"能不能自动修"的判据:
|
|
215
|
+
* - `fields`:摘要字段里有哪几个字面不同;
|
|
216
|
+
* - `metadataOnly`:字面不同但**身份视图相同**的字段(镜像源/标签/地址);
|
|
217
|
+
* - `identityChanged`:身份真的变了的字段(向量空间或制品内容),只能重建,不能重签。
|
|
218
|
+
*/
|
|
219
|
+
export function manifestDrift(profileManifest, entry) {
|
|
220
|
+
const fields = []
|
|
221
|
+
const metadataOnly = []
|
|
222
|
+
const identityChanged = []
|
|
223
|
+
if (!profileManifest || typeof profileManifest !== 'object') {
|
|
224
|
+
return { fields: ['manifest'], metadataOnly: [], identityChanged: ['manifest'] }
|
|
225
|
+
}
|
|
226
|
+
for (const field of DIGEST_FIELDS) {
|
|
227
|
+
if (stableStringify(profileManifest[field]) === stableStringify(entry?.[field])) continue
|
|
228
|
+
fields.push(field)
|
|
229
|
+
if (stableStringify(identityOf(field, profileManifest[field])) === stableStringify(identityOf(field, entry?.[field]))) metadataOnly.push(field)
|
|
230
|
+
else identityChanged.push(field)
|
|
231
|
+
}
|
|
232
|
+
return { fields, metadataOnly, identityChanged }
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
// 元数据漂移只 warn 一次:每回合都记一遍就变成新的日志洪水。
|
|
236
|
+
let lastMetadataDriftKey = null
|
|
237
|
+
|
|
238
|
+
/** 直接复用 embedding-catalog 的指纹协议(任何改变向量空间的字段都进指纹,§14.8)。 */
|
|
239
|
+
export { profileFingerprint }
|
|
240
|
+
|
|
241
|
+
// ---------------------------------------------------------------- catalog 注入点
|
|
242
|
+
|
|
243
|
+
// 默认只认 embedding-catalog.js 的目录。测试(以及将来多目录场景)可以换一个解析器:
|
|
244
|
+
// 指纹/校验协议不变,只是"哪个 id 对应哪份 manifest"可以注入。
|
|
245
|
+
let catalogEntryResolver = id => getEmbeddingModel(id)
|
|
246
|
+
|
|
247
|
+
export function setCatalogEntryResolver(resolver) {
|
|
248
|
+
catalogEntryResolver = typeof resolver === 'function' ? resolver : (id => getEmbeddingModel(id))
|
|
249
|
+
return catalogEntryResolver
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
export function resetCatalogEntryResolver() {
|
|
253
|
+
catalogEntryResolver = id => getEmbeddingModel(id)
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
/** 解析目录条目:只按稳定 id 取,未知 id 返回 null(不猜、不回退默认模型)。 */
|
|
257
|
+
export function resolveCatalogEntry(catalogId) {
|
|
258
|
+
if (typeof catalogId !== 'string' || !catalogId) return null
|
|
259
|
+
try {
|
|
260
|
+
return catalogEntryResolver(catalogId) ?? null
|
|
261
|
+
} catch {
|
|
262
|
+
return null
|
|
263
|
+
}
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
// ---------------------------------------------------------------- profile 构造
|
|
267
|
+
|
|
268
|
+
function primarySourceOf(entry) {
|
|
269
|
+
const sources = entry?.sources && typeof entry.sources === 'object' ? entry.sources : {}
|
|
270
|
+
for (const id of PROVIDER_ORDER) {
|
|
271
|
+
const source = sources[id]
|
|
272
|
+
if (source && typeof source.revision === 'string') return { provider: id, repo: source.repo, revision: source.revision }
|
|
273
|
+
}
|
|
274
|
+
return { provider: null, repo: null, revision: null }
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
/**
|
|
278
|
+
* 由 catalog/manifest 条目构造 profile。纯函数:不读 state、不写盘、不看当前 active。
|
|
279
|
+
* 返回的对象冻结,避免调用方改到指纹依赖的字段。
|
|
280
|
+
*/
|
|
281
|
+
export function buildProfile(entry, installation = {}) {
|
|
282
|
+
if (!entry || typeof entry !== 'object') throw vectorError(VECTOR_ERROR_CODES.PROFILE_MISSING, 'a catalog entry is required to build a vector profile')
|
|
283
|
+
// 永远按 catalog 协议现场重算:条目里存的 profileFingerprint 只是个缓存,
|
|
284
|
+
// 被改过的条目不能靠它冒充另一个向量空间。
|
|
285
|
+
const fingerprint = profileFingerprint(entry)
|
|
286
|
+
const source = primarySourceOf(entry)
|
|
287
|
+
const files = (Array.isArray(entry.files) ? entry.files : []).map(file => Object.freeze({
|
|
288
|
+
path: String(file.path), role: file.role ?? null, bytes: Number(file.bytes), sha256: String(file.sha256),
|
|
289
|
+
}))
|
|
290
|
+
const runtime = entry.runtime && typeof entry.runtime === 'object'
|
|
291
|
+
? Object.freeze({ engine: entry.runtime.engine ?? null, abi: entry.runtime.abi ?? null, version: entry.runtime.version ?? null, os: entry.runtime.os ?? null, arch: entry.runtime.arch ?? null })
|
|
292
|
+
: null
|
|
293
|
+
const quantization = entry.quantization && typeof entry.quantization === 'object'
|
|
294
|
+
? Object.freeze({ weights: entry.quantization.weights ?? null, scheme: entry.quantization.scheme ?? null })
|
|
295
|
+
: null
|
|
296
|
+
return Object.freeze({
|
|
297
|
+
schema: VECTOR_ACTIVE_SCHEMA,
|
|
298
|
+
catalogId: String(entry.id),
|
|
299
|
+
manifest: structuredClone(entry),
|
|
300
|
+
modelDir: installation.modelDir ?? entry.modelDir ?? null,
|
|
301
|
+
runtimeDir: installation.runtimeDir ?? entry.runtimeDir ?? null,
|
|
302
|
+
fingerprint,
|
|
303
|
+
short: fingerprint.slice(0, 8),
|
|
304
|
+
displayName: entry.displayName ?? String(entry.id),
|
|
305
|
+
manifestDigest: manifestDigest(entry),
|
|
306
|
+
provider: source.provider,
|
|
307
|
+
repo: source.repo,
|
|
308
|
+
revision: source.revision,
|
|
309
|
+
dimension: entry.dimension ?? null,
|
|
310
|
+
maxTokens: entry.maxTokens ?? null,
|
|
311
|
+
pooling: entry.pooling ?? null,
|
|
312
|
+
normalization: entry.normalization ?? null,
|
|
313
|
+
prefixes: entry.prefixes ? Object.freeze({ query: entry.prefixes.query ?? '', document: entry.prefixes.document ?? '' }) : null,
|
|
314
|
+
quantization,
|
|
315
|
+
runtime,
|
|
316
|
+
files: Object.freeze(files),
|
|
317
|
+
graphSha256: files.find(file => file.role === 'graph')?.sha256 ?? null,
|
|
318
|
+
tokenizerSha256: files.find(file => file.role === 'tokenizer')?.sha256 ?? null,
|
|
319
|
+
verification: Object.freeze({
|
|
320
|
+
status: entry.verification?.status ?? 'unverified',
|
|
321
|
+
method: entry.verification?.method ?? null,
|
|
322
|
+
checkedAt: entry.verification?.checkedAt ?? null,
|
|
323
|
+
}),
|
|
324
|
+
})
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
/**
|
|
328
|
+
* 只校验 manifest 本身能不能用:pending(未核实制品)与未验证 manifest 都拒绝(§14.4 V0)。
|
|
329
|
+
* 单独导出,便于"候选模型是否可启用"这类只读判断,也便于测试直接喂一份坏 manifest。
|
|
330
|
+
*/
|
|
331
|
+
export function assertManifestUsable(entry) {
|
|
332
|
+
if (!entry || typeof entry !== 'object' || Array.isArray(entry)) {
|
|
333
|
+
throw vectorError(VECTOR_ERROR_CODES.PROFILE_MISSING, 'a manifest entry is required')
|
|
334
|
+
}
|
|
335
|
+
if (entry.availability !== 'available') {
|
|
336
|
+
throw vectorError(VECTOR_ERROR_CODES.PROFILE_PENDING, String(entry.id ?? 'unknown model') + ' has no verified artifact; pending models cannot be activated', {
|
|
337
|
+
catalogId: entry.id ?? null,
|
|
338
|
+
pendingReasons: [...(entry.pendingReasons || [])],
|
|
339
|
+
})
|
|
340
|
+
}
|
|
341
|
+
if (entry.verification?.status !== 'verified') {
|
|
342
|
+
throw vectorError(VECTOR_ERROR_CODES.PROFILE_UNVERIFIED, String(entry.id ?? 'unknown model') + ' is not verified; refusing to build a vector space on it', { catalogId: entry.id ?? null })
|
|
343
|
+
}
|
|
344
|
+
const report = validateEmbeddingManifest(entry)
|
|
345
|
+
if (!report.ok) {
|
|
346
|
+
throw vectorError(VECTOR_ERROR_CODES.PROFILE_UNVERIFIED, String(entry.id ?? 'unknown model') + ' manifest is not usable: ' + report.errors.map(item => item.code).join(', '), {
|
|
347
|
+
catalogId: entry.id ?? null,
|
|
348
|
+
errors: report.errors,
|
|
349
|
+
})
|
|
350
|
+
}
|
|
351
|
+
return true
|
|
352
|
+
}
|
|
353
|
+
|
|
354
|
+
/**
|
|
355
|
+
* 校验一个 profile 仍然被当前 catalog 认可:条目存在、指纹与完整 manifest 哈希都对得上、
|
|
356
|
+
* 制品可用(availability === 'available')、manifest 通过 validateEmbeddingManifest。
|
|
357
|
+
* 未验证 manifest 与 pending 制品在这里就被拒绝(§14.4/§14.8)。
|
|
358
|
+
*/
|
|
359
|
+
export function assertProfileVerified(profile) {
|
|
360
|
+
if (!profile || typeof profile !== 'object' || !profile.catalogId) {
|
|
361
|
+
throw vectorError(VECTOR_ERROR_CODES.PROFILE_MISSING, 'no vector profile to verify')
|
|
362
|
+
}
|
|
363
|
+
const entry = resolveCatalogEntry(profile.catalogId)
|
|
364
|
+
if (!entry) {
|
|
365
|
+
throw vectorError(VECTOR_ERROR_CODES.PROFILE_UNKNOWN, 'the catalog no longer defines ' + profile.catalogId + '; refusing to use a vector space that cannot be reproduced', { catalogId: profile.catalogId })
|
|
366
|
+
}
|
|
367
|
+
const expected = profileFingerprint(entry)
|
|
368
|
+
if (profile.fingerprint !== expected) {
|
|
369
|
+
throw vectorError(VECTOR_ERROR_CODES.PROFILE_FINGERPRINT_MISMATCH, 'profile fingerprint does not match the catalog for ' + entry.id, { expected, actual: profile.fingerprint })
|
|
370
|
+
}
|
|
371
|
+
const digest = manifestDigest(entry)
|
|
372
|
+
if (!manifestDigestAccepted(profile.manifestDigest, entry)) {
|
|
373
|
+
// 摘要对不上时先分类,别急着判废:镜像元数据变化不代表向量空间变了。
|
|
374
|
+
// 只有"身份视图也变了"才是真的换了制品(files/graph/dimension/runtime 版本…),
|
|
375
|
+
// 那种情况必须重建;否则重签即可,已算好的 25 条向量一条都不用重算。
|
|
376
|
+
const drift = manifestDrift(profile.manifest, entry)
|
|
377
|
+
if (drift.identityChanged.length) {
|
|
378
|
+
throw vectorError(VECTOR_ERROR_CODES.PROFILE_MANIFEST_CHANGED, 'the manifest for ' + entry.id + ' changed after this profile was recorded', {
|
|
379
|
+
expected: digest, actual: profile.manifestDigest, changedFields: drift.identityChanged, recoverable: false, catalogId: entry.id,
|
|
380
|
+
})
|
|
381
|
+
}
|
|
382
|
+
// 逐字段比下来一处都没变,摘要却对不上:这说明存下来的摘要本身不可信(被改过、
|
|
383
|
+
// 或用的是一个我们已经不认识的算法),不是"元数据漂移"。这种情况不能放过——
|
|
384
|
+
// 放过等于承认任意摘要都行。
|
|
385
|
+
if (!drift.fields.length) {
|
|
386
|
+
throw vectorError(VECTOR_ERROR_CODES.PROFILE_MANIFEST_CHANGED, 'the manifest for ' + entry.id + ' changed after this profile was recorded', {
|
|
387
|
+
expected: digest, actual: profile.manifestDigest, changedFields: [], recoverable: false, catalogId: entry.id,
|
|
388
|
+
})
|
|
389
|
+
}
|
|
390
|
+
const driftKey = [profile.catalogId, drift.fields.join(',')].join('|')
|
|
391
|
+
if (driftKey !== lastMetadataDriftKey) {
|
|
392
|
+
lastMetadataDriftKey = driftKey
|
|
393
|
+
warn(`vector profile ${profile.catalogId}: manifest metadata moved (${drift.fields.join(', ') || 'unknown'}); accepting the recorded profile because the artifacts themselves are unchanged`)
|
|
394
|
+
}
|
|
395
|
+
}
|
|
396
|
+
// The persisted manifest and derived processing fields are execution inputs,
|
|
397
|
+
// not harmless annotations. Reject tampering even if cached hashes survived.
|
|
398
|
+
// 存储的 manifest 只需在"向量空间"上仍然一致;指纹已覆盖这些字段。
|
|
399
|
+
if (!profile.manifest || profileFingerprint(profile.manifest) !== expected) {
|
|
400
|
+
throw vectorError(VECTOR_ERROR_CODES.PROFILE_MANIFEST_CHANGED, 'the stored profile manifest no longer matches the catalog for ' + entry.id)
|
|
401
|
+
}
|
|
402
|
+
const rebuilt = buildProfile(entry)
|
|
403
|
+
for (const field of ['schema', 'short', 'provider', 'repo', 'revision', 'dimension', 'maxTokens', 'pooling', 'normalization', 'prefixes', 'quantization', 'runtime', 'files', 'graphSha256', 'tokenizerSha256']) {
|
|
404
|
+
if (stableStringify(profile[field]) !== stableStringify(rebuilt[field])) throw vectorError(VECTOR_ERROR_CODES.PROFILE_MANIFEST_CHANGED, 'the stored profile processing field changed: ' + field)
|
|
405
|
+
}
|
|
406
|
+
assertManifestUsable(entry)
|
|
407
|
+
return profile
|
|
408
|
+
}
|
|
409
|
+
|
|
410
|
+
/** 按 catalog id 构造并验证 profile;pending/未知/未验证一律抛 typed error。 */
|
|
411
|
+
export function profileFromCatalog(catalogId, installation = {}) {
|
|
412
|
+
const id = typeof catalogId === 'string' ? catalogId : String(catalogId ?? '')
|
|
413
|
+
const entry = resolveCatalogEntry(id)
|
|
414
|
+
if (!entry) throw vectorError(VECTOR_ERROR_CODES.PROFILE_UNKNOWN, 'unknown embedding model: ' + JSON.stringify(id), { catalogId: id })
|
|
415
|
+
assertManifestUsable(entry)
|
|
416
|
+
const profile = buildProfile(entry, installation)
|
|
417
|
+
return assertProfileVerified(profile)
|
|
418
|
+
}
|
|
419
|
+
|
|
420
|
+
/** 接受 profile 对象 / catalog id / manifest 条目,统一成已验证 profile。 */
|
|
421
|
+
export function resolveProfile(value) {
|
|
422
|
+
if (value && typeof value === 'object' && value.catalogId) return assertProfileVerified(value)
|
|
423
|
+
if (value && typeof value === 'object' && value.id) return profileFromCatalog(value.id)
|
|
424
|
+
return profileFromCatalog(value)
|
|
425
|
+
}
|
|
426
|
+
|
|
427
|
+
// ---------------------------------------------------------------- 路径与 DB 集合
|
|
428
|
+
|
|
429
|
+
/** 受管 DB 一律用 "libraries/<name>.<fp8>.g<gen>.sqlite3":文件名自带代际,切换=换指针。 */
|
|
430
|
+
export function vectorDbRelPath({ libraryId = null, fingerprint, generation } = {}) {
|
|
431
|
+
if (typeof fingerprint !== 'string' || !fingerprint) {
|
|
432
|
+
throw vectorError(VECTOR_ERROR_CODES.BAD_UPDATE, 'vectorDbRelPath requires a fingerprint')
|
|
433
|
+
}
|
|
434
|
+
if (!Number.isSafeInteger(generation) || generation < 1) {
|
|
435
|
+
throw vectorError(VECTOR_ERROR_CODES.BAD_UPDATE, 'vectorDbRelPath requires a positive generation')
|
|
436
|
+
}
|
|
437
|
+
const short = fingerprint.slice(0, 8)
|
|
438
|
+
const gen = 'g' + generation
|
|
439
|
+
if (libraryId === null || libraryId === undefined || libraryId === 'global') {
|
|
440
|
+
return ['libraries', 'global.' + short + '.' + gen + '.sqlite3'].join('/')
|
|
441
|
+
}
|
|
442
|
+
if (!isSafeId(libraryId)) throw vectorError(VECTOR_ERROR_CODES.PATH_ESCAPE, 'unsafe library id: ' + JSON.stringify(libraryId), { libraryId })
|
|
443
|
+
return ['libraries', libraryId + '.' + short + '.' + gen + '.sqlite3'].join('/')
|
|
444
|
+
}
|
|
445
|
+
|
|
446
|
+
/** 相对 dataDir 的受管路径 → 绝对路径;绝对路径与越界路径一律拒绝。 */
|
|
447
|
+
export function resolveVectorPath(relPath) {
|
|
448
|
+
if (typeof relPath !== 'string' || !relPath.trim()) {
|
|
449
|
+
throw vectorError(VECTOR_ERROR_CODES.PATH_ESCAPE, 'vector storage path is missing', { path: relPath })
|
|
450
|
+
}
|
|
451
|
+
if (path.isAbsolute(relPath)) {
|
|
452
|
+
throw vectorError(VECTOR_ERROR_CODES.PATH_ESCAPE, 'vector storage paths must be relative to the data root', { path: relPath })
|
|
453
|
+
}
|
|
454
|
+
const root = path.resolve(dataDir())
|
|
455
|
+
const abs = path.resolve(root, ...relPath.split(/[\\/]+/).filter(Boolean))
|
|
456
|
+
if (abs !== root && !abs.startsWith(root + path.sep)) {
|
|
457
|
+
throw vectorError(VECTOR_ERROR_CODES.PATH_ESCAPE, 'vector storage path escapes the data root', { path: relPath })
|
|
458
|
+
}
|
|
459
|
+
return abs
|
|
460
|
+
}
|
|
461
|
+
|
|
462
|
+
export function vectorDbAbsPath(options) {
|
|
463
|
+
return resolveVectorPath(vectorDbRelPath(options))
|
|
464
|
+
}
|
|
465
|
+
|
|
466
|
+
/** 非受管模式(尚未启用本地向量)仍走原来的库路径。 */
|
|
467
|
+
export function legacyDbPath(libraryId = null) {
|
|
468
|
+
if (libraryId === null || libraryId === undefined || libraryId === 'global') return path.join(dataDir(), 'global.sqlite3')
|
|
469
|
+
if (!isSafeId(libraryId)) throw vectorError(VECTOR_ERROR_CODES.PATH_ESCAPE, 'unsafe library id: ' + JSON.stringify(libraryId), { libraryId })
|
|
470
|
+
return path.join(librariesDir(), libraryId + '.sqlite3')
|
|
471
|
+
}
|
|
472
|
+
|
|
473
|
+
// ---------------------------------------------------------------- active manifest
|
|
474
|
+
|
|
475
|
+
export function vectorActiveFile() {
|
|
476
|
+
return path.join(indexDir(), VECTOR_ACTIVE_FILE)
|
|
477
|
+
}
|
|
478
|
+
|
|
479
|
+
function emptyState() {
|
|
480
|
+
return { version: VECTOR_ACTIVE_SCHEMA, generation: 0, requested: null, active: null, pending: null }
|
|
481
|
+
}
|
|
482
|
+
|
|
483
|
+
function validDatabases(value) {
|
|
484
|
+
return Boolean(value) && typeof value === 'object' && !Array.isArray(value)
|
|
485
|
+
&& value.global && typeof value.global === 'object'
|
|
486
|
+
&& value.libraries && typeof value.libraries === 'object' && !Array.isArray(value.libraries)
|
|
487
|
+
}
|
|
488
|
+
|
|
489
|
+
function validActive(active) {
|
|
490
|
+
return Boolean(active) && typeof active === 'object'
|
|
491
|
+
&& active.status === 'active'
|
|
492
|
+
&& Number.isSafeInteger(active.generation) && active.generation >= 1
|
|
493
|
+
&& typeof active.fingerprint === 'string' && active.fingerprint.length > 0
|
|
494
|
+
&& active.profile && typeof active.profile === 'object'
|
|
495
|
+
&& validDatabases(active.databases)
|
|
496
|
+
}
|
|
497
|
+
|
|
498
|
+
const PENDING_STATUSES = Object.freeze(['preparing', 'prepared', 'committed', 'aborted', 'failed'])
|
|
499
|
+
|
|
500
|
+
function validPending(pending) {
|
|
501
|
+
return Boolean(pending) && typeof pending === 'object'
|
|
502
|
+
&& PENDING_STATUSES.includes(pending.status)
|
|
503
|
+
&& Number.isSafeInteger(pending.generation)
|
|
504
|
+
&& typeof pending.fingerprint === 'string'
|
|
505
|
+
}
|
|
506
|
+
|
|
507
|
+
/**
|
|
508
|
+
* 受管路由被选中了,是否真的有一代可用的向量空间。
|
|
509
|
+
*
|
|
510
|
+
* 只选了模型(state.requested)或 state 文件根本没写成时,写入没有可对齐的向量代际。
|
|
511
|
+
* 调用方必须据此降级,而不是让整条写入链失败:索引 + 引擎才是权威,向量可以在下一次
|
|
512
|
+
* 重建里补回来。active 存在但损坏(缺 DB、manifest 不全)仍然算"有",那种情况必须
|
|
513
|
+
* 大声失败,不能静默分叉。
|
|
514
|
+
*/
|
|
515
|
+
export function hasActiveVectorGeneration() {
|
|
516
|
+
try {
|
|
517
|
+
return Boolean(readVectorState({ tolerateMissing: true }).state?.active)
|
|
518
|
+
} catch {
|
|
519
|
+
return false
|
|
520
|
+
}
|
|
521
|
+
}
|
|
522
|
+
|
|
523
|
+
/**
|
|
524
|
+
* 读 active manifest。missing → { ok: true, state: null };
|
|
525
|
+
* 坏 JSON / 坏形状 → typed error(绝不把"读不懂"当成"没有",更不猜最近文件)。
|
|
526
|
+
*/
|
|
527
|
+
export function readVectorState({ tolerateMissing = true } = {}) {
|
|
528
|
+
const file = vectorActiveFile()
|
|
529
|
+
const result = readJsonStrict(file)
|
|
530
|
+
if (!result.ok) {
|
|
531
|
+
if (result.missing) {
|
|
532
|
+
if (tolerateMissing) return { ok: true, state: null, file }
|
|
533
|
+
throw vectorError(VECTOR_ERROR_CODES.NOT_ACTIVE, 'no vector-active manifest yet', { file })
|
|
534
|
+
}
|
|
535
|
+
if (result.kind === 'corrupt') throw vectorError(VECTOR_ERROR_CODES.ACTIVE_CORRUPT, 'vector-active.json is not valid JSON; refusing to guess a generation', { file })
|
|
536
|
+
throw vectorError(VECTOR_ERROR_CODES.ACTIVE_UNREADABLE, 'cannot read vector-active.json (' + (result.error?.code || 'io error') + ')', { file })
|
|
537
|
+
}
|
|
538
|
+
const state = result.value
|
|
539
|
+
if (!state || typeof state !== 'object' || Array.isArray(state)) {
|
|
540
|
+
throw vectorError(VECTOR_ERROR_CODES.ACTIVE_CORRUPT, 'vector-active.json is not an object', { file })
|
|
541
|
+
}
|
|
542
|
+
if (state.active !== null && state.active !== undefined && !validActive(state.active)) {
|
|
543
|
+
throw vectorError(VECTOR_ERROR_CODES.ACTIVE_CORRUPT, 'vector-active.json has an invalid active block', { file, active: state.active })
|
|
544
|
+
}
|
|
545
|
+
if (state.pending !== null && state.pending !== undefined && !validPending(state.pending)) {
|
|
546
|
+
throw vectorError(VECTOR_ERROR_CODES.TORN_STATE, 'vector-active.json has an invalid pending journal', { file, pending: state.pending })
|
|
547
|
+
}
|
|
548
|
+
if (state.version !== VECTOR_ACTIVE_SCHEMA || !Number.isSafeInteger(state.generation) || state.generation < 0) throw vectorError(VECTOR_ERROR_CODES.TORN_STATE, 'unsupported or invalid vector active schema/generation', { file })
|
|
549
|
+
if (state.active) {
|
|
550
|
+
const active = state.active
|
|
551
|
+
if (active.fingerprint !== active.profile.fingerprint || state.generation < active.generation) throw vectorError(VECTOR_ERROR_CODES.TORN_STATE, 'active profile and generation disagree', { file })
|
|
552
|
+
const entries = [[null, active.databases.global], ...Object.entries(active.databases.libraries)]
|
|
553
|
+
for (const [libraryId, entry] of entries) {
|
|
554
|
+
if (!entry || typeof entry !== 'object' || entry.path !== vectorDbRelPath({ libraryId, fingerprint: active.fingerprint, generation: active.generation })) throw vectorError(VECTOR_ERROR_CODES.TORN_STATE, 'active database mapping disagrees with its generation', { file, libraryId })
|
|
555
|
+
}
|
|
556
|
+
}
|
|
557
|
+
if (state.pending?.status === 'committed' && (!state.active || state.pending.generation !== state.active.generation || state.pending.fingerprint !== state.active.fingerprint)) throw vectorError(VECTOR_ERROR_CODES.TORN_STATE, 'committed journal disagrees with active generation', { file })
|
|
558
|
+
return { ok: true, state: normalizeState(state), file }
|
|
559
|
+
}
|
|
560
|
+
|
|
561
|
+
function normalizeState(state) {
|
|
562
|
+
return {
|
|
563
|
+
version: VECTOR_ACTIVE_SCHEMA,
|
|
564
|
+
generation: Number.isSafeInteger(state.generation) && state.generation >= 0 ? state.generation : 0,
|
|
565
|
+
requested: state.requested && typeof state.requested === 'object' ? state.requested : null,
|
|
566
|
+
active: state.active && typeof state.active === 'object' ? state.active : null,
|
|
567
|
+
pending: state.pending && typeof state.pending === 'object' ? state.pending : null,
|
|
568
|
+
writeGuard: state.writeGuard && typeof state.writeGuard === 'object' ? state.writeGuard : { frozen: null, leases: {} },
|
|
569
|
+
}
|
|
570
|
+
}
|
|
571
|
+
|
|
572
|
+
/** 读当前 state;缺失返回 null,损坏抛 typed error。 */
|
|
573
|
+
export function vectorState() {
|
|
574
|
+
return readVectorState({ tolerateMissing: true }).state
|
|
575
|
+
}
|
|
576
|
+
|
|
577
|
+
/**
|
|
578
|
+
* 唯一写入口:文件锁内做同步 compare + 原子指针写。mutator 必须同步——
|
|
579
|
+
* 绝不允许跨 await 持有文件锁(§14.8 第 5/7 条)。
|
|
580
|
+
*/
|
|
581
|
+
export function updateVectorStateSync(mutator) {
|
|
582
|
+
if (typeof mutator !== 'function') throw vectorError(VECTOR_ERROR_CODES.BAD_UPDATE, 'updateVectorStateSync requires a mutator')
|
|
583
|
+
const file = vectorActiveFile()
|
|
584
|
+
ensureDir(indexDir())
|
|
585
|
+
return withFileLock(file, () => {
|
|
586
|
+
const result = readJsonStrict(file)
|
|
587
|
+
let current
|
|
588
|
+
if (result.ok) {
|
|
589
|
+
if (!result.value || typeof result.value !== 'object' || Array.isArray(result.value)) {
|
|
590
|
+
throw vectorError(VECTOR_ERROR_CODES.ACTIVE_CORRUPT, 'vector-active.json is not an object', { file })
|
|
591
|
+
}
|
|
592
|
+
current = readVectorState({ tolerateMissing: false }).state
|
|
593
|
+
} else if (result.missing) {
|
|
594
|
+
current = emptyState()
|
|
595
|
+
} else if (result.kind === 'corrupt') {
|
|
596
|
+
throw vectorError(VECTOR_ERROR_CODES.ACTIVE_CORRUPT, 'vector-active.json is not valid JSON; refusing to overwrite it', { file })
|
|
597
|
+
} else {
|
|
598
|
+
throw vectorError(VECTOR_ERROR_CODES.ACTIVE_UNREADABLE, 'cannot read vector-active.json', { file })
|
|
599
|
+
}
|
|
600
|
+
const next = mutator(current)
|
|
601
|
+
if (next && typeof next.then === 'function') {
|
|
602
|
+
throw vectorError(VECTOR_ERROR_CODES.BAD_UPDATE, 'updateVectorStateSync mutator must be synchronous: never hold the vector lock across an await')
|
|
603
|
+
}
|
|
604
|
+
if (!next) return current
|
|
605
|
+
const payload = normalizeState(next)
|
|
606
|
+
writeJson(file, payload)
|
|
607
|
+
return payload
|
|
608
|
+
})
|
|
609
|
+
}
|
|
610
|
+
|
|
611
|
+
/** requested 与 active 分离:用户"选了"不等于"生效了"(§14.6 第 2 条)。 */
|
|
612
|
+
export function requestedProfile() {
|
|
613
|
+
const state = vectorState()
|
|
614
|
+
const requested = state?.requested
|
|
615
|
+
if (!requested || typeof requested !== 'object') return null
|
|
616
|
+
return requested
|
|
617
|
+
}
|
|
618
|
+
|
|
619
|
+
export function setRequestedProfile(value, extra = {}) {
|
|
620
|
+
const profile = resolveProfile(value)
|
|
621
|
+
const at = stamp()
|
|
622
|
+
const next = updateVectorStateSync(state => ({
|
|
623
|
+
...state,
|
|
624
|
+
requested: { status: 'requested', catalogId: profile.catalogId, fingerprint: profile.fingerprint, profile, at, ...extra },
|
|
625
|
+
}))
|
|
626
|
+
return next.requested
|
|
627
|
+
}
|
|
628
|
+
|
|
629
|
+
export function clearRequestedProfile() {
|
|
630
|
+
const next = updateVectorStateSync(state => ({ ...state, requested: null }))
|
|
631
|
+
return next.requested
|
|
632
|
+
}
|
|
633
|
+
|
|
634
|
+
/** 当前生效的 profile;没有就返回 null(不猜、不回退默认模型)。 */
|
|
635
|
+
export function activeProfile() {
|
|
636
|
+
const state = vectorState()
|
|
637
|
+
if (!state?.active) return null
|
|
638
|
+
assertProfileVerified(state.active.profile)
|
|
639
|
+
return state.active.profile
|
|
640
|
+
}
|
|
641
|
+
|
|
642
|
+
export function activeGeneration() {
|
|
643
|
+
const state = vectorState()
|
|
644
|
+
return state?.active?.generation ?? null
|
|
645
|
+
}
|
|
646
|
+
|
|
647
|
+
// ---------------------------------------------------------------- 兼容修复:重签与重指
|
|
648
|
+
|
|
649
|
+
/**
|
|
650
|
+
* 把落盘 profile 重写成 catalog 现在的规范形态(重签 manifest 摘要)。
|
|
651
|
+
*
|
|
652
|
+
* 只在"制品身份没变"时允许:身份变了就是真换了制品,重签会把不同向量空间混进同一个
|
|
653
|
+
* 代际(比报错更坏),那种情况必须走重建。重签保留 modelDir / runtimeDir——那是"本地装
|
|
654
|
+
* 在哪",不是制品身份。写盘走 updateVectorStateSync(文件锁 + 原子写),并先留一份
|
|
655
|
+
* .bak-resign-<时间> 备份。
|
|
656
|
+
*/
|
|
657
|
+
export function resignVectorProfile({ dryRun = false } = {}) {
|
|
658
|
+
const state = vectorState()
|
|
659
|
+
const slots = ['requested', 'active'].filter(slot => state?.[slot]?.profile?.catalogId)
|
|
660
|
+
if (!slots.length) return { changed: false, reason: 'no-profile', slots: [] }
|
|
661
|
+
const plan = []
|
|
662
|
+
for (const slot of slots) {
|
|
663
|
+
const profile = state[slot].profile
|
|
664
|
+
const entry = resolveCatalogEntry(profile.catalogId)
|
|
665
|
+
if (!entry) throw vectorError(VECTOR_ERROR_CODES.PROFILE_UNKNOWN, 'the catalog no longer defines ' + profile.catalogId, { catalogId: profile.catalogId })
|
|
666
|
+
const expected = profileFingerprint(entry)
|
|
667
|
+
if (profile.fingerprint !== expected) {
|
|
668
|
+
throw vectorError(VECTOR_ERROR_CODES.PROFILE_FINGERPRINT_MISMATCH, 'profile fingerprint does not match the catalog for ' + entry.id, { expected, actual: profile.fingerprint, catalogId: entry.id })
|
|
669
|
+
}
|
|
670
|
+
plan.push({ slot, profile, entry, drift: manifestDrift(profile.manifest, entry) })
|
|
671
|
+
}
|
|
672
|
+
const blocked = plan.find(item => item.drift.identityChanged.length)
|
|
673
|
+
if (blocked) {
|
|
674
|
+
throw vectorError(VECTOR_ERROR_CODES.PROFILE_MANIFEST_CHANGED, 'the artifact identity changed; re-signing cannot fix that', {
|
|
675
|
+
changedFields: blocked.drift.identityChanged, catalogId: blocked.profile.catalogId, recoverable: false,
|
|
676
|
+
})
|
|
677
|
+
}
|
|
678
|
+
const stale = plan.filter(item => item.drift.fields.length)
|
|
679
|
+
const report = {
|
|
680
|
+
changed: stale.length > 0,
|
|
681
|
+
reason: stale.length ? 'metadata-drift' : 'already-current',
|
|
682
|
+
file: vectorActiveFile(),
|
|
683
|
+
backup: null,
|
|
684
|
+
slots: stale.map(item => ({
|
|
685
|
+
slot: item.slot,
|
|
686
|
+
catalogId: item.profile.catalogId,
|
|
687
|
+
changedFields: item.drift.fields,
|
|
688
|
+
metadataOnly: item.drift.metadataOnly,
|
|
689
|
+
previousDigest: item.profile.manifestDigest,
|
|
690
|
+
nextDigest: manifestDigest(item.entry),
|
|
691
|
+
})),
|
|
692
|
+
}
|
|
693
|
+
if (!report.changed || dryRun) return report
|
|
694
|
+
try {
|
|
695
|
+
report.backup = `${report.file}.bak-resign-${stamp().replace(/[:.]/g, '-')}`
|
|
696
|
+
fs.copyFileSync(report.file, report.backup)
|
|
697
|
+
} catch { report.backup = null }
|
|
698
|
+
updateVectorStateSync(current => {
|
|
699
|
+
const next = { ...current }
|
|
700
|
+
for (const slot of ['requested', 'active']) {
|
|
701
|
+
const wrapper = next[slot]
|
|
702
|
+
const catalogId = wrapper?.profile?.catalogId
|
|
703
|
+
if (!catalogId) continue
|
|
704
|
+
const entry = resolveCatalogEntry(catalogId)
|
|
705
|
+
if (!entry) continue
|
|
706
|
+
const rebuilt = buildProfile(entry, { modelDir: wrapper.profile.modelDir, runtimeDir: wrapper.profile.runtimeDir })
|
|
707
|
+
next[slot] = {
|
|
708
|
+
...wrapper,
|
|
709
|
+
status: wrapper.status || (slot === 'active' ? 'active' : 'requested'),
|
|
710
|
+
catalogId: rebuilt.catalogId,
|
|
711
|
+
fingerprint: rebuilt.fingerprint,
|
|
712
|
+
manifestDigest: rebuilt.manifestDigest,
|
|
713
|
+
profile: rebuilt,
|
|
714
|
+
resignedAt: stamp(),
|
|
715
|
+
}
|
|
716
|
+
}
|
|
717
|
+
return next
|
|
718
|
+
})
|
|
719
|
+
return report
|
|
720
|
+
}
|
|
721
|
+
|
|
722
|
+
function runtimeDirHasArtifacts(dir) {
|
|
723
|
+
if (typeof dir !== 'string' || !dir.trim()) return false
|
|
724
|
+
try { return fs.existsSync(path.join(dir, 'node_modules', 'onnxruntime-node', 'package.json')) } catch { return false }
|
|
725
|
+
}
|
|
726
|
+
|
|
727
|
+
/**
|
|
728
|
+
* 候选 runtime 目录。
|
|
729
|
+
*
|
|
730
|
+
* 受管运行时住在 downloads/embeddings/runtime/<key>(与模型同级,见 local-vector-service.js
|
|
731
|
+
* 的 runtimeRoot);早期版本写过 downloads/runtime,所以两处都扫,新的优先。
|
|
732
|
+
*/
|
|
733
|
+
export function runtimeDirCandidates() {
|
|
734
|
+
const roots = [path.join(downloadsDir(), 'embeddings', 'runtime'), path.join(downloadsDir(), 'runtime')]
|
|
735
|
+
const out = []
|
|
736
|
+
for (const root of roots) {
|
|
737
|
+
try {
|
|
738
|
+
const active = JSON.parse(fs.readFileSync(path.join(root, 'active.json'), 'utf8'))
|
|
739
|
+
const hinted = active?.dir || active?.runtimeDir || active?.path || active?.active?.dir || null
|
|
740
|
+
if (typeof hinted === 'string' && hinted.trim()) {
|
|
741
|
+
const abs = path.isAbsolute(hinted) ? hinted : path.join(root, hinted)
|
|
742
|
+
if (runtimeDirHasArtifacts(abs)) out.push({ dir: abs, source: 'active.json', mtimeMs: 0 })
|
|
743
|
+
}
|
|
744
|
+
} catch {}
|
|
745
|
+
}
|
|
746
|
+
const found = []
|
|
747
|
+
for (const root of roots) {
|
|
748
|
+
let entries = []
|
|
749
|
+
try { entries = fs.readdirSync(root, { withFileTypes: true }) } catch { entries = [] }
|
|
750
|
+
for (const entry of entries) {
|
|
751
|
+
if (!entry.isDirectory()) continue
|
|
752
|
+
const abs = path.join(root, entry.name)
|
|
753
|
+
if (!runtimeDirHasArtifacts(abs)) continue
|
|
754
|
+
let mtimeMs = 0
|
|
755
|
+
try { mtimeMs = fs.statSync(path.join(abs, 'node_modules', 'onnxruntime-node', 'package.json')).mtimeMs } catch {}
|
|
756
|
+
found.push({ dir: abs, source: 'scan', mtimeMs })
|
|
757
|
+
}
|
|
758
|
+
}
|
|
759
|
+
found.sort((a, b) => b.mtimeMs - a.mtimeMs)
|
|
760
|
+
for (const item of found) if (!out.some(existing => existing.dir === item.dir)) out.push(item)
|
|
761
|
+
return out
|
|
762
|
+
}
|
|
763
|
+
|
|
764
|
+
/**
|
|
765
|
+
* 把 profile 的 runtimeDir 重指到一个真正装着 onnxruntime-node 的目录。
|
|
766
|
+
*
|
|
767
|
+
* 安装目录移动或被移除后,修复本地运行时路径以恢复 worker 启动。
|
|
768
|
+
* 重指只改变安装位置,保留制品身份与向量代际。
|
|
769
|
+
*/
|
|
770
|
+
export function repointVectorRuntimeDir({ dryRun = false, dir = null } = {}) {
|
|
771
|
+
const state = vectorState()
|
|
772
|
+
const slots = ['requested', 'active'].filter(slot => state?.[slot]?.profile?.catalogId)
|
|
773
|
+
if (!slots.length) return { changed: false, reason: 'no-profile', slots: [], candidates: runtimeDirCandidates().map(item => item.dir) }
|
|
774
|
+
const current = state.active?.profile?.runtimeDir || state.requested?.profile?.runtimeDir || null
|
|
775
|
+
if (!dir) {
|
|
776
|
+
const candidates = runtimeDirCandidates()
|
|
777
|
+
if (!candidates.length) return { changed: false, reason: 'no-runtime-installed', slots: [], current, candidates: [] }
|
|
778
|
+
dir = candidates[0].dir
|
|
779
|
+
}
|
|
780
|
+
if (runtimeDirHasArtifacts(current) && path.resolve(current) === path.resolve(dir)) {
|
|
781
|
+
return { changed: false, reason: 'already-pointed', slots: [], current, next: dir, candidates: [] }
|
|
782
|
+
}
|
|
783
|
+
const report = { changed: true, reason: 'repointed', file: vectorActiveFile(), backup: null, current, next: dir, slots: [], candidates: [] }
|
|
784
|
+
if (dryRun) return report
|
|
785
|
+
try {
|
|
786
|
+
report.backup = `${report.file}.bak-runtimedir-${stamp().replace(/[:.]/g, '-')}`
|
|
787
|
+
fs.copyFileSync(report.file, report.backup)
|
|
788
|
+
} catch { report.backup = null }
|
|
789
|
+
updateVectorStateSync(current2 => {
|
|
790
|
+
const next = { ...current2 }
|
|
791
|
+
for (const slot of ['requested', 'active']) {
|
|
792
|
+
const wrapper = next[slot]
|
|
793
|
+
if (!wrapper?.profile?.catalogId) continue
|
|
794
|
+
next[slot] = {
|
|
795
|
+
...wrapper,
|
|
796
|
+
profile: { ...wrapper.profile, runtimeDir: dir },
|
|
797
|
+
repointedAt: stamp(),
|
|
798
|
+
}
|
|
799
|
+
report.slots.push(slot)
|
|
800
|
+
}
|
|
801
|
+
return next
|
|
802
|
+
})
|
|
803
|
+
return report
|
|
804
|
+
}
|
|
805
|
+
|
|
806
|
+
/**
|
|
807
|
+
* 条目级"已入向量库"戳(entry.vector)。迁移写库故意不碰索引,所以迁移写入的条目没有
|
|
808
|
+
* 戳、只有账本知道;而迁移之后的每一次向量写入(remember/import/review/update/curator)
|
|
809
|
+
* 都必须在提交成功后把这条戳落进索引。词法路径没写库,不戳;remote-api 沿用历史口径
|
|
810
|
+
* (本地还留着 active 代际时照样记,界面只拿它回答"进没进向量后端")。空间归属由
|
|
811
|
+
* membership() 的戳腿自行过滤:只认 route === 'managed-local' 且代际匹配的戳。只读不抛错。
|
|
812
|
+
*/
|
|
813
|
+
export function activeEntryStamp(route) {
|
|
814
|
+
if (route === 'lexical') return null
|
|
815
|
+
try {
|
|
816
|
+
const active = readVectorState({ tolerateMissing: true }).state?.active
|
|
817
|
+
if (!active) return null
|
|
818
|
+
return {
|
|
819
|
+
route,
|
|
820
|
+
model: active.profile?.catalogId || null,
|
|
821
|
+
generation: active.generation,
|
|
822
|
+
fingerprint: String(active.fingerprint || '').slice(0, 8),
|
|
823
|
+
at: stamp(),
|
|
824
|
+
}
|
|
825
|
+
} catch {
|
|
826
|
+
return null
|
|
827
|
+
}
|
|
828
|
+
}
|
|
829
|
+
|
|
830
|
+
/** active manifest 里的 DB 集合,一次性取得(避免多库逐个换混空间)。 */
|
|
831
|
+
export function activeDatabases() {
|
|
832
|
+
return databaseMapFor(vectorState()?.active)
|
|
833
|
+
}
|
|
834
|
+
|
|
835
|
+
function databaseMapFor(active) {
|
|
836
|
+
if (!active) return null
|
|
837
|
+
const databases = { global: resolveVectorPath(active.databases.global.path), libraries: {} }
|
|
838
|
+
for (const [libraryId, entry] of Object.entries(active.databases.libraries || {})) {
|
|
839
|
+
databases.libraries[libraryId] = resolveVectorPath(entry?.path)
|
|
840
|
+
}
|
|
841
|
+
return {
|
|
842
|
+
generation: active.generation,
|
|
843
|
+
fingerprint: active.fingerprint,
|
|
844
|
+
profile: active.profile,
|
|
845
|
+
snapshot: active.snapshot ?? null,
|
|
846
|
+
global: databases.global,
|
|
847
|
+
libraries: databases.libraries,
|
|
848
|
+
}
|
|
849
|
+
}
|
|
850
|
+
|
|
851
|
+
/**
|
|
852
|
+
* 非受管模式仍可用:有 active 代际就用它的路径,否则回落 legacy 路径。
|
|
853
|
+
* state.js 的 memoryDbPath 通过此函数解析当前数据库路径。
|
|
854
|
+
*/
|
|
855
|
+
export function dbPathFor(libraryId = null) {
|
|
856
|
+
const state = vectorState()
|
|
857
|
+
const active = state?.active
|
|
858
|
+
if (!active) return legacyDbPath(libraryId)
|
|
859
|
+
assertProfileVerified(active.profile)
|
|
860
|
+
const entry = libraryId === null || libraryId === undefined || libraryId === 'global'
|
|
861
|
+
? active.databases.global
|
|
862
|
+
: active.databases.libraries?.[libraryId]
|
|
863
|
+
if (!entry) throw vectorError(VECTOR_ERROR_CODES.TORN_STATE, 'the active generation does not contain library ' + libraryId)
|
|
864
|
+
return resolveVectorPath(entry.path)
|
|
865
|
+
}
|
|
866
|
+
|
|
867
|
+
/**
|
|
868
|
+
* Register a genuinely empty new library in the current space, never legacy.
|
|
869
|
+
* Call within withVectorWrite and before the first commit/index submission.
|
|
870
|
+
* loadIndex must be synchronous; by default the authoritative raw index is read.
|
|
871
|
+
* A nonempty, corrupt, quarantined or unknown-shaped index requires rebuilding.
|
|
872
|
+
*/
|
|
873
|
+
/**
|
|
874
|
+
* Remove one library from the active database map under the manifest lock.
|
|
875
|
+
* The caller owns filesystem cleanup; returning the captured absolute path keeps
|
|
876
|
+
* the manifest mutation atomic without deleting a possibly newer generation.
|
|
877
|
+
*/
|
|
878
|
+
export function removeActiveLibrary(libraryId) {
|
|
879
|
+
if (!isSafeId(libraryId) || libraryId === 'global') throw vectorError(VECTOR_ERROR_CODES.PATH_ESCAPE, 'unsafe private library id: ' + JSON.stringify(libraryId))
|
|
880
|
+
let removed = null
|
|
881
|
+
updateVectorStateSync(state => {
|
|
882
|
+
const guard = liveGuard(state.writeGuard)
|
|
883
|
+
if (guard.frozen || Object.keys(guard.leases).length) {
|
|
884
|
+
throw vectorError('VECTOR_WRITE_BUSY', 'an in-flight vector write prevents deleting a library; retry shortly', { libraryId })
|
|
885
|
+
}
|
|
886
|
+
if (state.pending) {
|
|
887
|
+
throw vectorError('VECTOR_WRITE_BUSY', 'a vector generation switch prevents deleting a library; retry shortly', { libraryId })
|
|
888
|
+
}
|
|
889
|
+
const active = state.active
|
|
890
|
+
const entry = active?.databases?.libraries?.[libraryId]
|
|
891
|
+
if (!active || !entry) return null
|
|
892
|
+
removed = resolveVectorPath(entry.path)
|
|
893
|
+
const libraries = { ...active.databases.libraries }
|
|
894
|
+
delete libraries[libraryId]
|
|
895
|
+
return { ...state, active: { ...active, databases: { ...active.databases, libraries } } }
|
|
896
|
+
})
|
|
897
|
+
return removed
|
|
898
|
+
}
|
|
899
|
+
|
|
900
|
+
export function enrollActiveLibrary(libraryId, { loadIndex } = {}) {
|
|
901
|
+
if (!isSafeId(libraryId) || libraryId === 'global') throw vectorError(VECTOR_ERROR_CODES.PATH_ESCAPE, 'unsafe private library id: ' + JSON.stringify(libraryId))
|
|
902
|
+
let db = null
|
|
903
|
+
updateVectorStateSync(state => {
|
|
904
|
+
if (!state.active) { db = legacyDbPath(libraryId); return null }
|
|
905
|
+
const guard = liveGuard(state.writeGuard)
|
|
906
|
+
if (guard.frozen) throw vectorError('VECTOR_WRITE_FROZEN', 'cannot enroll a library during a vector generation switch')
|
|
907
|
+
if (!Object.values(guard.leases).some(lease => lease.pid === process.pid)) throw vectorError('VECTOR_WRITE_LEASE_REQUIRED', 'enrollActiveLibrary must run within withVectorWrite')
|
|
908
|
+
assertProfileVerified(state.active.profile)
|
|
909
|
+
const existing = state.active.databases.libraries[libraryId]
|
|
910
|
+
if (existing) { db = resolveVectorPath(existing.path); return null }
|
|
911
|
+
const indexFile = path.join(indexDir(), libraryId + '.json')
|
|
912
|
+
return withFileLock(indexFile, () => {
|
|
913
|
+
let index
|
|
914
|
+
if (loadIndex) index = loadIndex(libraryId)
|
|
915
|
+
else {
|
|
916
|
+
const result = readJsonStrict(indexFile)
|
|
917
|
+
if (result.ok) index = result.value
|
|
918
|
+
else if (result.missing && !fs.readdirSync(indexDir()).some(name => name.startsWith(libraryId + '.json.corrupt-'))) index = { entries: {} }
|
|
919
|
+
else throw vectorError('VECTOR_LIBRARY_REBUILD_REQUIRED', 'new library index cannot be proven empty; rebuild the vector generation', { libraryId })
|
|
920
|
+
}
|
|
921
|
+
if (index && typeof index.then === 'function') throw vectorError(VECTOR_ERROR_CODES.BAD_UPDATE, 'enrollActiveLibrary loadIndex must be synchronous')
|
|
922
|
+
if (!index || typeof index !== 'object' || !index.entries || typeof index.entries !== 'object' || Array.isArray(index.entries) || Object.keys(index.entries).length) throw vectorError('VECTOR_LIBRARY_REBUILD_REQUIRED', 'a nonempty or invalid library index requires shadow rebuilding', { libraryId })
|
|
923
|
+
const rel = vectorDbRelPath({ libraryId, fingerprint: state.active.fingerprint, generation: state.active.generation })
|
|
924
|
+
db = resolveVectorPath(rel)
|
|
925
|
+
ensureDir(path.dirname(db))
|
|
926
|
+
try { fs.writeFileSync(db, '', { flag: 'wx' }) } catch (error) {
|
|
927
|
+
throw vectorError(VECTOR_ERROR_CODES.SHADOW_PATH_TAKEN, 'new library vector path already exists or cannot be created; refusing to reuse it', { libraryId, causeCode: error?.code })
|
|
928
|
+
}
|
|
929
|
+
return { ...state, active: { ...state.active, databases: { ...state.active.databases, libraries: { ...state.active.databases.libraries, [libraryId]: { path: rel, bytes: 0, sha256: sha256Hex('') } } } } }
|
|
930
|
+
})
|
|
931
|
+
})
|
|
932
|
+
return db
|
|
933
|
+
}
|
|
934
|
+
|
|
935
|
+
export function profileDatabaseMap(libraryIds = [], profile = activeProfile()) {
|
|
936
|
+
const state = vectorState()
|
|
937
|
+
const active = state?.active
|
|
938
|
+
const out = {}
|
|
939
|
+
for (const id of libraryIds) {
|
|
940
|
+
if (active?.databases?.libraries?.[id]) out[id] = resolveVectorPath(active.databases.libraries[id].path)
|
|
941
|
+
else if (profile) out[id] = vectorDbAbsPath({ libraryId: id, fingerprint: profile.fingerprint, generation: (active?.generation ?? 0) + 1 })
|
|
942
|
+
else out[id] = legacyDbPath(id)
|
|
943
|
+
}
|
|
944
|
+
return out
|
|
945
|
+
}
|
|
946
|
+
|
|
947
|
+
/** memu 子进程需要的本地嵌入环境(不写 key 到磁盘,只在进程环境里传)。 */
|
|
948
|
+
export function profileEnv(profile, { baseUrl, token } = {}) {
|
|
949
|
+
if (!profile) return {}
|
|
950
|
+
const env = {
|
|
951
|
+
MEMU_MEMORY_MODE: 'local',
|
|
952
|
+
MEMU_EMBED_PROVIDER: 'openai',
|
|
953
|
+
MEMU_EMBED_MODEL: String(profile.catalogId || profile.model || ''),
|
|
954
|
+
MEMU_BASE_URL: String(baseUrl || '').replace(/\/$/, ''),
|
|
955
|
+
MEMU_TELEMETRY: '0',
|
|
956
|
+
DO_NOT_TRACK: '1',
|
|
957
|
+
MEMU_EVENTS_BASE_URL: '',
|
|
958
|
+
}
|
|
959
|
+
if (token) env.MEMU_API_KEY = String(token)
|
|
960
|
+
return env
|
|
961
|
+
}
|
|
962
|
+
|
|
963
|
+
// ---------------------------------------------------------------- 代际与 pending journal
|
|
964
|
+
|
|
965
|
+
export function nextGeneration(state = null) {
|
|
966
|
+
const current = state ?? vectorState()
|
|
967
|
+
const active = Number.isSafeInteger(current?.active?.generation) ? current.active.generation : 0
|
|
968
|
+
const pending = Number.isSafeInteger(current?.pending?.generation) ? current.pending.generation : 0
|
|
969
|
+
const counter = Number.isSafeInteger(current?.generation) ? current.generation : 0
|
|
970
|
+
return Math.max(active, pending, counter) + 1
|
|
971
|
+
}
|
|
972
|
+
|
|
973
|
+
export function buildDatabaseSet({ profile, generation, libraryIds = [] }) {
|
|
974
|
+
const databases = {
|
|
975
|
+
global: { path: vectorDbRelPath({ libraryId: null, fingerprint: profile.fingerprint, generation }), bytes: null, sha256: null },
|
|
976
|
+
libraries: {},
|
|
977
|
+
}
|
|
978
|
+
for (const libraryId of libraryIds) {
|
|
979
|
+
if (!isSafeId(libraryId)) throw vectorError(VECTOR_ERROR_CODES.PATH_ESCAPE, 'unsafe library id: ' + JSON.stringify(libraryId), { libraryId })
|
|
980
|
+
databases.libraries[libraryId] = { path: vectorDbRelPath({ libraryId, fingerprint: profile.fingerprint, generation }), bytes: null, sha256: null }
|
|
981
|
+
}
|
|
982
|
+
return databases
|
|
983
|
+
}
|
|
984
|
+
|
|
985
|
+
/**
|
|
986
|
+
* 为一次影子重建分配全新代际,并把 prepared journal 先持久化。
|
|
987
|
+
* 这一步之后 DB 路径才存在,所以"每次重建都是全新路径",绝不复用上一轮的影子库
|
|
988
|
+
* (避免把一次 recommit 当成一次 reembedding,§14.8 第 2/4 条)。
|
|
989
|
+
*/
|
|
990
|
+
export function reserveShadowGeneration({ profile, libraryIds = [], reason = 'switch' } = {}) {
|
|
991
|
+
const verified = assertProfileVerified(profile)
|
|
992
|
+
const at = stamp()
|
|
993
|
+
let reserved = null
|
|
994
|
+
const state = updateVectorStateSync(current => {
|
|
995
|
+
const generation = nextGeneration(current)
|
|
996
|
+
const databases = buildDatabaseSet({ profile: verified, generation, libraryIds })
|
|
997
|
+
const token = sha256Hex(stableStringify({ generation, fingerprint: verified.fingerprint, previousGeneration: current.active?.generation ?? null, at, reason }))
|
|
998
|
+
reserved = { generation, token, databases, at }
|
|
999
|
+
return {
|
|
1000
|
+
...current,
|
|
1001
|
+
generation: Math.max(current.generation || 0, generation),
|
|
1002
|
+
pending: {
|
|
1003
|
+
status: 'preparing',
|
|
1004
|
+
generation,
|
|
1005
|
+
fingerprint: verified.fingerprint,
|
|
1006
|
+
catalogId: verified.catalogId,
|
|
1007
|
+
profile: verified,
|
|
1008
|
+
previousGeneration: current.active?.generation ?? null,
|
|
1009
|
+
previousFingerprint: current.active?.fingerprint ?? null,
|
|
1010
|
+
databases,
|
|
1011
|
+
reason,
|
|
1012
|
+
token,
|
|
1013
|
+
at,
|
|
1014
|
+
updatedAt: at,
|
|
1015
|
+
error: null,
|
|
1016
|
+
report: null,
|
|
1017
|
+
},
|
|
1018
|
+
}
|
|
1019
|
+
})
|
|
1020
|
+
return { ...reserved, state }
|
|
1021
|
+
}
|
|
1022
|
+
|
|
1023
|
+
/** pending journal 的读取与更新(都在同一把同步锁里)。 */
|
|
1024
|
+
export function pendingJournal() {
|
|
1025
|
+
const state = vectorState()
|
|
1026
|
+
return state?.pending ?? null
|
|
1027
|
+
}
|
|
1028
|
+
|
|
1029
|
+
export function updatePendingJournal(mutator) {
|
|
1030
|
+
let result = null
|
|
1031
|
+
updateVectorStateSync(state => {
|
|
1032
|
+
if (!state.pending) return null
|
|
1033
|
+
const next = typeof mutator === 'function' ? mutator(state.pending) : { ...state.pending, ...mutator }
|
|
1034
|
+
if (!next) return null
|
|
1035
|
+
result = { ...next, updatedAt: stamp() }
|
|
1036
|
+
return { ...state, pending: result }
|
|
1037
|
+
})
|
|
1038
|
+
return result
|
|
1039
|
+
}
|
|
1040
|
+
|
|
1041
|
+
export function clearPendingJournal() {
|
|
1042
|
+
const next = updateVectorStateSync(state => (state.pending ? { ...state, pending: null } : null))
|
|
1043
|
+
return next.pending ?? null
|
|
1044
|
+
}
|
|
1045
|
+
|
|
1046
|
+
// ---------------------------------------------------------------- 写入护栏
|
|
1047
|
+
|
|
1048
|
+
function databasePaths(databases) {
|
|
1049
|
+
const paths = [resolveVectorPath(databases.global.path)]
|
|
1050
|
+
for (const entry of Object.values(databases.libraries || {})) paths.push(resolveVectorPath(entry?.path))
|
|
1051
|
+
return paths
|
|
1052
|
+
}
|
|
1053
|
+
|
|
1054
|
+
/**
|
|
1055
|
+
* 护栏核心:此刻是否允许读/写向量。
|
|
1056
|
+
* deep=true 时额外核对文件大小(启动恢复/切换前用;运行期不查,因为 active 库会正常增长)。
|
|
1057
|
+
*/
|
|
1058
|
+
export function assertVectorWriteAllowed({ deep = false, readOnly = false } = {}) {
|
|
1059
|
+
const state = readVectorState({ tolerateMissing: false }).state
|
|
1060
|
+
if (!readOnly && liveGuard(state.writeGuard).frozen) throw vectorError('VECTOR_WRITE_FROZEN', 'vector writes are paused for the final generation switch; retry shortly')
|
|
1061
|
+
const active = state.active
|
|
1062
|
+
if (!active) throw vectorError(VECTOR_ERROR_CODES.NOT_ACTIVE, 'no active vector generation; use lexical recall')
|
|
1063
|
+
if (!validActive(active)) throw vectorError(VECTOR_ERROR_CODES.TORN_STATE, 'the active vector manifest is incomplete; refusing vectors')
|
|
1064
|
+
if (state.pending?.status === 'committed' && state.pending.generation !== active.generation) {
|
|
1065
|
+
throw vectorError(VECTOR_ERROR_CODES.TORN_STATE, 'the commit journal and the active pointer disagree about the generation; refusing vectors', {
|
|
1066
|
+
pendingGeneration: state.pending.generation, activeGeneration: active.generation,
|
|
1067
|
+
})
|
|
1068
|
+
}
|
|
1069
|
+
if (state.pending?.status === 'preparing' && state.pending.previousGeneration === null && !state.active) {
|
|
1070
|
+
throw vectorError(VECTOR_ERROR_CODES.TORN_STATE, 'a build was reserved before any generation became active; refusing vectors')
|
|
1071
|
+
}
|
|
1072
|
+
// 未验证/未知/pending 的 manifest 一律拒绝,绝不拿旧向量空间继续算。
|
|
1073
|
+
assertProfileVerified(active.profile)
|
|
1074
|
+
let paths
|
|
1075
|
+
try {
|
|
1076
|
+
paths = databasePaths(active.databases)
|
|
1077
|
+
} catch (error) {
|
|
1078
|
+
if (isVectorStateError(error)) throw error
|
|
1079
|
+
throw vectorError(VECTOR_ERROR_CODES.TORN_STATE, 'cannot resolve the active database set: ' + (error?.message || error))
|
|
1080
|
+
}
|
|
1081
|
+
for (let index = 0; index < paths.length; index++) {
|
|
1082
|
+
let info
|
|
1083
|
+
try { info = fs.statSync(paths[index]) } catch {
|
|
1084
|
+
throw vectorError(VECTOR_ERROR_CODES.TORN_STATE, 'a database in the active generation is missing: ' + path.basename(paths[index]), { missing: paths[index] })
|
|
1085
|
+
}
|
|
1086
|
+
if (!info.isFile()) {
|
|
1087
|
+
throw vectorError(VECTOR_ERROR_CODES.TORN_STATE, 'a database in the active generation is not a file: ' + path.basename(paths[index]), { path: paths[index] })
|
|
1088
|
+
}
|
|
1089
|
+
const recorded = index === 0 ? active.databases.global.bytes : Object.values(active.databases.libraries || {})[index - 1]?.bytes
|
|
1090
|
+
if (deep && Number.isSafeInteger(recorded) && recorded > 0 && info.size < recorded) {
|
|
1091
|
+
throw vectorError(VECTOR_ERROR_CODES.TORN_STATE, 'a database in the active generation shrank below its committed size: ' + path.basename(paths[index]), {
|
|
1092
|
+
path: paths[index], expected: recorded, actual: info.size,
|
|
1093
|
+
})
|
|
1094
|
+
}
|
|
1095
|
+
}
|
|
1096
|
+
return {
|
|
1097
|
+
generation: active.generation,
|
|
1098
|
+
fingerprint: active.fingerprint,
|
|
1099
|
+
profile: active.profile,
|
|
1100
|
+
databases: databaseMapFor(active),
|
|
1101
|
+
snapshot: active.snapshot ?? null,
|
|
1102
|
+
pending: state.pending ? { status: state.pending.status, generation: state.pending.generation, fingerprint: state.pending.fingerprint } : null,
|
|
1103
|
+
}
|
|
1104
|
+
}
|
|
1105
|
+
|
|
1106
|
+
/** 回合开始捕获单代(§14.8 第 7 条);失败返回 null,调用方退词法。 */
|
|
1107
|
+
export function captureGeneration() {
|
|
1108
|
+
const allowed = assertVectorWriteAllowed({ readOnly: true })
|
|
1109
|
+
return Object.freeze({
|
|
1110
|
+
token: 'gen:' + allowed.generation + ':' + allowed.fingerprint.slice(0, 8),
|
|
1111
|
+
generation: allowed.generation,
|
|
1112
|
+
fingerprint: allowed.fingerprint,
|
|
1113
|
+
profile: allowed.profile,
|
|
1114
|
+
global: allowed.databases.global,
|
|
1115
|
+
libraries: Object.freeze({ ...allowed.databases.libraries }),
|
|
1116
|
+
snapshot: allowed.snapshot,
|
|
1117
|
+
capturedAt: stamp(),
|
|
1118
|
+
})
|
|
1119
|
+
}
|
|
1120
|
+
|
|
1121
|
+
export function tryCaptureGeneration() {
|
|
1122
|
+
try { return captureGeneration() } catch { return null }
|
|
1123
|
+
}
|
|
1124
|
+
|
|
1125
|
+
/**
|
|
1126
|
+
* 投放前重验:代际/指纹/路径必须与捕获时完全一致,否则抛 STALE_GENERATION
|
|
1127
|
+
* (in-flight 的旧代结果不得计入新代成功)。
|
|
1128
|
+
*/
|
|
1129
|
+
export function assertGeneration(captured) {
|
|
1130
|
+
if (!captured || typeof captured !== 'object') {
|
|
1131
|
+
throw vectorError(VECTOR_ERROR_CODES.NO_GENERATION, 'no captured vector generation for this turn; use lexical recall')
|
|
1132
|
+
}
|
|
1133
|
+
const allowed = assertVectorWriteAllowed({ readOnly: true })
|
|
1134
|
+
if (allowed.generation !== captured.generation || allowed.fingerprint !== captured.fingerprint) {
|
|
1135
|
+
throw vectorError(VECTOR_ERROR_CODES.STALE_GENERATION, 'the active vector generation changed during the turn; discard this result', {
|
|
1136
|
+
expected: { generation: captured.generation, fingerprint: captured.fingerprint },
|
|
1137
|
+
actual: { generation: allowed.generation, fingerprint: allowed.fingerprint },
|
|
1138
|
+
})
|
|
1139
|
+
}
|
|
1140
|
+
const currentGlobal = allowed.databases.global
|
|
1141
|
+
const capturedGlobal = captured.global
|
|
1142
|
+
if (capturedGlobal && currentGlobal !== capturedGlobal) {
|
|
1143
|
+
throw vectorError(VECTOR_ERROR_CODES.STALE_GENERATION, 'the active database set changed during the turn', { expected: capturedGlobal, actual: currentGlobal })
|
|
1144
|
+
}
|
|
1145
|
+
for (const [id, db] of Object.entries(captured.libraries || {})) {
|
|
1146
|
+
if (db !== allowed.databases.libraries[id]) throw vectorError(VECTOR_ERROR_CODES.STALE_GENERATION, 'a captured library path no longer belongs to the active generation', { libraryId: id })
|
|
1147
|
+
}
|
|
1148
|
+
const currentIds = Object.keys(allowed.databases.libraries).sort().join(',')
|
|
1149
|
+
const capturedIds = Object.keys(captured.libraries || {}).sort().join(',')
|
|
1150
|
+
if (currentIds !== capturedIds) {
|
|
1151
|
+
throw vectorError(VECTOR_ERROR_CODES.STALE_GENERATION, 'the active library set changed during the turn', { expected: capturedIds, actual: currentIds })
|
|
1152
|
+
}
|
|
1153
|
+
return allowed
|
|
1154
|
+
}
|
|
1155
|
+
|
|
1156
|
+
/** Capture/revalidate an explicit shadow operation; never accept an arbitrary profile/DB. */
|
|
1157
|
+
export function assertMigrationProfile({ profile, db, generation, token } = {}) {
|
|
1158
|
+
assertProfileVerified(profile)
|
|
1159
|
+
const state = vectorState()
|
|
1160
|
+
const pending = state?.pending
|
|
1161
|
+
const stale = () => vectorError(VECTOR_ERROR_CODES.STALE_GENERATION, 'the migration profile or database no longer belongs to the pending generation; discard this result')
|
|
1162
|
+
if (!pending || pending.status === 'committed' || pending.fingerprint !== profile.fingerprint || (generation !== undefined && pending.generation !== generation) || (token !== undefined && pending.token !== token)) throw stale()
|
|
1163
|
+
if ((pending.previousGeneration ?? null) !== (state.active?.generation ?? null) || (pending.previousFingerprint ?? null) !== (state.active?.fingerprint ?? null)) throw stale()
|
|
1164
|
+
const paths = databasePaths(pending.databases)
|
|
1165
|
+
if (typeof db !== 'string' || !paths.includes(path.resolve(db))) throw stale()
|
|
1166
|
+
return Object.freeze({ profile, db: path.resolve(db), generation: pending.generation, token: pending.token })
|
|
1167
|
+
}
|
|
1168
|
+
|
|
1169
|
+
/** 只读状态汇总,供 RPC/UI 用;不抛错(损坏时给 status: 'torn')。 */
|
|
1170
|
+
export function vectorStatus() {
|
|
1171
|
+
let state
|
|
1172
|
+
try {
|
|
1173
|
+
state = vectorState()
|
|
1174
|
+
} catch (error) {
|
|
1175
|
+
return { status: 'torn', error: { code: error.code || 'VECTOR_UNKNOWN', message: String(error?.message || error) }, requested: null, active: null, pending: null }
|
|
1176
|
+
}
|
|
1177
|
+
if (!state) return { status: 'absent', requested: null, active: null, pending: null }
|
|
1178
|
+
// 旧版本在切换成功后会留下 requested = { status: 'active' }。那不是"待切换的另一个
|
|
1179
|
+
// 模型",读的时候按没有请求处理,界面才不会同时显示"当前生效 + 待切换"。
|
|
1180
|
+
const requestedState = state.requested && typeof state.requested === 'object' && state.requested.status !== 'active'
|
|
1181
|
+
? state.requested : null
|
|
1182
|
+
let status = 'absent'
|
|
1183
|
+
if (state.active) {
|
|
1184
|
+
try {
|
|
1185
|
+
assertVectorWriteAllowed({ readOnly: true })
|
|
1186
|
+
status = 'active'
|
|
1187
|
+
} catch (error) {
|
|
1188
|
+
return {
|
|
1189
|
+
status: 'torn',
|
|
1190
|
+
error: { code: error.code || 'VECTOR_UNKNOWN', message: String(error?.message || error) },
|
|
1191
|
+
requested: requestedState ? { catalogId: requestedState.catalogId, fingerprint: requestedState.fingerprint } : null,
|
|
1192
|
+
active: { generation: state.active.generation, fingerprint: state.active.fingerprint, catalogId: state.active.profile?.catalogId ?? null },
|
|
1193
|
+
pending: state.pending ? { status: state.pending.status, generation: state.pending.generation, fingerprint: state.pending.fingerprint } : null,
|
|
1194
|
+
}
|
|
1195
|
+
}
|
|
1196
|
+
}
|
|
1197
|
+
return {
|
|
1198
|
+
status,
|
|
1199
|
+
requested: requestedState ? { catalogId: requestedState.catalogId, fingerprint: requestedState.fingerprint, at: requestedState.at ?? null } : null,
|
|
1200
|
+
active: state.active ? {
|
|
1201
|
+
generation: state.active.generation,
|
|
1202
|
+
fingerprint: state.active.fingerprint,
|
|
1203
|
+
catalogId: state.active.profile?.catalogId ?? null,
|
|
1204
|
+
profile: state.active.profile,
|
|
1205
|
+
databases: activeDatabases(),
|
|
1206
|
+
previous: state.active.previous ?? null,
|
|
1207
|
+
lastMigration: state.active.lastMigration ?? null,
|
|
1208
|
+
updatedAt: state.active.updatedAt ?? null,
|
|
1209
|
+
} : null,
|
|
1210
|
+
pending: state.pending ? {
|
|
1211
|
+
status: state.pending.status,
|
|
1212
|
+
generation: state.pending.generation,
|
|
1213
|
+
fingerprint: state.pending.fingerprint,
|
|
1214
|
+
previousGeneration: state.pending.previousGeneration ?? null,
|
|
1215
|
+
report: state.pending.report ?? null,
|
|
1216
|
+
error: state.pending.error ?? null,
|
|
1217
|
+
} : null,
|
|
1218
|
+
}
|
|
1219
|
+
}
|
|
1220
|
+
|
|
1221
|
+
// Leases are persisted under the same short synchronous manifest lock. No file
|
|
1222
|
+
// lock spans the backend await; a final freeze fails fast while a writer runs.
|
|
1223
|
+
function ownerAlive(owner) {
|
|
1224
|
+
if (!owner || !Number.isSafeInteger(owner.pid) || owner.pid < 1) return false
|
|
1225
|
+
try { process.kill(owner.pid, 0); return true } catch (error) { return error?.code !== 'ESRCH' }
|
|
1226
|
+
}
|
|
1227
|
+
function liveGuard(guard = {}) {
|
|
1228
|
+
return {
|
|
1229
|
+
frozen: ownerAlive(guard.frozen) ? guard.frozen : null,
|
|
1230
|
+
leases: Object.fromEntries(Object.entries(guard.leases || {}).filter(([, lease]) => ownerAlive(lease))),
|
|
1231
|
+
}
|
|
1232
|
+
}
|
|
1233
|
+
export async function withVectorWrite(action) {
|
|
1234
|
+
if (typeof action !== 'function') throw new TypeError('withVectorWrite requires an action')
|
|
1235
|
+
const token = crypto.randomUUID()
|
|
1236
|
+
let generation = null
|
|
1237
|
+
updateVectorStateSync(state => {
|
|
1238
|
+
const guard = liveGuard(state.writeGuard)
|
|
1239
|
+
if (guard.frozen) throw vectorError('VECTOR_WRITE_FROZEN', 'vector writes are paused for a generation switch; retry shortly')
|
|
1240
|
+
if (state.active) generation = assertVectorWriteAllowed()
|
|
1241
|
+
guard.leases[token] = { pid: process.pid, at: stamp() }
|
|
1242
|
+
return { ...state, writeGuard: guard }
|
|
1243
|
+
})
|
|
1244
|
+
try { return await action(generation) } finally {
|
|
1245
|
+
updateVectorStateSync(state => {
|
|
1246
|
+
const guard = liveGuard(state.writeGuard)
|
|
1247
|
+
delete guard.leases[token]
|
|
1248
|
+
return { ...state, writeGuard: guard }
|
|
1249
|
+
})
|
|
1250
|
+
}
|
|
1251
|
+
}
|
|
1252
|
+
export async function withVectorWriteFreeze(action) {
|
|
1253
|
+
if (typeof action !== 'function') throw new TypeError('withVectorWriteFreeze requires an action')
|
|
1254
|
+
const token = crypto.randomUUID()
|
|
1255
|
+
updateVectorStateSync(state => {
|
|
1256
|
+
const guard = liveGuard(state.writeGuard)
|
|
1257
|
+
if (guard.frozen || Object.keys(guard.leases).length) throw vectorError('VECTOR_WRITE_BUSY', 'an in-flight vector write prevents switching; retry shortly')
|
|
1258
|
+
return { ...state, writeGuard: { ...guard, frozen: { pid: process.pid, token, at: stamp() } } }
|
|
1259
|
+
})
|
|
1260
|
+
try { return await action() } finally {
|
|
1261
|
+
updateVectorStateSync(state => {
|
|
1262
|
+
const guard = liveGuard(state.writeGuard)
|
|
1263
|
+
if (guard.frozen?.token === token) guard.frozen = null
|
|
1264
|
+
return { ...state, writeGuard: guard }
|
|
1265
|
+
})
|
|
1266
|
+
}
|
|
1267
|
+
}
|
|
1268
|
+
|
|
1269
|
+
export const activeVectorState = vectorState
|
|
1270
|
+
export const memuDbFor = dbPathFor
|
|
1271
|
+
export const memuGlobalDbFor = () => dbPathFor(null)
|
|
1272
|
+
export const captureVectorGeneration = captureGeneration
|
|
1273
|
+
export const assertVectorGeneration = assertGeneration
|
|
1274
|
+
// ---------------------------------------------------------------- Vector generation GC
|
|
1275
|
+
//
|
|
1276
|
+
// Generation files are safe to collect only when they are (a) not referenced by
|
|
1277
|
+
// the active/pending manifest, (b) older than the active generation by the
|
|
1278
|
+
// configured keep count, and (c) older than a retention window. The pure
|
|
1279
|
+
// candidate filter is exported so the script and tests share exactly one rule.
|
|
1280
|
+
const VECTOR_GC_DAY_MS = 86_400_000
|
|
1281
|
+
|
|
1282
|
+
export function vectorGcCandidates({
|
|
1283
|
+
files = [], activeGeneration = 0, keepGenerations = 2, olderThanDays = 7,
|
|
1284
|
+
now = Date.now(), keepPaths = [],
|
|
1285
|
+
} = {}) {
|
|
1286
|
+
const keepGenerationsCount = Math.max(1, Number(keepGenerations) || 2)
|
|
1287
|
+
const minKeep = Math.max(0, (Number(activeGeneration) || 0) - (keepGenerationsCount - 1))
|
|
1288
|
+
const cutoff = Number(now) - Math.max(0, Number(olderThanDays) || 0) * VECTOR_GC_DAY_MS
|
|
1289
|
+
const keep = new Set((keepPaths || []).map((file) => path.resolve(String(file))))
|
|
1290
|
+
return (files || []).filter((item) => {
|
|
1291
|
+
const generation = Number(item?.generation)
|
|
1292
|
+
if (!Number.isSafeInteger(generation) || generation < 1) return false
|
|
1293
|
+
if (generation >= minKeep) return false
|
|
1294
|
+
if (keep.has(path.resolve(String(item.file)))) return false
|
|
1295
|
+
return Number(item.mtimeMs) < cutoff
|
|
1296
|
+
})
|
|
1297
|
+
}
|
|
1298
|
+
|
|
1299
|
+
export function listVectorArtifacts() {
|
|
1300
|
+
const state = readVectorState({ tolerateMissing: true }).state
|
|
1301
|
+
const keepPaths = []
|
|
1302
|
+
const collect = (manifest) => {
|
|
1303
|
+
if (!manifest?.databases) return
|
|
1304
|
+
const global = manifest.databases.global
|
|
1305
|
+
if (global?.path) keepPaths.push(resolveVectorPath(global.path))
|
|
1306
|
+
for (const entry of Object.values(manifest.databases.libraries || {})) {
|
|
1307
|
+
if (entry?.path) keepPaths.push(resolveVectorPath(entry.path))
|
|
1308
|
+
}
|
|
1309
|
+
}
|
|
1310
|
+
collect(state?.active)
|
|
1311
|
+
collect(state?.pending?.databases ? { databases: state.pending.databases } : null)
|
|
1312
|
+
const files = []
|
|
1313
|
+
for (const dir of [librariesDir(), indexDir()]) {
|
|
1314
|
+
let names = []
|
|
1315
|
+
try { names = fs.readdirSync(dir) } catch { continue }
|
|
1316
|
+
for (const name of names) {
|
|
1317
|
+
const match = /\.g(\d+)\.(?:sqlite3|json)$/.exec(name)
|
|
1318
|
+
if (!match) continue
|
|
1319
|
+
if (!name.endsWith('.sqlite3') && !name.startsWith('vector-ledger.')) continue
|
|
1320
|
+
const file = path.join(dir, name)
|
|
1321
|
+
let info
|
|
1322
|
+
try { info = fs.statSync(file) } catch { continue }
|
|
1323
|
+
files.push({ file, generation: Number(match[1]), bytes: info.size, mtimeMs: info.mtimeMs })
|
|
1324
|
+
}
|
|
1325
|
+
}
|
|
1326
|
+
return { activeGeneration: state?.active?.generation ?? 0, keepPaths, files }
|
|
1327
|
+
}
|
|
1328
|
+
|
|
1329
|
+
export function pruneVectorArtifacts({ apply = false, keepGenerations = 2, olderThanDays = 7, now = Date.now() } = {}) {
|
|
1330
|
+
const info = listVectorArtifacts()
|
|
1331
|
+
const candidates = vectorGcCandidates({
|
|
1332
|
+
files: info.files,
|
|
1333
|
+
activeGeneration: info.activeGeneration,
|
|
1334
|
+
keepGenerations,
|
|
1335
|
+
olderThanDays,
|
|
1336
|
+
now,
|
|
1337
|
+
keepPaths: info.keepPaths,
|
|
1338
|
+
})
|
|
1339
|
+
const removed = []
|
|
1340
|
+
if (apply) {
|
|
1341
|
+
for (const item of candidates) {
|
|
1342
|
+
try { fs.unlinkSync(item.file); removed.push(item.file) } catch {}
|
|
1343
|
+
}
|
|
1344
|
+
}
|
|
1345
|
+
return {
|
|
1346
|
+
dryRun: apply !== true,
|
|
1347
|
+
activeGeneration: info.activeGeneration,
|
|
1348
|
+
keepGenerations,
|
|
1349
|
+
olderThanDays,
|
|
1350
|
+
candidates: candidates.map((item) => ({ file: item.file, generation: item.generation, bytes: item.bytes })),
|
|
1351
|
+
removed,
|
|
1352
|
+
}
|
|
1353
|
+
}
|