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