dsh-memu-memory 1.4.1 → 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 -108
  2. package/CHANGELOG.md +169 -848
  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 -72
  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 -0
  18. package/docs/memory-semantics.md +271 -259
  19. package/docs/pending-work.md +44 -51
  20. package/docs/troubleshooting.md +909 -840
  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 -9648
  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 -1035
  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 -4911
  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 -0
  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 -2518
  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 -1066
  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 -152
  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 -455
  182. package/tests/client-export.test.mjs +521 -520
  183. package/tests/client-render.test.mjs +2008 -1727
  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 -48
  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 -415
  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 -616
  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 -0
  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 -23
  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 -221
  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 -212
  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 -414
  388. package/tests/windows-env.test.mjs +89 -89
  389. package/tests/worker-lifecycle.test.mjs +1521 -1429
package/lib/backup.js CHANGED
@@ -1,1254 +1,1254 @@
1
- import crypto from 'node:crypto'
2
- import fs from 'node:fs'
3
- import path from 'node:path'
4
- import { spawn } from 'node:child_process'
5
- import {
6
- backupsDir, dataDir, ensureDir, indexDir, isSafeId, librariesDir,
7
- readJson, warn, withFileLock, writeJson,
8
- } from './paths.js'
9
-
10
- /**
11
- * Local-vector backup policy - safe latest-three backup retention.
12
- *
13
- * One rule, one place. Every managed backup of the current data root is created
14
- * by createBackup(), published atomically, and only then may the oldest
15
- * complete backups beyond BACKUP_KEEP be deleted. Create, delete, restore and
16
- * prune share a single lock, so the safety backup a restore just made can never
17
- * collect the very directory that restore is reading from.
18
- *
19
- * Invariants:
20
- * 1. A failed or interrupted creation deletes nothing. The backup is built in
21
- * backups/.staging/<name>.<pid>.<rand>, hashed file by file, given its
22
- * manifest last (the completion marker) and only then renamed into place.
23
- * 2. Only directories that prove themselves complete are ever deleted.
24
- * Corrupt, half-written, foreign, linked or unknown entries are reported
25
- * and left exactly where they are.
26
- * 3. Ordering is the verified manifest createdAt plus a unique id - never an
27
- * mtime that a copy or a clock change can reorder.
28
- * 4. A lease pins the directory a restore (or migration) is about to read, so
29
- * prune cannot remove it mid-flight; going briefly over the limit is
30
- * allowed and is reclaimed as soon as the operation finishes.
31
- * 5. A recursive delete re-checks realpath containment and refuses links
32
- * before it removes a single byte.
33
- * 6. SQLite is snapshotted only by SQLite's own backup API, run by the
34
- * plugin's isolated engine/<version>/venv interpreter. A live db+wal+shm is
35
- * never copied by hand, and a global Python is never borrowed: if the
36
- * managed engine cannot prove a consistent snapshot, the backup fails
37
- * instead of publishing a copy that would restore as silent corruption.
38
- * Only a zero-byte placeholder (no page, no WAL frame) may be copied.
39
- */
40
-
41
- export const BACKUP_KEEP = 3
42
- export const BACKUP_SCHEMA = 2
43
-
44
- // Timestamp name of a published backup, optionally suffixed for uniqueness
45
- // within the same millisecond. Anything else in backups/ is not a managed
46
- // backup and is never counted or deleted by retention.
47
- const MANAGED_NAME = /^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}-[0-9]{2}-[0-9]{2}-[0-9]{3}Z(-[A-Za-z0-9]+)*$/
48
- const SQLITE_MAGIC = 'SQLite format 3' + String.fromCharCode(0)
49
- const BACKSLASH = String.fromCharCode(92)
50
- const NEWLINE = String.fromCharCode(10)
51
- const STAGING_TTL_MS = 30 * 60 * 1000
52
- const LEASE_TTL_MS = 15 * 60 * 1000
53
- const RETRY_MS = 8
54
- const PYTHON_TIMEOUT_MS = 120000
55
- const PROBE_TIMEOUT_MS = 20000
56
-
57
- const stagingRoot = () => path.join(backupsDir(), '.staging')
58
- const leaseFile = () => path.join(backupsDir(), '.leases.json')
59
- const lockAnchor = () => path.join(backupsDir(), '.backup')
60
- const stateFile = () => path.join(dataDir(), 'state.json')
61
- const globalDbFile = () => path.join(dataDir(), 'global.sqlite3')
62
- const lexiconRoot = () => path.join(dataDir(), 'lexicon')
63
- const vectorActiveFile = () => path.join(indexDir(), 'vector-active.json')
64
- const engineCurrentFile = () => path.join(dataDir(), 'engine', 'current.json')
65
-
66
- function isoStamp() { return new Date().toISOString() }
67
- function pause(ms) { Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms) }
68
-
69
- function statOrNull(file) {
70
- try { return fs.lstatSync(file) } catch { return null }
71
- }
72
-
73
- function readdirSafe(dir, options) {
74
- try { return fs.readdirSync(dir, options) } catch { return [] }
75
- }
76
-
77
- function realpathOrNull(file) {
78
- try { return fs.realpathSync.native(file) } catch { return null }
79
- }
80
-
81
- function samePath(a, b) {
82
- const left = path.resolve(String(a))
83
- const right = path.resolve(String(b))
84
- return process.platform === 'win32' ? left.toLowerCase() === right.toLowerCase() : left === right
85
- }
86
-
87
- function readJsonQuiet(file) {
88
- try { return JSON.parse(fs.readFileSync(file, 'utf8')) } catch { return null }
89
- }
90
-
91
- function sha256File(file) {
92
- return crypto.createHash('sha256').update(fs.readFileSync(file)).digest('hex')
93
- }
94
-
95
- function fileSize(file) {
96
- const info = statOrNull(file)
97
- return info ? info.size : -1
98
- }
99
-
100
- function hasSqliteHeader(file) {
101
- let fd
102
- try {
103
- fd = fs.openSync(file, 'r')
104
- const buffer = Buffer.alloc(SQLITE_MAGIC.length)
105
- const read = fs.readSync(fd, buffer, 0, buffer.length, 0)
106
- return read === buffer.length && buffer.toString('latin1') === SQLITE_MAGIC
107
- } catch {
108
- return false
109
- } finally {
110
- if (fd !== undefined) { try { fs.closeSync(fd) } catch {} }
111
- }
112
- }
113
-
114
- // ---------------------------------------------------------------- lock & leases
115
-
116
- // 同进程可重入的锁集合。paths.js 的 withFileLock 是纯同步的(try { return action() }
117
- // finally 立刻删锁文件):直接把 async action 传进去,锁会在第一个 await 之前
118
- // 就释放,restore 的 safety backup 与 prune 便失去互斥。这里自己管理同一把
119
- // .backup.lock,持锁直到 action 的 Promise 完成;同步 action 仍返回同步结果。
120
- const heldBackupLocks = new Set()
121
-
122
- function acquireBackupLock() {
123
- const lock = path.resolve(lockAnchor()) + '.lock'
124
- if (heldBackupLocks.has(lock)) return () => {}
125
- ensureDir(backupsDir())
126
- const until = Date.now() + 500
127
- let fd
128
- while (fd === undefined) {
129
- try {
130
- fd = fs.openSync(lock, 'wx', 0o600)
131
- fs.writeFileSync(fd, String(process.pid))
132
- } catch (error) {
133
- if (error?.code !== 'EEXIST') throw error
134
- try {
135
- const owner = Number(fs.readFileSync(lock, 'utf8'))
136
- if (Number.isSafeInteger(owner) && owner > 0 && !pidAlive(owner)) { fs.unlinkSync(lock); continue }
137
- } catch {}
138
- if (Date.now() >= until) {
139
- const busy = new Error('memory store is busy: backup; retry the operation')
140
- busy.code = 'DSH_MEMU_STORE_BUSY'
141
- throw busy
142
- }
143
- pause(10)
144
- }
145
- }
146
- heldBackupLocks.add(lock)
147
- return () => {
148
- heldBackupLocks.delete(lock)
149
- try { fs.closeSync(fd) } catch {}
150
- for (let attempt = 0; ; attempt += 1) {
151
- try { fs.unlinkSync(lock); break } catch (error) {
152
- if (error?.code === 'ENOENT') break
153
- if (['EPERM', 'EBUSY', 'EACCES'].includes(error?.code) && attempt < 5) { pause(RETRY_MS * (attempt + 1)); continue }
154
- warn('backups: could not release backup lock (' + (error?.code || 'io error') + ')')
155
- break
156
- }
157
- }
158
- }
159
- }
160
-
161
- /**
162
- * The one lock that coordinates create/delete/restore/prune. It is reentrant
163
- * inside this process, so a restore may create its own safety backup and prune
164
- * while still holding it. A synchronous action returns its value synchronously;
165
- * an async action returns a Promise and the lock stays held until it settles.
166
- */
167
- export function withBackupLock(action) {
168
- const release = acquireBackupLock()
169
- let result
170
- try {
171
- result = action()
172
- } catch (error) {
173
- release()
174
- throw error
175
- }
176
- if (result && typeof result.then === 'function') return Promise.resolve(result).finally(release)
177
- release()
178
- return result
179
- }
180
-
181
- function pidAlive(pid) {
182
- if (!Number.isSafeInteger(pid) || pid <= 0) return false
183
- if (pid === process.pid) return true
184
- try { process.kill(pid, 0); return true } catch (error) { return error?.code === 'EPERM' }
185
- }
186
-
187
- function readLeases() {
188
- const raw = readJson(leaseFile(), {})
189
- return raw && typeof raw === 'object' && !Array.isArray(raw) ? raw : {}
190
- }
191
-
192
- /** Leases of operations that are still running right now. */
193
- export function activeLeases() {
194
- const now = Date.now()
195
- const live = {}
196
- for (const [name, lease] of Object.entries(readLeases())) {
197
- if (!lease || typeof lease !== 'object') continue
198
- if (now - Number(lease.at || 0) > LEASE_TTL_MS) continue
199
- if (!pidAlive(Number(lease.pid))) continue
200
- live[name] = lease
201
- }
202
- return live
203
- }
204
-
205
- function writeLease(name, lease) {
206
- const leases = readLeases()
207
- if (lease) leases[name] = lease
208
- else delete leases[name]
209
- writeJson(leaseFile(), leases)
210
- }
211
-
212
- // ------------------------------------------------------------- sqlite snapshots
213
- //
214
- // One rule: a live SQLite database is only ever snapshotted by SQLite itself,
215
- // through the plugin's own isolated interpreter (engine/<version>/venv). There
216
- // is no global-Python path and no byte-copy fallback. A copy of a live database
217
- // - or of a database plus its WAL - is torn the moment a writer commits between
218
- // the two reads, and a torn copy restores as silent corruption, which is worse
219
- // than no backup at all. So when the managed engine cannot produce a provable
220
- // snapshot, the whole backup FAILS and nothing is published.
221
- //
222
- // The one file that may be copied verbatim is a zero-byte placeholder: no page
223
- // was ever written and there are no WAL frames, so there is nothing to tear.
224
-
225
- function engineRoot() { return path.join(dataDir(), 'engine') }
226
-
227
- function engineCurrent() {
228
- const raw = readJsonQuiet(engineCurrentFile())
229
- if (!raw || typeof raw !== 'object') return null
230
- return {
231
- version: raw.version || null,
232
- schemaVersion: raw.schemaVersion || null,
233
- python: typeof raw.python === 'string' && raw.python ? raw.python : null,
234
- venv: typeof raw.venv === 'string' && raw.venv ? raw.venv : null,
235
- }
236
- }
237
-
238
- function venvPythonPath(venv) {
239
- return process.platform === 'win32'
240
- ? path.join(venv, 'Scripts', 'python.exe')
241
- : path.join(venv, 'bin', 'python3')
242
- }
243
-
244
- /** True when both paths exist and `child` resolves inside `parent`. */
245
- function insideDir(child, parent) {
246
- if (typeof child !== 'string' || !child) return false
247
- const left = realpathOrNull(child)
248
- const right = realpathOrNull(parent)
249
- if (!left || !right) return false
250
- const a = process.platform === 'win32' ? left.toLowerCase() : left
251
- const b = process.platform === 'win32' ? right.toLowerCase() : right
252
- return a === b || a.startsWith(b.endsWith(path.sep) ? b : b + path.sep)
253
- }
254
-
255
- /**
256
- * Every interpreter the plugin itself installed: whatever `engine/current.json`
257
- * points at first (that file is only written after the engine was verified
258
- * against the real databases), then any engine/<version>/venv* directory found
259
- * on disk, newest first. The on-disk scan is what makes an engine repair
260
- * possible: while a new engine installs, its venv is still `venv.tmp-*` and
261
- * current.json still points at the broken one.
262
- */
263
- function engineVenvCandidates() {
264
- const root = engineRoot()
265
- const out = []
266
- const seen = new Set()
267
- const add = (venv, version, source) => {
268
- if (typeof venv !== 'string' || !venv) return
269
- const key = process.platform === 'win32' ? venv.toLowerCase() : venv
270
- if (seen.has(key)) return
271
- seen.add(key)
272
- out.push({ venv, version: version || null, source })
273
- }
274
- const current = engineCurrent()
275
- add(current?.venv, current?.version, 'engine/current.json')
276
- const mtimeOf = (file) => { const info = statOrNull(file); return info ? info.mtimeMs : 0 }
277
- const versions = readdirSafe(root, { withFileTypes: true })
278
- .filter((item) => item.isDirectory())
279
- .map((item) => ({ name: item.name, at: mtimeOf(path.join(root, item.name)) }))
280
- .sort((a, b) => b.at - a.at)
281
- for (const version of versions) {
282
- const dir = path.join(root, version.name)
283
- const venvs = readdirSafe(dir, { withFileTypes: true })
284
- .filter((item) => item.isDirectory() && item.name.indexOf('venv') === 0)
285
- .map((item) => ({ name: item.name, at: mtimeOf(path.join(dir, item.name)) }))
286
- .sort((a, b) => b.at - a.at)
287
- for (const venv of venvs) add(path.join(dir, venv.name), version.name, 'engine/' + version.name + '/' + venv.name)
288
- }
289
- return out
290
- }
291
-
292
- // The probe answers two questions at once: does this interpreter have sqlite3,
293
- // and is it really the isolated venv (sys.prefix) rather than a shim that hands
294
- // the work to a global Python.
295
- const PYTHON_PROBE_SCRIPT = [
296
- 'import json, sys',
297
- 'out = {"ok": False, "error": "unknown"}',
298
- 'try:',
299
- ' import sqlite3',
300
- ' out = {"ok": True, "prefix": sys.prefix, "sqlite": getattr(sqlite3, "sqlite_version", "unknown")}',
301
- 'except Exception as error:',
302
- ' out = {"ok": False, "prefix": sys.prefix, "error": str(error)}',
303
- 'sys.stdout.write(json.dumps(out))',
304
- ].join(NEWLINE)
305
-
306
- const SQLITE_SNAPSHOT_SCRIPT = [
307
- 'import json, sqlite3, sys',
308
- 'src, dst = sys.argv[1], sys.argv[2]',
309
- 'out = {"ok": False, "error": "unknown"}',
310
- 'try:',
311
- ' source = sqlite3.connect(src, timeout=10)',
312
- ' try:',
313
- ' target = sqlite3.connect(dst)',
314
- ' try:',
315
- ' source.backup(target)',
316
- ' row = target.execute("pragma quick_check").fetchone()',
317
- ' out = {"ok": True, "quickCheck": (row[0] if row else "unknown")}',
318
- ' finally:',
319
- ' target.close()',
320
- ' finally:',
321
- ' source.close()',
322
- 'except Exception as error:',
323
- ' out = {"ok": False, "error": str(error)}',
324
- 'sys.stdout.write(json.dumps(out))',
325
- ].join(NEWLINE)
326
-
327
- let enginePythonCache = null
328
-
329
- /** Forget the cached interpreter probe (tests use this between scenarios). */
330
- export function resetBackupPythonProbe() { enginePythonCache = null }
331
-
332
- /**
333
- * spawn + Promise 版的解释器运行器:不再用 spawnSync 冻结事件循环(S-3)。
334
- * 超时先软终止,5s 后硬杀并主动 reject,不等 'close';Windows 用
335
- * taskkill /T /F 连带杀掉子进程树。maxBuffer 超限走同一条终止路径。
336
- */
337
- function spawnPython(cmd, args, { timeout, maxBuffer }) {
338
- return new Promise((resolve, reject) => {
339
- let child
340
- try {
341
- child = spawn(cmd, args, { windowsHide: true, stdio: ['ignore', 'pipe', 'pipe'] })
342
- } catch (error) {
343
- reject(error)
344
- return
345
- }
346
- let settled = false
347
- let stdout = ''
348
- let stderr = ''
349
- let timeoutTimer = null
350
- let killTimer = null
351
- const signalChild = force => {
352
- if (!child || child.exitCode !== null) return
353
- if (process.platform === 'win32') {
354
- try { spawn('taskkill', ['/pid', String(child.pid), '/T', '/F'], { windowsHide: true, stdio: 'ignore' }) } catch {}
355
- } else {
356
- try { child.kill(force ? 'SIGKILL' : 'SIGTERM') } catch {}
357
- }
358
- }
359
- const finish = (error, value) => {
360
- if (settled) return
361
- settled = true
362
- if (timeoutTimer) clearTimeout(timeoutTimer)
363
- if (killTimer) clearTimeout(killTimer)
364
- if (error) reject(error)
365
- else resolve(value)
366
- }
367
- const abort = reason => {
368
- if (settled || killTimer) return
369
- if (timeoutTimer) { clearTimeout(timeoutTimer); timeoutTimer = null }
370
- signalChild(false)
371
- killTimer = setTimeout(() => {
372
- signalChild(true)
373
- finish(reason, null) // 主动结束,不依赖 'close'
374
- }, 5000)
375
- killTimer.unref?.()
376
- }
377
- if (Number.isFinite(timeout) && timeout > 0) {
378
- timeoutTimer = setTimeout(() => abort(Object.assign(new Error('python process timed out'), { code: 'ETIMEDOUT' })), timeout)
379
- timeoutTimer.unref?.()
380
- }
381
- try { child.stdout?.setEncoding?.('utf8') } catch {}
382
- try { child.stderr?.setEncoding?.('utf8') } catch {}
383
- child.stdout?.on?.('data', chunk => {
384
- if (settled) return
385
- stdout += chunk
386
- if (Buffer.byteLength(stdout) > maxBuffer) abort(Object.assign(new Error('maxBuffer exceeded'), { code: 'ENOBUFS' }))
387
- })
388
- child.stderr?.on?.('data', chunk => {
389
- if (settled) return
390
- stderr += chunk
391
- if (Buffer.byteLength(stderr) > maxBuffer) abort(Object.assign(new Error('maxBuffer exceeded'), { code: 'ENOBUFS' }))
392
- })
393
- child.on?.('error', error => finish(error, null))
394
- child.on?.('close', (code, signal) => finish(null, { status: code, signal, stdout, stderr }))
395
- })
396
- }
397
-
398
- /**
399
- * Runs an interpreter. `exec` is a seam for tests only (a fake interpreter);
400
- * production always spawns the verified venv binary and nothing else.
401
- * 兼容同步的测试 seam:await 一个普通返回值也照常拿到结果。
402
- */
403
- async function runPython(exec, cmd, args, timeout) {
404
- const runner = typeof exec === 'function' ? exec : spawnPython
405
- try {
406
- return await runner(cmd, args, { timeout, windowsHide: true, encoding: 'utf8', maxBuffer: 4 * 1024 * 1024 })
407
- } catch (error) {
408
- return { error, status: null, stdout: '', stderr: '' }
409
- }
410
- }
411
-
412
- function jsonOutcome(result) {
413
- const text = String(result?.stdout || '').trim()
414
- if (!text) return null
415
- try { return JSON.parse(text) } catch { return null }
416
- }
417
-
418
- /**
419
- * Resolves the engine interpreter a snapshot may use, or reports why there is
420
- * none. Never falls back to a global interpreter: a missing, foreign or broken
421
- * venv is a refusal, not a downgrade.
422
- */
423
- async function enginePythonForBackup(exec) {
424
- const disabled = process.env.DSH_MEMU_BACKUP_NO_PYTHON === '1'
425
- const root = engineRoot()
426
- const candidates = disabled ? [] : engineVenvCandidates()
427
- const key = JSON.stringify({ disabled, root, candidates })
428
- if (enginePythonCache && enginePythonCache.key === key) return enginePythonCache.value
429
- const value = { python: null, rejected: [] }
430
- for (const candidate of candidates) {
431
- const python = venvPythonPath(candidate.venv)
432
- if (!fs.existsSync(python)) {
433
- value.rejected.push(candidate.source + ': no interpreter on disk')
434
- continue
435
- }
436
- if (!insideDir(candidate.venv, root) || !insideDir(python, root)) {
437
- value.rejected.push(candidate.source + ': outside ' + root)
438
- continue
439
- }
440
- const probe = await runPython(exec, python, ['-c', PYTHON_PROBE_SCRIPT], PROBE_TIMEOUT_MS)
441
- const outcome = jsonOutcome(probe)
442
- if (!outcome || outcome.ok !== true) {
443
- const reason = outcome?.error || probe?.error?.message || (probe?.status != null ? 'exited ' + probe.status : 'no answer')
444
- value.rejected.push(candidate.source + ': ' + String(reason).slice(0, 200))
445
- continue
446
- }
447
- if (!insideDir(outcome.prefix, root)) {
448
- value.rejected.push(candidate.source + ': interpreter reports sys.prefix ' + String(outcome.prefix) + ', outside engine/')
449
- continue
450
- }
451
- value.python = {
452
- cmd: python,
453
- venv: candidate.venv,
454
- version: candidate.version,
455
- source: candidate.source,
456
- sqlite: outcome.sqlite ? String(outcome.sqlite) : null,
457
- }
458
- break
459
- }
460
- enginePythonCache = { key, value }
461
- return value
462
- }
463
-
464
- function backupRefusal(code, message) {
465
- const error = new Error(message)
466
- error.code = code
467
- return error
468
- }
469
-
470
- function removeQuietly(file) {
471
- try { fs.rmSync(file, { force: true }) } catch {}
472
- }
473
-
474
- /**
475
- * Asks the engine interpreter to run SQLite's online backup API: it folds any
476
- * live WAL into one self-contained file and hands back a proven-consistent
477
- * snapshot. Anything short of a clean `quick_check` is a failure, never a
478
- * reason to copy the bytes ourselves.
479
- */
480
- async function pythonSnapshot(exec, python, from, to) {
481
- const result = await runPython(exec, python.cmd, ['-c', SQLITE_SNAPSHOT_SCRIPT, from, to], PYTHON_TIMEOUT_MS)
482
- if (result?.error) return { ok: false, error: String(result.error.message || result.error) }
483
- if (result?.status !== 0) {
484
- return { ok: false, error: String(result?.stderr || ('engine interpreter exited ' + result?.status)).trim().slice(0, 400) }
485
- }
486
- const payload = jsonOutcome(result)
487
- if (!payload || payload.ok !== true) {
488
- return { ok: false, error: String(payload?.error || 'sqlite3 backup returned no result').slice(0, 400) }
489
- }
490
- if (payload.quickCheck !== 'ok') {
491
- return { ok: false, error: 'snapshot failed pragma quick_check: ' + String(payload.quickCheck || 'unknown').slice(0, 200) }
492
- }
493
- if (!hasSqliteHeader(to) || fileSize(to) <= 0) {
494
- return { ok: false, error: 'snapshot has no SQLite database header' }
495
- }
496
- return { ok: true, quickCheck: 'ok' }
497
- }
498
-
499
- /**
500
- * Produces one consistent copy of a live SQLite database inside the staging
501
- * directory. Two outcomes only: a snapshot the engine proved consistent, or a
502
- * thrown refusal that aborts the whole backup.
503
- */
504
- async function snapshotDatabase(from, to, exec) {
505
- const before = statOrNull(from)
506
- if (!before) return { mode: 'missing' }
507
- if (before.isSymbolicLink()) throw new Error('backup refuses symbolic links')
508
- if (!before.isFile()) throw new Error('backup refuses non-file: ' + path.basename(from))
509
- const name = path.basename(from)
510
- const walSize = fileSize(from + '-wal')
511
- const walContent = walSize > 0
512
- if (before.size === 0 && !walContent) {
513
- // A placeholder no engine has written a page to: copying it cannot tear.
514
- fs.copyFileSync(from, to)
515
- return { mode: 'empty-placeholder', quickCheck: 'empty' }
516
- }
517
- if (!hasSqliteHeader(from)) {
518
- throw backupRefusal('DSH_MEMU_BACKUP_NOT_SQLITE', 'backup refuses ' + name
519
- + ': it is neither an empty placeholder nor a SQLite database, so its contents cannot be verified'
520
- + (walContent ? ' (it has a non-empty WAL)' : ''))
521
- }
522
- const resolved = await enginePythonForBackup(exec)
523
- const python = resolved.python
524
- if (!python) {
525
- const why = resolved.rejected.length ? ' (' + resolved.rejected.join('; ') + ')' : ''
526
- throw backupRefusal('DSH_MEMU_BACKUP_ENGINE_REQUIRED', 'backup of ' + name
527
- + " needs the plugin engine: no verified engine/<version>/venv Python with sqlite3 was found under "
528
- + engineRoot() + why + '. Install or repair the engine, then retry. '
529
- + 'Nothing was copied: a live database copied by hand can restore as silent corruption.')
530
- }
531
- const snapshot = await pythonSnapshot(exec, python, from, to)
532
- if (!snapshot.ok) {
533
- removeQuietly(to)
534
- removeQuietly(to + '-wal')
535
- removeQuietly(to + '-shm')
536
- throw backupRefusal('DSH_MEMU_BACKUP_SNAPSHOT_FAILED', 'backup could not snapshot ' + name + ' with '
537
- + python.source + ' (engine ' + String(python.version || 'unknown') + '): ' + snapshot.error)
538
- }
539
- return {
540
- mode: 'sqlite-backup-api',
541
- engine: python.version ? String(python.version) : null,
542
- via: python.source,
543
- sqlite: python.sqlite,
544
- quickCheck: snapshot.quickCheck,
545
- }
546
- }
547
-
548
- // ------------------------------------------------------------------- inventory
549
-
550
- function copyRegular(from, to) {
551
- const info = statOrNull(from)
552
- if (!info) return false
553
- if (info.isSymbolicLink()) throw new Error('backup refuses symbolic links')
554
- if (!info.isFile()) throw new Error('backup refuses non-file: ' + path.basename(from))
555
- ensureDir(path.dirname(to))
556
- fs.copyFileSync(from, to)
557
- return true
558
- }
559
-
560
- function copyTree(from, to) {
561
- const entries = readdirSafe(from, { withFileTypes: true })
562
- if (!entries.length && !statOrNull(from)) return
563
- ensureDir(to)
564
- for (const item of entries) {
565
- if (item.isSymbolicLink()) throw new Error('backup refuses symbolic links')
566
- const source = path.join(from, item.name)
567
- const target = path.join(to, item.name)
568
- if (item.isDirectory()) copyTree(source, target)
569
- else copyRegular(source, target)
570
- }
571
- }
572
-
573
- function collectFiles(dir, prefix = '', out = {}) {
574
- for (const item of readdirSafe(dir, { withFileTypes: true })) {
575
- const full = path.join(dir, item.name)
576
- const rel = prefix ? prefix + '/' + item.name : item.name
577
- const info = statOrNull(full)
578
- if (!info) continue
579
- if (info.isSymbolicLink()) throw new Error('backup refuses symbolic links')
580
- if (info.isDirectory()) { collectFiles(full, rel, out); continue }
581
- if (!info.isFile()) continue
582
- out[rel] = { bytes: info.size, sha256: sha256File(full) }
583
- }
584
- return out
585
- }
586
-
587
- // --------------------------------------------------------------- backup creation
588
-
589
- function nextBackupName() {
590
- const base = isoStamp().replace(/[:.]/g, '-')
591
- let name = base
592
- for (let attempt = 0; fs.existsSync(path.join(backupsDir(), name)); attempt += 1) {
593
- if (attempt >= 64) throw new Error('cannot allocate a unique backup name')
594
- name = base + '-' + process.pid.toString(36) + attempt.toString(36)
595
- }
596
- return name
597
- }
598
-
599
- function vectorSummary() {
600
- const raw = readJsonQuiet(vectorActiveFile())
601
- if (!raw || typeof raw !== 'object') return { present: false }
602
- const active = raw.active && typeof raw.active === 'object' ? raw.active : null
603
- const profile = active && active.profile && typeof active.profile === 'object' ? active.profile : null
604
- const libraries = active && active.databases && active.databases.libraries && typeof active.databases.libraries === 'object'
605
- ? Object.keys(active.databases.libraries).length
606
- : 0
607
- return {
608
- present: true,
609
- generation: Number.isSafeInteger(raw.generation) ? raw.generation : null,
610
- active: active
611
- ? {
612
- generation: Number.isSafeInteger(active.generation) ? active.generation : null,
613
- fingerprint: typeof active.fingerprint === 'string' ? active.fingerprint : null,
614
- catalogId: typeof profile?.catalogId === 'string' ? profile.catalogId : null,
615
- revision: typeof profile?.revision === 'string' ? profile.revision : null,
616
- dimension: Number.isSafeInteger(profile?.dimension) ? profile.dimension : null,
617
- libraries,
618
- }
619
- : null,
620
- pending: raw.pending && typeof raw.pending === 'object' ? String(raw.pending.status || '') : null,
621
- }
622
- }
623
-
624
- function engineSummary() {
625
- const current = engineCurrent()
626
- return current ? { version: current.version, schemaVersion: current.schemaVersion } : null
627
- }
628
-
629
- /**
630
- * Copies every store a restore needs: plugin state, the global index and the
631
- * per-library index files, the per-library lexicon files, the active vector
632
- * profile journal, prompt overrides and their manifest, attachment references,
633
- * and every MemU SQLite database.
634
- * Deliberately absent: engine/, downloads/, logs/, tmp/ (large and
635
- * re-downloadable) and any key material - the manifest carries identity, never
636
- * a credential.
637
- *
638
- * `exec` only exists so tests can stand in for the engine interpreter; the
639
- * default path spawns the verified venv binary and nothing else.
640
- */
641
- async function writeStores(staging, exec) {
642
- ensureDir(path.join(staging, 'libraries'))
643
- ensureDir(path.join(staging, 'index'))
644
- ensureDir(path.join(staging, 'prompts'))
645
- copyRegular(stateFile(), path.join(staging, 'state.json'))
646
- // Consolidation ledger: per-session ranges/operations. It now participates in
647
- // backup/restore so a restored install does not re-fork work it already did.
648
- copyRegular(path.join(dataDir(), 'consolidation.json'), path.join(staging, 'consolidation.json'))
649
- for (const name of readdirSafe(indexDir())) {
650
- // Local deleted-memory stashes are a time-boxed undo buffer, not library
651
- // data: they must never leak permanently deleted bodies into a backup.
652
- if (name.endsWith('.json') && !name.endsWith('.deleted.json')) copyRegular(path.join(indexDir(), name), path.join(staging, 'index', name))
653
- }
654
- // 词典:data/lexicon/<libraryId>.json 与索引同权进备份清单。只收安全 id
655
- // 命名的 JSON(restore 侧 allowlist 用同一规则拒绝越界);目录还不存在(这个
656
- // 数据根从未写过词典)就是空集。
657
- ensureDir(path.join(staging, 'lexicon'))
658
- for (const name of readdirSafe(lexiconRoot())) {
659
- if (!name.endsWith('.json')) continue
660
- if (!isSafeId(name.slice(0, -'.json'.length))) continue
661
- copyRegular(path.join(lexiconRoot(), name), path.join(staging, 'lexicon', name))
662
- }
663
- copyRegular(path.join(dataDir(), 'prompts', 'manifest.json'), path.join(staging, 'prompts', 'manifest.json'))
664
- copyTree(path.join(dataDir(), 'prompts'), path.join(staging, 'prompts'))
665
- copyTree(path.join(dataDir(), 'attachments'), path.join(staging, 'attachments'))
666
- const databases = []
667
- const globalInfo = statOrNull(globalDbFile())
668
- if (globalInfo && globalInfo.isFile()) databases.push({ src: globalDbFile(), rel: 'global.sqlite3' })
669
- for (const item of readdirSafe(librariesDir(), { withFileTypes: true })) {
670
- if (!item.isFile() || !item.name.endsWith('.sqlite3')) continue
671
- databases.push({ src: path.join(librariesDir(), item.name), rel: 'libraries/' + item.name })
672
- }
673
- const snapshots = []
674
- for (const database of databases) {
675
- const target = path.join(staging, database.rel.split('/').join(path.sep))
676
- ensureDir(path.dirname(target))
677
- const result = await snapshotDatabase(database.src, target, exec)
678
- snapshots.push({
679
- file: database.rel,
680
- mode: result.mode,
681
- engine: result.engine || null,
682
- quickCheck: result.quickCheck || null,
683
- })
684
- }
685
- return snapshots
686
- }
687
-
688
- function publishStaging(staging, name) {
689
- const dir = path.join(backupsDir(), name)
690
- if (fs.existsSync(dir)) throw new Error('backup directory already exists: ' + name)
691
- try {
692
- fs.renameSync(staging, dir)
693
- } catch (error) {
694
- throw new Error('could not publish backup ' + name + ': ' + (error?.code || 'io error'))
695
- }
696
- return dir
697
- }
698
-
699
- function discardStaging(staging) {
700
- try { fs.rmSync(staging, { recursive: true, force: true, maxRetries: 3 }) } catch (error) {
701
- warn('backups: could not discard staging directory (' + (error?.code || 'io error') + ')')
702
- }
703
- }
704
-
705
- /** Staging leftovers of crashed runs are reclaimed; a live sibling is kept. */
706
- function cleanupStaging() {
707
- const root = stagingRoot()
708
- const now = Date.now()
709
- for (const item of readdirSafe(root, { withFileTypes: true })) {
710
- if (!item.isDirectory()) continue
711
- const full = path.join(root, item.name)
712
- const parts = item.name.split('.')
713
- const pid = Number(parts.length > 1 ? parts[parts.length - 2] : NaN)
714
- const info = statOrNull(full)
715
- const age = info ? now - info.mtimeMs : 0
716
- const mine = Number.isSafeInteger(pid) && pid === process.pid
717
- const stale = mine ? age > STAGING_TTL_MS : (!Number.isSafeInteger(pid) || !pidAlive(pid) || age > STAGING_TTL_MS)
718
- if (!stale) continue
719
- try { fs.rmSync(full, { recursive: true, force: true, maxRetries: 3 }) } catch {}
720
- }
721
- }
722
-
723
- /**
724
- * Creates one managed backup of the current data root, then keeps the newest
725
- * BACKUP_KEEP complete ones. Returns a report whose dir is the published
726
- * directory, so every existing caller that treats the return value as a path
727
- * keeps working.
728
- *
729
- * `pythonExec` is a test seam for the engine interpreter (see writeStores).
730
- * A database that cannot be snapshotted by the verified engine throws, and the
731
- * throw happens before anything is published, so no partial or torn backup can
732
- * ever appear in backups/.
733
- */
734
- export async function createBackup({ label = 'auto', keep = BACKUP_KEEP, flushState = null, pythonExec = null } = {}) {
735
- return withBackupLock(async () => {
736
- ensureDir(backupsDir())
737
- cleanupStaging()
738
- const name = nextBackupName()
739
- const staging = path.join(stagingRoot(), name + '.' + process.pid + '.' + crypto.randomBytes(4).toString('hex'))
740
- ensureDir(staging)
741
- try {
742
- // Plugin state is flushed first: a backup must never capture the pending
743
- // bookkeeping edits that are still only in memory.
744
- if (typeof flushState === 'function') flushState()
745
- const snapshots = await writeStores(staging, pythonExec)
746
- const files = collectFiles(staging)
747
- const totals = { files: 0, bytes: 0 }
748
- for (const rel of Object.keys(files)) {
749
- totals.files += 1
750
- totals.bytes += Number(files[rel].bytes || 0)
751
- }
752
- const createdAt = isoStamp()
753
- const manifest = {
754
- version: BACKUP_SCHEMA,
755
- kind: 'dsh-memu-memory/backup',
756
- name,
757
- uniqueId: name + '-' + crypto.randomBytes(4).toString('hex'),
758
- createdAt,
759
- createdAtMs: Date.parse(createdAt) || Date.now(),
760
- label: String(label || 'auto'),
761
- complete: true,
762
- engine: engineSummary(),
763
- vector: vectorSummary(),
764
- snapshot: { databases: snapshots },
765
- totals,
766
- files,
767
- }
768
- // Written last and atomically: a finished manifest is the completion
769
- // marker that prune requires before it may delete anything.
770
- writeJson(path.join(staging, 'manifest.json'), manifest)
771
- const dir = publishStaging(staging, name)
772
- const prune = pruneBackups({ keep })
773
- return {
774
- name,
775
- dir,
776
- createdAt,
777
- files: totals.files,
778
- bytes: totals.bytes,
779
- snapshots: snapshots.map(item => ({ file: item.file, mode: item.mode, engine: item.engine || null })),
780
- pruned: prune.deleted,
781
- pruneFailed: prune.failed,
782
- pendingCleanup: prune.pendingCleanup,
783
- notice: prune.notice,
784
- }
785
- } catch (error) {
786
- discardStaging(staging)
787
- throw error
788
- }
789
- })
790
- }
791
-
792
- // -------------------------------------------------------------- listing / scan
793
-
794
- function isManagedName(name) {
795
- return typeof name === 'string' && isSafeId(name) && MANAGED_NAME.test(name)
796
- }
797
-
798
- /** A relative path inside a backup that we are willing to copy back. */
799
- function isSafeRelative(rel) {
800
- if (typeof rel !== 'string' || !rel) return false
801
- if (path.isAbsolute(rel)) return false
802
- if (rel.indexOf(BACKSLASH) !== -1) return false
803
- for (const part of rel.split('/')) {
804
- if (!part || part === '.' || part === '..') return false
805
- }
806
- return true
807
- }
808
-
809
- function inventoryIssues(dir, files) {
810
- const issues = []
811
- const rels = Object.keys(files)
812
- if (!rels.length) return ['manifest lists no files']
813
- for (const rel of rels) {
814
- if (!isSafeRelative(rel)) { issues.push('unsafe path in manifest: ' + rel.slice(0, 120)); continue }
815
- if (issues.length >= 5) { issues.push('and more'); break }
816
- const full = path.join(dir, rel.split('/').join(path.sep))
817
- const info = statOrNull(full)
818
- if (!info) { issues.push('missing: ' + rel); continue }
819
- if (!info.isFile()) { issues.push('not a file: ' + rel); continue }
820
- const expected = Number(files[rel]?.bytes)
821
- if (Number.isFinite(expected) && expected !== info.size) issues.push('size mismatch: ' + rel)
822
- }
823
- return issues
824
- }
825
-
826
- function buildEntry(name, dir, manifest, status, issues) {
827
- const files = manifest?.files && typeof manifest.files === 'object' ? manifest.files : null
828
- let bytes = null
829
- if (files) {
830
- bytes = 0
831
- for (const rel of Object.keys(files)) bytes += Number(files[rel]?.bytes || 0)
832
- }
833
- const createdAt = typeof manifest?.createdAt === 'string' ? manifest.createdAt : null
834
- const info = statOrNull(dir)
835
- const parsed = Date.parse(createdAt || '')
836
- return {
837
- name,
838
- dir,
839
- createdAt: createdAt || (info ? new Date(info.mtimeMs).toISOString() : null),
840
- createdAtMs: Number.isFinite(Number(manifest?.createdAtMs)) ? Number(manifest.createdAtMs) : (Number.isFinite(parsed) ? parsed : (info ? info.mtimeMs : 0)),
841
- engine: manifest?.engine || null,
842
- files: files ? Object.keys(files).length : null,
843
- bytes,
844
- hasManifest: Boolean(manifest),
845
- complete: status === 'complete',
846
- status,
847
- issues: issues.slice(0, 6),
848
- uniqueId: typeof manifest?.uniqueId === 'string' ? manifest.uniqueId : null,
849
- label: typeof manifest?.label === 'string' ? manifest.label : null,
850
- vector: manifest?.vector || null,
851
- }
852
- }
853
-
854
- /**
855
- * Reads one directory in backups/ and classifies it. status is 'complete'
856
- * (only these are counted or deleted), 'incomplete', 'corrupt' or 'unknown'.
857
- * verify re-hashes every file: cheap listing stays cheap, but retention must
858
- * never count a backup it has not actually checked.
859
- */
860
- function scanEntry(name, { verify = false } = {}) {
861
- const dir = path.join(backupsDir(), name)
862
- const info = statOrNull(dir)
863
- if (!info) return null
864
- if (info.isSymbolicLink()) return buildEntry(name, dir, null, 'unknown', ['backups entry is a symbolic link or junction'])
865
- if (!info.isDirectory()) return buildEntry(name, dir, null, 'unknown', ['backups entry is not a directory'])
866
- const manifest = readJsonQuiet(path.join(dir, 'manifest.json'))
867
- const issues = []
868
- let status = 'complete'
869
- if (!manifest || typeof manifest !== 'object' || Array.isArray(manifest)) {
870
- status = 'unknown'
871
- issues.push('manifest.json is missing or unreadable')
872
- } else if (!isManagedName(name)) {
873
- status = 'unknown'
874
- issues.push('not a managed backup name')
875
- } else if (!manifest.files || typeof manifest.files !== 'object' || Array.isArray(manifest.files)) {
876
- status = 'incomplete'
877
- issues.push('manifest has no file inventory')
878
- } else if (manifest.complete !== true) {
879
- status = 'incomplete'
880
- issues.push('backup was never completed')
881
- }
882
- if (status === 'complete') {
883
- for (const issue of inventoryIssues(dir, manifest.files)) issues.push(issue)
884
- if (issues.length) status = 'incomplete'
885
- }
886
- if (status === 'complete' && verify) {
887
- for (const rel of Object.keys(manifest.files)) {
888
- const expected = manifest.files[rel] || {}
889
- if (typeof expected.sha256 !== 'string' || !expected.sha256) continue
890
- const full = path.join(dir, rel.split('/').join(path.sep))
891
- let actual = null
892
- try { actual = sha256File(full) } catch { actual = null }
893
- if (actual === expected.sha256) continue
894
- status = 'corrupt'
895
- issues.push('checksum mismatch: ' + rel)
896
- break
897
- }
898
- }
899
- if (status !== 'unknown') {
900
- const real = realpathOrNull(dir)
901
- if (!real || !samePath(real, dir)) { status = 'unknown'; issues.push('directory resolves somewhere else (link or junction)') }
902
- else if (!samePath(path.dirname(path.resolve(dir)), path.resolve(backupsDir()))) { status = 'unknown'; issues.push('directory is not a direct child of backups/') }
903
- }
904
- return buildEntry(name, dir, manifest, status, issues)
905
- }
906
-
907
- function compareEntries(a, b) {
908
- // createdAt first because mtimes lie, then the name: names are unique inside
909
- // backups/ and a colliding millisecond appends a monotonic suffix, so the
910
- // order stays deterministic without trusting the filesystem's clock.
911
- if (b.createdAtMs !== a.createdAtMs) return b.createdAtMs - a.createdAtMs
912
- return String(b.name).localeCompare(String(a.name))
913
- }
914
-
915
- /** Every entry in backups/, newest first, including incomplete and unknown. */
916
- export function scanBackups({ verify = false } = {}) {
917
- const out = []
918
- for (const item of readdirSafe(backupsDir(), { withFileTypes: true })) {
919
- if (item.name.startsWith('.')) continue
920
- const scanned = scanEntry(item.name, { verify })
921
- if (scanned) out.push(scanned)
922
- }
923
- return out.sort(compareEntries)
924
- }
925
-
926
- /** Public listing used by the UI: newest first, with completeness reported. */
927
- export function listBackupEntries() { return scanBackups() }
928
-
929
- export function findBackup(name) {
930
- if (!isSafeId(name) || name.startsWith('.')) throw new Error('invalid backup name')
931
- const dir = path.join(backupsDir(), name)
932
- if (!statOrNull(dir)) throw new Error('backup not found: ' + name)
933
- const found = scanEntry(name)
934
- if (!found) throw new Error('backup not found: ' + name)
935
- return found
936
- }
937
-
938
- // ----------------------------------------------------------------------- prune
939
-
940
- function assertNoLinks(dir, prefix) {
941
- for (const item of readdirSafe(dir, { withFileTypes: true })) {
942
- const rel = prefix ? prefix + '/' + item.name : item.name
943
- if (item.isSymbolicLink()) throw new Error('refusing to delete: ' + rel + ' is a link')
944
- if (item.isDirectory()) assertNoLinks(path.join(dir, item.name), rel)
945
- }
946
- }
947
-
948
- /**
949
- * Every guard a recursive delete needs, re-checked on the resolved path:
950
- * managed single-segment name, direct child of backups/, realpath unchanged,
951
- * and no link or junction anywhere inside.
952
- */
953
- function assertRemovable(found) {
954
- if (!found || typeof found.name !== 'string' || !isManagedName(found.name)) throw new Error('refusing to delete a backup with an unmanaged name')
955
- const dir = path.join(backupsDir(), found.name)
956
- const info = statOrNull(dir)
957
- if (!info) throw new Error('backup not found: ' + found.name)
958
- if (info.isSymbolicLink()) throw new Error('refusing to delete a link: ' + found.name)
959
- if (!info.isDirectory()) throw new Error('refusing to delete a non-directory: ' + found.name)
960
- if (!samePath(path.dirname(path.resolve(dir)), path.resolve(backupsDir()))) throw new Error('refusing to delete outside backups/: ' + found.name)
961
- const real = realpathOrNull(dir)
962
- if (!real || !samePath(real, dir)) throw new Error('refusing to delete a redirected path: ' + found.name)
963
- assertNoLinks(dir, '')
964
- }
965
-
966
- function removeBackupDir(found) {
967
- assertRemovable(found)
968
- fs.rmSync(path.join(backupsDir(), found.name), { recursive: true, force: true, maxRetries: 3 })
969
- }
970
-
971
- /**
972
- * Keeps the newest keep complete managed backups and deletes the rest.
973
- * Incomplete and unknown entries are reported, never counted, never deleted.
974
- * A leased directory (a restore or migration is reading it) is skipped, as is
975
- * the safety backup named in protect - retention may briefly exceed the limit,
976
- * and the next prune reclaims it.
977
- */
978
- export function pruneBackups({ keep = BACKUP_KEEP, protect = [] } = {}) {
979
- return withBackupLock(() => {
980
- ensureDir(backupsDir())
981
- cleanupStaging()
982
- const protectSet = new Set()
983
- for (const name of protect) if (name) protectSet.add(path.basename(String(name)))
984
- for (const name of Object.keys(activeLeases())) protectSet.add(name)
985
- // Retention decides what to delete, so it pays for the full hash pass: a
986
- // backup whose bytes no longer match its manifest must not occupy one of the
987
- // three slots, and must never be the reason an intact one is deleted.
988
- const all = scanBackups({ verify: true })
989
- const complete = all.filter(found => found.status === 'complete')
990
- const victims = complete.slice(keep).filter(found => !protectSet.has(found.name))
991
- const deleted = []
992
- const failed = []
993
- for (const victim of victims) {
994
- try {
995
- removeBackupDir(victim)
996
- deleted.push(victim.name)
997
- } catch (error) {
998
- failed.push({ name: victim.name, error: String(error?.message || error) })
999
- warn('backups: could not remove ' + victim.name + ' (' + String(error?.message || error) + ')')
1000
- }
1001
- }
1002
- const kept = deleted.length
1003
- ? scanBackups().filter(found => found.status === 'complete')
1004
- : complete.filter(found => !deleted.includes(found.name))
1005
- const notice = 'at most ' + keep + ' complete backups are kept; older ones are cleaned up automatically'
1006
- if (deleted.length) {
1007
- warn('backups: ' + notice + ' (deleted ' + deleted.join(', ') + ')')
1008
- try {
1009
- const marker = path.join(backupsDir(), '.retention-notice.json')
1010
- if (!readJsonQuiet(marker)) writeJson(marker, { at: isoStamp(), policy: 'keep ' + keep, notice })
1011
- } catch {}
1012
- }
1013
- return {
1014
- keep,
1015
- notice,
1016
- deleted,
1017
- failed,
1018
- protected: Array.from(protectSet),
1019
- pendingCleanup: Math.max(0, kept.length - keep),
1020
- kept: kept.map(found => found.name),
1021
- skipped: all.filter(found => found.status !== 'complete').map(found => ({ name: found.name, status: found.status, issues: found.issues })),
1022
- }
1023
- })
1024
- }
1025
-
1026
- /** Explicit removal requested by the user. */
1027
- export function deleteBackupEntry(name) {
1028
- return withBackupLock(() => {
1029
- const found = findBackup(name)
1030
- if (activeLeases()[found.name]) throw new Error('backup is in use by a running restore: ' + found.name)
1031
- removeBackupDir(found)
1032
- return { deleted: found.name, status: found.status }
1033
- })
1034
- }
1035
-
1036
- // --------------------------------------------------------------------- restore
1037
-
1038
- /** Where one relative path inside a backup lands in the live data root. */
1039
- function liveTargetFor(rel) {
1040
- const parts = rel.split('/')
1041
- const head = parts[0]
1042
- if (parts.length === 1) {
1043
- if (head === 'state.json') return stateFile()
1044
- if (head === 'consolidation.json') return path.join(dataDir(), 'consolidation.json')
1045
- if (head === 'global.sqlite3') return globalDbFile()
1046
- if (head === 'global.sqlite3-wal') return globalDbFile() + '-wal'
1047
- if (head === 'global.sqlite3-shm') return globalDbFile() + '-shm'
1048
- }
1049
- if ((head === 'index' || head === 'libraries') && parts.length === 2) {
1050
- if (parts[1].endsWith('.deleted.json')) throw new Error('backup contains a deleted-memory stash that must not be restored: ' + rel)
1051
- return path.join(head === 'index' ? indexDir() : librariesDir(), parts[1])
1052
- }
1053
- if (head === 'lexicon' && parts.length === 2) {
1054
- // 词典只接受 <libraryId>.json:isSafeId 挡掉 ..、路径分隔符和任意文件名,
1055
- // 与 writeStores 收录时的同一规则对称。
1056
- const id = parts[1].endsWith('.json') ? parts[1].slice(0, -'.json'.length) : ''
1057
- if (!id || !isSafeId(id)) throw new Error('backup contains an entry this version cannot restore: ' + rel)
1058
- return path.join(lexiconRoot(), parts[1])
1059
- }
1060
- if ((head === 'prompts' || head === 'attachments') && parts.length >= 2) {
1061
- return path.join(dataDir(), parts.join(path.sep))
1062
- }
1063
- throw new Error('backup contains an entry this version cannot restore: ' + rel)
1064
- }
1065
-
1066
- function writeAtomicCopy(from, to) {
1067
- ensureDir(path.dirname(to))
1068
- const tmp = to + '.restore-' + process.pid + '-' + crypto.randomBytes(4).toString('hex')
1069
- try {
1070
- fs.copyFileSync(from, tmp)
1071
- const fd = fs.openSync(tmp, 'r+')
1072
- try { fs.fsyncSync(fd) } finally { fs.closeSync(fd) }
1073
- for (let attempt = 0; ; attempt += 1) {
1074
- try { fs.renameSync(tmp, to); return } catch (error) {
1075
- if (!['EPERM', 'EBUSY', 'EACCES'].includes(error?.code) || attempt >= 5) throw error
1076
- pause(RETRY_MS * (attempt + 1))
1077
- }
1078
- }
1079
- } catch (error) {
1080
- try { fs.rmSync(tmp, { force: true }) } catch {}
1081
- throw error
1082
- }
1083
- }
1084
-
1085
- /** A restored database must not inherit the WAL of the one it replaces. */
1086
- function dropCompanions(target) {
1087
- for (const suffix of ['-wal', '-shm']) {
1088
- try { fs.rmSync(target + suffix, { force: true }) } catch (error) {
1089
- if (error?.code !== 'ENOENT') throw error
1090
- }
1091
- }
1092
- }
1093
-
1094
- function isSidecar(rel) {
1095
- return rel.endsWith('-wal') || rel.endsWith('-shm')
1096
- }
1097
-
1098
- /** A database file always lands before its sidecars. */
1099
- function restoreOrder(rels) {
1100
- return rels.slice().sort((left, right) => {
1101
- const delta = (isSidecar(left) ? 1 : 0) - (isSidecar(right) ? 1 : 0)
1102
- if (delta !== 0) return delta
1103
- return left.localeCompare(right)
1104
- })
1105
- }
1106
-
1107
- /**
1108
- * Validates the WHOLE inventory before anything is written, so a restore either
1109
- * has every byte it needs or leaves the live root untouched.
1110
- */
1111
- function verifyInventory(found) {
1112
- const manifest = readJsonQuiet(path.join(found.dir, 'manifest.json'))
1113
- if (!manifest || typeof manifest !== 'object' || !manifest.files || typeof manifest.files !== 'object') {
1114
- throw new Error('backup is incomplete: ' + found.name + ' has no file inventory')
1115
- }
1116
- const rels = []
1117
- for (const rel of Object.keys(manifest.files)) {
1118
- if (!isSafeRelative(rel)) throw new Error('invalid backup manifest path')
1119
- // Backups made before stashes were excluded still list them. Skip rather
1120
- // than fail, so restoring an older backup neither breaks nor resurrects
1121
- // permanently deleted text.
1122
- if (/^index\/[^/]+\.deleted\.json$/.test(rel)) continue
1123
- const full = path.join(found.dir, rel.split('/').join(path.sep))
1124
- const info = statOrNull(full)
1125
- if (!info || info.isSymbolicLink() || !info.isFile()) throw new Error('backup is incomplete: ' + rel + ' is missing')
1126
- const expected = manifest.files[rel] || {}
1127
- if (Number.isFinite(Number(expected.bytes)) && Number(expected.bytes) !== info.size) {
1128
- throw new Error('backup is corrupt: ' + rel + ' has the wrong size')
1129
- }
1130
- if (expected.sha256 && sha256File(full) !== expected.sha256) {
1131
- throw new Error('backup is corrupt: ' + rel + ' failed its checksum')
1132
- }
1133
- liveTargetFor(rel)
1134
- rels.push(rel)
1135
- }
1136
- if (!rels.length) throw new Error('backup is incomplete: ' + found.name + ' lists no files')
1137
- return { manifest, rels }
1138
- }
1139
-
1140
- function normalizeDbRel(value) {
1141
- if (typeof value !== 'string' || !value) return null
1142
- const rel = value.split(BACKSLASH).join('/').replace(/^\.\//, '')
1143
- if (rel.startsWith('libraries/')) return rel
1144
- if (rel.indexOf('/') === -1) return 'libraries/' + rel
1145
- return rel
1146
- }
1147
-
1148
- /**
1149
- * A backup made before the vector journal existed carries no vector-active
1150
- * manifest. Restoring it over a live root that still points at the newer
1151
- * generation would leave recall reading tables the restored text index never
1152
- * saw, so that pointer must be retired, and the same holds for a journal that
1153
- * points at databases the backup does not contain.
1154
- */
1155
- function planVectorActive(found, rels) {
1156
- const rel = 'index/vector-active.json'
1157
- if (!rels.includes(rel)) return { action: 'absent', restore: false }
1158
- const raw = readJsonQuiet(path.join(found.dir, 'index', 'vector-active.json'))
1159
- if (!raw || typeof raw !== 'object') return { action: 'unreadable', restore: false }
1160
- const active = raw.active && typeof raw.active === 'object' ? raw.active : null
1161
- if (!active) return { action: 'restore', restore: true }
1162
- const needed = []
1163
- const global = active.databases && active.databases.global
1164
- if (global && typeof global.path === 'string') needed.push(global.path)
1165
- const libraries = active.databases && active.databases.libraries
1166
- if (libraries && typeof libraries === 'object') {
1167
- for (const key of Object.keys(libraries)) {
1168
- const item = libraries[key]
1169
- if (item && typeof item.path === 'string') needed.push(item.path)
1170
- }
1171
- }
1172
- const missing = []
1173
- for (const value of needed) {
1174
- const normalized = normalizeDbRel(value)
1175
- if (!normalized || !rels.includes(normalized)) missing.push(String(value))
1176
- }
1177
- if (missing.length) return { action: 'missing-databases', restore: false, missing: missing.slice(0, 5) }
1178
- return { action: 'restore', restore: true }
1179
- }
1180
-
1181
- /** Moves the live vector-active pointer aside so recall falls back to text. */
1182
- function retireVectorActive(reason) {
1183
- const live = vectorActiveFile()
1184
- const info = statOrNull(live)
1185
- if (!info) return 'absent'
1186
- if (info.isSymbolicLink()) {
1187
- warn('backups: the live vector-active.json is a link; leaving it alone')
1188
- return 'unreadable'
1189
- }
1190
- const aside = live + '.stale-' + isoStamp().replace(/[:.]/g, '-')
1191
- try { fs.renameSync(live, aside) } catch (error) {
1192
- throw new Error('the restored data has no usable vector-active manifest and the stale pointer could not be retired: ' + String(error?.message || error))
1193
- }
1194
- warn('backups: ' + reason + '; the stale vector-active pointer was moved to ' + path.basename(aside) + ' so recall falls back to lexical text')
1195
- return 'cleared'
1196
- }
1197
-
1198
- /**
1199
- * Puts a backup back. The target is leased and fully verified first, the live
1200
- * root is saved as a safety backup second, and only then is anything written.
1201
- * A failure after that point is recoverable: the safety backup holds the state
1202
- * that was replaced, and it is protected from this operation's prune.
1203
- */
1204
- export async function restoreFromBackup(name, { beforeRestore = null, flushState = null, clearCaches = null, keep = BACKUP_KEEP } = {}) {
1205
- return withBackupLock(async () => {
1206
- const found = findBackup(name)
1207
- const plan = verifyInventory(found)
1208
- const vector = planVectorActive(found, plan.rels)
1209
- writeLease(found.name, { pid: process.pid, at: Date.now(), kind: 'restore' })
1210
- let safety = null
1211
- try {
1212
- const created = await (typeof beforeRestore === 'function'
1213
- ? beforeRestore()
1214
- : createBackup({ label: 'before-restore', flushState }))
1215
- safety = typeof created === 'string' ? created : (created && created.dir ? created.dir : null)
1216
- const rels = restoreOrder(plan.rels.filter(rel => rel !== 'index/vector-active.json' || vector.restore))
1217
- for (const rel of rels) {
1218
- const target = liveTargetFor(rel)
1219
- if (rel.endsWith('.sqlite3')) dropCompanions(target)
1220
- writeAtomicCopy(path.join(found.dir, rel.split('/').join(path.sep)), target)
1221
- }
1222
- const vectorActive = vector.restore
1223
- ? 'restored'
1224
- : retireVectorActive(vector.action === 'absent'
1225
- ? 'this backup predates the vector generation journal'
1226
- : 'the vector journal in this backup does not match the databases it contains')
1227
- if (typeof clearCaches === 'function') clearCaches()
1228
- const prune = pruneBackups({ keep, protect: safety ? [path.basename(safety)] : [] })
1229
- return {
1230
- restored: found.name,
1231
- safety,
1232
- files: rels.length,
1233
- vectorActive,
1234
- pruned: prune.deleted,
1235
- pendingCleanup: prune.pendingCleanup,
1236
- }
1237
- } catch (error) {
1238
- const reason = String(error?.message || error)
1239
- warn('backups: restore of ' + found.name + ' failed: ' + reason)
1240
- const wrapped = new Error(safety
1241
- ? 'restore failed (' + reason + '); the live state it replaced is saved as ' + path.basename(safety)
1242
- : 'restore failed (' + reason + ') and no safety backup could be made')
1243
- wrapped.code = 'DSH_MEMU_BACKUP_RESTORE_FAILED'
1244
- wrapped.cause = error
1245
- wrapped.safety = safety ? path.basename(safety) : null
1246
- // Whatever landed on disk is the truth now: cached readers must not keep
1247
- // serving the half-replaced state.
1248
- try { if (typeof clearCaches === 'function') clearCaches() } catch {}
1249
- throw wrapped
1250
- } finally {
1251
- try { writeLease(found.name, null) } catch {}
1252
- }
1253
- })
1254
- }
1
+ import crypto from 'node:crypto'
2
+ import fs from 'node:fs'
3
+ import path from 'node:path'
4
+ import { spawn } from 'node:child_process'
5
+ import {
6
+ backupsDir, dataDir, ensureDir, indexDir, isSafeId, librariesDir,
7
+ readJson, warn, withFileLock, writeJson,
8
+ } from './paths.js'
9
+
10
+ /**
11
+ * Local-vector backup policy - safe latest-three backup retention.
12
+ *
13
+ * One rule, one place. Every managed backup of the current data root is created
14
+ * by createBackup(), published atomically, and only then may the oldest
15
+ * complete backups beyond BACKUP_KEEP be deleted. Create, delete, restore and
16
+ * prune share a single lock, so the safety backup a restore just made can never
17
+ * collect the very directory that restore is reading from.
18
+ *
19
+ * Invariants:
20
+ * 1. A failed or interrupted creation deletes nothing. The backup is built in
21
+ * backups/.staging/<name>.<pid>.<rand>, hashed file by file, given its
22
+ * manifest last (the completion marker) and only then renamed into place.
23
+ * 2. Only directories that prove themselves complete are ever deleted.
24
+ * Corrupt, half-written, foreign, linked or unknown entries are reported
25
+ * and left exactly where they are.
26
+ * 3. Ordering is the verified manifest createdAt plus a unique id - never an
27
+ * mtime that a copy or a clock change can reorder.
28
+ * 4. A lease pins the directory a restore (or migration) is about to read, so
29
+ * prune cannot remove it mid-flight; going briefly over the limit is
30
+ * allowed and is reclaimed as soon as the operation finishes.
31
+ * 5. A recursive delete re-checks realpath containment and refuses links
32
+ * before it removes a single byte.
33
+ * 6. SQLite is snapshotted only by SQLite's own backup API, run by the
34
+ * plugin's isolated engine/<version>/venv interpreter. A live db+wal+shm is
35
+ * never copied by hand, and a global Python is never borrowed: if the
36
+ * managed engine cannot prove a consistent snapshot, the backup fails
37
+ * instead of publishing a copy that would restore as silent corruption.
38
+ * Only a zero-byte placeholder (no page, no WAL frame) may be copied.
39
+ */
40
+
41
+ export const BACKUP_KEEP = 3
42
+ export const BACKUP_SCHEMA = 2
43
+
44
+ // Timestamp name of a published backup, optionally suffixed for uniqueness
45
+ // within the same millisecond. Anything else in backups/ is not a managed
46
+ // backup and is never counted or deleted by retention.
47
+ const MANAGED_NAME = /^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}-[0-9]{2}-[0-9]{2}-[0-9]{3}Z(-[A-Za-z0-9]+)*$/
48
+ const SQLITE_MAGIC = 'SQLite format 3' + String.fromCharCode(0)
49
+ const BACKSLASH = String.fromCharCode(92)
50
+ const NEWLINE = String.fromCharCode(10)
51
+ const STAGING_TTL_MS = 30 * 60 * 1000
52
+ const LEASE_TTL_MS = 15 * 60 * 1000
53
+ const RETRY_MS = 8
54
+ const PYTHON_TIMEOUT_MS = 120000
55
+ const PROBE_TIMEOUT_MS = 20000
56
+
57
+ const stagingRoot = () => path.join(backupsDir(), '.staging')
58
+ const leaseFile = () => path.join(backupsDir(), '.leases.json')
59
+ const lockAnchor = () => path.join(backupsDir(), '.backup')
60
+ const stateFile = () => path.join(dataDir(), 'state.json')
61
+ const globalDbFile = () => path.join(dataDir(), 'global.sqlite3')
62
+ const lexiconRoot = () => path.join(dataDir(), 'lexicon')
63
+ const vectorActiveFile = () => path.join(indexDir(), 'vector-active.json')
64
+ const engineCurrentFile = () => path.join(dataDir(), 'engine', 'current.json')
65
+
66
+ function isoStamp() { return new Date().toISOString() }
67
+ function pause(ms) { Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms) }
68
+
69
+ function statOrNull(file) {
70
+ try { return fs.lstatSync(file) } catch { return null }
71
+ }
72
+
73
+ function readdirSafe(dir, options) {
74
+ try { return fs.readdirSync(dir, options) } catch { return [] }
75
+ }
76
+
77
+ function realpathOrNull(file) {
78
+ try { return fs.realpathSync.native(file) } catch { return null }
79
+ }
80
+
81
+ function samePath(a, b) {
82
+ const left = path.resolve(String(a))
83
+ const right = path.resolve(String(b))
84
+ return process.platform === 'win32' ? left.toLowerCase() === right.toLowerCase() : left === right
85
+ }
86
+
87
+ function readJsonQuiet(file) {
88
+ try { return JSON.parse(fs.readFileSync(file, 'utf8')) } catch { return null }
89
+ }
90
+
91
+ function sha256File(file) {
92
+ return crypto.createHash('sha256').update(fs.readFileSync(file)).digest('hex')
93
+ }
94
+
95
+ function fileSize(file) {
96
+ const info = statOrNull(file)
97
+ return info ? info.size : -1
98
+ }
99
+
100
+ function hasSqliteHeader(file) {
101
+ let fd
102
+ try {
103
+ fd = fs.openSync(file, 'r')
104
+ const buffer = Buffer.alloc(SQLITE_MAGIC.length)
105
+ const read = fs.readSync(fd, buffer, 0, buffer.length, 0)
106
+ return read === buffer.length && buffer.toString('latin1') === SQLITE_MAGIC
107
+ } catch {
108
+ return false
109
+ } finally {
110
+ if (fd !== undefined) { try { fs.closeSync(fd) } catch {} }
111
+ }
112
+ }
113
+
114
+ // ---------------------------------------------------------------- lock & leases
115
+
116
+ // 同进程可重入的锁集合。paths.js 的 withFileLock 是纯同步的(try { return action() }
117
+ // finally 立刻删锁文件):直接把 async action 传进去,锁会在第一个 await 之前
118
+ // 就释放,restore 的 safety backup 与 prune 便失去互斥。这里自己管理同一把
119
+ // .backup.lock,持锁直到 action 的 Promise 完成;同步 action 仍返回同步结果。
120
+ const heldBackupLocks = new Set()
121
+
122
+ function acquireBackupLock() {
123
+ const lock = path.resolve(lockAnchor()) + '.lock'
124
+ if (heldBackupLocks.has(lock)) return () => {}
125
+ ensureDir(backupsDir())
126
+ const until = Date.now() + 500
127
+ let fd
128
+ while (fd === undefined) {
129
+ try {
130
+ fd = fs.openSync(lock, 'wx', 0o600)
131
+ fs.writeFileSync(fd, String(process.pid))
132
+ } catch (error) {
133
+ if (error?.code !== 'EEXIST') throw error
134
+ try {
135
+ const owner = Number(fs.readFileSync(lock, 'utf8'))
136
+ if (Number.isSafeInteger(owner) && owner > 0 && !pidAlive(owner)) { fs.unlinkSync(lock); continue }
137
+ } catch {}
138
+ if (Date.now() >= until) {
139
+ const busy = new Error('memory store is busy: backup; retry the operation')
140
+ busy.code = 'DSH_MEMU_STORE_BUSY'
141
+ throw busy
142
+ }
143
+ pause(10)
144
+ }
145
+ }
146
+ heldBackupLocks.add(lock)
147
+ return () => {
148
+ heldBackupLocks.delete(lock)
149
+ try { fs.closeSync(fd) } catch {}
150
+ for (let attempt = 0; ; attempt += 1) {
151
+ try { fs.unlinkSync(lock); break } catch (error) {
152
+ if (error?.code === 'ENOENT') break
153
+ if (['EPERM', 'EBUSY', 'EACCES'].includes(error?.code) && attempt < 5) { pause(RETRY_MS * (attempt + 1)); continue }
154
+ warn('backups: could not release backup lock (' + (error?.code || 'io error') + ')')
155
+ break
156
+ }
157
+ }
158
+ }
159
+ }
160
+
161
+ /**
162
+ * The one lock that coordinates create/delete/restore/prune. It is reentrant
163
+ * inside this process, so a restore may create its own safety backup and prune
164
+ * while still holding it. A synchronous action returns its value synchronously;
165
+ * an async action returns a Promise and the lock stays held until it settles.
166
+ */
167
+ export function withBackupLock(action) {
168
+ const release = acquireBackupLock()
169
+ let result
170
+ try {
171
+ result = action()
172
+ } catch (error) {
173
+ release()
174
+ throw error
175
+ }
176
+ if (result && typeof result.then === 'function') return Promise.resolve(result).finally(release)
177
+ release()
178
+ return result
179
+ }
180
+
181
+ function pidAlive(pid) {
182
+ if (!Number.isSafeInteger(pid) || pid <= 0) return false
183
+ if (pid === process.pid) return true
184
+ try { process.kill(pid, 0); return true } catch (error) { return error?.code === 'EPERM' }
185
+ }
186
+
187
+ function readLeases() {
188
+ const raw = readJson(leaseFile(), {})
189
+ return raw && typeof raw === 'object' && !Array.isArray(raw) ? raw : {}
190
+ }
191
+
192
+ /** Leases of operations that are still running right now. */
193
+ export function activeLeases() {
194
+ const now = Date.now()
195
+ const live = {}
196
+ for (const [name, lease] of Object.entries(readLeases())) {
197
+ if (!lease || typeof lease !== 'object') continue
198
+ if (now - Number(lease.at || 0) > LEASE_TTL_MS) continue
199
+ if (!pidAlive(Number(lease.pid))) continue
200
+ live[name] = lease
201
+ }
202
+ return live
203
+ }
204
+
205
+ function writeLease(name, lease) {
206
+ const leases = readLeases()
207
+ if (lease) leases[name] = lease
208
+ else delete leases[name]
209
+ writeJson(leaseFile(), leases)
210
+ }
211
+
212
+ // ------------------------------------------------------------- sqlite snapshots
213
+ //
214
+ // One rule: a live SQLite database is only ever snapshotted by SQLite itself,
215
+ // through the plugin's own isolated interpreter (engine/<version>/venv). There
216
+ // is no global-Python path and no byte-copy fallback. A copy of a live database
217
+ // - or of a database plus its WAL - is torn the moment a writer commits between
218
+ // the two reads, and a torn copy restores as silent corruption, which is worse
219
+ // than no backup at all. So when the managed engine cannot produce a provable
220
+ // snapshot, the whole backup FAILS and nothing is published.
221
+ //
222
+ // The one file that may be copied verbatim is a zero-byte placeholder: no page
223
+ // was ever written and there are no WAL frames, so there is nothing to tear.
224
+
225
+ function engineRoot() { return path.join(dataDir(), 'engine') }
226
+
227
+ function engineCurrent() {
228
+ const raw = readJsonQuiet(engineCurrentFile())
229
+ if (!raw || typeof raw !== 'object') return null
230
+ return {
231
+ version: raw.version || null,
232
+ schemaVersion: raw.schemaVersion || null,
233
+ python: typeof raw.python === 'string' && raw.python ? raw.python : null,
234
+ venv: typeof raw.venv === 'string' && raw.venv ? raw.venv : null,
235
+ }
236
+ }
237
+
238
+ function venvPythonPath(venv) {
239
+ return process.platform === 'win32'
240
+ ? path.join(venv, 'Scripts', 'python.exe')
241
+ : path.join(venv, 'bin', 'python3')
242
+ }
243
+
244
+ /** True when both paths exist and `child` resolves inside `parent`. */
245
+ function insideDir(child, parent) {
246
+ if (typeof child !== 'string' || !child) return false
247
+ const left = realpathOrNull(child)
248
+ const right = realpathOrNull(parent)
249
+ if (!left || !right) return false
250
+ const a = process.platform === 'win32' ? left.toLowerCase() : left
251
+ const b = process.platform === 'win32' ? right.toLowerCase() : right
252
+ return a === b || a.startsWith(b.endsWith(path.sep) ? b : b + path.sep)
253
+ }
254
+
255
+ /**
256
+ * Every interpreter the plugin itself installed: whatever `engine/current.json`
257
+ * points at first (that file is only written after the engine was verified
258
+ * against the real databases), then any engine/<version>/venv* directory found
259
+ * on disk, newest first. The on-disk scan is what makes an engine repair
260
+ * possible: while a new engine installs, its venv is still `venv.tmp-*` and
261
+ * current.json still points at the broken one.
262
+ */
263
+ function engineVenvCandidates() {
264
+ const root = engineRoot()
265
+ const out = []
266
+ const seen = new Set()
267
+ const add = (venv, version, source) => {
268
+ if (typeof venv !== 'string' || !venv) return
269
+ const key = process.platform === 'win32' ? venv.toLowerCase() : venv
270
+ if (seen.has(key)) return
271
+ seen.add(key)
272
+ out.push({ venv, version: version || null, source })
273
+ }
274
+ const current = engineCurrent()
275
+ add(current?.venv, current?.version, 'engine/current.json')
276
+ const mtimeOf = (file) => { const info = statOrNull(file); return info ? info.mtimeMs : 0 }
277
+ const versions = readdirSafe(root, { withFileTypes: true })
278
+ .filter((item) => item.isDirectory())
279
+ .map((item) => ({ name: item.name, at: mtimeOf(path.join(root, item.name)) }))
280
+ .sort((a, b) => b.at - a.at)
281
+ for (const version of versions) {
282
+ const dir = path.join(root, version.name)
283
+ const venvs = readdirSafe(dir, { withFileTypes: true })
284
+ .filter((item) => item.isDirectory() && item.name.indexOf('venv') === 0)
285
+ .map((item) => ({ name: item.name, at: mtimeOf(path.join(dir, item.name)) }))
286
+ .sort((a, b) => b.at - a.at)
287
+ for (const venv of venvs) add(path.join(dir, venv.name), version.name, 'engine/' + version.name + '/' + venv.name)
288
+ }
289
+ return out
290
+ }
291
+
292
+ // The probe answers two questions at once: does this interpreter have sqlite3,
293
+ // and is it really the isolated venv (sys.prefix) rather than a shim that hands
294
+ // the work to a global Python.
295
+ const PYTHON_PROBE_SCRIPT = [
296
+ 'import json, sys',
297
+ 'out = {"ok": False, "error": "unknown"}',
298
+ 'try:',
299
+ ' import sqlite3',
300
+ ' out = {"ok": True, "prefix": sys.prefix, "sqlite": getattr(sqlite3, "sqlite_version", "unknown")}',
301
+ 'except Exception as error:',
302
+ ' out = {"ok": False, "prefix": sys.prefix, "error": str(error)}',
303
+ 'sys.stdout.write(json.dumps(out))',
304
+ ].join(NEWLINE)
305
+
306
+ const SQLITE_SNAPSHOT_SCRIPT = [
307
+ 'import json, sqlite3, sys',
308
+ 'src, dst = sys.argv[1], sys.argv[2]',
309
+ 'out = {"ok": False, "error": "unknown"}',
310
+ 'try:',
311
+ ' source = sqlite3.connect(src, timeout=10)',
312
+ ' try:',
313
+ ' target = sqlite3.connect(dst)',
314
+ ' try:',
315
+ ' source.backup(target)',
316
+ ' row = target.execute("pragma quick_check").fetchone()',
317
+ ' out = {"ok": True, "quickCheck": (row[0] if row else "unknown")}',
318
+ ' finally:',
319
+ ' target.close()',
320
+ ' finally:',
321
+ ' source.close()',
322
+ 'except Exception as error:',
323
+ ' out = {"ok": False, "error": str(error)}',
324
+ 'sys.stdout.write(json.dumps(out))',
325
+ ].join(NEWLINE)
326
+
327
+ let enginePythonCache = null
328
+
329
+ /** Forget the cached interpreter probe (tests use this between scenarios). */
330
+ export function resetBackupPythonProbe() { enginePythonCache = null }
331
+
332
+ /**
333
+ * spawn + Promise 版的解释器运行器:不再用 spawnSync 冻结事件循环(S-3)。
334
+ * 超时先软终止,5s 后硬杀并主动 reject,不等 'close';Windows 用
335
+ * taskkill /T /F 连带杀掉子进程树。maxBuffer 超限走同一条终止路径。
336
+ */
337
+ function spawnPython(cmd, args, { timeout, maxBuffer }) {
338
+ return new Promise((resolve, reject) => {
339
+ let child
340
+ try {
341
+ child = spawn(cmd, args, { windowsHide: true, stdio: ['ignore', 'pipe', 'pipe'] })
342
+ } catch (error) {
343
+ reject(error)
344
+ return
345
+ }
346
+ let settled = false
347
+ let stdout = ''
348
+ let stderr = ''
349
+ let timeoutTimer = null
350
+ let killTimer = null
351
+ const signalChild = force => {
352
+ if (!child || child.exitCode !== null) return
353
+ if (process.platform === 'win32') {
354
+ try { spawn('taskkill', ['/pid', String(child.pid), '/T', '/F'], { windowsHide: true, stdio: 'ignore' }) } catch {}
355
+ } else {
356
+ try { child.kill(force ? 'SIGKILL' : 'SIGTERM') } catch {}
357
+ }
358
+ }
359
+ const finish = (error, value) => {
360
+ if (settled) return
361
+ settled = true
362
+ if (timeoutTimer) clearTimeout(timeoutTimer)
363
+ if (killTimer) clearTimeout(killTimer)
364
+ if (error) reject(error)
365
+ else resolve(value)
366
+ }
367
+ const abort = reason => {
368
+ if (settled || killTimer) return
369
+ if (timeoutTimer) { clearTimeout(timeoutTimer); timeoutTimer = null }
370
+ signalChild(false)
371
+ killTimer = setTimeout(() => {
372
+ signalChild(true)
373
+ finish(reason, null) // 主动结束,不依赖 'close'
374
+ }, 5000)
375
+ killTimer.unref?.()
376
+ }
377
+ if (Number.isFinite(timeout) && timeout > 0) {
378
+ timeoutTimer = setTimeout(() => abort(Object.assign(new Error('python process timed out'), { code: 'ETIMEDOUT' })), timeout)
379
+ timeoutTimer.unref?.()
380
+ }
381
+ try { child.stdout?.setEncoding?.('utf8') } catch {}
382
+ try { child.stderr?.setEncoding?.('utf8') } catch {}
383
+ child.stdout?.on?.('data', chunk => {
384
+ if (settled) return
385
+ stdout += chunk
386
+ if (Buffer.byteLength(stdout) > maxBuffer) abort(Object.assign(new Error('maxBuffer exceeded'), { code: 'ENOBUFS' }))
387
+ })
388
+ child.stderr?.on?.('data', chunk => {
389
+ if (settled) return
390
+ stderr += chunk
391
+ if (Buffer.byteLength(stderr) > maxBuffer) abort(Object.assign(new Error('maxBuffer exceeded'), { code: 'ENOBUFS' }))
392
+ })
393
+ child.on?.('error', error => finish(error, null))
394
+ child.on?.('close', (code, signal) => finish(null, { status: code, signal, stdout, stderr }))
395
+ })
396
+ }
397
+
398
+ /**
399
+ * Runs an interpreter. `exec` is a seam for tests only (a fake interpreter);
400
+ * production always spawns the verified venv binary and nothing else.
401
+ * 兼容同步的测试 seam:await 一个普通返回值也照常拿到结果。
402
+ */
403
+ async function runPython(exec, cmd, args, timeout) {
404
+ const runner = typeof exec === 'function' ? exec : spawnPython
405
+ try {
406
+ return await runner(cmd, args, { timeout, windowsHide: true, encoding: 'utf8', maxBuffer: 4 * 1024 * 1024 })
407
+ } catch (error) {
408
+ return { error, status: null, stdout: '', stderr: '' }
409
+ }
410
+ }
411
+
412
+ function jsonOutcome(result) {
413
+ const text = String(result?.stdout || '').trim()
414
+ if (!text) return null
415
+ try { return JSON.parse(text) } catch { return null }
416
+ }
417
+
418
+ /**
419
+ * Resolves the engine interpreter a snapshot may use, or reports why there is
420
+ * none. Never falls back to a global interpreter: a missing, foreign or broken
421
+ * venv is a refusal, not a downgrade.
422
+ */
423
+ async function enginePythonForBackup(exec) {
424
+ const disabled = process.env.DSH_MEMU_BACKUP_NO_PYTHON === '1'
425
+ const root = engineRoot()
426
+ const candidates = disabled ? [] : engineVenvCandidates()
427
+ const key = JSON.stringify({ disabled, root, candidates })
428
+ if (enginePythonCache && enginePythonCache.key === key) return enginePythonCache.value
429
+ const value = { python: null, rejected: [] }
430
+ for (const candidate of candidates) {
431
+ const python = venvPythonPath(candidate.venv)
432
+ if (!fs.existsSync(python)) {
433
+ value.rejected.push(candidate.source + ': no interpreter on disk')
434
+ continue
435
+ }
436
+ if (!insideDir(candidate.venv, root) || !insideDir(python, root)) {
437
+ value.rejected.push(candidate.source + ': outside ' + root)
438
+ continue
439
+ }
440
+ const probe = await runPython(exec, python, ['-c', PYTHON_PROBE_SCRIPT], PROBE_TIMEOUT_MS)
441
+ const outcome = jsonOutcome(probe)
442
+ if (!outcome || outcome.ok !== true) {
443
+ const reason = outcome?.error || probe?.error?.message || (probe?.status != null ? 'exited ' + probe.status : 'no answer')
444
+ value.rejected.push(candidate.source + ': ' + String(reason).slice(0, 200))
445
+ continue
446
+ }
447
+ if (!insideDir(outcome.prefix, root)) {
448
+ value.rejected.push(candidate.source + ': interpreter reports sys.prefix ' + String(outcome.prefix) + ', outside engine/')
449
+ continue
450
+ }
451
+ value.python = {
452
+ cmd: python,
453
+ venv: candidate.venv,
454
+ version: candidate.version,
455
+ source: candidate.source,
456
+ sqlite: outcome.sqlite ? String(outcome.sqlite) : null,
457
+ }
458
+ break
459
+ }
460
+ enginePythonCache = { key, value }
461
+ return value
462
+ }
463
+
464
+ function backupRefusal(code, message) {
465
+ const error = new Error(message)
466
+ error.code = code
467
+ return error
468
+ }
469
+
470
+ function removeQuietly(file) {
471
+ try { fs.rmSync(file, { force: true }) } catch {}
472
+ }
473
+
474
+ /**
475
+ * Asks the engine interpreter to run SQLite's online backup API: it folds any
476
+ * live WAL into one self-contained file and hands back a proven-consistent
477
+ * snapshot. Anything short of a clean `quick_check` is a failure, never a
478
+ * reason to copy the bytes ourselves.
479
+ */
480
+ async function pythonSnapshot(exec, python, from, to) {
481
+ const result = await runPython(exec, python.cmd, ['-c', SQLITE_SNAPSHOT_SCRIPT, from, to], PYTHON_TIMEOUT_MS)
482
+ if (result?.error) return { ok: false, error: String(result.error.message || result.error) }
483
+ if (result?.status !== 0) {
484
+ return { ok: false, error: String(result?.stderr || ('engine interpreter exited ' + result?.status)).trim().slice(0, 400) }
485
+ }
486
+ const payload = jsonOutcome(result)
487
+ if (!payload || payload.ok !== true) {
488
+ return { ok: false, error: String(payload?.error || 'sqlite3 backup returned no result').slice(0, 400) }
489
+ }
490
+ if (payload.quickCheck !== 'ok') {
491
+ return { ok: false, error: 'snapshot failed pragma quick_check: ' + String(payload.quickCheck || 'unknown').slice(0, 200) }
492
+ }
493
+ if (!hasSqliteHeader(to) || fileSize(to) <= 0) {
494
+ return { ok: false, error: 'snapshot has no SQLite database header' }
495
+ }
496
+ return { ok: true, quickCheck: 'ok' }
497
+ }
498
+
499
+ /**
500
+ * Produces one consistent copy of a live SQLite database inside the staging
501
+ * directory. Two outcomes only: a snapshot the engine proved consistent, or a
502
+ * thrown refusal that aborts the whole backup.
503
+ */
504
+ async function snapshotDatabase(from, to, exec) {
505
+ const before = statOrNull(from)
506
+ if (!before) return { mode: 'missing' }
507
+ if (before.isSymbolicLink()) throw new Error('backup refuses symbolic links')
508
+ if (!before.isFile()) throw new Error('backup refuses non-file: ' + path.basename(from))
509
+ const name = path.basename(from)
510
+ const walSize = fileSize(from + '-wal')
511
+ const walContent = walSize > 0
512
+ if (before.size === 0 && !walContent) {
513
+ // A placeholder no engine has written a page to: copying it cannot tear.
514
+ fs.copyFileSync(from, to)
515
+ return { mode: 'empty-placeholder', quickCheck: 'empty' }
516
+ }
517
+ if (!hasSqliteHeader(from)) {
518
+ throw backupRefusal('DSH_MEMU_BACKUP_NOT_SQLITE', 'backup refuses ' + name
519
+ + ': it is neither an empty placeholder nor a SQLite database, so its contents cannot be verified'
520
+ + (walContent ? ' (it has a non-empty WAL)' : ''))
521
+ }
522
+ const resolved = await enginePythonForBackup(exec)
523
+ const python = resolved.python
524
+ if (!python) {
525
+ const why = resolved.rejected.length ? ' (' + resolved.rejected.join('; ') + ')' : ''
526
+ throw backupRefusal('DSH_MEMU_BACKUP_ENGINE_REQUIRED', 'backup of ' + name
527
+ + " needs the plugin engine: no verified engine/<version>/venv Python with sqlite3 was found under "
528
+ + engineRoot() + why + '. Install or repair the engine, then retry. '
529
+ + 'Nothing was copied: a live database copied by hand can restore as silent corruption.')
530
+ }
531
+ const snapshot = await pythonSnapshot(exec, python, from, to)
532
+ if (!snapshot.ok) {
533
+ removeQuietly(to)
534
+ removeQuietly(to + '-wal')
535
+ removeQuietly(to + '-shm')
536
+ throw backupRefusal('DSH_MEMU_BACKUP_SNAPSHOT_FAILED', 'backup could not snapshot ' + name + ' with '
537
+ + python.source + ' (engine ' + String(python.version || 'unknown') + '): ' + snapshot.error)
538
+ }
539
+ return {
540
+ mode: 'sqlite-backup-api',
541
+ engine: python.version ? String(python.version) : null,
542
+ via: python.source,
543
+ sqlite: python.sqlite,
544
+ quickCheck: snapshot.quickCheck,
545
+ }
546
+ }
547
+
548
+ // ------------------------------------------------------------------- inventory
549
+
550
+ function copyRegular(from, to) {
551
+ const info = statOrNull(from)
552
+ if (!info) return false
553
+ if (info.isSymbolicLink()) throw new Error('backup refuses symbolic links')
554
+ if (!info.isFile()) throw new Error('backup refuses non-file: ' + path.basename(from))
555
+ ensureDir(path.dirname(to))
556
+ fs.copyFileSync(from, to)
557
+ return true
558
+ }
559
+
560
+ function copyTree(from, to) {
561
+ const entries = readdirSafe(from, { withFileTypes: true })
562
+ if (!entries.length && !statOrNull(from)) return
563
+ ensureDir(to)
564
+ for (const item of entries) {
565
+ if (item.isSymbolicLink()) throw new Error('backup refuses symbolic links')
566
+ const source = path.join(from, item.name)
567
+ const target = path.join(to, item.name)
568
+ if (item.isDirectory()) copyTree(source, target)
569
+ else copyRegular(source, target)
570
+ }
571
+ }
572
+
573
+ function collectFiles(dir, prefix = '', out = {}) {
574
+ for (const item of readdirSafe(dir, { withFileTypes: true })) {
575
+ const full = path.join(dir, item.name)
576
+ const rel = prefix ? prefix + '/' + item.name : item.name
577
+ const info = statOrNull(full)
578
+ if (!info) continue
579
+ if (info.isSymbolicLink()) throw new Error('backup refuses symbolic links')
580
+ if (info.isDirectory()) { collectFiles(full, rel, out); continue }
581
+ if (!info.isFile()) continue
582
+ out[rel] = { bytes: info.size, sha256: sha256File(full) }
583
+ }
584
+ return out
585
+ }
586
+
587
+ // --------------------------------------------------------------- backup creation
588
+
589
+ function nextBackupName() {
590
+ const base = isoStamp().replace(/[:.]/g, '-')
591
+ let name = base
592
+ for (let attempt = 0; fs.existsSync(path.join(backupsDir(), name)); attempt += 1) {
593
+ if (attempt >= 64) throw new Error('cannot allocate a unique backup name')
594
+ name = base + '-' + process.pid.toString(36) + attempt.toString(36)
595
+ }
596
+ return name
597
+ }
598
+
599
+ function vectorSummary() {
600
+ const raw = readJsonQuiet(vectorActiveFile())
601
+ if (!raw || typeof raw !== 'object') return { present: false }
602
+ const active = raw.active && typeof raw.active === 'object' ? raw.active : null
603
+ const profile = active && active.profile && typeof active.profile === 'object' ? active.profile : null
604
+ const libraries = active && active.databases && active.databases.libraries && typeof active.databases.libraries === 'object'
605
+ ? Object.keys(active.databases.libraries).length
606
+ : 0
607
+ return {
608
+ present: true,
609
+ generation: Number.isSafeInteger(raw.generation) ? raw.generation : null,
610
+ active: active
611
+ ? {
612
+ generation: Number.isSafeInteger(active.generation) ? active.generation : null,
613
+ fingerprint: typeof active.fingerprint === 'string' ? active.fingerprint : null,
614
+ catalogId: typeof profile?.catalogId === 'string' ? profile.catalogId : null,
615
+ revision: typeof profile?.revision === 'string' ? profile.revision : null,
616
+ dimension: Number.isSafeInteger(profile?.dimension) ? profile.dimension : null,
617
+ libraries,
618
+ }
619
+ : null,
620
+ pending: raw.pending && typeof raw.pending === 'object' ? String(raw.pending.status || '') : null,
621
+ }
622
+ }
623
+
624
+ function engineSummary() {
625
+ const current = engineCurrent()
626
+ return current ? { version: current.version, schemaVersion: current.schemaVersion } : null
627
+ }
628
+
629
+ /**
630
+ * Copies every store a restore needs: plugin state, the global index and the
631
+ * per-library index files, the per-library lexicon files, the active vector
632
+ * profile journal, prompt overrides and their manifest, attachment references,
633
+ * and every MemU SQLite database.
634
+ * Deliberately absent: engine/, downloads/, logs/, tmp/ (large and
635
+ * re-downloadable) and any key material - the manifest carries identity, never
636
+ * a credential.
637
+ *
638
+ * `exec` only exists so tests can stand in for the engine interpreter; the
639
+ * default path spawns the verified venv binary and nothing else.
640
+ */
641
+ async function writeStores(staging, exec) {
642
+ ensureDir(path.join(staging, 'libraries'))
643
+ ensureDir(path.join(staging, 'index'))
644
+ ensureDir(path.join(staging, 'prompts'))
645
+ copyRegular(stateFile(), path.join(staging, 'state.json'))
646
+ // Consolidation ledger: per-session ranges/operations. It now participates in
647
+ // backup/restore so a restored install does not re-fork work it already did.
648
+ copyRegular(path.join(dataDir(), 'consolidation.json'), path.join(staging, 'consolidation.json'))
649
+ for (const name of readdirSafe(indexDir())) {
650
+ // Local deleted-memory stashes are a time-boxed undo buffer, not library
651
+ // data: they must never leak permanently deleted bodies into a backup.
652
+ if (name.endsWith('.json') && !name.endsWith('.deleted.json')) copyRegular(path.join(indexDir(), name), path.join(staging, 'index', name))
653
+ }
654
+ // 词典:data/lexicon/<libraryId>.json 与索引同权进备份清单。只收安全 id
655
+ // 命名的 JSON(restore 侧 allowlist 用同一规则拒绝越界);目录还不存在(这个
656
+ // 数据根从未写过词典)就是空集。
657
+ ensureDir(path.join(staging, 'lexicon'))
658
+ for (const name of readdirSafe(lexiconRoot())) {
659
+ if (!name.endsWith('.json')) continue
660
+ if (!isSafeId(name.slice(0, -'.json'.length))) continue
661
+ copyRegular(path.join(lexiconRoot(), name), path.join(staging, 'lexicon', name))
662
+ }
663
+ copyRegular(path.join(dataDir(), 'prompts', 'manifest.json'), path.join(staging, 'prompts', 'manifest.json'))
664
+ copyTree(path.join(dataDir(), 'prompts'), path.join(staging, 'prompts'))
665
+ copyTree(path.join(dataDir(), 'attachments'), path.join(staging, 'attachments'))
666
+ const databases = []
667
+ const globalInfo = statOrNull(globalDbFile())
668
+ if (globalInfo && globalInfo.isFile()) databases.push({ src: globalDbFile(), rel: 'global.sqlite3' })
669
+ for (const item of readdirSafe(librariesDir(), { withFileTypes: true })) {
670
+ if (!item.isFile() || !item.name.endsWith('.sqlite3')) continue
671
+ databases.push({ src: path.join(librariesDir(), item.name), rel: 'libraries/' + item.name })
672
+ }
673
+ const snapshots = []
674
+ for (const database of databases) {
675
+ const target = path.join(staging, database.rel.split('/').join(path.sep))
676
+ ensureDir(path.dirname(target))
677
+ const result = await snapshotDatabase(database.src, target, exec)
678
+ snapshots.push({
679
+ file: database.rel,
680
+ mode: result.mode,
681
+ engine: result.engine || null,
682
+ quickCheck: result.quickCheck || null,
683
+ })
684
+ }
685
+ return snapshots
686
+ }
687
+
688
+ function publishStaging(staging, name) {
689
+ const dir = path.join(backupsDir(), name)
690
+ if (fs.existsSync(dir)) throw new Error('backup directory already exists: ' + name)
691
+ try {
692
+ fs.renameSync(staging, dir)
693
+ } catch (error) {
694
+ throw new Error('could not publish backup ' + name + ': ' + (error?.code || 'io error'))
695
+ }
696
+ return dir
697
+ }
698
+
699
+ function discardStaging(staging) {
700
+ try { fs.rmSync(staging, { recursive: true, force: true, maxRetries: 3 }) } catch (error) {
701
+ warn('backups: could not discard staging directory (' + (error?.code || 'io error') + ')')
702
+ }
703
+ }
704
+
705
+ /** Staging leftovers of crashed runs are reclaimed; a live sibling is kept. */
706
+ function cleanupStaging() {
707
+ const root = stagingRoot()
708
+ const now = Date.now()
709
+ for (const item of readdirSafe(root, { withFileTypes: true })) {
710
+ if (!item.isDirectory()) continue
711
+ const full = path.join(root, item.name)
712
+ const parts = item.name.split('.')
713
+ const pid = Number(parts.length > 1 ? parts[parts.length - 2] : NaN)
714
+ const info = statOrNull(full)
715
+ const age = info ? now - info.mtimeMs : 0
716
+ const mine = Number.isSafeInteger(pid) && pid === process.pid
717
+ const stale = mine ? age > STAGING_TTL_MS : (!Number.isSafeInteger(pid) || !pidAlive(pid) || age > STAGING_TTL_MS)
718
+ if (!stale) continue
719
+ try { fs.rmSync(full, { recursive: true, force: true, maxRetries: 3 }) } catch {}
720
+ }
721
+ }
722
+
723
+ /**
724
+ * Creates one managed backup of the current data root, then keeps the newest
725
+ * BACKUP_KEEP complete ones. Returns a report whose dir is the published
726
+ * directory, so every existing caller that treats the return value as a path
727
+ * keeps working.
728
+ *
729
+ * `pythonExec` is a test seam for the engine interpreter (see writeStores).
730
+ * A database that cannot be snapshotted by the verified engine throws, and the
731
+ * throw happens before anything is published, so no partial or torn backup can
732
+ * ever appear in backups/.
733
+ */
734
+ export async function createBackup({ label = 'auto', keep = BACKUP_KEEP, flushState = null, pythonExec = null } = {}) {
735
+ return withBackupLock(async () => {
736
+ ensureDir(backupsDir())
737
+ cleanupStaging()
738
+ const name = nextBackupName()
739
+ const staging = path.join(stagingRoot(), name + '.' + process.pid + '.' + crypto.randomBytes(4).toString('hex'))
740
+ ensureDir(staging)
741
+ try {
742
+ // Plugin state is flushed first: a backup must never capture the pending
743
+ // bookkeeping edits that are still only in memory.
744
+ if (typeof flushState === 'function') flushState()
745
+ const snapshots = await writeStores(staging, pythonExec)
746
+ const files = collectFiles(staging)
747
+ const totals = { files: 0, bytes: 0 }
748
+ for (const rel of Object.keys(files)) {
749
+ totals.files += 1
750
+ totals.bytes += Number(files[rel].bytes || 0)
751
+ }
752
+ const createdAt = isoStamp()
753
+ const manifest = {
754
+ version: BACKUP_SCHEMA,
755
+ kind: 'dsh-memu-memory/backup',
756
+ name,
757
+ uniqueId: name + '-' + crypto.randomBytes(4).toString('hex'),
758
+ createdAt,
759
+ createdAtMs: Date.parse(createdAt) || Date.now(),
760
+ label: String(label || 'auto'),
761
+ complete: true,
762
+ engine: engineSummary(),
763
+ vector: vectorSummary(),
764
+ snapshot: { databases: snapshots },
765
+ totals,
766
+ files,
767
+ }
768
+ // Written last and atomically: a finished manifest is the completion
769
+ // marker that prune requires before it may delete anything.
770
+ writeJson(path.join(staging, 'manifest.json'), manifest)
771
+ const dir = publishStaging(staging, name)
772
+ const prune = pruneBackups({ keep })
773
+ return {
774
+ name,
775
+ dir,
776
+ createdAt,
777
+ files: totals.files,
778
+ bytes: totals.bytes,
779
+ snapshots: snapshots.map(item => ({ file: item.file, mode: item.mode, engine: item.engine || null })),
780
+ pruned: prune.deleted,
781
+ pruneFailed: prune.failed,
782
+ pendingCleanup: prune.pendingCleanup,
783
+ notice: prune.notice,
784
+ }
785
+ } catch (error) {
786
+ discardStaging(staging)
787
+ throw error
788
+ }
789
+ })
790
+ }
791
+
792
+ // -------------------------------------------------------------- listing / scan
793
+
794
+ function isManagedName(name) {
795
+ return typeof name === 'string' && isSafeId(name) && MANAGED_NAME.test(name)
796
+ }
797
+
798
+ /** A relative path inside a backup that we are willing to copy back. */
799
+ function isSafeRelative(rel) {
800
+ if (typeof rel !== 'string' || !rel) return false
801
+ if (path.isAbsolute(rel)) return false
802
+ if (rel.indexOf(BACKSLASH) !== -1) return false
803
+ for (const part of rel.split('/')) {
804
+ if (!part || part === '.' || part === '..') return false
805
+ }
806
+ return true
807
+ }
808
+
809
+ function inventoryIssues(dir, files) {
810
+ const issues = []
811
+ const rels = Object.keys(files)
812
+ if (!rels.length) return ['manifest lists no files']
813
+ for (const rel of rels) {
814
+ if (!isSafeRelative(rel)) { issues.push('unsafe path in manifest: ' + rel.slice(0, 120)); continue }
815
+ if (issues.length >= 5) { issues.push('and more'); break }
816
+ const full = path.join(dir, rel.split('/').join(path.sep))
817
+ const info = statOrNull(full)
818
+ if (!info) { issues.push('missing: ' + rel); continue }
819
+ if (!info.isFile()) { issues.push('not a file: ' + rel); continue }
820
+ const expected = Number(files[rel]?.bytes)
821
+ if (Number.isFinite(expected) && expected !== info.size) issues.push('size mismatch: ' + rel)
822
+ }
823
+ return issues
824
+ }
825
+
826
+ function buildEntry(name, dir, manifest, status, issues) {
827
+ const files = manifest?.files && typeof manifest.files === 'object' ? manifest.files : null
828
+ let bytes = null
829
+ if (files) {
830
+ bytes = 0
831
+ for (const rel of Object.keys(files)) bytes += Number(files[rel]?.bytes || 0)
832
+ }
833
+ const createdAt = typeof manifest?.createdAt === 'string' ? manifest.createdAt : null
834
+ const info = statOrNull(dir)
835
+ const parsed = Date.parse(createdAt || '')
836
+ return {
837
+ name,
838
+ dir,
839
+ createdAt: createdAt || (info ? new Date(info.mtimeMs).toISOString() : null),
840
+ createdAtMs: Number.isFinite(Number(manifest?.createdAtMs)) ? Number(manifest.createdAtMs) : (Number.isFinite(parsed) ? parsed : (info ? info.mtimeMs : 0)),
841
+ engine: manifest?.engine || null,
842
+ files: files ? Object.keys(files).length : null,
843
+ bytes,
844
+ hasManifest: Boolean(manifest),
845
+ complete: status === 'complete',
846
+ status,
847
+ issues: issues.slice(0, 6),
848
+ uniqueId: typeof manifest?.uniqueId === 'string' ? manifest.uniqueId : null,
849
+ label: typeof manifest?.label === 'string' ? manifest.label : null,
850
+ vector: manifest?.vector || null,
851
+ }
852
+ }
853
+
854
+ /**
855
+ * Reads one directory in backups/ and classifies it. status is 'complete'
856
+ * (only these are counted or deleted), 'incomplete', 'corrupt' or 'unknown'.
857
+ * verify re-hashes every file: cheap listing stays cheap, but retention must
858
+ * never count a backup it has not actually checked.
859
+ */
860
+ function scanEntry(name, { verify = false } = {}) {
861
+ const dir = path.join(backupsDir(), name)
862
+ const info = statOrNull(dir)
863
+ if (!info) return null
864
+ if (info.isSymbolicLink()) return buildEntry(name, dir, null, 'unknown', ['backups entry is a symbolic link or junction'])
865
+ if (!info.isDirectory()) return buildEntry(name, dir, null, 'unknown', ['backups entry is not a directory'])
866
+ const manifest = readJsonQuiet(path.join(dir, 'manifest.json'))
867
+ const issues = []
868
+ let status = 'complete'
869
+ if (!manifest || typeof manifest !== 'object' || Array.isArray(manifest)) {
870
+ status = 'unknown'
871
+ issues.push('manifest.json is missing or unreadable')
872
+ } else if (!isManagedName(name)) {
873
+ status = 'unknown'
874
+ issues.push('not a managed backup name')
875
+ } else if (!manifest.files || typeof manifest.files !== 'object' || Array.isArray(manifest.files)) {
876
+ status = 'incomplete'
877
+ issues.push('manifest has no file inventory')
878
+ } else if (manifest.complete !== true) {
879
+ status = 'incomplete'
880
+ issues.push('backup was never completed')
881
+ }
882
+ if (status === 'complete') {
883
+ for (const issue of inventoryIssues(dir, manifest.files)) issues.push(issue)
884
+ if (issues.length) status = 'incomplete'
885
+ }
886
+ if (status === 'complete' && verify) {
887
+ for (const rel of Object.keys(manifest.files)) {
888
+ const expected = manifest.files[rel] || {}
889
+ if (typeof expected.sha256 !== 'string' || !expected.sha256) continue
890
+ const full = path.join(dir, rel.split('/').join(path.sep))
891
+ let actual = null
892
+ try { actual = sha256File(full) } catch { actual = null }
893
+ if (actual === expected.sha256) continue
894
+ status = 'corrupt'
895
+ issues.push('checksum mismatch: ' + rel)
896
+ break
897
+ }
898
+ }
899
+ if (status !== 'unknown') {
900
+ const real = realpathOrNull(dir)
901
+ if (!real || !samePath(real, dir)) { status = 'unknown'; issues.push('directory resolves somewhere else (link or junction)') }
902
+ else if (!samePath(path.dirname(path.resolve(dir)), path.resolve(backupsDir()))) { status = 'unknown'; issues.push('directory is not a direct child of backups/') }
903
+ }
904
+ return buildEntry(name, dir, manifest, status, issues)
905
+ }
906
+
907
+ function compareEntries(a, b) {
908
+ // createdAt first because mtimes lie, then the name: names are unique inside
909
+ // backups/ and a colliding millisecond appends a monotonic suffix, so the
910
+ // order stays deterministic without trusting the filesystem's clock.
911
+ if (b.createdAtMs !== a.createdAtMs) return b.createdAtMs - a.createdAtMs
912
+ return String(b.name).localeCompare(String(a.name))
913
+ }
914
+
915
+ /** Every entry in backups/, newest first, including incomplete and unknown. */
916
+ export function scanBackups({ verify = false } = {}) {
917
+ const out = []
918
+ for (const item of readdirSafe(backupsDir(), { withFileTypes: true })) {
919
+ if (item.name.startsWith('.')) continue
920
+ const scanned = scanEntry(item.name, { verify })
921
+ if (scanned) out.push(scanned)
922
+ }
923
+ return out.sort(compareEntries)
924
+ }
925
+
926
+ /** Public listing used by the UI: newest first, with completeness reported. */
927
+ export function listBackupEntries() { return scanBackups() }
928
+
929
+ export function findBackup(name) {
930
+ if (!isSafeId(name) || name.startsWith('.')) throw new Error('invalid backup name')
931
+ const dir = path.join(backupsDir(), name)
932
+ if (!statOrNull(dir)) throw new Error('backup not found: ' + name)
933
+ const found = scanEntry(name)
934
+ if (!found) throw new Error('backup not found: ' + name)
935
+ return found
936
+ }
937
+
938
+ // ----------------------------------------------------------------------- prune
939
+
940
+ function assertNoLinks(dir, prefix) {
941
+ for (const item of readdirSafe(dir, { withFileTypes: true })) {
942
+ const rel = prefix ? prefix + '/' + item.name : item.name
943
+ if (item.isSymbolicLink()) throw new Error('refusing to delete: ' + rel + ' is a link')
944
+ if (item.isDirectory()) assertNoLinks(path.join(dir, item.name), rel)
945
+ }
946
+ }
947
+
948
+ /**
949
+ * Every guard a recursive delete needs, re-checked on the resolved path:
950
+ * managed single-segment name, direct child of backups/, realpath unchanged,
951
+ * and no link or junction anywhere inside.
952
+ */
953
+ function assertRemovable(found) {
954
+ if (!found || typeof found.name !== 'string' || !isManagedName(found.name)) throw new Error('refusing to delete a backup with an unmanaged name')
955
+ const dir = path.join(backupsDir(), found.name)
956
+ const info = statOrNull(dir)
957
+ if (!info) throw new Error('backup not found: ' + found.name)
958
+ if (info.isSymbolicLink()) throw new Error('refusing to delete a link: ' + found.name)
959
+ if (!info.isDirectory()) throw new Error('refusing to delete a non-directory: ' + found.name)
960
+ if (!samePath(path.dirname(path.resolve(dir)), path.resolve(backupsDir()))) throw new Error('refusing to delete outside backups/: ' + found.name)
961
+ const real = realpathOrNull(dir)
962
+ if (!real || !samePath(real, dir)) throw new Error('refusing to delete a redirected path: ' + found.name)
963
+ assertNoLinks(dir, '')
964
+ }
965
+
966
+ function removeBackupDir(found) {
967
+ assertRemovable(found)
968
+ fs.rmSync(path.join(backupsDir(), found.name), { recursive: true, force: true, maxRetries: 3 })
969
+ }
970
+
971
+ /**
972
+ * Keeps the newest keep complete managed backups and deletes the rest.
973
+ * Incomplete and unknown entries are reported, never counted, never deleted.
974
+ * A leased directory (a restore or migration is reading it) is skipped, as is
975
+ * the safety backup named in protect - retention may briefly exceed the limit,
976
+ * and the next prune reclaims it.
977
+ */
978
+ export function pruneBackups({ keep = BACKUP_KEEP, protect = [] } = {}) {
979
+ return withBackupLock(() => {
980
+ ensureDir(backupsDir())
981
+ cleanupStaging()
982
+ const protectSet = new Set()
983
+ for (const name of protect) if (name) protectSet.add(path.basename(String(name)))
984
+ for (const name of Object.keys(activeLeases())) protectSet.add(name)
985
+ // Retention decides what to delete, so it pays for the full hash pass: a
986
+ // backup whose bytes no longer match its manifest must not occupy one of the
987
+ // three slots, and must never be the reason an intact one is deleted.
988
+ const all = scanBackups({ verify: true })
989
+ const complete = all.filter(found => found.status === 'complete')
990
+ const victims = complete.slice(keep).filter(found => !protectSet.has(found.name))
991
+ const deleted = []
992
+ const failed = []
993
+ for (const victim of victims) {
994
+ try {
995
+ removeBackupDir(victim)
996
+ deleted.push(victim.name)
997
+ } catch (error) {
998
+ failed.push({ name: victim.name, error: String(error?.message || error) })
999
+ warn('backups: could not remove ' + victim.name + ' (' + String(error?.message || error) + ')')
1000
+ }
1001
+ }
1002
+ const kept = deleted.length
1003
+ ? scanBackups().filter(found => found.status === 'complete')
1004
+ : complete.filter(found => !deleted.includes(found.name))
1005
+ const notice = 'at most ' + keep + ' complete backups are kept; older ones are cleaned up automatically'
1006
+ if (deleted.length) {
1007
+ warn('backups: ' + notice + ' (deleted ' + deleted.join(', ') + ')')
1008
+ try {
1009
+ const marker = path.join(backupsDir(), '.retention-notice.json')
1010
+ if (!readJsonQuiet(marker)) writeJson(marker, { at: isoStamp(), policy: 'keep ' + keep, notice })
1011
+ } catch {}
1012
+ }
1013
+ return {
1014
+ keep,
1015
+ notice,
1016
+ deleted,
1017
+ failed,
1018
+ protected: Array.from(protectSet),
1019
+ pendingCleanup: Math.max(0, kept.length - keep),
1020
+ kept: kept.map(found => found.name),
1021
+ skipped: all.filter(found => found.status !== 'complete').map(found => ({ name: found.name, status: found.status, issues: found.issues })),
1022
+ }
1023
+ })
1024
+ }
1025
+
1026
+ /** Explicit removal requested by the user. */
1027
+ export function deleteBackupEntry(name) {
1028
+ return withBackupLock(() => {
1029
+ const found = findBackup(name)
1030
+ if (activeLeases()[found.name]) throw new Error('backup is in use by a running restore: ' + found.name)
1031
+ removeBackupDir(found)
1032
+ return { deleted: found.name, status: found.status }
1033
+ })
1034
+ }
1035
+
1036
+ // --------------------------------------------------------------------- restore
1037
+
1038
+ /** Where one relative path inside a backup lands in the live data root. */
1039
+ function liveTargetFor(rel) {
1040
+ const parts = rel.split('/')
1041
+ const head = parts[0]
1042
+ if (parts.length === 1) {
1043
+ if (head === 'state.json') return stateFile()
1044
+ if (head === 'consolidation.json') return path.join(dataDir(), 'consolidation.json')
1045
+ if (head === 'global.sqlite3') return globalDbFile()
1046
+ if (head === 'global.sqlite3-wal') return globalDbFile() + '-wal'
1047
+ if (head === 'global.sqlite3-shm') return globalDbFile() + '-shm'
1048
+ }
1049
+ if ((head === 'index' || head === 'libraries') && parts.length === 2) {
1050
+ if (parts[1].endsWith('.deleted.json')) throw new Error('backup contains a deleted-memory stash that must not be restored: ' + rel)
1051
+ return path.join(head === 'index' ? indexDir() : librariesDir(), parts[1])
1052
+ }
1053
+ if (head === 'lexicon' && parts.length === 2) {
1054
+ // 词典只接受 <libraryId>.json:isSafeId 挡掉 ..、路径分隔符和任意文件名,
1055
+ // 与 writeStores 收录时的同一规则对称。
1056
+ const id = parts[1].endsWith('.json') ? parts[1].slice(0, -'.json'.length) : ''
1057
+ if (!id || !isSafeId(id)) throw new Error('backup contains an entry this version cannot restore: ' + rel)
1058
+ return path.join(lexiconRoot(), parts[1])
1059
+ }
1060
+ if ((head === 'prompts' || head === 'attachments') && parts.length >= 2) {
1061
+ return path.join(dataDir(), parts.join(path.sep))
1062
+ }
1063
+ throw new Error('backup contains an entry this version cannot restore: ' + rel)
1064
+ }
1065
+
1066
+ function writeAtomicCopy(from, to) {
1067
+ ensureDir(path.dirname(to))
1068
+ const tmp = to + '.restore-' + process.pid + '-' + crypto.randomBytes(4).toString('hex')
1069
+ try {
1070
+ fs.copyFileSync(from, tmp)
1071
+ const fd = fs.openSync(tmp, 'r+')
1072
+ try { fs.fsyncSync(fd) } finally { fs.closeSync(fd) }
1073
+ for (let attempt = 0; ; attempt += 1) {
1074
+ try { fs.renameSync(tmp, to); return } catch (error) {
1075
+ if (!['EPERM', 'EBUSY', 'EACCES'].includes(error?.code) || attempt >= 5) throw error
1076
+ pause(RETRY_MS * (attempt + 1))
1077
+ }
1078
+ }
1079
+ } catch (error) {
1080
+ try { fs.rmSync(tmp, { force: true }) } catch {}
1081
+ throw error
1082
+ }
1083
+ }
1084
+
1085
+ /** A restored database must not inherit the WAL of the one it replaces. */
1086
+ function dropCompanions(target) {
1087
+ for (const suffix of ['-wal', '-shm']) {
1088
+ try { fs.rmSync(target + suffix, { force: true }) } catch (error) {
1089
+ if (error?.code !== 'ENOENT') throw error
1090
+ }
1091
+ }
1092
+ }
1093
+
1094
+ function isSidecar(rel) {
1095
+ return rel.endsWith('-wal') || rel.endsWith('-shm')
1096
+ }
1097
+
1098
+ /** A database file always lands before its sidecars. */
1099
+ function restoreOrder(rels) {
1100
+ return rels.slice().sort((left, right) => {
1101
+ const delta = (isSidecar(left) ? 1 : 0) - (isSidecar(right) ? 1 : 0)
1102
+ if (delta !== 0) return delta
1103
+ return left.localeCompare(right)
1104
+ })
1105
+ }
1106
+
1107
+ /**
1108
+ * Validates the WHOLE inventory before anything is written, so a restore either
1109
+ * has every byte it needs or leaves the live root untouched.
1110
+ */
1111
+ function verifyInventory(found) {
1112
+ const manifest = readJsonQuiet(path.join(found.dir, 'manifest.json'))
1113
+ if (!manifest || typeof manifest !== 'object' || !manifest.files || typeof manifest.files !== 'object') {
1114
+ throw new Error('backup is incomplete: ' + found.name + ' has no file inventory')
1115
+ }
1116
+ const rels = []
1117
+ for (const rel of Object.keys(manifest.files)) {
1118
+ if (!isSafeRelative(rel)) throw new Error('invalid backup manifest path')
1119
+ // Backups made before stashes were excluded still list them. Skip rather
1120
+ // than fail, so restoring an older backup neither breaks nor resurrects
1121
+ // permanently deleted text.
1122
+ if (/^index\/[^/]+\.deleted\.json$/.test(rel)) continue
1123
+ const full = path.join(found.dir, rel.split('/').join(path.sep))
1124
+ const info = statOrNull(full)
1125
+ if (!info || info.isSymbolicLink() || !info.isFile()) throw new Error('backup is incomplete: ' + rel + ' is missing')
1126
+ const expected = manifest.files[rel] || {}
1127
+ if (Number.isFinite(Number(expected.bytes)) && Number(expected.bytes) !== info.size) {
1128
+ throw new Error('backup is corrupt: ' + rel + ' has the wrong size')
1129
+ }
1130
+ if (expected.sha256 && sha256File(full) !== expected.sha256) {
1131
+ throw new Error('backup is corrupt: ' + rel + ' failed its checksum')
1132
+ }
1133
+ liveTargetFor(rel)
1134
+ rels.push(rel)
1135
+ }
1136
+ if (!rels.length) throw new Error('backup is incomplete: ' + found.name + ' lists no files')
1137
+ return { manifest, rels }
1138
+ }
1139
+
1140
+ function normalizeDbRel(value) {
1141
+ if (typeof value !== 'string' || !value) return null
1142
+ const rel = value.split(BACKSLASH).join('/').replace(/^\.\//, '')
1143
+ if (rel.startsWith('libraries/')) return rel
1144
+ if (rel.indexOf('/') === -1) return 'libraries/' + rel
1145
+ return rel
1146
+ }
1147
+
1148
+ /**
1149
+ * A backup made before the vector journal existed carries no vector-active
1150
+ * manifest. Restoring it over a live root that still points at the newer
1151
+ * generation would leave recall reading tables the restored text index never
1152
+ * saw, so that pointer must be retired, and the same holds for a journal that
1153
+ * points at databases the backup does not contain.
1154
+ */
1155
+ function planVectorActive(found, rels) {
1156
+ const rel = 'index/vector-active.json'
1157
+ if (!rels.includes(rel)) return { action: 'absent', restore: false }
1158
+ const raw = readJsonQuiet(path.join(found.dir, 'index', 'vector-active.json'))
1159
+ if (!raw || typeof raw !== 'object') return { action: 'unreadable', restore: false }
1160
+ const active = raw.active && typeof raw.active === 'object' ? raw.active : null
1161
+ if (!active) return { action: 'restore', restore: true }
1162
+ const needed = []
1163
+ const global = active.databases && active.databases.global
1164
+ if (global && typeof global.path === 'string') needed.push(global.path)
1165
+ const libraries = active.databases && active.databases.libraries
1166
+ if (libraries && typeof libraries === 'object') {
1167
+ for (const key of Object.keys(libraries)) {
1168
+ const item = libraries[key]
1169
+ if (item && typeof item.path === 'string') needed.push(item.path)
1170
+ }
1171
+ }
1172
+ const missing = []
1173
+ for (const value of needed) {
1174
+ const normalized = normalizeDbRel(value)
1175
+ if (!normalized || !rels.includes(normalized)) missing.push(String(value))
1176
+ }
1177
+ if (missing.length) return { action: 'missing-databases', restore: false, missing: missing.slice(0, 5) }
1178
+ return { action: 'restore', restore: true }
1179
+ }
1180
+
1181
+ /** Moves the live vector-active pointer aside so recall falls back to text. */
1182
+ function retireVectorActive(reason) {
1183
+ const live = vectorActiveFile()
1184
+ const info = statOrNull(live)
1185
+ if (!info) return 'absent'
1186
+ if (info.isSymbolicLink()) {
1187
+ warn('backups: the live vector-active.json is a link; leaving it alone')
1188
+ return 'unreadable'
1189
+ }
1190
+ const aside = live + '.stale-' + isoStamp().replace(/[:.]/g, '-')
1191
+ try { fs.renameSync(live, aside) } catch (error) {
1192
+ throw new Error('the restored data has no usable vector-active manifest and the stale pointer could not be retired: ' + String(error?.message || error))
1193
+ }
1194
+ warn('backups: ' + reason + '; the stale vector-active pointer was moved to ' + path.basename(aside) + ' so recall falls back to lexical text')
1195
+ return 'cleared'
1196
+ }
1197
+
1198
+ /**
1199
+ * Puts a backup back. The target is leased and fully verified first, the live
1200
+ * root is saved as a safety backup second, and only then is anything written.
1201
+ * A failure after that point is recoverable: the safety backup holds the state
1202
+ * that was replaced, and it is protected from this operation's prune.
1203
+ */
1204
+ export async function restoreFromBackup(name, { beforeRestore = null, flushState = null, clearCaches = null, keep = BACKUP_KEEP } = {}) {
1205
+ return withBackupLock(async () => {
1206
+ const found = findBackup(name)
1207
+ const plan = verifyInventory(found)
1208
+ const vector = planVectorActive(found, plan.rels)
1209
+ writeLease(found.name, { pid: process.pid, at: Date.now(), kind: 'restore' })
1210
+ let safety = null
1211
+ try {
1212
+ const created = await (typeof beforeRestore === 'function'
1213
+ ? beforeRestore()
1214
+ : createBackup({ label: 'before-restore', flushState }))
1215
+ safety = typeof created === 'string' ? created : (created && created.dir ? created.dir : null)
1216
+ const rels = restoreOrder(plan.rels.filter(rel => rel !== 'index/vector-active.json' || vector.restore))
1217
+ for (const rel of rels) {
1218
+ const target = liveTargetFor(rel)
1219
+ if (rel.endsWith('.sqlite3')) dropCompanions(target)
1220
+ writeAtomicCopy(path.join(found.dir, rel.split('/').join(path.sep)), target)
1221
+ }
1222
+ const vectorActive = vector.restore
1223
+ ? 'restored'
1224
+ : retireVectorActive(vector.action === 'absent'
1225
+ ? 'this backup predates the vector generation journal'
1226
+ : 'the vector journal in this backup does not match the databases it contains')
1227
+ if (typeof clearCaches === 'function') clearCaches()
1228
+ const prune = pruneBackups({ keep, protect: safety ? [path.basename(safety)] : [] })
1229
+ return {
1230
+ restored: found.name,
1231
+ safety,
1232
+ files: rels.length,
1233
+ vectorActive,
1234
+ pruned: prune.deleted,
1235
+ pendingCleanup: prune.pendingCleanup,
1236
+ }
1237
+ } catch (error) {
1238
+ const reason = String(error?.message || error)
1239
+ warn('backups: restore of ' + found.name + ' failed: ' + reason)
1240
+ const wrapped = new Error(safety
1241
+ ? 'restore failed (' + reason + '); the live state it replaced is saved as ' + path.basename(safety)
1242
+ : 'restore failed (' + reason + ') and no safety backup could be made')
1243
+ wrapped.code = 'DSH_MEMU_BACKUP_RESTORE_FAILED'
1244
+ wrapped.cause = error
1245
+ wrapped.safety = safety ? path.basename(safety) : null
1246
+ // Whatever landed on disk is the truth now: cached readers must not keep
1247
+ // serving the half-replaced state.
1248
+ try { if (typeof clearCaches === 'function') clearCaches() } catch {}
1249
+ throw wrapped
1250
+ } finally {
1251
+ try { writeLease(found.name, null) } catch {}
1252
+ }
1253
+ })
1254
+ }