dsh-memu-memory 1.4.2 → 1.4.3

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 +169 -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 +79 -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 +1015 -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 +1586 -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 +124 -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 +1521 -1429
@@ -1,930 +1,928 @@
1
- import fs from 'node:fs'
2
- import path from 'node:path'
3
- import crypto from 'node:crypto'
4
- import { indexDir, librariesDir, ensureDir, readJsonStrict, writeJson, stamp } from './paths.js'
5
- import {
6
- VECTOR_ERROR_CODES, vectorError,
7
- stableStringify, sha256Hex, resolveProfile, assertProfileVerified, vectorDbRelPath,
8
- resolveVectorPath, readVectorState, vectorState, activeDatabases, updateVectorStateSync,
9
- reserveShadowGeneration, updatePendingJournal, clearPendingJournal, pendingJournal,
10
- assertVectorWriteAllowed, captureGeneration, assertGeneration, vectorStatus, withVectorWriteFreeze, profileEnv, setRequestedProfile,
11
- } from './vector-profile.js'
12
-
13
- // §14.8 影子重建 / 追平 / 原子代际切换 / 回滚 / 启动恢复。
14
- //
15
- // 原则:
16
- // * 绝不原地重嵌入:每次都写到一个全新的影子库路径(代际号进文件名),旧库保持只读可用。
17
- // * 账本键 = profile fingerprint + libraryId + itemId + content hash。命中即跳过,
18
- // 所以"再来一次 commit"不是"再来一次 embed";内容变了才算重新嵌入。
19
- // * tombstone:从索引里消失的条目要真的从影子库里删掉并记账,断点续建不得把它复活。
20
- // * 切换只在最后短窗口里做同步 compare + 原子写 active 指针;之前的锁外工作可以失败,
21
- // 失败就不动 active(§14.8 第 4/7/8 条)。
22
- // * 索引快照在追平前后必须一致;不一致说明追平已经过期,中止切换而不是切到半步状态。
23
- //
24
- // 依赖全部注入,便于 fixture 测试:
25
- // listLibraries() → [{ id }] | string[]
26
- // loadIndex(libraryId | null) → { entries: { [itemId]: entry } } (null = 全局库)
27
- // commit({ db, libraryId, item, entry, profile, generation }) → Promise
28
- // forget({ db, libraryId, itemId, profile, generation }) → Promise
29
- // listFiles({ db, libraryId, profile, generation }) → Promise<string[]> (影子里已有的条目名/ id)
30
- // smoke({ profile, generation, databases, report }) → Promise<{ ok, checks? }>
31
- // 主代理接 state.js/memu.js 时按上面的形状包一层即可。
32
-
33
- export const VECTOR_LEDGER_PREFIX = 'vector-ledger.'
34
- export const VECTOR_LEDGER_SCHEMA = 1
35
-
36
- /** 这些状态不进入向量空间:重建不得把 held 的条目重新激活(§14.8 第 3 条)。 */
37
- export const HELD_STATUSES = Object.freeze(['archived', 'suppressed', 'expired', 'pending_review', 'superseded', 'deleted'])
38
-
39
- export function admitEntry(entry, nowMs = Date.now()) {
40
- if (!entry || typeof entry !== 'object' || Array.isArray(entry)) return false
41
- if (HELD_STATUSES.includes(String(entry.status || ''))) return false
42
- if (entry.expiresAt && !(Date.parse(entry.expiresAt) > nowMs)) return false
43
- return true
44
- }
45
-
46
- export function itemText(entry) {
47
- if (!entry || typeof entry !== 'object') return ''
48
- for (const key of ['text', 'content', 'body']) {
49
- if (typeof entry[key] === 'string' && entry[key].trim()) return entry[key]
50
- }
51
- return ''
52
- }
53
-
54
- /** 内容/版本哈希:只有正文(与 id)改变才算需要重新嵌入。 */
55
- export function contentHash(id, text, version = null) {
56
- return sha256Hex(stableStringify({ id: String(id), text: String(text), version }))
57
- }
58
-
59
- /** 从插件 index 里取出"可写进向量空间"的条目(已按准入过滤,按 id 稳定排序)。 */
60
- export function admittedItems(index, nowMs = Date.now()) {
61
- const entries = index && typeof index.entries === 'object' && index.entries ? index.entries : {}
62
- const items = []
63
- for (const [id, entry] of Object.entries(entries)) {
64
- if (!admitEntry(entry, nowMs)) continue
65
- const text = itemText(entry)
66
- if (!text.trim()) continue
67
- items.push({ id, text, hash: contentHash(id, text, entry.contentVersion ?? entry.version ?? entry.updatedAt ?? null), entry: structuredClone(entry) })
68
- }
69
- items.sort((a, b) => (a.id < b.id ? -1 : a.id > b.id ? 1 : 0))
70
- return items
71
- }
72
-
73
- function scopeSnapshotDigest(items) {
74
- return sha256Hex(stableStringify(items.map(item => [item.id, item.hash])))
75
- }
76
-
77
- export function ledgerFile(fingerprint, generation) {
78
- return path.join(indexDir(), VECTOR_LEDGER_PREFIX + String(fingerprint).slice(0, 8) + '.g' + Number(generation) + '.json')
79
- }
80
-
81
- function emptyLedger(fingerprint, generation) {
82
- return {
83
- version: VECTOR_LEDGER_SCHEMA,
84
- fingerprint,
85
- generation,
86
- createdAt: stamp(),
87
- updatedAt: stamp(),
88
- snapshot: null,
89
- libraries: {},
90
- }
91
- }
92
-
93
- export function loadLedger(fingerprint, generation) {
94
- const file = ledgerFile(fingerprint, generation)
95
- const result = readJsonStrict(file)
96
- if (!result.ok) {
97
- if (result.missing) return { ok: true, ledger: emptyLedger(fingerprint, generation) }
98
- return { ok: false, ledger: emptyLedger(fingerprint, generation), error: { code: result.kind === 'corrupt' ? 'VECTOR_LEDGER_CORRUPT' : 'VECTOR_LEDGER_UNREADABLE', file } }
99
- }
100
- const value = result.value
101
- if (!value || typeof value !== 'object' || value.fingerprint !== fingerprint || Number(value.generation) !== Number(generation)) {
102
- // 账本对不上代际/指纹:当作空账本重建(宁可贵一点,也不复用别人的进度)
103
- return { ok: true, ledger: emptyLedger(fingerprint, generation), restarted: true }
104
- }
105
- return {
106
- ok: true,
107
- ledger: {
108
- version: VECTOR_LEDGER_SCHEMA,
109
- fingerprint,
110
- generation: Number(generation),
111
- createdAt: value.createdAt || stamp(),
112
- updatedAt: value.updatedAt || stamp(),
113
- snapshot: value.snapshot || null,
114
- libraries: value.libraries && typeof value.libraries === 'object' ? value.libraries : {},
115
- },
116
- }
117
- }
118
-
119
- export function saveLedger(ledger) {
120
- ensureDir(indexDir())
121
- writeJson(ledgerFile(ledger.fingerprint, ledger.generation), ledger)
122
- return ledger
123
- }
124
-
125
- function ledgerBucket(ledger, key) {
126
- const existing = ledger.libraries[key]
127
- if (existing && typeof existing === 'object') {
128
- return ledger.libraries[key] = {
129
- items: existing.items && typeof existing.items === 'object' ? existing.items : {},
130
- tombstones: existing.tombstones && typeof existing.tombstones === 'object' ? existing.tombstones : {},
131
- snapshot: existing.snapshot || null,
132
- }
133
- }
134
- const bucket = { items: {}, tombstones: {}, snapshot: null }
135
- ledger.libraries[key] = bucket
136
- return bucket
137
- }
138
-
139
- export function ledgerSummary(ledger) {
140
- const out = { fingerprint: ledger.fingerprint, generation: ledger.generation, libraries: {}, committed: 0, tombstones: 0 }
141
- for (const [key, bucket] of Object.entries(ledger.libraries || {})) {
142
- const committed = Object.keys(bucket?.items || {}).length
143
- const tombstones = Object.keys(bucket?.tombstones || {}).length
144
- out.libraries[key] = { committed, tombstones }
145
- out.committed += committed
146
- out.tombstones += tombstones
147
- }
148
- out.snapshot = ledger.snapshot
149
- return out
150
- }
151
-
152
- function fileStats(absPath) {
153
- const buffer = fs.readFileSync(absPath)
154
- return { bytes: buffer.length, sha256: crypto.createHash('sha256').update(buffer).digest('hex') }
155
- }
156
-
157
- // ---------------------------------------------------------------- 迁移器
158
-
159
- const REQUIRED_DEPS = Object.freeze(['listLibraries', 'loadIndex', 'commit', 'forget', 'listFiles'])
160
-
161
- /**
162
- * createVectorMigrator({ listLibraries, loadIndex, commit, forget, listFiles, smoke?, now?, log?, maxCatchUpAttempts?, itemRetries? })
163
- * 也接受 { deps: {...}, ... } 形式。所有副作用都经注入依赖,便于纯 fixture 测试。
164
- */
165
- export function createVectorMigrator(options = {}) {
166
- const configured = options && typeof options.deps === 'object' && options.deps ? { ...options.deps, ...options } : { ...options }
167
- const impl = {
168
- listLibraries: configured.listLibraries,
169
- loadIndex: configured.loadIndex,
170
- commit: configured.commit,
171
- forget: configured.forget,
172
- listFiles: configured.listFiles ?? configured.list,
173
- retrieve: typeof configured.retrieve === 'function' ? configured.retrieve : null,
174
- smoke: typeof configured.smoke === 'function' ? configured.smoke : null,
175
- // Optional: drop the index-side `vectorPending` marker for ids that this rebuild
176
- // has just proven present in the shadow. Without it the marker was write-only —
177
- // nothing ever cleared it after a successful migration, so a fully migrated
178
- // library kept advertising itself as "not in the vector store yet".
179
- clearVectorPending: typeof configured.clearVectorPending === 'function' ? configured.clearVectorPending : null,
180
- }
181
- for (const name of REQUIRED_DEPS) {
182
- if (typeof impl[name] !== 'function') throw new TypeError('createVectorMigrator requires a ' + name + '(… ) dependency')
183
- }
184
- const now = typeof configured.now === 'function' ? configured.now : () => new Date().toISOString()
185
- const log = typeof configured.log === 'function' ? configured.log : () => {}
186
- const onProgress = typeof configured.onProgress === 'function' ? configured.onProgress : null
187
- const maxCatchUpAttempts = Number.isSafeInteger(configured.maxCatchUpAttempts) && configured.maxCatchUpAttempts > 0 ? configured.maxCatchUpAttempts : 3
188
- const itemRetries = Number.isSafeInteger(configured.itemRetries) && configured.itemRetries >= 0 ? configured.itemRetries : 1
189
-
190
- function publishProgress(progress, { persist = true } = {}) {
191
- const snapshot = { ...progress, updatedAt: now() }
192
- if (persist) {
193
- updatePendingJournal(current => {
194
- if (current.generation !== snapshot.generation || current.fingerprint !== snapshot.fingerprint) throw vectorError(VECTOR_ERROR_CODES.STALE_GENERATION, 'progress belongs to a replaced shadow generation')
195
- return { ...current, report: { ...(current.report || {}), progress: snapshot } }
196
- })
197
- }
198
- if (onProgress) {
199
- try {
200
- const result = onProgress(structuredClone(snapshot))
201
- if (result && typeof result.then === 'function') result.catch(error => log('progress callback failed: ' + (error?.message || error)))
202
- } catch (error) {
203
- log('progress callback failed: ' + (error?.message || error))
204
- }
205
- }
206
- return snapshot
207
- }
208
-
209
- function idOf(value) {
210
- const id = typeof value === 'string' ? value : value?.id
211
- if (typeof id !== 'string' || !id || id === 'global') return null
212
- return id
213
- }
214
-
215
- async function resolveLibraryIds(libraries) {
216
- const raw = Array.isArray(libraries) ? libraries : await impl.listLibraries()
217
- const ids = []
218
- for (const item of raw ?? []) {
219
- const id = idOf(item)
220
- if (id && !ids.includes(id)) ids.push(id)
221
- }
222
- return ids
223
- }
224
-
225
- function scopesFor(databases) {
226
- const scopes = [{ key: 'global', libraryId: null, rel: databases.global.path, db: resolveVectorPath(databases.global.path) }]
227
- for (const [libraryId, entry] of Object.entries(databases.libraries || {})) {
228
- scopes.push({ key: libraryId, libraryId, rel: entry.path, db: resolveVectorPath(entry.path) })
229
- }
230
- return scopes
231
- }
232
-
233
- async function captureSnapshot(scopes) {
234
- const parts = []
235
- for (const scope of scopes) {
236
- const index = structuredClone(await impl.loadIndex(scope.libraryId))
237
- const items = admittedItems(index)
238
- parts.push({ key: scope.key, items, digest: sha256Hex(stableStringify({ index, admitted: scopeSnapshotDigest(items) })) })
239
- }
240
- return {
241
- digest: sha256Hex(stableStringify(parts.map(part => [part.key, part.digest]))),
242
- scopes: parts,
243
- at: now(),
244
- }
245
- }
246
-
247
- async function presentIds(scope, profile, generation) {
248
- const ids = new Set()
249
- if (!fs.existsSync(scope.db)) return ids
250
- const listed = await impl.listFiles({ db: scope.db, libraryId: scope.libraryId, profile, generation })
251
- if (!Array.isArray(listed) && !Array.isArray(listed?.recall_files)) throw vectorError('VECTOR_LIST_INVALID', 'shadow list returned an invalid result for ' + scope.key)
252
- const names = Array.isArray(listed) ? listed : Array.isArray(listed?.recall_files) ? listed.recall_files : []
253
- for (const value of names) {
254
- if (typeof value === 'string') ids.add(value)
255
- else if (value && typeof value === 'object') {
256
- const name = value.name ?? value.id
257
- if (typeof name === 'string') ids.add(name)
258
- }
259
- }
260
- return ids
261
- }
262
-
263
- async function commitItem(scope, item, profile, generation) {
264
- let lastError = null
265
- for (let attempt = 0; attempt <= itemRetries; attempt++) {
266
- try {
267
- // Failure may still persist a row. Forget first: unchanged-description
268
- // recommit is not proof that the backend regenerated an embedding.
269
- if ((await presentIds(scope, profile, generation)).has(item.id)) {
270
- await impl.forget({ db: scope.db, libraryId: scope.libraryId, itemId: item.id, profile, generation })
271
- if ((await presentIds(scope, profile, generation)).has(item.id)) throw vectorError('VECTOR_FORGET_FAILED', 'shadow item still exists after forget: ' + item.id)
272
- }
273
- await impl.commit({ db: scope.db, libraryId: scope.libraryId, item, entry: item.entry ?? null, profile, generation })
274
- if (!(await presentIds(scope, profile, generation)).has(item.id)) throw vectorError('VECTOR_READBACK_FAILED', 'committed item is missing from shadow: ' + item.id)
275
- if (impl.retrieve) {
276
- const result = await impl.retrieve({ db: scope.db, libraryId: scope.libraryId, itemId: item.id, item, profile, generation })
277
- if (result == null || result === false || result.ok === false) throw vectorError('VECTOR_READBACK_FAILED', 'cannot retrieve committed shadow item: ' + item.id)
278
- }
279
- return { ok: true }
280
- } catch (error) {
281
- lastError = error
282
- if (attempt < itemRetries) log('commit retry ' + scope.key + '/' + item.id + ' after ' + (error?.code || error?.message || error))
283
- }
284
- }
285
- return { ok: false, error: lastError }
286
- }
287
-
288
- // -------------------------------------------------------------- prepareShadow
289
-
290
- /**
291
- * 为一次重建分配"全新代际 + 全新影子路径",并把 prepared journal 先落盘。
292
- * 不写 active 指针、不碰旧库。同指纹的未完成重建默认续建(同一代际、同一路径、账本跳过
293
- * 已嵌入条目);fresh:true 则强制换新代际(= 真正重来一遍)。
294
- */
295
- async function prepareShadow(stepOptions = {}) {
296
- const profile = resolveProfile(stepOptions.profile ?? stepOptions.catalogId)
297
- const libraryIds = await resolveLibraryIds(stepOptions.libraries)
298
- const fresh = stepOptions.fresh === true
299
- const reason = typeof stepOptions.reason === 'string' ? stepOptions.reason : 'switch'
300
- const current = vectorState()
301
- const pending = current?.pending
302
- let resumable = !fresh && pending && pending.fingerprint === profile.fingerprint
303
- && (pending.status === 'preparing' || pending.status === 'prepared' || pending.status === 'failed')
304
- if (resumable) {
305
- // Same fingerprint is not enough: the manifest digest covers the artifact
306
- // list, and a catalog update (for example adding a download source) makes the
307
- // old journal profile unverifiable. Resuming it would fail later in
308
- // syncShadowImpl; discard it now and start a clean generation instead.
309
- try {
310
- assertProfileVerified(pending.profile)
311
- } catch (error) {
312
- log('discarding stale pending generation ' + pending.generation + ': ' + String(error?.code || error?.message || error))
313
- resumable = false
314
- }
315
- }
316
- if (resumable) {
317
- // 续建:同一代际,只把新出现的库补进同一个 DB 集合(同一次原子切换里生效)
318
- const extended = updatePendingJournal(journal => {
319
- const libraries = { ...(journal.databases?.libraries || {}) }
320
- for (const id of libraryIds) {
321
- if (!libraries[id]) libraries[id] = { path: vectorDbRelPath({ libraryId: id, fingerprint: journal.fingerprint, generation: journal.generation }), bytes: null, sha256: null }
322
- }
323
- return { ...journal, databases: { ...journal.databases, libraries } }
324
- })
325
- try {
326
- ensureShadowFiles(extended.databases)
327
- } catch (error) {
328
- failPending(error?.code || 'VECTOR_PREPARE_FAILED', String(error?.message || error), {}, extended)
329
- throw error
330
- }
331
- setRequestedProfile(profile, { reason })
332
- log('resuming shadow generation ' + extended.generation + ' for ' + profile.catalogId)
333
- return describeShadow(extended, true)
334
- }
335
- const reservation = reserveShadowGeneration({ profile, libraryIds, reason })
336
- // 全新代际 = 全新空影子库。路径上已经有文件说明编号冲突,绝不覆盖/复用。
337
- try {
338
- ensureShadowFiles(reservation.databases, { refuseExisting: true })
339
- } catch (error) {
340
- failPending(error?.code || 'VECTOR_PREPARE_FAILED', String(error?.message || error), {}, reservation)
341
- throw error
342
- }
343
- setRequestedProfile(profile, { reason })
344
- log('prepared shadow generation ' + reservation.generation + ' for ' + profile.catalogId)
345
- return describeShadow(pendingJournal(), false)
346
- }
347
-
348
- /**
349
- * 影子库集合必须是"存在且为空"的:空 sqlite 文件是合法起点,缺文件会被误当成撕裂。
350
- * refuseExisting=true 用于全新代际——路径上已有文件说明编号被复用,直接拒绝。
351
- */
352
- function ensureShadowFiles(databases, { refuseExisting = false } = {}) {
353
- ensureDir(librariesDir())
354
- for (const scope of scopesFor(databases)) {
355
- ensureDir(path.dirname(scope.db))
356
- if (fs.existsSync(scope.db)) {
357
- if (refuseExisting) {
358
- throw vectorError(VECTOR_ERROR_CODES.SHADOW_PATH_TAKEN, 'the reserved shadow path already exists; refusing to reuse a database from another attempt', {
359
- path: scope.rel,
360
- })
361
- }
362
- continue
363
- }
364
- fs.writeFileSync(scope.db, '', { flag: 'wx' })
365
- }
366
- }
367
-
368
- function describeShadow(journal, resumed) {
369
- const scopes = scopesFor(journal.databases)
370
- return {
371
- generation: journal.generation,
372
- token: journal.token,
373
- fingerprint: journal.fingerprint,
374
- profile: journal.profile,
375
- status: journal.status,
376
- reason: journal.reason ?? null,
377
- resumed: Boolean(resumed),
378
- previousGeneration: journal.previousGeneration ?? null,
379
- databases: {
380
- global: scopes[0].db,
381
- libraries: Object.fromEntries(scopes.slice(1).map(scope => [scope.key, scope.db])),
382
- },
383
- env: profileEnv(journal.profile),
384
- relative: {
385
- global: journal.databases.global.path,
386
- libraries: Object.fromEntries(Object.entries(journal.databases.libraries || {}).map(([id, entry]) => [id, entry.path])),
387
- },
388
- }
389
- }
390
-
391
- // -------------------------------------------------------------- syncShadow
392
-
393
- /**
394
- * 把索引里所有准入条目写进影子库;命中账本的跳过(那已经是这一代的向量),
395
- * 消失的条目 forget + tombstone。返回追平报告与前后快照(快照不一致 = 追平已过期)。
396
- */
397
- // 只报"有几条失败"没法修:把前几条的 id/错误码/消息留下来。syncShadow 与
398
- // switchProfile 两处都要带,后者会覆盖前者的 pending.error。
399
- function syncFailureDetail(report) {
400
- return report.failed.slice(0, 10).map(item => ({
401
- libraryId: item.libraryId ?? null,
402
- itemId: item.itemId ?? null,
403
- code: item.code ?? 'VECTOR_COMMIT_FAILED',
404
- message: String(item.message ?? '').slice(0, 300),
405
- }))
406
- }
407
-
408
- async function syncShadow(stepOptions = {}) {
409
- const expected = pendingJournal()
410
- try {
411
- const report = await syncShadowImpl(stepOptions)
412
- if (report.failed.length) {
413
- // 只报"有几条失败"没法排查:把前几条的 id/错误码/消息留下来,日志里也打一行。
414
- // 现场(2026-10-29)9 条失败只显示一句"未覆盖全部记忆",必须重放才知道原因。
415
- const failedItems = syncFailureDetail(report)
416
- log('rebuild sync failures: ' + failedItems.slice(0, 3).map(item => `${item.itemId || item.libraryId}:${item.code}:${item.message}`).join(' | '))
417
- failPending('VECTOR_SYNC_INCOMPLETE', 'the rebuild did not cover every admitted memory; the active generation is untouched', { failed: report.failed.length, failedItems }, expected)
418
- }
419
- return report
420
- } catch (error) {
421
- const matches = expected && (stepOptions.generation == null || stepOptions.generation === expected.generation)
422
- && (stepOptions.fingerprint == null || stepOptions.fingerprint === expected.fingerprint)
423
- if (matches) failPending(error?.code || 'VECTOR_SYNC_FAILED', String(error?.message || error), { causeCode: error?.code ?? null }, expected)
424
- throw error
425
- }
426
- }
427
-
428
- async function syncShadowImpl(stepOptions = {}) {
429
- const journal = pendingJournal()
430
- if (!journal) throw vectorError('VECTOR_PENDING_MISSING', 'there is no prepared rebuild to sync')
431
- const generation = Number.isSafeInteger(stepOptions.generation) ? stepOptions.generation : journal.generation
432
- const fingerprint = typeof stepOptions.fingerprint === 'string' ? stepOptions.fingerprint : journal.fingerprint
433
- if (journal.generation !== generation || journal.fingerprint !== fingerprint) {
434
- throw vectorError('VECTOR_PENDING_MISSING', 'the prepared rebuild belongs to a different generation', { generation, fingerprint, preparedGeneration: journal.generation })
435
- }
436
- if (journal.status === 'committed') throw vectorError(VECTOR_ERROR_CODES.TORN_STATE, 'this generation is already committed; nothing to sync')
437
- const profile = assertProfileVerified(journal.profile)
438
- const scopes = scopesFor(journal.databases)
439
- if (Array.isArray(stepOptions.libraries)) {
440
- // 只追平指定的私有库;全局库永远在同一代际里(不能漏,否则新代缺全局空间)
441
- const wanted = new Set(stepOptions.libraries.map(idOf).filter(Boolean))
442
- if (wanted.size) {
443
- const libraries = Object.fromEntries(Object.entries(journal.databases.libraries || {}).filter(([id]) => wanted.has(id)))
444
- scopes.length = 0
445
- scopes.push(...scopesFor({ global: journal.databases.global, libraries }))
446
- }
447
- }
448
- const loaded = loadLedger(fingerprint, generation)
449
- const ledger = loaded.ledger
450
- if (loaded.error) log('ledger unreadable (' + loaded.error.code + '); rebuilding it from the index')
451
- const before = await captureSnapshot(scopes)
452
- const total = before.scopes.reduce((sum, scope) => sum + scope.items.length, 0)
453
- const report = { generation, fingerprint, committed: 0, skipped: 0, tombstoned: 0, failed: [], libraries: {}, restarted: Boolean(loaded.restarted || loaded.error) }
454
- const progress = { stage: 'syncing', generation, fingerprint, total, completed: 0, skipped: 0, committed: 0, tombstoned: 0, failed: 0, current: null }
455
- publishProgress(progress)
456
- for (let index = 0; index < scopes.length; index++) {
457
- const scope = scopes[index]
458
- const items = before.scopes[index].items
459
- const bucket = ledgerBucket(ledger, scope.key)
460
- ensureDir(path.dirname(scope.db))
461
- const present = await presentIds(scope, profile, generation)
462
- const known = new Set(items.map(item => item.id))
463
- for (const item of items) {
464
- const recorded = bucket.items[item.id]
465
- const tombstoned = bucket.tombstones[item.id]
466
- if (recorded && recorded.hash === item.hash && present.has(item.id) && !tombstoned) {
467
- report.skipped += 1
468
- progress.skipped = report.skipped
469
- progress.completed = report.committed + report.skipped
470
- progress.current = { stage: 'skipped', libraryId: scope.key, itemId: item.id }
471
- publishProgress(progress)
472
- continue
473
- }
474
- const outcome = await commitItem(scope, item, profile, generation)
475
- if (!outcome.ok) {
476
- const error = outcome.error
477
- report.failed.push({
478
- libraryId: scope.key,
479
- itemId: item.id,
480
- code: error?.code || 'VECTOR_COMMIT_FAILED',
481
- message: String(error?.message || error || 'commit failed'),
482
- })
483
- progress.failed = report.failed.length
484
- progress.completed = report.committed + report.skipped + progress.failed
485
- progress.current = { stage: 'failed', libraryId: scope.key, itemId: item.id, code: error?.code || 'VECTOR_COMMIT_FAILED' }
486
- publishProgress(progress)
487
- continue
488
- }
489
- bucket.items[item.id] = { hash: item.hash, at: now() }
490
- delete bucket.tombstones[item.id]
491
- report.committed += 1
492
- progress.committed = report.committed
493
- progress.completed = report.committed + report.skipped + progress.failed
494
- progress.current = { stage: 'committed', libraryId: scope.key, itemId: item.id }
495
- publishProgress(progress)
496
- ledger.updatedAt = now()
497
- saveLedger(ledger)
498
- }
499
- for (const name of present) {
500
- if (known.has(name)) continue
501
- try {
502
- await impl.forget({ db: scope.db, libraryId: scope.libraryId, itemId: name, profile, generation })
503
- } catch (error) {
504
- report.failed.push({ libraryId: scope.key, itemId: name, code: error?.code || 'VECTOR_FORGET_FAILED', message: String(error?.message || error || 'forget failed') })
505
- progress.failed = report.failed.length
506
- progress.completed = report.committed + report.skipped + report.tombstoned + progress.failed
507
- progress.current = { stage: 'failed', libraryId: scope.key, itemId: name, code: error?.code || 'VECTOR_FORGET_FAILED' }
508
- publishProgress(progress)
509
- continue
510
- }
511
- bucket.tombstones[name] = { hash: bucket.items[name]?.hash ?? null, at: now(), reason: 'absent-from-index' }
512
- delete bucket.items[name]
513
- report.tombstoned += 1
514
- progress.tombstoned = report.tombstoned
515
- progress.completed = report.committed + report.skipped + report.tombstoned + progress.failed
516
- progress.current = { stage: 'tombstoned', libraryId: scope.key, itemId: name }
517
- publishProgress(progress)
518
- ledger.updatedAt = now()
519
- saveLedger(ledger)
520
- }
521
- for (const [itemId, record] of Object.entries(bucket.items)) {
522
- // 索引里已经没有它、影子库里也没有:留 tombstone,避免断点续建把它复活。
523
- if (known.has(itemId) || present.has(itemId)) continue
524
- bucket.tombstones[itemId] = { hash: record?.hash ?? null, at: now(), reason: 'not-present' }
525
- delete bucket.items[itemId]
526
- report.tombstoned += 1
527
- progress.tombstoned = report.tombstoned
528
- progress.completed = report.committed + report.skipped + report.tombstoned + progress.failed
529
- progress.current = { stage: 'tombstoned', libraryId: scope.key, itemId }
530
- publishProgress(progress)
531
- }
532
- const verifiedPresent = await presentIds(scope, profile, generation)
533
- if (verifiedPresent.size !== known.size || [...known].some(id => !verifiedPresent.has(id))) {
534
- report.failed.push({ libraryId: scope.key, code: 'VECTOR_COVERAGE_FAILED', message: 'shadow membership differs from eligible index snapshot' })
535
- } else if (impl.clearVectorPending) {
536
- // Coverage passed: every admitted entry is provably in this generation's
537
- // shadow, so "write me into the vector store later" is finished for all of
538
- // them. Fail-open — a stale flag costs a little wasted work next rebuild, it
539
- // must never turn a successful migration into a failed one.
540
- try {
541
- impl.clearVectorPending({ libraryId: scope.libraryId, ids: [...known], generation })
542
- } catch (error) {
543
- log('clear vectorPending failed for ' + scope.key + ': ' + (error?.message || error))
544
- }
545
- }
546
- bucket.snapshot = { digest: before.scopes[index].digest, items: items.length, at: before.at }
547
- report.libraries[scope.key] = { items: items.length, present: present.size, digest: before.scopes[index].digest }
548
- ledger.updatedAt = now()
549
- saveLedger(ledger)
550
- }
551
- const after = await captureSnapshot(scopes)
552
- const stable = after.digest === before.digest
553
- ledger.snapshot = { digest: before.digest, at: before.at, stable, libraries: report.libraries }
554
- ledger.updatedAt = now()
555
- saveLedger(ledger)
556
- report.snapshot = { digest: before.digest, at: before.at, libraries: report.libraries }
557
- report.afterDigest = after.digest
558
- report.stable = stable
559
- report.ledger = ledgerSummary(ledger)
560
- progress.stage = report.failed.length ? 'failed' : 'prepared'
561
- progress.failed = report.failed.length
562
- progress.completed = report.committed + report.skipped + report.tombstoned + progress.failed
563
- progress.current = null
564
- report.progress = publishProgress(progress)
565
- if (report.failed.length === 0) {
566
- updatePendingJournal(current => ({ ...current, status: 'prepared', preparedAt: now(), snapshot: report.snapshot, report: { committed: report.committed, skipped: report.skipped, tombstoned: report.tombstoned, libraries: report.libraries, progress: report.progress } }))
567
- }
568
- return report
569
- }
570
-
571
- // -------------------------------------------------------------- 切换
572
-
573
- function measureDatabases(databases) {
574
- const stats = {}
575
- for (const scope of scopesFor(databases)) {
576
- let info
577
- try {
578
- info = fileStats(scope.db)
579
- } catch (error) {
580
- throw vectorError(VECTOR_ERROR_CODES.TORN_STATE, 'cannot read back shadow database ' + scope.rel + ' (' + (error?.code || error?.message || error) + ')', { path: scope.rel })
581
- }
582
- stats[scope.rel] = info
583
- }
584
- return stats
585
- }
586
-
587
- function failPending(code, message, extra = {}, expected = null) {
588
- let failedProgress = null
589
- updatePendingJournal(current => {
590
- if (expected && (current.token !== expected.token || current.generation !== expected.generation || current.fingerprint !== expected.fingerprint)) return null
591
- if (current.status === 'committed' || current.status === 'aborted') return null
592
- const prior = current.report?.progress || { generation: current.generation, fingerprint: current.fingerprint, total: 0, completed: 0, skipped: 0, committed: 0, tombstoned: 0, failed: 0, current: null }
593
- failedProgress = { ...prior, stage: 'failed', failed: Math.max(1, prior.failed || 0), current: { stage: 'failed', code }, updatedAt: now() }
594
- return { ...current, status: 'failed', error: { code, message, at: now(), ...extra }, report: { ...(current.report || {}), progress: failedProgress } }
595
- })
596
- if (failedProgress && onProgress) {
597
- try { onProgress(structuredClone(failedProgress)) } catch (error) { log('progress callback failed: ' + (error?.message || error)) }
598
- }
599
- }
600
-
601
- /**
602
- * 最后短窗口:锁内只做同步 compare(token/代际/文件大小)与一次原子指针写。
603
- * 这里没有 await,也不允许有(§14.8 第 5/7 条)。
604
- */
605
- function commitActiveGeneration({ profile, journal, sync, stats }) {
606
- const committedAt = now()
607
- return updateVectorStateSync(current => {
608
- const pending = current.pending
609
- if (!pending) {
610
- throw vectorError('VECTOR_PENDING_MISSING', 'the prepared rebuild disappeared before the switch', { generation: journal.generation })
611
- }
612
- if (pending.token !== journal.token || pending.generation !== journal.generation || pending.fingerprint !== profile.fingerprint) {
613
- throw vectorError(VECTOR_ERROR_CODES.TORN_STATE, 'another rebuild replaced this prepared generation; refusing to switch', {
614
- prepared: { generation: journal.generation, token: journal.token }, currentPending: { generation: pending.generation, token: pending.token },
615
- })
616
- }
617
- if (pending.status !== 'prepared') throw vectorError('VECTOR_SYNC_INCOMPLETE', 'only a prepared shadow generation can be activated')
618
- const preparedAgainst = pending.previousGeneration ?? null
619
- const activeGeneration = current.active?.generation ?? null
620
- if (preparedAgainst !== activeGeneration) {
621
- throw vectorError(VECTOR_ERROR_CODES.TORN_STATE, 'the active generation changed while the rebuild was prepared; refusing to switch', { activeGeneration, preparedAgainst })
622
- }
623
- for (const scope of scopesFor(pending.databases)) {
624
- let info
625
- try {
626
- info = fs.statSync(scope.db)
627
- } catch {
628
- throw vectorError(VECTOR_ERROR_CODES.TORN_STATE, 'a shadow database vanished before the switch: ' + scope.rel, { path: scope.rel })
629
- }
630
- const expected = stats[scope.rel]
631
- if (!info.isFile() || !expected || info.size !== expected.bytes || fileStats(scope.db).sha256 !== expected.sha256) {
632
- throw vectorError(VECTOR_ERROR_CODES.TORN_STATE, 'a shadow database changed after the final sync: ' + scope.rel, { path: scope.rel, expected: expected?.bytes ?? null, actual: info.size })
633
- }
634
- }
635
- const databases = {
636
- global: { path: pending.databases.global.path, bytes: stats[pending.databases.global.path].bytes, sha256: stats[pending.databases.global.path].sha256 },
637
- libraries: Object.fromEntries(Object.entries(pending.databases.libraries || {}).map(([libraryId, entry]) => [
638
- libraryId, { path: entry.path, bytes: stats[entry.path]?.bytes ?? null, sha256: stats[entry.path]?.sha256 ?? null },
639
- ])),
640
- }
641
- const previous = current.active ? {
642
- generation: current.active.generation,
643
- fingerprint: current.active.fingerprint,
644
- catalogId: current.active.profile?.catalogId ?? null,
645
- profile: current.active.profile,
646
- at: current.active.updatedAt ?? null,
647
- } : null
648
- return {
649
- ...current,
650
- generation: Math.max(current.generation || 0, pending.generation),
651
- // 切换成功后 requested 必须清空:它表示"待切换的另一个模型"。留着它,界面会
652
- // 同时显示"当前生效 + 待切换",让人以为还有一步没做完(2026-10-30 现场)。
653
- requested: null,
654
- active: {
655
- status: 'active',
656
- generation: pending.generation,
657
- fingerprint: profile.fingerprint,
658
- profile,
659
- databases,
660
- snapshot: sync.snapshot ?? null,
661
- lastMigration: sync.progress ?? pending.report?.progress ?? null,
662
- previous,
663
- reason: pending.reason ?? null,
664
- updatedAt: committedAt,
665
- },
666
- pending: { ...pending, status: 'committed', databases, committedAt },
667
- }
668
- })
669
- }
670
-
671
- /**
672
- * 完整切换:prepare(全新代际/全新影子)→ 追平(快照必须稳定)→ smoke → 原子切指针。
673
- * 任一步失败都不动 active;同一空间已生效时直接返回 already-active(不重建、不重嵌入)。
674
- */
675
- async function switchProfile(stepOptions = {}) {
676
- const profile = resolveProfile(stepOptions.profile ?? stepOptions.catalogId)
677
- const state = vectorState()
678
- const active = state?.active
679
- if (stepOptions.force !== true && active && active.fingerprint === profile.fingerprint) {
680
- const allowed = assertVectorWriteAllowed()
681
- return {
682
- ok: true, status: 'already-active', switched: false,
683
- generation: allowed.generation, fingerprint: allowed.fingerprint, profile: allowed.profile,
684
- databases: allowed.databases, env: profileEnv(allowed.profile), previous: active.previous ?? null, report: null,
685
- }
686
- }
687
- const prepared = await prepareShadow({ profile, libraries: stepOptions.libraries, fresh: stepOptions.fresh === true, reason: stepOptions.reason ?? 'switch' })
688
- let sync = await syncShadow({ generation: prepared.generation, fingerprint: prepared.fingerprint })
689
- let attempt = 1
690
- while (!sync.stable && attempt < maxCatchUpAttempts) {
691
- attempt += 1
692
- log('index moved during catch-up; re-syncing generation ' + prepared.generation + ' (attempt ' + attempt + ')')
693
- sync = await syncShadow({ generation: prepared.generation, fingerprint: prepared.fingerprint })
694
- }
695
- if (!sync.stable) {
696
- const message = 'the memory index changed while catching up; the active generation is untouched'
697
- failPending('VECTOR_INDEX_MOVED', message, { before: sync.snapshot?.digest ?? null, after: sync.afterDigest ?? null }, prepared)
698
- throw vectorError('VECTOR_INDEX_MOVED', message, { generation: prepared.generation, before: sync.snapshot?.digest ?? null, after: sync.afterDigest ?? null })
699
- }
700
- if (sync.failed.length) {
701
- const message = 'the rebuild did not cover every admitted memory; the active generation is untouched'
702
- failPending('VECTOR_SYNC_INCOMPLETE', message, { failed: sync.failed.length, failedItems: syncFailureDetail(sync) }, prepared)
703
- throw vectorError('VECTOR_SYNC_INCOMPLETE', message, { generation: prepared.generation, failed: sync.failed })
704
- }
705
- if (impl.smoke) {
706
- let outcome
707
- try {
708
- outcome = await impl.smoke({ profile, generation: prepared.generation, databases: prepared.databases, relative: prepared.relative, report: sync })
709
- } catch (error) {
710
- failPending('VECTOR_SMOKE_FAILED', String(error?.message || error), {}, prepared)
711
- throw vectorError('VECTOR_SMOKE_FAILED', 'smoke failed for generation ' + prepared.generation + ': ' + (error?.message || error), { causeCode: error?.code ?? null })
712
- }
713
- if (!outcome || outcome.ok === false) {
714
- failPending('VECTOR_SMOKE_FAILED', 'smoke rejected generation ' + prepared.generation, {}, prepared)
715
- throw vectorError('VECTOR_SMOKE_FAILED', 'smoke rejected generation ' + prepared.generation, { smoke: outcome ?? null })
716
- }
717
- }
718
- let next
719
- try {
720
- next = await withVectorWriteFreeze(async () => {
721
- const journal = pendingJournal()
722
- if (journal?.token !== prepared.token) throw vectorError(VECTOR_ERROR_CODES.TORN_STATE, 'the prepared shadow was replaced before final verification')
723
- const actualIds = (await resolveLibraryIds()).sort()
724
- const expectedIds = Object.keys(journal.databases.libraries).sort()
725
- if (stableStringify(actualIds) !== stableStringify(expectedIds)) throw vectorError('VECTOR_INDEX_MOVED', 'the library set changed after rebuild; active is untouched')
726
- const final = await captureSnapshot(scopesFor(journal.databases))
727
- if (final.digest !== sync.snapshot.digest) {
728
- failPending('VECTOR_INDEX_MOVED', 'the memory index changed after smoke; active is untouched', {}, prepared)
729
- throw vectorError('VECTOR_INDEX_MOVED', 'the memory index changed after smoke; active is untouched')
730
- }
731
- assertProfileVerified(profile)
732
- const stats = measureDatabases(journal.databases)
733
- // No await between final verified snapshot and atomic pointer swap.
734
- return commitActiveGeneration({ profile, journal: prepared, sync, stats })
735
- })
736
- } catch (error) {
737
- failPending(error?.code || 'VECTOR_SWITCH_FAILED', String(error?.message || error), {}, prepared)
738
- throw error
739
- }
740
- // 第二次极短原子写:清掉 committed journal。若在此崩溃,recoverProfile 仍能从 committed 记录认出新代。
741
- clearPendingJournal()
742
- log('activated vector generation ' + next.active.generation + ' (' + profile.catalogId + ')')
743
- return {
744
- ok: true,
745
- status: stepOptions.reason === 'rollback' ? 'rolled-back' : 'switched',
746
- switched: true,
747
- generation: next.active.generation,
748
- fingerprint: next.active.fingerprint,
749
- profile: next.active.profile,
750
- env: profileEnv(next.active.profile),
751
- databases: activeDatabases(),
752
- previous: next.active.previous ?? null,
753
- requested: next.requested ?? null,
754
- report: {
755
- committed: sync.committed,
756
- skipped: sync.skipped,
757
- tombstoned: sync.tombstoned,
758
- libraries: sync.libraries,
759
- snapshot: sync.snapshot,
760
- progress: sync.progress ?? null,
761
- },
762
- }
763
- }
764
-
765
- // -------------------------------------------------------------- 回滚
766
-
767
- /**
768
- * 回滚不是"恢复旧指针":切换后的新写入也要回到旧代,所以走同一套重建流程,
769
- * 把**最新 index** 重放进旧 profile 的一个全新代际里,再原子切回去(§14.8 第 9 条)。
770
- */
771
- async function rollbackProfile(stepOptions = {}) {
772
- const state = vectorState()
773
- const active = state?.active
774
- const target = stepOptions.profile ?? stepOptions.catalogId ?? active?.previous?.profile
775
- if (!target) throw vectorError('VECTOR_NO_ROLLBACK_TARGET', 'there is no previous generation to roll back to')
776
- const profile = resolveProfile(target)
777
- if (active && active.fingerprint === profile.fingerprint) {
778
- throw vectorError('VECTOR_NO_ROLLBACK_TARGET', 'the rollback target is already the active profile', { catalogId: profile.catalogId })
779
- }
780
- const result = await switchProfile({
781
- profile,
782
- libraries: stepOptions.libraries,
783
- fresh: stepOptions.fresh !== false,
784
- force: true,
785
- reason: 'rollback',
786
- })
787
- return { ...result, status: 'rolled-back', replayed: true, rolledBackFrom: active ? { generation: active.generation, catalogId: active.profile?.catalogId ?? null } : null }
788
- }
789
-
790
- // -------------------------------------------------------------- 启动恢复
791
-
792
- /**
793
- * 读 journal 恢复:prepared 未切 → 继续旧代(不切);committed → 认新代并清 journal;
794
- * 任何说不清的状态(journal 与指针矛盾、库文件缺失/变小、profile 不再有效)→ 抛 typed error,
795
- * 调用方必须退词法,不能猜最近文件,也不能回落 legacy 远端。
796
- */
797
- async function recoverProfile() {
798
- const state = readVectorState({ tolerateMissing: true }).state
799
- if (!state) return { status: 'absent', generation: null, fingerprint: null, profile: null, pending: null }
800
- const active = state.active
801
- const pending = state.pending
802
- if (pending && pending.status === 'committed') {
803
- if (!active || active.generation !== pending.generation) {
804
- throw vectorError(VECTOR_ERROR_CODES.TORN_STATE, 'the commit journal and the active pointer disagree; refusing vectors', {
805
- pendingGeneration: pending.generation, activeGeneration: active?.generation ?? null,
806
- })
807
- }
808
- clearPendingJournal()
809
- const allowed = assertVectorWriteAllowed({ deep: true })
810
- return { status: 'committed', recovered: true, generation: allowed.generation, fingerprint: allowed.fingerprint, profile: allowed.profile, databases: allowed.databases, pending: null }
811
- }
812
- if (pending && (pending.status === 'preparing' || pending.status === 'prepared')) {
813
- const preparedAgainst = pending.previousGeneration ?? null
814
- const activeGeneration = active?.generation ?? null
815
- if (preparedAgainst !== activeGeneration) {
816
- throw vectorError(VECTOR_ERROR_CODES.TORN_STATE, 'a rebuild was prepared against a generation that is no longer active; refusing vectors', {
817
- preparedAgainst, activeGeneration, pendingGeneration: pending.generation,
818
- })
819
- }
820
- if (!active) return { status: 'interrupted', generation: null, fingerprint: null, profile: null, pending: { generation: pending.generation, resume: true } }
821
- const allowed = assertVectorWriteAllowed({ deep: true })
822
- return {
823
- status: pending.status === 'prepared' ? 'prepared' : 'interrupted',
824
- recovered: false,
825
- generation: allowed.generation,
826
- fingerprint: allowed.fingerprint,
827
- profile: allowed.profile,
828
- databases: allowed.databases,
829
- pending: { generation: pending.generation, fingerprint: pending.fingerprint, token: pending.token, resume: pending.status === 'prepared', restart: pending.status === 'preparing' },
830
- }
831
- }
832
- if (pending && (pending.status === 'aborted' || pending.status === 'failed')) {
833
- clearPendingJournal()
834
- }
835
- if (!active) return { status: 'absent', generation: null, fingerprint: null, profile: null, pending: null }
836
- const allowed = assertVectorWriteAllowed({ deep: true })
837
- return {
838
- status: 'active',
839
- recovered: false,
840
- generation: allowed.generation,
841
- fingerprint: allowed.fingerprint,
842
- profile: allowed.profile,
843
- databases: allowed.databases,
844
- snapshot: allowed.snapshot,
845
- pending: null,
846
- }
847
- }
848
-
849
- /** 放弃一次未切换的重建;active 指针与旧库完全不动。 */
850
- function abortPending(reason = 'aborted by user') {
851
- const journal = pendingJournal()
852
- if (!journal) return { ok: true, aborted: false }
853
- if (journal.status === 'aborted' || journal.status === 'committed') return { ok: true, aborted: false }
854
- updatePendingJournal(current => ({ ...current, status: 'aborted', error: { code: 'VECTOR_BUILD_ABORTED', message: String(reason), at: now() } }))
855
- return { ok: true, aborted: true, generation: journal.generation, fingerprint: journal.fingerprint }
856
- }
857
-
858
- function readLedger(stepOptions = {}) {
859
- const journal = pendingJournal()
860
- const state = vectorState()
861
- const fingerprint = stepOptions.fingerprint ?? journal?.fingerprint ?? state?.active?.fingerprint
862
- const generation = Number.isSafeInteger(stepOptions.generation) ? stepOptions.generation : (journal?.generation ?? state?.active?.generation)
863
- if (!fingerprint || !Number.isSafeInteger(generation)) return null
864
- return loadLedger(fingerprint, generation).ledger
865
- }
866
-
867
- return {
868
- prepareShadow,
869
- syncShadow,
870
- switchProfile,
871
- rollbackProfile,
872
- recoverProfile,
873
- abortPending,
874
- status: () => vectorStatus(),
875
- pending: () => pendingJournal(),
876
- ledger: readLedger,
877
- /**
878
- * 当前生效代际里"哪些 id 已经写进向量库"(按 scope key:libraryId 或 'global')。
879
- * 两条腿合成,缺一都会数错:
880
- * * 账本腿:迁移写库时刻意不碰索引,所以迁移写入的条目没有 entry.vector 戳,
881
- * 只能查账本。但永久删除(forget)只删引擎行和索引行、不动账本,所以账本里的
882
- * id 还要扣掉"索引里已经没有的"(删掉的条目必然已从索引移除)。
883
- * * 戳腿:迁移之后的写入(remember/import/review/update/curator)在索引条目上带
884
- * entry.vector 戳。只认当前代际的戳 —— 旧代际的戳说明它属于旧空间,是否还在
885
- * 当前空间由账本腿回答(切代际会把当时可准入的条目全部重写一遍并记账)。
886
- */
887
- membership: () => {
888
- const state = vectorState()
889
- const active = state?.active
890
- if (!active) return null
891
- const ledger = readLedger({ fingerprint: active.fingerprint, generation: active.generation })
892
- if (!ledger) return null
893
- const generation = Number(active.generation)
894
- const out = {}
895
- for (const scope of scopesFor(active.databases)) {
896
- const bucket = ledger.libraries?.[scope.key]
897
- const migrated = bucket?.items && typeof bucket.items === 'object' ? Object.keys(bucket.items) : []
898
- let entries = null
899
- try {
900
- const loaded = impl.loadIndex(scope.libraryId)
901
- // loadIndex 的约定是同步读盘;拿到 Promise(测试替身)时按读不到处理,不猜。
902
- entries = loaded && typeof loaded.then === 'function' ? null : (loaded?.entries || {})
903
- } catch { entries = null }
904
- const ids = new Set()
905
- for (const id of migrated) {
906
- // 索引读不出来时宁可贵一点按"还在"算:损坏是暂时的,误扣会让用户以为记忆丢了。
907
- if (!entries || Object.prototype.hasOwnProperty.call(entries, id)) ids.add(id)
908
- }
909
- if (entries) {
910
- for (const [id, entry] of Object.entries(entries)) {
911
- // remote-api 的戳描述的是远端空间,不属于本地代际;词法路径没有戳。
912
- if (!entry || typeof entry !== 'object' || entry.vector?.route !== 'managed-local') continue
913
- if (Number(entry.vector.generation) === generation) ids.add(id)
914
- }
915
- }
916
- out[scope.key] = [...ids]
917
- }
918
- return out
919
- },
920
- ledgerSummary: stepOptions => {
921
- const ledger = readLedger(stepOptions)
922
- return ledger ? ledgerSummary(ledger) : null
923
- },
924
- captureGeneration,
925
- assertGeneration,
926
- assertVectorWriteAllowed,
927
- admittedItems,
928
- contentHash,
929
- }
930
- }
1
+ import fs from 'node:fs'
2
+ import path from 'node:path'
3
+ import crypto from 'node:crypto'
4
+ import { indexDir, librariesDir, ensureDir, readJsonStrict, writeJson, stamp } from './paths.js'
5
+ import {
6
+ VECTOR_ERROR_CODES, vectorError,
7
+ stableStringify, sha256Hex, resolveProfile, assertProfileVerified, vectorDbRelPath,
8
+ resolveVectorPath, readVectorState, vectorState, activeDatabases, updateVectorStateSync,
9
+ reserveShadowGeneration, updatePendingJournal, clearPendingJournal, pendingJournal,
10
+ assertVectorWriteAllowed, captureGeneration, assertGeneration, vectorStatus, withVectorWriteFreeze, profileEnv, setRequestedProfile,
11
+ } from './vector-profile.js'
12
+
13
+ // §14.8 影子重建 / 追平 / 原子代际切换 / 回滚 / 启动恢复。
14
+ //
15
+ // 原则:
16
+ // * 绝不原地重嵌入:每次都写到一个全新的影子库路径(代际号进文件名),旧库保持只读可用。
17
+ // * 账本键 = profile fingerprint + libraryId + itemId + content hash。命中即跳过,
18
+ // 所以"再来一次 commit"不是"再来一次 embed";内容变了才算重新嵌入。
19
+ // * tombstone:从索引里消失的条目要真的从影子库里删掉并记账,断点续建不得把它复活。
20
+ // * 切换只在最后短窗口里做同步 compare + 原子写 active 指针;之前的锁外工作可以失败,
21
+ // 失败就不动 active(§14.8 第 4/7/8 条)。
22
+ // * 索引快照在追平前后必须一致;不一致说明追平已经过期,中止切换而不是切到半步状态。
23
+ //
24
+ // 依赖全部注入,便于 fixture 测试:
25
+ // listLibraries() → [{ id }] | string[]
26
+ // loadIndex(libraryId | null) → { entries: { [itemId]: entry } } (null = 全局库)
27
+ // commit({ db, libraryId, item, entry, profile, generation }) → Promise
28
+ // forget({ db, libraryId, itemId, profile, generation }) → Promise
29
+ // listFiles({ db, libraryId, profile, generation }) → Promise<string[]> (影子里已有的条目名/ id)
30
+ // smoke({ profile, generation, databases, report }) → Promise<{ ok, checks? }>
31
+ // 调用方负责将状态存储与引擎接口适配为上述依赖形状。
32
+
33
+ export const VECTOR_LEDGER_PREFIX = 'vector-ledger.'
34
+ export const VECTOR_LEDGER_SCHEMA = 1
35
+
36
+ /** 这些状态不进入向量空间:重建不得把 held 的条目重新激活(§14.8 第 3 条)。 */
37
+ export const HELD_STATUSES = Object.freeze(['archived', 'suppressed', 'expired', 'pending_review', 'superseded', 'deleted'])
38
+
39
+ export function admitEntry(entry, nowMs = Date.now()) {
40
+ if (!entry || typeof entry !== 'object' || Array.isArray(entry)) return false
41
+ if (HELD_STATUSES.includes(String(entry.status || ''))) return false
42
+ if (entry.expiresAt && !(Date.parse(entry.expiresAt) > nowMs)) return false
43
+ return true
44
+ }
45
+
46
+ export function itemText(entry) {
47
+ if (!entry || typeof entry !== 'object') return ''
48
+ for (const key of ['text', 'content', 'body']) {
49
+ if (typeof entry[key] === 'string' && entry[key].trim()) return entry[key]
50
+ }
51
+ return ''
52
+ }
53
+
54
+ /** 内容/版本哈希:只有正文(与 id)改变才算需要重新嵌入。 */
55
+ export function contentHash(id, text, version = null) {
56
+ return sha256Hex(stableStringify({ id: String(id), text: String(text), version }))
57
+ }
58
+
59
+ /** 从插件 index 里取出"可写进向量空间"的条目(已按准入过滤,按 id 稳定排序)。 */
60
+ export function admittedItems(index, nowMs = Date.now()) {
61
+ const entries = index && typeof index.entries === 'object' && index.entries ? index.entries : {}
62
+ const items = []
63
+ for (const [id, entry] of Object.entries(entries)) {
64
+ if (!admitEntry(entry, nowMs)) continue
65
+ const text = itemText(entry)
66
+ if (!text.trim()) continue
67
+ items.push({ id, text, hash: contentHash(id, text, entry.contentVersion ?? entry.version ?? entry.updatedAt ?? null), entry: structuredClone(entry) })
68
+ }
69
+ items.sort((a, b) => (a.id < b.id ? -1 : a.id > b.id ? 1 : 0))
70
+ return items
71
+ }
72
+
73
+ function scopeSnapshotDigest(items) {
74
+ return sha256Hex(stableStringify(items.map(item => [item.id, item.hash])))
75
+ }
76
+
77
+ export function ledgerFile(fingerprint, generation) {
78
+ return path.join(indexDir(), VECTOR_LEDGER_PREFIX + String(fingerprint).slice(0, 8) + '.g' + Number(generation) + '.json')
79
+ }
80
+
81
+ function emptyLedger(fingerprint, generation) {
82
+ return {
83
+ version: VECTOR_LEDGER_SCHEMA,
84
+ fingerprint,
85
+ generation,
86
+ createdAt: stamp(),
87
+ updatedAt: stamp(),
88
+ snapshot: null,
89
+ libraries: {},
90
+ }
91
+ }
92
+
93
+ export function loadLedger(fingerprint, generation) {
94
+ const file = ledgerFile(fingerprint, generation)
95
+ const result = readJsonStrict(file)
96
+ if (!result.ok) {
97
+ if (result.missing) return { ok: true, ledger: emptyLedger(fingerprint, generation) }
98
+ return { ok: false, ledger: emptyLedger(fingerprint, generation), error: { code: result.kind === 'corrupt' ? 'VECTOR_LEDGER_CORRUPT' : 'VECTOR_LEDGER_UNREADABLE', file } }
99
+ }
100
+ const value = result.value
101
+ if (!value || typeof value !== 'object' || value.fingerprint !== fingerprint || Number(value.generation) !== Number(generation)) {
102
+ // 账本对不上代际/指纹:当作空账本重建(宁可贵一点,也不复用别人的进度)
103
+ return { ok: true, ledger: emptyLedger(fingerprint, generation), restarted: true }
104
+ }
105
+ return {
106
+ ok: true,
107
+ ledger: {
108
+ version: VECTOR_LEDGER_SCHEMA,
109
+ fingerprint,
110
+ generation: Number(generation),
111
+ createdAt: value.createdAt || stamp(),
112
+ updatedAt: value.updatedAt || stamp(),
113
+ snapshot: value.snapshot || null,
114
+ libraries: value.libraries && typeof value.libraries === 'object' ? value.libraries : {},
115
+ },
116
+ }
117
+ }
118
+
119
+ export function saveLedger(ledger) {
120
+ ensureDir(indexDir())
121
+ writeJson(ledgerFile(ledger.fingerprint, ledger.generation), ledger)
122
+ return ledger
123
+ }
124
+
125
+ function ledgerBucket(ledger, key) {
126
+ const existing = ledger.libraries[key]
127
+ if (existing && typeof existing === 'object') {
128
+ return ledger.libraries[key] = {
129
+ items: existing.items && typeof existing.items === 'object' ? existing.items : {},
130
+ tombstones: existing.tombstones && typeof existing.tombstones === 'object' ? existing.tombstones : {},
131
+ snapshot: existing.snapshot || null,
132
+ }
133
+ }
134
+ const bucket = { items: {}, tombstones: {}, snapshot: null }
135
+ ledger.libraries[key] = bucket
136
+ return bucket
137
+ }
138
+
139
+ export function ledgerSummary(ledger) {
140
+ const out = { fingerprint: ledger.fingerprint, generation: ledger.generation, libraries: {}, committed: 0, tombstones: 0 }
141
+ for (const [key, bucket] of Object.entries(ledger.libraries || {})) {
142
+ const committed = Object.keys(bucket?.items || {}).length
143
+ const tombstones = Object.keys(bucket?.tombstones || {}).length
144
+ out.libraries[key] = { committed, tombstones }
145
+ out.committed += committed
146
+ out.tombstones += tombstones
147
+ }
148
+ out.snapshot = ledger.snapshot
149
+ return out
150
+ }
151
+
152
+ function fileStats(absPath) {
153
+ const buffer = fs.readFileSync(absPath)
154
+ return { bytes: buffer.length, sha256: crypto.createHash('sha256').update(buffer).digest('hex') }
155
+ }
156
+
157
+ // ---------------------------------------------------------------- 迁移器
158
+
159
+ const REQUIRED_DEPS = Object.freeze(['listLibraries', 'loadIndex', 'commit', 'forget', 'listFiles'])
160
+
161
+ /**
162
+ * createVectorMigrator({ listLibraries, loadIndex, commit, forget, listFiles, smoke?, now?, log?, maxCatchUpAttempts?, itemRetries? })
163
+ * 也接受 { deps: {...}, ... } 形式。所有副作用都经注入依赖,便于纯 fixture 测试。
164
+ */
165
+ export function createVectorMigrator(options = {}) {
166
+ const configured = options && typeof options.deps === 'object' && options.deps ? { ...options.deps, ...options } : { ...options }
167
+ const impl = {
168
+ listLibraries: configured.listLibraries,
169
+ loadIndex: configured.loadIndex,
170
+ commit: configured.commit,
171
+ forget: configured.forget,
172
+ listFiles: configured.listFiles ?? configured.list,
173
+ retrieve: typeof configured.retrieve === 'function' ? configured.retrieve : null,
174
+ smoke: typeof configured.smoke === 'function' ? configured.smoke : null,
175
+ // Optional: drop the index-side `vectorPending` marker for ids that this rebuild
176
+ // has just proven present in the shadow. Without it the marker was write-only —
177
+ // nothing ever cleared it after a successful migration, so a fully migrated
178
+ // library kept advertising itself as "not in the vector store yet".
179
+ clearVectorPending: typeof configured.clearVectorPending === 'function' ? configured.clearVectorPending : null,
180
+ }
181
+ for (const name of REQUIRED_DEPS) {
182
+ if (typeof impl[name] !== 'function') throw new TypeError('createVectorMigrator requires a ' + name + '(… ) dependency')
183
+ }
184
+ const now = typeof configured.now === 'function' ? configured.now : () => new Date().toISOString()
185
+ const log = typeof configured.log === 'function' ? configured.log : () => {}
186
+ const onProgress = typeof configured.onProgress === 'function' ? configured.onProgress : null
187
+ const maxCatchUpAttempts = Number.isSafeInteger(configured.maxCatchUpAttempts) && configured.maxCatchUpAttempts > 0 ? configured.maxCatchUpAttempts : 3
188
+ const itemRetries = Number.isSafeInteger(configured.itemRetries) && configured.itemRetries >= 0 ? configured.itemRetries : 1
189
+
190
+ function publishProgress(progress, { persist = true } = {}) {
191
+ const snapshot = { ...progress, updatedAt: now() }
192
+ if (persist) {
193
+ updatePendingJournal(current => {
194
+ if (current.generation !== snapshot.generation || current.fingerprint !== snapshot.fingerprint) throw vectorError(VECTOR_ERROR_CODES.STALE_GENERATION, 'progress belongs to a replaced shadow generation')
195
+ return { ...current, report: { ...(current.report || {}), progress: snapshot } }
196
+ })
197
+ }
198
+ if (onProgress) {
199
+ try {
200
+ const result = onProgress(structuredClone(snapshot))
201
+ if (result && typeof result.then === 'function') result.catch(error => log('progress callback failed: ' + (error?.message || error)))
202
+ } catch (error) {
203
+ log('progress callback failed: ' + (error?.message || error))
204
+ }
205
+ }
206
+ return snapshot
207
+ }
208
+
209
+ function idOf(value) {
210
+ const id = typeof value === 'string' ? value : value?.id
211
+ if (typeof id !== 'string' || !id || id === 'global') return null
212
+ return id
213
+ }
214
+
215
+ async function resolveLibraryIds(libraries) {
216
+ const raw = Array.isArray(libraries) ? libraries : await impl.listLibraries()
217
+ const ids = []
218
+ for (const item of raw ?? []) {
219
+ const id = idOf(item)
220
+ if (id && !ids.includes(id)) ids.push(id)
221
+ }
222
+ return ids
223
+ }
224
+
225
+ function scopesFor(databases) {
226
+ const scopes = [{ key: 'global', libraryId: null, rel: databases.global.path, db: resolveVectorPath(databases.global.path) }]
227
+ for (const [libraryId, entry] of Object.entries(databases.libraries || {})) {
228
+ scopes.push({ key: libraryId, libraryId, rel: entry.path, db: resolveVectorPath(entry.path) })
229
+ }
230
+ return scopes
231
+ }
232
+
233
+ async function captureSnapshot(scopes) {
234
+ const parts = []
235
+ for (const scope of scopes) {
236
+ const index = structuredClone(await impl.loadIndex(scope.libraryId))
237
+ const items = admittedItems(index)
238
+ parts.push({ key: scope.key, items, digest: sha256Hex(stableStringify({ index, admitted: scopeSnapshotDigest(items) })) })
239
+ }
240
+ return {
241
+ digest: sha256Hex(stableStringify(parts.map(part => [part.key, part.digest]))),
242
+ scopes: parts,
243
+ at: now(),
244
+ }
245
+ }
246
+
247
+ async function presentIds(scope, profile, generation) {
248
+ const ids = new Set()
249
+ if (!fs.existsSync(scope.db)) return ids
250
+ const listed = await impl.listFiles({ db: scope.db, libraryId: scope.libraryId, profile, generation })
251
+ if (!Array.isArray(listed) && !Array.isArray(listed?.recall_files)) throw vectorError('VECTOR_LIST_INVALID', 'shadow list returned an invalid result for ' + scope.key)
252
+ const names = Array.isArray(listed) ? listed : Array.isArray(listed?.recall_files) ? listed.recall_files : []
253
+ for (const value of names) {
254
+ if (typeof value === 'string') ids.add(value)
255
+ else if (value && typeof value === 'object') {
256
+ const name = value.name ?? value.id
257
+ if (typeof name === 'string') ids.add(name)
258
+ }
259
+ }
260
+ return ids
261
+ }
262
+
263
+ async function commitItem(scope, item, profile, generation) {
264
+ let lastError = null
265
+ for (let attempt = 0; attempt <= itemRetries; attempt++) {
266
+ try {
267
+ // Failure may still persist a row. Forget first: unchanged-description
268
+ // recommit is not proof that the backend regenerated an embedding.
269
+ if ((await presentIds(scope, profile, generation)).has(item.id)) {
270
+ await impl.forget({ db: scope.db, libraryId: scope.libraryId, itemId: item.id, profile, generation })
271
+ if ((await presentIds(scope, profile, generation)).has(item.id)) throw vectorError('VECTOR_FORGET_FAILED', 'shadow item still exists after forget: ' + item.id)
272
+ }
273
+ await impl.commit({ db: scope.db, libraryId: scope.libraryId, item, entry: item.entry ?? null, profile, generation })
274
+ if (!(await presentIds(scope, profile, generation)).has(item.id)) throw vectorError('VECTOR_READBACK_FAILED', 'committed item is missing from shadow: ' + item.id)
275
+ if (impl.retrieve) {
276
+ const result = await impl.retrieve({ db: scope.db, libraryId: scope.libraryId, itemId: item.id, item, profile, generation })
277
+ if (result == null || result === false || result.ok === false) throw vectorError('VECTOR_READBACK_FAILED', 'cannot retrieve committed shadow item: ' + item.id)
278
+ }
279
+ return { ok: true }
280
+ } catch (error) {
281
+ lastError = error
282
+ if (attempt < itemRetries) log('commit retry ' + scope.key + '/' + item.id + ' after ' + (error?.code || error?.message || error))
283
+ }
284
+ }
285
+ return { ok: false, error: lastError }
286
+ }
287
+
288
+ // -------------------------------------------------------------- prepareShadow
289
+
290
+ /**
291
+ * 为一次重建分配"全新代际 + 全新影子路径",并把 prepared journal 先落盘。
292
+ * 不写 active 指针、不碰旧库。同指纹的未完成重建默认续建(同一代际、同一路径、账本跳过
293
+ * 已嵌入条目);fresh:true 则强制换新代际(= 真正重来一遍)。
294
+ */
295
+ async function prepareShadow(stepOptions = {}) {
296
+ const profile = resolveProfile(stepOptions.profile ?? stepOptions.catalogId)
297
+ const libraryIds = await resolveLibraryIds(stepOptions.libraries)
298
+ const fresh = stepOptions.fresh === true
299
+ const reason = typeof stepOptions.reason === 'string' ? stepOptions.reason : 'switch'
300
+ const current = vectorState()
301
+ const pending = current?.pending
302
+ let resumable = !fresh && pending && pending.fingerprint === profile.fingerprint
303
+ && (pending.status === 'preparing' || pending.status === 'prepared' || pending.status === 'failed')
304
+ if (resumable) {
305
+ // Same fingerprint is not enough: the manifest digest covers the artifact
306
+ // list, and a catalog update (for example adding a download source) makes the
307
+ // old journal profile unverifiable. Resuming it would fail later in
308
+ // syncShadowImpl; discard it now and start a clean generation instead.
309
+ try {
310
+ assertProfileVerified(pending.profile)
311
+ } catch (error) {
312
+ log('discarding stale pending generation ' + pending.generation + ': ' + String(error?.code || error?.message || error))
313
+ resumable = false
314
+ }
315
+ }
316
+ if (resumable) {
317
+ // 续建:同一代际,只把新出现的库补进同一个 DB 集合(同一次原子切换里生效)
318
+ const extended = updatePendingJournal(journal => {
319
+ const libraries = { ...(journal.databases?.libraries || {}) }
320
+ for (const id of libraryIds) {
321
+ if (!libraries[id]) libraries[id] = { path: vectorDbRelPath({ libraryId: id, fingerprint: journal.fingerprint, generation: journal.generation }), bytes: null, sha256: null }
322
+ }
323
+ return { ...journal, databases: { ...journal.databases, libraries } }
324
+ })
325
+ try {
326
+ ensureShadowFiles(extended.databases)
327
+ } catch (error) {
328
+ failPending(error?.code || 'VECTOR_PREPARE_FAILED', String(error?.message || error), {}, extended)
329
+ throw error
330
+ }
331
+ setRequestedProfile(profile, { reason })
332
+ log('resuming shadow generation ' + extended.generation + ' for ' + profile.catalogId)
333
+ return describeShadow(extended, true)
334
+ }
335
+ const reservation = reserveShadowGeneration({ profile, libraryIds, reason })
336
+ // 全新代际 = 全新空影子库。路径上已经有文件说明编号冲突,绝不覆盖/复用。
337
+ try {
338
+ ensureShadowFiles(reservation.databases, { refuseExisting: true })
339
+ } catch (error) {
340
+ failPending(error?.code || 'VECTOR_PREPARE_FAILED', String(error?.message || error), {}, reservation)
341
+ throw error
342
+ }
343
+ setRequestedProfile(profile, { reason })
344
+ log('prepared shadow generation ' + reservation.generation + ' for ' + profile.catalogId)
345
+ return describeShadow(pendingJournal(), false)
346
+ }
347
+
348
+ /**
349
+ * 影子库集合必须是"存在且为空"的:空 sqlite 文件是合法起点,缺文件会被误当成撕裂。
350
+ * refuseExisting=true 用于全新代际——路径上已有文件说明编号被复用,直接拒绝。
351
+ */
352
+ function ensureShadowFiles(databases, { refuseExisting = false } = {}) {
353
+ ensureDir(librariesDir())
354
+ for (const scope of scopesFor(databases)) {
355
+ ensureDir(path.dirname(scope.db))
356
+ if (fs.existsSync(scope.db)) {
357
+ if (refuseExisting) {
358
+ throw vectorError(VECTOR_ERROR_CODES.SHADOW_PATH_TAKEN, 'the reserved shadow path already exists; refusing to reuse a database from another attempt', {
359
+ path: scope.rel,
360
+ })
361
+ }
362
+ continue
363
+ }
364
+ fs.writeFileSync(scope.db, '', { flag: 'wx' })
365
+ }
366
+ }
367
+
368
+ function describeShadow(journal, resumed) {
369
+ const scopes = scopesFor(journal.databases)
370
+ return {
371
+ generation: journal.generation,
372
+ token: journal.token,
373
+ fingerprint: journal.fingerprint,
374
+ profile: journal.profile,
375
+ status: journal.status,
376
+ reason: journal.reason ?? null,
377
+ resumed: Boolean(resumed),
378
+ previousGeneration: journal.previousGeneration ?? null,
379
+ databases: {
380
+ global: scopes[0].db,
381
+ libraries: Object.fromEntries(scopes.slice(1).map(scope => [scope.key, scope.db])),
382
+ },
383
+ env: profileEnv(journal.profile),
384
+ relative: {
385
+ global: journal.databases.global.path,
386
+ libraries: Object.fromEntries(Object.entries(journal.databases.libraries || {}).map(([id, entry]) => [id, entry.path])),
387
+ },
388
+ }
389
+ }
390
+
391
+ // -------------------------------------------------------------- syncShadow
392
+
393
+ /**
394
+ * 把索引里所有准入条目写进影子库;命中账本的跳过(那已经是这一代的向量),
395
+ * 消失的条目 forget + tombstone。返回追平报告与前后快照(快照不一致 = 追平已过期)。
396
+ */
397
+ // 只报"有几条失败"没法修:把前几条的 id/错误码/消息留下来。syncShadow 与
398
+ // switchProfile 两处都要带,后者会覆盖前者的 pending.error。
399
+ function syncFailureDetail(report) {
400
+ return report.failed.slice(0, 10).map(item => ({
401
+ libraryId: item.libraryId ?? null,
402
+ itemId: item.itemId ?? null,
403
+ code: item.code ?? 'VECTOR_COMMIT_FAILED',
404
+ message: String(item.message ?? '').slice(0, 300),
405
+ }))
406
+ }
407
+
408
+ async function syncShadow(stepOptions = {}) {
409
+ const expected = pendingJournal()
410
+ try {
411
+ const report = await syncShadowImpl(stepOptions)
412
+ if (report.failed.length) {
413
+ // 保留失败条目的 id、错误码与消息,并在日志中输出摘要,便于定位未覆盖原因。
414
+ const failedItems = syncFailureDetail(report)
415
+ log('rebuild sync failures: ' + failedItems.slice(0, 3).map(item => `${item.itemId || item.libraryId}:${item.code}:${item.message}`).join(' | '))
416
+ failPending('VECTOR_SYNC_INCOMPLETE', 'the rebuild did not cover every admitted memory; the active generation is untouched', { failed: report.failed.length, failedItems }, expected)
417
+ }
418
+ return report
419
+ } catch (error) {
420
+ const matches = expected && (stepOptions.generation == null || stepOptions.generation === expected.generation)
421
+ && (stepOptions.fingerprint == null || stepOptions.fingerprint === expected.fingerprint)
422
+ if (matches) failPending(error?.code || 'VECTOR_SYNC_FAILED', String(error?.message || error), { causeCode: error?.code ?? null }, expected)
423
+ throw error
424
+ }
425
+ }
426
+
427
+ async function syncShadowImpl(stepOptions = {}) {
428
+ const journal = pendingJournal()
429
+ if (!journal) throw vectorError('VECTOR_PENDING_MISSING', 'there is no prepared rebuild to sync')
430
+ const generation = Number.isSafeInteger(stepOptions.generation) ? stepOptions.generation : journal.generation
431
+ const fingerprint = typeof stepOptions.fingerprint === 'string' ? stepOptions.fingerprint : journal.fingerprint
432
+ if (journal.generation !== generation || journal.fingerprint !== fingerprint) {
433
+ throw vectorError('VECTOR_PENDING_MISSING', 'the prepared rebuild belongs to a different generation', { generation, fingerprint, preparedGeneration: journal.generation })
434
+ }
435
+ if (journal.status === 'committed') throw vectorError(VECTOR_ERROR_CODES.TORN_STATE, 'this generation is already committed; nothing to sync')
436
+ const profile = assertProfileVerified(journal.profile)
437
+ const scopes = scopesFor(journal.databases)
438
+ if (Array.isArray(stepOptions.libraries)) {
439
+ // 只追平指定的私有库;全局库永远在同一代际里(不能漏,否则新代缺全局空间)
440
+ const wanted = new Set(stepOptions.libraries.map(idOf).filter(Boolean))
441
+ if (wanted.size) {
442
+ const libraries = Object.fromEntries(Object.entries(journal.databases.libraries || {}).filter(([id]) => wanted.has(id)))
443
+ scopes.length = 0
444
+ scopes.push(...scopesFor({ global: journal.databases.global, libraries }))
445
+ }
446
+ }
447
+ const loaded = loadLedger(fingerprint, generation)
448
+ const ledger = loaded.ledger
449
+ if (loaded.error) log('ledger unreadable (' + loaded.error.code + '); rebuilding it from the index')
450
+ const before = await captureSnapshot(scopes)
451
+ const total = before.scopes.reduce((sum, scope) => sum + scope.items.length, 0)
452
+ const report = { generation, fingerprint, committed: 0, skipped: 0, tombstoned: 0, failed: [], libraries: {}, restarted: Boolean(loaded.restarted || loaded.error) }
453
+ const progress = { stage: 'syncing', generation, fingerprint, total, completed: 0, skipped: 0, committed: 0, tombstoned: 0, failed: 0, current: null }
454
+ publishProgress(progress)
455
+ for (let index = 0; index < scopes.length; index++) {
456
+ const scope = scopes[index]
457
+ const items = before.scopes[index].items
458
+ const bucket = ledgerBucket(ledger, scope.key)
459
+ ensureDir(path.dirname(scope.db))
460
+ const present = await presentIds(scope, profile, generation)
461
+ const known = new Set(items.map(item => item.id))
462
+ for (const item of items) {
463
+ const recorded = bucket.items[item.id]
464
+ const tombstoned = bucket.tombstones[item.id]
465
+ if (recorded && recorded.hash === item.hash && present.has(item.id) && !tombstoned) {
466
+ report.skipped += 1
467
+ progress.skipped = report.skipped
468
+ progress.completed = report.committed + report.skipped
469
+ progress.current = { stage: 'skipped', libraryId: scope.key, itemId: item.id }
470
+ publishProgress(progress)
471
+ continue
472
+ }
473
+ const outcome = await commitItem(scope, item, profile, generation)
474
+ if (!outcome.ok) {
475
+ const error = outcome.error
476
+ report.failed.push({
477
+ libraryId: scope.key,
478
+ itemId: item.id,
479
+ code: error?.code || 'VECTOR_COMMIT_FAILED',
480
+ message: String(error?.message || error || 'commit failed'),
481
+ })
482
+ progress.failed = report.failed.length
483
+ progress.completed = report.committed + report.skipped + progress.failed
484
+ progress.current = { stage: 'failed', libraryId: scope.key, itemId: item.id, code: error?.code || 'VECTOR_COMMIT_FAILED' }
485
+ publishProgress(progress)
486
+ continue
487
+ }
488
+ bucket.items[item.id] = { hash: item.hash, at: now() }
489
+ delete bucket.tombstones[item.id]
490
+ report.committed += 1
491
+ progress.committed = report.committed
492
+ progress.completed = report.committed + report.skipped + progress.failed
493
+ progress.current = { stage: 'committed', libraryId: scope.key, itemId: item.id }
494
+ publishProgress(progress)
495
+ ledger.updatedAt = now()
496
+ saveLedger(ledger)
497
+ }
498
+ for (const name of present) {
499
+ if (known.has(name)) continue
500
+ try {
501
+ await impl.forget({ db: scope.db, libraryId: scope.libraryId, itemId: name, profile, generation })
502
+ } catch (error) {
503
+ report.failed.push({ libraryId: scope.key, itemId: name, code: error?.code || 'VECTOR_FORGET_FAILED', message: String(error?.message || error || 'forget failed') })
504
+ progress.failed = report.failed.length
505
+ progress.completed = report.committed + report.skipped + report.tombstoned + progress.failed
506
+ progress.current = { stage: 'failed', libraryId: scope.key, itemId: name, code: error?.code || 'VECTOR_FORGET_FAILED' }
507
+ publishProgress(progress)
508
+ continue
509
+ }
510
+ bucket.tombstones[name] = { hash: bucket.items[name]?.hash ?? null, at: now(), reason: 'absent-from-index' }
511
+ delete bucket.items[name]
512
+ report.tombstoned += 1
513
+ progress.tombstoned = report.tombstoned
514
+ progress.completed = report.committed + report.skipped + report.tombstoned + progress.failed
515
+ progress.current = { stage: 'tombstoned', libraryId: scope.key, itemId: name }
516
+ publishProgress(progress)
517
+ ledger.updatedAt = now()
518
+ saveLedger(ledger)
519
+ }
520
+ for (const [itemId, record] of Object.entries(bucket.items)) {
521
+ // 索引里已经没有它、影子库里也没有:留 tombstone,避免断点续建把它复活。
522
+ if (known.has(itemId) || present.has(itemId)) continue
523
+ bucket.tombstones[itemId] = { hash: record?.hash ?? null, at: now(), reason: 'not-present' }
524
+ delete bucket.items[itemId]
525
+ report.tombstoned += 1
526
+ progress.tombstoned = report.tombstoned
527
+ progress.completed = report.committed + report.skipped + report.tombstoned + progress.failed
528
+ progress.current = { stage: 'tombstoned', libraryId: scope.key, itemId }
529
+ publishProgress(progress)
530
+ }
531
+ const verifiedPresent = await presentIds(scope, profile, generation)
532
+ if (verifiedPresent.size !== known.size || [...known].some(id => !verifiedPresent.has(id))) {
533
+ report.failed.push({ libraryId: scope.key, code: 'VECTOR_COVERAGE_FAILED', message: 'shadow membership differs from eligible index snapshot' })
534
+ } else if (impl.clearVectorPending) {
535
+ // Coverage passed: every admitted entry is provably in this generation's
536
+ // shadow, so "write me into the vector store later" is finished for all of
537
+ // them. Fail-open — a stale flag costs a little wasted work next rebuild, it
538
+ // must never turn a successful migration into a failed one.
539
+ try {
540
+ impl.clearVectorPending({ libraryId: scope.libraryId, ids: [...known], generation })
541
+ } catch (error) {
542
+ log('clear vectorPending failed for ' + scope.key + ': ' + (error?.message || error))
543
+ }
544
+ }
545
+ bucket.snapshot = { digest: before.scopes[index].digest, items: items.length, at: before.at }
546
+ report.libraries[scope.key] = { items: items.length, present: present.size, digest: before.scopes[index].digest }
547
+ ledger.updatedAt = now()
548
+ saveLedger(ledger)
549
+ }
550
+ const after = await captureSnapshot(scopes)
551
+ const stable = after.digest === before.digest
552
+ ledger.snapshot = { digest: before.digest, at: before.at, stable, libraries: report.libraries }
553
+ ledger.updatedAt = now()
554
+ saveLedger(ledger)
555
+ report.snapshot = { digest: before.digest, at: before.at, libraries: report.libraries }
556
+ report.afterDigest = after.digest
557
+ report.stable = stable
558
+ report.ledger = ledgerSummary(ledger)
559
+ progress.stage = report.failed.length ? 'failed' : 'prepared'
560
+ progress.failed = report.failed.length
561
+ progress.completed = report.committed + report.skipped + report.tombstoned + progress.failed
562
+ progress.current = null
563
+ report.progress = publishProgress(progress)
564
+ if (report.failed.length === 0) {
565
+ updatePendingJournal(current => ({ ...current, status: 'prepared', preparedAt: now(), snapshot: report.snapshot, report: { committed: report.committed, skipped: report.skipped, tombstoned: report.tombstoned, libraries: report.libraries, progress: report.progress } }))
566
+ }
567
+ return report
568
+ }
569
+
570
+ // -------------------------------------------------------------- 切换
571
+
572
+ function measureDatabases(databases) {
573
+ const stats = {}
574
+ for (const scope of scopesFor(databases)) {
575
+ let info
576
+ try {
577
+ info = fileStats(scope.db)
578
+ } catch (error) {
579
+ throw vectorError(VECTOR_ERROR_CODES.TORN_STATE, 'cannot read back shadow database ' + scope.rel + ' (' + (error?.code || error?.message || error) + ')', { path: scope.rel })
580
+ }
581
+ stats[scope.rel] = info
582
+ }
583
+ return stats
584
+ }
585
+
586
+ function failPending(code, message, extra = {}, expected = null) {
587
+ let failedProgress = null
588
+ updatePendingJournal(current => {
589
+ if (expected && (current.token !== expected.token || current.generation !== expected.generation || current.fingerprint !== expected.fingerprint)) return null
590
+ if (current.status === 'committed' || current.status === 'aborted') return null
591
+ const prior = current.report?.progress || { generation: current.generation, fingerprint: current.fingerprint, total: 0, completed: 0, skipped: 0, committed: 0, tombstoned: 0, failed: 0, current: null }
592
+ failedProgress = { ...prior, stage: 'failed', failed: Math.max(1, prior.failed || 0), current: { stage: 'failed', code }, updatedAt: now() }
593
+ return { ...current, status: 'failed', error: { code, message, at: now(), ...extra }, report: { ...(current.report || {}), progress: failedProgress } }
594
+ })
595
+ if (failedProgress && onProgress) {
596
+ try { onProgress(structuredClone(failedProgress)) } catch (error) { log('progress callback failed: ' + (error?.message || error)) }
597
+ }
598
+ }
599
+
600
+ /**
601
+ * 最后短窗口:锁内只做同步 compare(token/代际/文件大小)与一次原子指针写。
602
+ * 这里没有 await,也不允许有(§14.8 第 5/7 条)。
603
+ */
604
+ function commitActiveGeneration({ profile, journal, sync, stats }) {
605
+ const committedAt = now()
606
+ return updateVectorStateSync(current => {
607
+ const pending = current.pending
608
+ if (!pending) {
609
+ throw vectorError('VECTOR_PENDING_MISSING', 'the prepared rebuild disappeared before the switch', { generation: journal.generation })
610
+ }
611
+ if (pending.token !== journal.token || pending.generation !== journal.generation || pending.fingerprint !== profile.fingerprint) {
612
+ throw vectorError(VECTOR_ERROR_CODES.TORN_STATE, 'another rebuild replaced this prepared generation; refusing to switch', {
613
+ prepared: { generation: journal.generation, token: journal.token }, currentPending: { generation: pending.generation, token: pending.token },
614
+ })
615
+ }
616
+ if (pending.status !== 'prepared') throw vectorError('VECTOR_SYNC_INCOMPLETE', 'only a prepared shadow generation can be activated')
617
+ const preparedAgainst = pending.previousGeneration ?? null
618
+ const activeGeneration = current.active?.generation ?? null
619
+ if (preparedAgainst !== activeGeneration) {
620
+ throw vectorError(VECTOR_ERROR_CODES.TORN_STATE, 'the active generation changed while the rebuild was prepared; refusing to switch', { activeGeneration, preparedAgainst })
621
+ }
622
+ for (const scope of scopesFor(pending.databases)) {
623
+ let info
624
+ try {
625
+ info = fs.statSync(scope.db)
626
+ } catch {
627
+ throw vectorError(VECTOR_ERROR_CODES.TORN_STATE, 'a shadow database vanished before the switch: ' + scope.rel, { path: scope.rel })
628
+ }
629
+ const expected = stats[scope.rel]
630
+ if (!info.isFile() || !expected || info.size !== expected.bytes || fileStats(scope.db).sha256 !== expected.sha256) {
631
+ throw vectorError(VECTOR_ERROR_CODES.TORN_STATE, 'a shadow database changed after the final sync: ' + scope.rel, { path: scope.rel, expected: expected?.bytes ?? null, actual: info.size })
632
+ }
633
+ }
634
+ const databases = {
635
+ global: { path: pending.databases.global.path, bytes: stats[pending.databases.global.path].bytes, sha256: stats[pending.databases.global.path].sha256 },
636
+ libraries: Object.fromEntries(Object.entries(pending.databases.libraries || {}).map(([libraryId, entry]) => [
637
+ libraryId, { path: entry.path, bytes: stats[entry.path]?.bytes ?? null, sha256: stats[entry.path]?.sha256 ?? null },
638
+ ])),
639
+ }
640
+ const previous = current.active ? {
641
+ generation: current.active.generation,
642
+ fingerprint: current.active.fingerprint,
643
+ catalogId: current.active.profile?.catalogId ?? null,
644
+ profile: current.active.profile,
645
+ at: current.active.updatedAt ?? null,
646
+ } : null
647
+ return {
648
+ ...current,
649
+ generation: Math.max(current.generation || 0, pending.generation),
650
+ // 切换成功后清空 requested,避免界面继续显示已经完成的待切换请求。
651
+ requested: null,
652
+ active: {
653
+ status: 'active',
654
+ generation: pending.generation,
655
+ fingerprint: profile.fingerprint,
656
+ profile,
657
+ databases,
658
+ snapshot: sync.snapshot ?? null,
659
+ lastMigration: sync.progress ?? pending.report?.progress ?? null,
660
+ previous,
661
+ reason: pending.reason ?? null,
662
+ updatedAt: committedAt,
663
+ },
664
+ pending: { ...pending, status: 'committed', databases, committedAt },
665
+ }
666
+ })
667
+ }
668
+
669
+ /**
670
+ * 完整切换:prepare(全新代际/全新影子)→ 追平(快照必须稳定)→ smoke → 原子切指针。
671
+ * 任一步失败都不动 active;同一空间已生效时直接返回 already-active(不重建、不重嵌入)。
672
+ */
673
+ async function switchProfile(stepOptions = {}) {
674
+ const profile = resolveProfile(stepOptions.profile ?? stepOptions.catalogId)
675
+ const state = vectorState()
676
+ const active = state?.active
677
+ if (stepOptions.force !== true && active && active.fingerprint === profile.fingerprint) {
678
+ const allowed = assertVectorWriteAllowed()
679
+ return {
680
+ ok: true, status: 'already-active', switched: false,
681
+ generation: allowed.generation, fingerprint: allowed.fingerprint, profile: allowed.profile,
682
+ databases: allowed.databases, env: profileEnv(allowed.profile), previous: active.previous ?? null, report: null,
683
+ }
684
+ }
685
+ const prepared = await prepareShadow({ profile, libraries: stepOptions.libraries, fresh: stepOptions.fresh === true, reason: stepOptions.reason ?? 'switch' })
686
+ let sync = await syncShadow({ generation: prepared.generation, fingerprint: prepared.fingerprint })
687
+ let attempt = 1
688
+ while (!sync.stable && attempt < maxCatchUpAttempts) {
689
+ attempt += 1
690
+ log('index moved during catch-up; re-syncing generation ' + prepared.generation + ' (attempt ' + attempt + ')')
691
+ sync = await syncShadow({ generation: prepared.generation, fingerprint: prepared.fingerprint })
692
+ }
693
+ if (!sync.stable) {
694
+ const message = 'the memory index changed while catching up; the active generation is untouched'
695
+ failPending('VECTOR_INDEX_MOVED', message, { before: sync.snapshot?.digest ?? null, after: sync.afterDigest ?? null }, prepared)
696
+ throw vectorError('VECTOR_INDEX_MOVED', message, { generation: prepared.generation, before: sync.snapshot?.digest ?? null, after: sync.afterDigest ?? null })
697
+ }
698
+ if (sync.failed.length) {
699
+ const message = 'the rebuild did not cover every admitted memory; the active generation is untouched'
700
+ failPending('VECTOR_SYNC_INCOMPLETE', message, { failed: sync.failed.length, failedItems: syncFailureDetail(sync) }, prepared)
701
+ throw vectorError('VECTOR_SYNC_INCOMPLETE', message, { generation: prepared.generation, failed: sync.failed })
702
+ }
703
+ if (impl.smoke) {
704
+ let outcome
705
+ try {
706
+ outcome = await impl.smoke({ profile, generation: prepared.generation, databases: prepared.databases, relative: prepared.relative, report: sync })
707
+ } catch (error) {
708
+ failPending('VECTOR_SMOKE_FAILED', String(error?.message || error), {}, prepared)
709
+ throw vectorError('VECTOR_SMOKE_FAILED', 'smoke failed for generation ' + prepared.generation + ': ' + (error?.message || error), { causeCode: error?.code ?? null })
710
+ }
711
+ if (!outcome || outcome.ok === false) {
712
+ failPending('VECTOR_SMOKE_FAILED', 'smoke rejected generation ' + prepared.generation, {}, prepared)
713
+ throw vectorError('VECTOR_SMOKE_FAILED', 'smoke rejected generation ' + prepared.generation, { smoke: outcome ?? null })
714
+ }
715
+ }
716
+ let next
717
+ try {
718
+ next = await withVectorWriteFreeze(async () => {
719
+ const journal = pendingJournal()
720
+ if (journal?.token !== prepared.token) throw vectorError(VECTOR_ERROR_CODES.TORN_STATE, 'the prepared shadow was replaced before final verification')
721
+ const actualIds = (await resolveLibraryIds()).sort()
722
+ const expectedIds = Object.keys(journal.databases.libraries).sort()
723
+ if (stableStringify(actualIds) !== stableStringify(expectedIds)) throw vectorError('VECTOR_INDEX_MOVED', 'the library set changed after rebuild; active is untouched')
724
+ const final = await captureSnapshot(scopesFor(journal.databases))
725
+ if (final.digest !== sync.snapshot.digest) {
726
+ failPending('VECTOR_INDEX_MOVED', 'the memory index changed after smoke; active is untouched', {}, prepared)
727
+ throw vectorError('VECTOR_INDEX_MOVED', 'the memory index changed after smoke; active is untouched')
728
+ }
729
+ assertProfileVerified(profile)
730
+ const stats = measureDatabases(journal.databases)
731
+ // No await between final verified snapshot and atomic pointer swap.
732
+ return commitActiveGeneration({ profile, journal: prepared, sync, stats })
733
+ })
734
+ } catch (error) {
735
+ failPending(error?.code || 'VECTOR_SWITCH_FAILED', String(error?.message || error), {}, prepared)
736
+ throw error
737
+ }
738
+ // 第二次极短原子写:清掉 committed journal。若在此崩溃,recoverProfile 仍能从 committed 记录认出新代。
739
+ clearPendingJournal()
740
+ log('activated vector generation ' + next.active.generation + ' (' + profile.catalogId + ')')
741
+ return {
742
+ ok: true,
743
+ status: stepOptions.reason === 'rollback' ? 'rolled-back' : 'switched',
744
+ switched: true,
745
+ generation: next.active.generation,
746
+ fingerprint: next.active.fingerprint,
747
+ profile: next.active.profile,
748
+ env: profileEnv(next.active.profile),
749
+ databases: activeDatabases(),
750
+ previous: next.active.previous ?? null,
751
+ requested: next.requested ?? null,
752
+ report: {
753
+ committed: sync.committed,
754
+ skipped: sync.skipped,
755
+ tombstoned: sync.tombstoned,
756
+ libraries: sync.libraries,
757
+ snapshot: sync.snapshot,
758
+ progress: sync.progress ?? null,
759
+ },
760
+ }
761
+ }
762
+
763
+ // -------------------------------------------------------------- 回滚
764
+
765
+ /**
766
+ * 回滚不是"恢复旧指针":切换后的新写入也要回到旧代,所以走同一套重建流程,
767
+ * 把**最新 index** 重放进旧 profile 的一个全新代际里,再原子切回去(§14.8 第 9 条)。
768
+ */
769
+ async function rollbackProfile(stepOptions = {}) {
770
+ const state = vectorState()
771
+ const active = state?.active
772
+ const target = stepOptions.profile ?? stepOptions.catalogId ?? active?.previous?.profile
773
+ if (!target) throw vectorError('VECTOR_NO_ROLLBACK_TARGET', 'there is no previous generation to roll back to')
774
+ const profile = resolveProfile(target)
775
+ if (active && active.fingerprint === profile.fingerprint) {
776
+ throw vectorError('VECTOR_NO_ROLLBACK_TARGET', 'the rollback target is already the active profile', { catalogId: profile.catalogId })
777
+ }
778
+ const result = await switchProfile({
779
+ profile,
780
+ libraries: stepOptions.libraries,
781
+ fresh: stepOptions.fresh !== false,
782
+ force: true,
783
+ reason: 'rollback',
784
+ })
785
+ return { ...result, status: 'rolled-back', replayed: true, rolledBackFrom: active ? { generation: active.generation, catalogId: active.profile?.catalogId ?? null } : null }
786
+ }
787
+
788
+ // -------------------------------------------------------------- 启动恢复
789
+
790
+ /**
791
+ * 读 journal 恢复:prepared 未切 → 继续旧代(不切);committed → 认新代并清 journal;
792
+ * 任何说不清的状态(journal 与指针矛盾、库文件缺失/变小、profile 不再有效)→ 抛 typed error,
793
+ * 调用方必须退词法,不能猜最近文件,也不能回落 legacy 远端。
794
+ */
795
+ async function recoverProfile() {
796
+ const state = readVectorState({ tolerateMissing: true }).state
797
+ if (!state) return { status: 'absent', generation: null, fingerprint: null, profile: null, pending: null }
798
+ const active = state.active
799
+ const pending = state.pending
800
+ if (pending && pending.status === 'committed') {
801
+ if (!active || active.generation !== pending.generation) {
802
+ throw vectorError(VECTOR_ERROR_CODES.TORN_STATE, 'the commit journal and the active pointer disagree; refusing vectors', {
803
+ pendingGeneration: pending.generation, activeGeneration: active?.generation ?? null,
804
+ })
805
+ }
806
+ clearPendingJournal()
807
+ const allowed = assertVectorWriteAllowed({ deep: true })
808
+ return { status: 'committed', recovered: true, generation: allowed.generation, fingerprint: allowed.fingerprint, profile: allowed.profile, databases: allowed.databases, pending: null }
809
+ }
810
+ if (pending && (pending.status === 'preparing' || pending.status === 'prepared')) {
811
+ const preparedAgainst = pending.previousGeneration ?? null
812
+ const activeGeneration = active?.generation ?? null
813
+ if (preparedAgainst !== activeGeneration) {
814
+ throw vectorError(VECTOR_ERROR_CODES.TORN_STATE, 'a rebuild was prepared against a generation that is no longer active; refusing vectors', {
815
+ preparedAgainst, activeGeneration, pendingGeneration: pending.generation,
816
+ })
817
+ }
818
+ if (!active) return { status: 'interrupted', generation: null, fingerprint: null, profile: null, pending: { generation: pending.generation, resume: true } }
819
+ const allowed = assertVectorWriteAllowed({ deep: true })
820
+ return {
821
+ status: pending.status === 'prepared' ? 'prepared' : 'interrupted',
822
+ recovered: false,
823
+ generation: allowed.generation,
824
+ fingerprint: allowed.fingerprint,
825
+ profile: allowed.profile,
826
+ databases: allowed.databases,
827
+ pending: { generation: pending.generation, fingerprint: pending.fingerprint, token: pending.token, resume: pending.status === 'prepared', restart: pending.status === 'preparing' },
828
+ }
829
+ }
830
+ if (pending && (pending.status === 'aborted' || pending.status === 'failed')) {
831
+ clearPendingJournal()
832
+ }
833
+ if (!active) return { status: 'absent', generation: null, fingerprint: null, profile: null, pending: null }
834
+ const allowed = assertVectorWriteAllowed({ deep: true })
835
+ return {
836
+ status: 'active',
837
+ recovered: false,
838
+ generation: allowed.generation,
839
+ fingerprint: allowed.fingerprint,
840
+ profile: allowed.profile,
841
+ databases: allowed.databases,
842
+ snapshot: allowed.snapshot,
843
+ pending: null,
844
+ }
845
+ }
846
+
847
+ /** 放弃一次未切换的重建;active 指针与旧库完全不动。 */
848
+ function abortPending(reason = 'aborted by user') {
849
+ const journal = pendingJournal()
850
+ if (!journal) return { ok: true, aborted: false }
851
+ if (journal.status === 'aborted' || journal.status === 'committed') return { ok: true, aborted: false }
852
+ updatePendingJournal(current => ({ ...current, status: 'aborted', error: { code: 'VECTOR_BUILD_ABORTED', message: String(reason), at: now() } }))
853
+ return { ok: true, aborted: true, generation: journal.generation, fingerprint: journal.fingerprint }
854
+ }
855
+
856
+ function readLedger(stepOptions = {}) {
857
+ const journal = pendingJournal()
858
+ const state = vectorState()
859
+ const fingerprint = stepOptions.fingerprint ?? journal?.fingerprint ?? state?.active?.fingerprint
860
+ const generation = Number.isSafeInteger(stepOptions.generation) ? stepOptions.generation : (journal?.generation ?? state?.active?.generation)
861
+ if (!fingerprint || !Number.isSafeInteger(generation)) return null
862
+ return loadLedger(fingerprint, generation).ledger
863
+ }
864
+
865
+ return {
866
+ prepareShadow,
867
+ syncShadow,
868
+ switchProfile,
869
+ rollbackProfile,
870
+ recoverProfile,
871
+ abortPending,
872
+ status: () => vectorStatus(),
873
+ pending: () => pendingJournal(),
874
+ ledger: readLedger,
875
+ /**
876
+ * 当前生效代际里"哪些 id 已经写进向量库"(按 scope key:libraryId 或 'global')。
877
+ * 两条腿合成,缺一都会数错:
878
+ * * 账本腿:迁移写库时刻意不碰索引,所以迁移写入的条目没有 entry.vector 戳,
879
+ * 只能查账本。但永久删除(forget)只删引擎行和索引行、不动账本,所以账本里的
880
+ * id 还要扣掉"索引里已经没有的"(删掉的条目必然已从索引移除)。
881
+ * * 戳腿:迁移之后的写入(remember/import/review/update/curator)在索引条目上带
882
+ * entry.vector 戳。只认当前代际的戳 —— 旧代际的戳说明它属于旧空间,是否还在
883
+ * 当前空间由账本腿回答(切代际会把当时可准入的条目全部重写一遍并记账)。
884
+ */
885
+ membership: () => {
886
+ const state = vectorState()
887
+ const active = state?.active
888
+ if (!active) return null
889
+ const ledger = readLedger({ fingerprint: active.fingerprint, generation: active.generation })
890
+ if (!ledger) return null
891
+ const generation = Number(active.generation)
892
+ const out = {}
893
+ for (const scope of scopesFor(active.databases)) {
894
+ const bucket = ledger.libraries?.[scope.key]
895
+ const migrated = bucket?.items && typeof bucket.items === 'object' ? Object.keys(bucket.items) : []
896
+ let entries = null
897
+ try {
898
+ const loaded = impl.loadIndex(scope.libraryId)
899
+ // loadIndex 的约定是同步读盘;拿到 Promise(测试替身)时按读不到处理,不猜。
900
+ entries = loaded && typeof loaded.then === 'function' ? null : (loaded?.entries || {})
901
+ } catch { entries = null }
902
+ const ids = new Set()
903
+ for (const id of migrated) {
904
+ // 索引读不出来时宁可贵一点按"还在"算:损坏是暂时的,误扣会让用户以为记忆丢了。
905
+ if (!entries || Object.prototype.hasOwnProperty.call(entries, id)) ids.add(id)
906
+ }
907
+ if (entries) {
908
+ for (const [id, entry] of Object.entries(entries)) {
909
+ // remote-api 的戳描述的是远端空间,不属于本地代际;词法路径没有戳。
910
+ if (!entry || typeof entry !== 'object' || entry.vector?.route !== 'managed-local') continue
911
+ if (Number(entry.vector.generation) === generation) ids.add(id)
912
+ }
913
+ }
914
+ out[scope.key] = [...ids]
915
+ }
916
+ return out
917
+ },
918
+ ledgerSummary: stepOptions => {
919
+ const ledger = readLedger(stepOptions)
920
+ return ledger ? ledgerSummary(ledger) : null
921
+ },
922
+ captureGeneration,
923
+ assertGeneration,
924
+ assertVectorWriteAllowed,
925
+ admittedItems,
926
+ contentHash,
927
+ }
928
+ }