dsh-memu-memory 1.4.2 → 1.4.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (389) hide show
  1. package/AGENTS.md +108 -110
  2. package/CHANGELOG.md +169 -868
  3. package/LICENSE +21 -21
  4. package/README.md +368 -374
  5. package/README.zh.md +354 -360
  6. package/assets/icon.svg +7 -7
  7. package/cordis.patch.yml +8 -8
  8. package/docs/active-memory-ab.md +279 -385
  9. package/docs/binding-lifecycle.md +99 -99
  10. package/docs/client-conventions.md +75 -75
  11. package/docs/contributing.md +217 -217
  12. package/docs/emotion-model-spec.md +247 -281
  13. package/docs/env-and-commands.md +149 -152
  14. package/docs/host-adaptation.md +339 -360
  15. package/docs/host-api.md +131 -137
  16. package/docs/host-versions.md +117 -120
  17. package/docs/mcp-porting.md +146 -146
  18. package/docs/memory-semantics.md +271 -259
  19. package/docs/pending-work.md +44 -51
  20. package/docs/troubleshooting.md +909 -854
  21. package/lib/active-memory.js +160 -165
  22. package/lib/activity-log.js +207 -207
  23. package/lib/auto-link/apply.js +248 -249
  24. package/lib/auto-link/candidates.js +163 -163
  25. package/lib/auto-link/decide.js +300 -300
  26. package/lib/auto-link/normalize.js +99 -99
  27. package/lib/auto-link/policy.js +42 -42
  28. package/lib/auto-link/suppression.js +101 -101
  29. package/lib/auto-link/terminology.js +311 -311
  30. package/lib/backup.js +1254 -1254
  31. package/lib/binding-diagnostics.js +634 -634
  32. package/lib/budget.js +118 -118
  33. package/lib/client.js +9820 -9751
  34. package/lib/commitment.js +178 -138
  35. package/lib/consolidation-ledger.js +434 -438
  36. package/lib/consolidation-receipt.js +386 -387
  37. package/lib/consolidation-snapshot.js +420 -405
  38. package/lib/consolidation-worker.js +240 -241
  39. package/lib/context.js +33 -33
  40. package/lib/curator-evidence.js +131 -131
  41. package/lib/curator-policy.js +198 -202
  42. package/lib/curator.js +1813 -1811
  43. package/lib/cycle.js +524 -513
  44. package/lib/diagnostics.js +524 -524
  45. package/lib/embedding-catalog.js +1051 -1055
  46. package/lib/embedding-download.js +637 -607
  47. package/lib/embedding-runtime.js +946 -946
  48. package/lib/engine.js +1103 -1103
  49. package/lib/entity-repair.js +285 -285
  50. package/lib/environment-check.js +394 -394
  51. package/lib/fork-model.js +312 -312
  52. package/lib/freshness.js +128 -121
  53. package/lib/global-graph.js +389 -389
  54. package/lib/graph.js +1193 -1193
  55. package/lib/host-surface.js +30 -30
  56. package/lib/inbound.js +284 -281
  57. package/lib/index.js +506 -511
  58. package/lib/inject.js +2639 -2619
  59. package/lib/lexicon-scope.js +143 -143
  60. package/lib/lexicon.js +1183 -1192
  61. package/lib/lifecycle-audit.js +37 -0
  62. package/lib/local-embedding-entry.js +145 -145
  63. package/lib/local-embedding-manager.js +306 -306
  64. package/lib/local-embedding-protocol.js +210 -210
  65. package/lib/local-embedding-worker.js +682 -682
  66. package/lib/local-vector-service.js +506 -453
  67. package/lib/maintenance-ledger.js +138 -0
  68. package/lib/maintenance-review.js +103 -0
  69. package/lib/maintenance-runner.js +267 -0
  70. package/lib/managed-runtime.js +118 -118
  71. package/lib/media.js +607 -513
  72. package/lib/memory.js +5035 -4941
  73. package/lib/memu-config.js +213 -213
  74. package/lib/memu.js +565 -565
  75. package/lib/migrate.js +200 -200
  76. package/lib/mood.js +300 -300
  77. package/lib/paths.js +453 -457
  78. package/lib/port-surface.js +82 -82
  79. package/lib/preset-mount.js +79 -0
  80. package/lib/preset-scope.js +126 -126
  81. package/lib/private-links.js +567 -567
  82. package/lib/private.js +2198 -2209
  83. package/lib/prompts/global-curator.md +135 -135
  84. package/lib/prompts/image-caption.md +1 -1
  85. package/lib/prompts/private-consolidation.coding.md +39 -39
  86. package/lib/prompts/private-consolidation.md +32 -32
  87. package/lib/prompts/private-consolidation.mixed.md +37 -37
  88. package/lib/prompts/private-consolidation.rp.md +47 -47
  89. package/lib/prompts/private-policy.coding.md +35 -35
  90. package/lib/prompts/private-policy.md +36 -36
  91. package/lib/prompts/private-policy.mixed.md +29 -29
  92. package/lib/prompts/private-policy.rp.md +43 -43
  93. package/lib/prompts/system-guide.coding.md +20 -20
  94. package/lib/prompts/system-guide.md +25 -25
  95. package/lib/prompts/system-guide.mixed.md +22 -22
  96. package/lib/prompts/system-guide.rp.md +23 -23
  97. package/lib/prompts.js +331 -331
  98. package/lib/recall-cache.js +212 -212
  99. package/lib/remote-summary.js +123 -123
  100. package/lib/rpc.js +2531 -2532
  101. package/lib/salient-wake.js +438 -438
  102. package/lib/snippet.js +125 -125
  103. package/lib/state.js +1948 -1928
  104. package/lib/stats.js +236 -236
  105. package/lib/temporal.js +345 -348
  106. package/lib/text-retrieval.js +992 -1001
  107. package/lib/text-similarity.js +305 -305
  108. package/lib/tokenizer-v2.js +271 -271
  109. package/lib/tools.js +1098 -1091
  110. package/lib/turn-log.js +545 -545
  111. package/lib/vector-migration.js +928 -930
  112. package/lib/vector-profile.js +1353 -1359
  113. package/lib/visibility.js +59 -59
  114. package/lib/webui/graph-LICENSE.txt +1 -1
  115. package/lib/webui/graph-view.bundle.js +2 -2
  116. package/lib/webui/graph-view.js +1171 -1175
  117. package/lib/webui/mark.svg +7 -7
  118. package/lib/webui/standalone.css +1178 -1178
  119. package/lib/webui/standalone.js +238 -238
  120. package/lib/webui.js +136 -136
  121. package/lib/worker-pool.js +1015 -979
  122. package/package.json +153 -153
  123. package/requirements.lock +34 -34
  124. package/scripts/acceptance-local.mjs +946 -946
  125. package/scripts/active-memory-ab-live.mjs +653 -655
  126. package/scripts/active-memory-ab.mjs +1302 -1302
  127. package/scripts/audit-memory-lifecycle.mjs +55 -0
  128. package/scripts/bench-recall.mjs +142 -142
  129. package/scripts/build-graph.mjs +44 -45
  130. package/scripts/chain-matrix.mjs +541 -541
  131. package/scripts/check-all.mjs +68 -74
  132. package/scripts/check-doc-drift.mjs +547 -547
  133. package/scripts/check-graph-browser.mjs +261 -261
  134. package/scripts/check-i18n.mjs +81 -83
  135. package/scripts/check-idle-compositing.mjs +61 -61
  136. package/scripts/check-seed-compat.mjs +115 -118
  137. package/scripts/check-text-format.mjs +55 -0
  138. package/scripts/curator-pair-calibrate.mjs +259 -259
  139. package/scripts/diagnose-bindings.mjs +176 -176
  140. package/scripts/drive-session.mjs +863 -864
  141. package/scripts/engine-smoke.mjs +69 -69
  142. package/scripts/entity-dedupe.mjs +110 -110
  143. package/scripts/lexicon-calibrate.mjs +230 -230
  144. package/scripts/lexicon-dedupe.mjs +318 -318
  145. package/scripts/local-runtime-install.mjs +142 -142
  146. package/scripts/local-runtime-verify.mjs +56 -56
  147. package/scripts/local-vector-verify.mjs +93 -93
  148. package/scripts/make-readme-shots.mjs +59 -59
  149. package/scripts/migrate-visibility.mjs +94 -94
  150. package/scripts/mock-llm.mjs +938 -903
  151. package/scripts/preview.mjs +58 -58
  152. package/scripts/prune-sessions.mjs +31 -34
  153. package/scripts/prune-turnlogs.mjs +29 -30
  154. package/scripts/prune-vectors.mjs +24 -24
  155. package/scripts/rebuild-auto-links.mjs +252 -252
  156. package/scripts/recall-bench.mjs +820 -820
  157. package/scripts/repetition-ab-scenarios.mjs +93 -93
  158. package/scripts/repetition-detector-snapshot.mjs +314 -314
  159. package/scripts/repetition-eval-live.mjs +360 -360
  160. package/scripts/repetition-eval.mjs +702 -702
  161. package/scripts/replay.mjs +705 -575
  162. package/scripts/setup.mjs +46 -46
  163. package/scripts/simulate-injection.mjs +299 -301
  164. package/tests/absorb-review.test.mjs +354 -354
  165. package/tests/activation.test.mjs +89 -89
  166. package/tests/active-memory-ab.test.mjs +745 -745
  167. package/tests/active-memory.test.mjs +129 -129
  168. package/tests/activity-log.test.mjs +126 -126
  169. package/tests/activity-wiring.test.mjs +155 -155
  170. package/tests/appendix-b.test.mjs +217 -217
  171. package/tests/appendix-b2.test.mjs +166 -166
  172. package/tests/audit-batch3.test.mjs +247 -247
  173. package/tests/audit-regression.test.mjs +275 -275
  174. package/tests/audit-safety.test.mjs +227 -227
  175. package/tests/auto-link-candidates.test.mjs +245 -245
  176. package/tests/auto-link-decide.test.mjs +512 -512
  177. package/tests/auto-link-migration.test.mjs +133 -133
  178. package/tests/backend-compensation.test.mjs +272 -272
  179. package/tests/backup.test.mjs +793 -793
  180. package/tests/binding-diagnostics.test.mjs +720 -720
  181. package/tests/browser.test.mjs +476 -476
  182. package/tests/client-export.test.mjs +521 -521
  183. package/tests/client-render.test.mjs +2008 -1728
  184. package/tests/coalesce.test.mjs +113 -113
  185. package/tests/commitment.test.mjs +243 -144
  186. package/tests/config.test.mjs +159 -159
  187. package/tests/consolidation-credential.test.mjs +330 -330
  188. package/tests/consolidation-feed.test.mjs +122 -122
  189. package/tests/consolidation-fork.test.mjs +1586 -1539
  190. package/tests/consolidation-ledger.test.mjs +389 -389
  191. package/tests/consolidation-snapshot.test.mjs +567 -505
  192. package/tests/consolidation-value.test.mjs +89 -89
  193. package/tests/context-scope.test.mjs +40 -40
  194. package/tests/cross-library-recall.test.mjs +269 -269
  195. package/tests/cue.test.mjs +58 -58
  196. package/tests/curator-absorb.test.mjs +444 -444
  197. package/tests/curator-calibrate.test.mjs +173 -173
  198. package/tests/curator-clusters.test.mjs +306 -306
  199. package/tests/curator-commit.test.mjs +325 -325
  200. package/tests/curator-contract.test.mjs +191 -191
  201. package/tests/curator-evidence.test.mjs +102 -102
  202. package/tests/curator-link.test.mjs +317 -317
  203. package/tests/curator-pairing.test.mjs +339 -339
  204. package/tests/curator-probe.test.mjs +490 -490
  205. package/tests/curator-review-mode.test.mjs +315 -315
  206. package/tests/curator.test.mjs +152 -152
  207. package/tests/cycle.test.mjs +567 -568
  208. package/tests/diagnostics.test.mjs +278 -278
  209. package/tests/disclosure.test.mjs +249 -249
  210. package/tests/doc-drift.test.mjs +342 -342
  211. package/tests/drive-session.test.mjs +152 -152
  212. package/tests/dynamic-rrf.test.mjs +182 -182
  213. package/tests/dynamic-threshold.test.mjs +52 -52
  214. package/tests/embedding-catalog.test.mjs +374 -374
  215. package/tests/embedding-download.test.mjs +529 -486
  216. package/tests/embedding-runtime.test.mjs +449 -449
  217. package/tests/emotion-chain.test.mjs +84 -84
  218. package/tests/emotion-contract.test.mjs +445 -445
  219. package/tests/engine.test.mjs +108 -108
  220. package/tests/entity-merge.test.mjs +278 -278
  221. package/tests/environment-check.test.mjs +187 -187
  222. package/tests/fact-version.test.mjs +146 -146
  223. package/tests/fixtures/active-memory-ab/README.md +56 -56
  224. package/tests/fixtures/active-memory-ab/cases/01-clean-dense-turn.json +351 -351
  225. package/tests/fixtures/active-memory-ab/cases/02-clean-thin-turn.json +122 -122
  226. package/tests/fixtures/active-memory-ab/cases/03-clean-starved-small.json +125 -125
  227. package/tests/fixtures/active-memory-ab/cases/04-clean-large-thin.json +137 -137
  228. package/tests/fixtures/active-memory-ab/cases/05-clean-half-step.json +166 -166
  229. package/tests/fixtures/active-memory-ab/cases/06-clean-duplicate-reread.json +197 -197
  230. package/tests/fixtures/active-memory-ab/cases/07-clean-recent-recall.json +125 -125
  231. package/tests/fixtures/active-memory-ab/cases/08-global-relevant.json +111 -111
  232. package/tests/fixtures/active-memory-ab/cases/09-global-irrelevant-conflict.json +158 -158
  233. package/tests/fixtures/active-memory-ab/cases/10-no-human-turn.json +97 -97
  234. package/tests/fixtures/active-memory-ab/cases/11-clean-scale-100.json +137 -137
  235. package/tests/fixtures/active-memory-ab/cases/12-clean-scale-1000.json +137 -137
  236. package/tests/fixtures/active-memory-ab/cases/13-clean-scale-5000.json +137 -137
  237. package/tests/fixtures/active-memory-ab/cases/14-clean-scale-20000.json +137 -137
  238. package/tests/fixtures/active-memory-ab/lead-ai-reviewed-reference.json +191 -191
  239. package/tests/fixtures/active-memory-ab/manifest.json +199 -199
  240. package/tests/fixtures/curator-pairs/labeled.v1.jsonl +90 -90
  241. package/tests/fixtures/lexicon-stub-hooks.mjs +15 -15
  242. package/tests/fixtures/lexicon-stub.mjs +284 -284
  243. package/tests/fixtures/mock-llm/reply.txt +1 -1
  244. package/tests/fixtures/recall-bench/01-paraphrase.json +183 -183
  245. package/tests/fixtures/recall-bench/02-exact.json +152 -152
  246. package/tests/fixtures/recall-bench/03-negation.json +172 -172
  247. package/tests/fixtures/recall-bench/04-no-answer.json +161 -161
  248. package/tests/fixtures/recall-bench/05-conflict.json +193 -193
  249. package/tests/fixtures/recall-bench/06-boundary.json +272 -272
  250. package/tests/fixtures/recall-bench/07-secret.json +190 -190
  251. package/tests/fixtures/recall-bench/08-coding.json +163 -163
  252. package/tests/fixtures/recall-bench-gold-candidates/01-paraphrase.json +193 -193
  253. package/tests/fixtures/recall-bench-gold-candidates/02-exact.json +197 -197
  254. package/tests/fixtures/recall-bench-gold-candidates/03-negation.json +244 -244
  255. package/tests/fixtures/recall-bench-gold-candidates/04-no-answer.json +189 -189
  256. package/tests/fixtures/recall-bench-gold-candidates/05-conflict.json +245 -245
  257. package/tests/fixtures/recall-bench-gold-candidates/06-boundary.json +279 -279
  258. package/tests/fixtures/recall-bench-gold-candidates/07-secret.json +224 -224
  259. package/tests/fixtures/recall-bench-gold-candidates/08-coding.json +218 -218
  260. package/tests/fixtures/repetition-eval/01-zh-rp.json +92 -92
  261. package/tests/fixtures/repetition-eval/02-en.json +96 -96
  262. package/tests/fixtures/repetition-eval/03-code.json +90 -90
  263. package/tests/fixtures/repetition-eval/04-names.json +115 -115
  264. package/tests/fixtures/repetition-eval/05-user-quote.json +95 -95
  265. package/tests/fixtures/repetition-eval/06-agreement.json +85 -85
  266. package/tests/fixtures/tokenizer-cases.mjs +27 -27
  267. package/tests/fork-model.test.mjs +345 -345
  268. package/tests/freshness.test.mjs +140 -140
  269. package/tests/global-graph.test.mjs +106 -106
  270. package/tests/global-lifecycle.test.mjs +149 -149
  271. package/tests/graph-cascade.test.mjs +363 -363
  272. package/tests/graph-view.test.mjs +414 -414
  273. package/tests/graph.test.mjs +371 -371
  274. package/tests/help-page.test.mjs +416 -416
  275. package/tests/hook-order.test.mjs +72 -72
  276. package/tests/humanlike.test.mjs +232 -232
  277. package/tests/hybrid-recall.test.mjs +610 -610
  278. package/tests/inbound.test.mjs +441 -441
  279. package/tests/inject-conflict.test.mjs +173 -173
  280. package/tests/inject-guide.test.mjs +513 -513
  281. package/tests/inject.test.mjs +384 -384
  282. package/tests/injection-budget-settings.test.mjs +35 -35
  283. package/tests/injection-budget.test.mjs +165 -165
  284. package/tests/injection-chain.test.mjs +442 -442
  285. package/tests/injection-intent-budget.test.mjs +92 -92
  286. package/tests/injection-rollback.test.mjs +428 -428
  287. package/tests/issue2-chain.test.mjs +169 -169
  288. package/tests/lexical-bm25.test.mjs +171 -171
  289. package/tests/lexicon-calibrate.test.mjs +48 -48
  290. package/tests/lexicon-dedupe.test.mjs +171 -171
  291. package/tests/lexicon-frequency.test.mjs +195 -195
  292. package/tests/lexicon-inject.test.mjs +459 -459
  293. package/tests/lexicon-perf.test.mjs +464 -464
  294. package/tests/lexicon-scope.test.mjs +256 -256
  295. package/tests/lexicon-ui.test.mjs +667 -667
  296. package/tests/lexicon.test.mjs +922 -922
  297. package/tests/lifecycle-audit.test.mjs +56 -0
  298. package/tests/loader-register.mjs +3 -3
  299. package/tests/loader.mjs +17 -17
  300. package/tests/local-embedding-entry.test.mjs +95 -95
  301. package/tests/local-embedding-env.test.mjs +51 -51
  302. package/tests/local-embedding-manager.test.mjs +494 -494
  303. package/tests/local-embedding-protocol.test.mjs +121 -121
  304. package/tests/local-embedding-worker.test.mjs +440 -440
  305. package/tests/local-vector-service.test.mjs +41 -0
  306. package/tests/maintenance-status.test.mjs +77 -0
  307. package/tests/maintenance.test.mjs +438 -0
  308. package/tests/managed-memory.test.mjs +1234 -1234
  309. package/tests/managed-runtime.test.mjs +72 -72
  310. package/tests/media-injection.test.mjs +225 -0
  311. package/tests/media.test.mjs +135 -135
  312. package/tests/memory-chain.test.mjs +169 -169
  313. package/tests/memory-fields.test.mjs +134 -134
  314. package/tests/memu-resident-route.test.mjs +130 -130
  315. package/tests/memu-resident.test.mjs +33 -33
  316. package/tests/migration-payload.test.mjs +40 -42
  317. package/tests/mock-llm.test.mjs +263 -225
  318. package/tests/mood.test.mjs +109 -109
  319. package/tests/multiprocess.test.mjs +29 -29
  320. package/tests/negation-polarity.test.mjs +135 -135
  321. package/tests/new-session-gate.test.mjs +617 -617
  322. package/tests/open-loop-date.test.mjs +416 -416
  323. package/tests/ops-hardening.test.mjs +209 -209
  324. package/tests/package-shipping.test.mjs +88 -88
  325. package/tests/pending-injection.test.mjs +107 -107
  326. package/tests/port-surface.test.mjs +138 -138
  327. package/tests/preset-mount.test.mjs +124 -0
  328. package/tests/preset-scope.test.mjs +212 -212
  329. package/tests/private-links.test.mjs +493 -493
  330. package/tests/prompt-semantics.test.mjs +51 -51
  331. package/tests/prompts.test.mjs +315 -315
  332. package/tests/query-decompose.test.mjs +62 -62
  333. package/tests/react-snapshot.test.mjs +24 -24
  334. package/tests/recall-bench.test.mjs +317 -317
  335. package/tests/recall-cache.test.mjs +292 -292
  336. package/tests/recall-corpus-eligibility.test.mjs +51 -51
  337. package/tests/recall-dedup.test.mjs +446 -446
  338. package/tests/recall-intent.test.mjs +172 -172
  339. package/tests/regression-sweep.test.mjs +311 -311
  340. package/tests/reminder-fairness.test.mjs +55 -0
  341. package/tests/remote.test.mjs +140 -140
  342. package/tests/rename.test.mjs +30 -30
  343. package/tests/repetition-detector-snapshot.test.mjs +231 -231
  344. package/tests/repetition-eval-live.test.mjs +177 -177
  345. package/tests/repetition-eval.test.mjs +373 -373
  346. package/tests/salience-domain.test.mjs +173 -173
  347. package/tests/salient-date.test.mjs +142 -142
  348. package/tests/salient-wake.test.mjs +389 -389
  349. package/tests/settings-beat.test.mjs +222 -222
  350. package/tests/settings-coverage.test.mjs +97 -97
  351. package/tests/settings-plumbing.test.mjs +79 -79
  352. package/tests/short-term.test.mjs +182 -166
  353. package/tests/sidebar-beat.test.mjs +213 -213
  354. package/tests/sidebar-refresh.test.mjs +123 -123
  355. package/tests/sidebar.test.mjs +102 -74
  356. package/tests/simulate-injection.test.mjs +76 -76
  357. package/tests/slot-similarity.test.mjs +153 -153
  358. package/tests/snippet.test.mjs +79 -79
  359. package/tests/source-kind.test.mjs +52 -52
  360. package/tests/speaker-provenance.test.mjs +120 -120
  361. package/tests/stale-maintenance.test.mjs +206 -131
  362. package/tests/state-gc.test.mjs +34 -34
  363. package/tests/state.test.mjs +155 -155
  364. package/tests/stats.test.mjs +112 -112
  365. package/tests/storage.test.mjs +125 -125
  366. package/tests/stubs/child-process-spy.mjs +14 -14
  367. package/tests/stubs/dsh-llm-pi-ai.js +13 -13
  368. package/tests/stubs/dsh-llm.js +5 -5
  369. package/tests/stubs/dsh-schedule.js +140 -140
  370. package/tests/stubs/dsh-session-query.js +26 -26
  371. package/tests/stubs/dsh-session.js +7 -7
  372. package/tests/stubs/dsh-tools.js +101 -101
  373. package/tests/temporal-repair.test.mjs +78 -0
  374. package/tests/temporal.test.mjs +124 -124
  375. package/tests/text-format.test.mjs +24 -0
  376. package/tests/tokenizer-v2.test.mjs +142 -142
  377. package/tests/tool-schema.test.mjs +126 -126
  378. package/tests/tools.test.mjs +810 -810
  379. package/tests/turn-log.test.mjs +487 -487
  380. package/tests/ui-defaults.test.mjs +57 -57
  381. package/tests/update-fields.test.mjs +138 -138
  382. package/tests/vector-gc.test.mjs +37 -37
  383. package/tests/vector-migration.test.mjs +810 -810
  384. package/tests/vector-profile.test.mjs +449 -449
  385. package/tests/visibility-migration.test.mjs +152 -152
  386. package/tests/webui-auth.test.mjs +963 -963
  387. package/tests/webui.test.mjs +421 -421
  388. package/tests/windows-env.test.mjs +89 -89
  389. package/tests/worker-lifecycle.test.mjs +1521 -1429
package/lib/engine.js CHANGED
@@ -1,1103 +1,1103 @@
1
- import fs from 'node:fs'
2
- import fsp from 'node:fs/promises'
3
- import os from 'node:os'
4
- import path from 'node:path'
5
- import crypto from 'node:crypto'
6
- import { spawn } from 'node:child_process'
7
- import { fileURLToPath } from 'node:url'
8
- import {
9
- dataDir, engineDir, downloadsDir, logsDir, librariesDir, ensureDir, readJson, writeJson, stamp, windowsSystemEnv,
10
- } from './paths.js'
11
- import { getSettings, globalDbPath } from './state.js'
12
- import { ensureManagedPython } from './managed-runtime.js'
13
-
14
- const HERE = path.dirname(fileURLToPath(import.meta.url))
15
- const LOCK_PATH = path.join(HERE, '..', 'requirements.lock')
16
-
17
- export const ENGINE_VERSION = '0.11.0b3'
18
- export const REQUIRED_COMMANDS = ['retrieve', 'list-files', 'commit']
19
- export const OPTIONAL_COMMANDS = ['search', 'memorize']
20
-
21
- const STATE_FILE = () => path.join(engineDir(), 'state.json')
22
- const CURRENT_FILE = () => path.join(engineDir(), 'current.json')
23
- const LOCK_FILE = () => path.join(engineDir(), 'install.lock')
24
- const INSTALL_LOG = () => path.join(logsDir(), 'install.log')
25
- const AVAILABLE_FILE = () => path.join(engineDir(), 'available-versions.json')
26
-
27
- const VERSION_CACHE_MS = 5 * 60 * 1000
28
- // Persisted version lists are good enough to show without a network round trip.
29
- const PERSISTED_TTL_MS = 24 * 60 * 60 * 1000
30
- let versionCache = { at: 0, value: null }
31
-
32
- // 本进程是否正在装引擎。`engineStatus` 每次轮询都会跑一次中断收尾,必须能把
33
- // 「自己正在跑的安装」和「上次死掉的安装」分开,否则会把自己判成中断。
34
- let installInFlight = false
35
- // 多久没有进展就认定安装已死。与 acquireLock 的过期锁阈值保持一致(30 分钟),
36
- // 这样一个僵死安装会在状态、锁、界面三处同时被判定为过期。
37
- const STALE_INSTALL_MS = 30 * 60 * 1000
38
-
39
- // Compare PEP 440-ish versions without a dependency. A plain release is newer
40
- // than a pre-release of the same number (`0.11.0` > `0.11.0b3`).
41
- export function compareVersions(a, b) {
42
- const split = (value) => {
43
- const text = String(value || '').trim()
44
- const match = text.match(/^(\d+)\.(\d+)\.(\d+)(.*)$/)
45
- if (!match) return { nums: [0, 0, 0], pre: text }
46
- return { nums: [Number(match[1]), Number(match[2]), Number(match[3])], pre: match[4] || '' }
47
- }
48
- const left = split(a)
49
- const right = split(b)
50
- for (let i = 0; i < 3; i += 1) {
51
- if (left.nums[i] !== right.nums[i]) return left.nums[i] - right.nums[i]
52
- }
53
- if (left.pre === right.pre) return 0
54
- if (!left.pre) return 1
55
- if (!right.pre) return -1
56
- return left.pre.localeCompare(right.pre, undefined, { numeric: true })
57
- }
58
-
59
- export function normalizeVersion(raw) {
60
- const match = String(raw || '').match(/^(\d+\.\d+\.\d+(?:[A-Za-z]+\d*)?)/)
61
- return match ? match[1] : null
62
- }
63
-
64
- export function parseSimpleVersions(html) {
65
- const found = new Set()
66
- // The distribution is `memu-cli`, while the CLI command is `memu`. Match the
67
- // distribution name here; matching bare `memu` picks up the unrelated MeMu
68
- // Game Boy package that owns that PyPI name.
69
- const re = /memu[_-]cli-(\d[0-9A-Za-z.]*[0-9A-Za-z])[-.]/g
70
- let match
71
- while ((match = re.exec(String(html || ''))) !== null) {
72
- const version = normalizeVersion(match[1])
73
- if (version) found.add(version)
74
- }
75
- return [...found]
76
- }
77
-
78
- export function readAvailableVersions() {
79
- try {
80
- const cached = readJson(AVAILABLE_FILE(), null)
81
- if (cached && cached.package === 'memu-cli' && Array.isArray(cached.versions)) return cached
82
- } catch {}
83
- return null
84
- }
85
-
86
- // The plugin never silently installs the newest release (CLI/JSON changes are
87
- // real), but it can still answer "what exists?" without the user leaving Settings.
88
- // PyPI JSON is tried first; the mirrors only expose simple indexes, so their HTML
89
- // is parsed as a fallback. Failures are reported, never thrown into the page.
90
- export async function fetchAvailableVersions({ force = false, timeoutMs = 6000 } = {}) {
91
- if (!force) {
92
- if (versionCache.value && Date.now() - versionCache.at < VERSION_CACHE_MS) {
93
- return { ...versionCache.value, cached: true }
94
- }
95
- // A cold process used to re-query PyPI every time Settings opened, and with
96
- // pypi.org unreachable that meant waiting out every timeout in turn. A
97
- // day-old answer is fine for a "what could I install" list.
98
- const persisted = readAvailableVersions()
99
- const fetchedAt = Date.parse(persisted?.fetchedAt || '') || 0
100
- if (persisted && fetchedAt > 0 && Date.now() - fetchedAt < PERSISTED_TTL_MS) {
101
- versionCache = { at: fetchedAt, value: persisted }
102
- return { ...persisted, cached: true }
103
- }
104
- }
105
- // Mirrors first: the package is mirrored in full, and pypi.org is the slowest
106
- // of these from mainland China.
107
- const sources = [
108
- { name: 'Tsinghua', url: 'https://pypi.tuna.tsinghua.edu.cn/pypi/memu-cli/json', json: true },
109
- { name: 'Aliyun', url: 'https://mirrors.aliyun.com/pypi/simple/memu-cli/', json: false },
110
- { name: 'PyPI', url: 'https://pypi.org/pypi/memu-cli/json', json: true },
111
- { name: 'Tsinghua-simple', url: 'https://pypi.tuna.tsinghua.edu.cn/simple/memu-cli/', json: false },
112
- { name: 'PyPI-simple', url: 'https://pypi.org/simple/memu-cli/', json: false },
113
- ]
114
- const errors = []
115
- for (const source of sources) {
116
- try {
117
- const response = await fetch(source.url, {
118
- headers: { accept: source.json ? 'application/json' : 'text/html' },
119
- signal: AbortSignal.timeout(timeoutMs),
120
- })
121
- if (!response.ok) throw new Error(`HTTP ${response.status}`)
122
- const body = source.json ? await response.json() : await response.text()
123
- const releases = body?.releases ?? body?.info?.releases ?? {}
124
- const versions = source.json
125
- ? Object.keys(releases)
126
- : parseSimpleVersions(body)
127
- const clean = [...new Set(versions.map(normalizeVersion).filter(Boolean))]
128
- .sort((a, b) => compareVersions(b, a))
129
- if (clean.length === 0) throw new Error('no versions in response')
130
- const value = {
131
- ok: true,
132
- package: 'memu-cli',
133
- source: source.name,
134
- versions: clean.slice(0, 40),
135
- latest: clean[0],
136
- fetchedAt: stamp(),
137
- }
138
- versionCache = { at: Date.now(), value }
139
- try { writeJson(AVAILABLE_FILE(), value) } catch {}
140
- return { ...value, cached: false }
141
- } catch (error) {
142
- errors.push(`${source.name}: ${error?.message || error}`)
143
- }
144
- }
145
- const persisted = readAvailableVersions()
146
- if (persisted) return { ...persisted, ok: false, cached: true, errors }
147
- return { ok: false, versions: [], latest: null, errors, fetchedAt: stamp() }
148
- }
149
-
150
- const DEFAULT_INDEXES = [
151
- 'https://pypi.tuna.tsinghua.edu.cn/simple',
152
- 'https://mirrors.aliyun.com/pypi/simple/',
153
- 'https://pypi.org/simple',
154
- ]
155
-
156
- function isWindows() {
157
- return process.platform === 'win32'
158
- }
159
-
160
- function isMac() {
161
- return process.platform === 'darwin'
162
- }
163
-
164
- // macOS library validation rejects the ad-hoc-signed `.so` files inside PyPI
165
- // wheels when the running interpreter itself is Developer-ID signed with the
166
- // hardened runtime (python-build-standalone: the uv-managed Python and the DSH
167
- // bundled runtime). The dlopen error names "different Team IDs"; ad-hoc
168
- // re-signing the interpreter drops the hardened runtime flag and lets every
169
- // wheel load. Matched against verifyEngine's error text so the repair only
170
- // fires on real signature failures, never on unrelated import errors.
171
- export function isMacOSLibraryValidationError(text) {
172
- return /code signature|different Team IDs|SignatureInvalid|library validation/i.test(String(text || ''))
173
- }
174
-
175
- // Best-effort: codesign always exists on macOS, but re-signing an interpreter
176
- // we don't own (Homebrew, python.org) may fail on permissions; callers treat
177
- // `false` as "repair unavailable" and let the normal error path report.
178
- async function resignDarwinInterpreter(python, log) {
179
- if (!isMac()) return false
180
- let target = python
181
- try { target = fs.realpathSync(python) } catch {}
182
- logLine(`re-signing interpreter ad-hoc (macOS library validation): ${target}`, log)
183
- const res = await run('/usr/bin/codesign', ['--force', '--sign', '-', target], { timeoutMs: 60_000 })
184
- if (res.code !== 0) {
185
- logLine(`codesign failed: ${(res.stderr || res.stdout || '').trim().slice(-200)}`, log)
186
- return false
187
- }
188
- // Files written by other tools can carry a quarantine xattr that would break
189
- // the next exec even with a valid signature; clearing it is harmless if absent.
190
- await run('/usr/bin/xattr', ['-d', 'com.apple.quarantine', target], { timeoutMs: 15_000 })
191
- return true
192
- }
193
-
194
- // verifyEngine plus the macOS signature repair: on a signature-shaped failure,
195
- // re-sign the venv's base interpreter once and verify again before declaring
196
- // the candidate broken. Every verify site goes through here so existing
197
- // installs self-heal on the next ensure/install too.
198
- async function verifyEngineRepaired(python, { log, expectedVersion = null } = {}) {
199
- const verified = await verifyEngine(python, { log, expectedVersion })
200
- if (verified.ok || !isMac() || !isMacOSLibraryValidationError(verified.error)) return verified
201
- logLine(`verify failed with a macOS code-signature error; repairing and retrying`, log)
202
- await resignDarwinInterpreter(python, log)
203
- return verifyEngine(python, { log, expectedVersion })
204
- }
205
-
206
- export function venvPython(venv) {
207
- return isWindows()
208
- ? path.join(venv, 'Scripts', 'python.exe')
209
- : path.join(venv, 'bin', 'python3')
210
- }
211
-
212
- function run(cmd, args, opts = {}) {
213
- return new Promise((resolve) => {
214
- const child = spawn(cmd, args, {
215
- cwd: opts.cwd,
216
- env: { ...windowsSystemEnv(), ...process.env, ...(opts.env || {}) },
217
- windowsHide: true,
218
- stdio: ['ignore', 'pipe', 'pipe'],
219
- })
220
- let stdout = ''
221
- let stderr = ''
222
- let timedOut = false
223
- const timer = setTimeout(() => {
224
- timedOut = true
225
- try { child.kill() } catch {}
226
- }, opts.timeoutMs ?? 120_000)
227
- child.stdout?.on('data', (d) => {
228
- const s = d.toString()
229
- stdout += s
230
- opts.onData?.(s)
231
- })
232
- child.stderr?.on('data', (d) => {
233
- const s = d.toString()
234
- stderr += s
235
- opts.onData?.(s)
236
- })
237
- child.on('error', (error) => {
238
- clearTimeout(timer)
239
- resolve({ code: -1, stdout, stderr, error, timedOut })
240
- })
241
- child.on('close', (code) => {
242
- clearTimeout(timer)
243
- resolve({ code, stdout, stderr, timedOut })
244
- })
245
- })
246
- }
247
-
248
- function logLine(message, sink) {
249
- const line = `[${stamp()}] ${message}`
250
- try {
251
- ensureDir(logsDir())
252
- fs.appendFileSync(INSTALL_LOG(), line + '\n', 'utf8')
253
- } catch {}
254
- try { sink?.(line) } catch {}
255
- }
256
-
257
- function readState() {
258
- return readJson(STATE_FILE(), {}) || {}
259
- }
260
-
261
- function writeState(patch) {
262
- const next = { ...readState(), ...patch, updatedAt: stamp() }
263
- writeJson(STATE_FILE(), next)
264
- return next
265
- }
266
-
267
- export function readCurrent() {
268
- const current = readJson(CURRENT_FILE(), null)
269
- if (!current || typeof current.python !== 'string' || typeof current.venv !== 'string') return null
270
- return current
271
- }
272
-
273
- // Every version this machine has actually installed, kept so the engine page can
274
- // offer a rollback target after the plugin itself is upgraded. It is a record of
275
- // intent; `listEngineVersions` still verifies the venv is really on disk.
276
- const HISTORY_FILE = () => engineDir('history.json')
277
-
278
- function readHistory() {
279
- const raw = readJson(HISTORY_FILE(), null)
280
- return raw && typeof raw === 'object' ? raw : {}
281
- }
282
-
283
- function recordHistory(entry) {
284
- const history = readHistory()
285
- history[entry.version] = {
286
- ...history[entry.version],
287
- ...entry,
288
- }
289
- writeJson(HISTORY_FILE(), history)
290
- return history
291
- }
292
-
293
- function entryFromCurrent(current) {
294
- return {
295
- version: current.version,
296
- venv: current.venv,
297
- python: current.python,
298
- commands: current.commands || null,
299
- mirror: current.mirror || null,
300
- installedAt: current.installedAt || current.switchedAt || null,
301
- }
302
- }
303
-
304
- // Installs made before the history file existed (or a history file removed by
305
- // hand) otherwise render as a bare version row with no install time or mirror.
306
- // `current.json` still has that data, so backfill it once on the next read.
307
- function ensureHistory(current = readCurrent()) {
308
- const history = readHistory()
309
- if (!current) return history
310
- const known = history[current.version]
311
- if (known?.installedAt && known?.mirror) return history
312
- const fresh = entryFromCurrent(current)
313
- history[current.version] = {
314
- ...fresh,
315
- ...known,
316
- installedAt: known?.installedAt || fresh.installedAt,
317
- mirror: known?.mirror || fresh.mirror,
318
- commands: known?.commands || fresh.commands,
319
- venv: known?.venv || fresh.venv,
320
- python: known?.python || fresh.python,
321
- }
322
- try { writeJson(HISTORY_FILE(), history) } catch {}
323
- return history
324
- }
325
-
326
- // Walking a venv is thousands of stat() calls; doing it on every `getState`
327
- // made opening Settings slow. The number is stable until the version is
328
- // reinstalled, so it is remembered in history.json and memoised per process.
329
- const sizeCache = new Map()
330
- const sizedThisSession = new Set()
331
-
332
- function rememberedSize(version) {
333
- try {
334
- const history = JSON.parse(fs.readFileSync(HISTORY_FILE(), 'utf8'))
335
- const bytes = history?.[version]?.sizeBytes
336
- return Number.isFinite(bytes) ? bytes : null
337
- } catch {
338
- return null
339
- }
340
- }
341
-
342
- function rememberSize(version, bytes) {
343
- try {
344
- const history = JSON.parse(fs.readFileSync(HISTORY_FILE(), 'utf8'))
345
- if (!history?.[version]) return
346
- if (history[version].sizeBytes === bytes) return
347
- history[version].sizeBytes = bytes
348
- writeJson(HISTORY_FILE(), history)
349
- } catch {}
350
- }
351
-
352
- function sizeOfVersion(version, dir) {
353
- if (sizeCache.has(version)) return sizeCache.get(version)
354
- const stored = rememberedSize(version)
355
- const bytes = stored === null ? dirSizeBytes(dir) : stored
356
- sizeCache.set(version, bytes)
357
- if (stored === null && !sizedThisSession.has(version)) {
358
- sizedThisSession.add(version)
359
- rememberSize(version, bytes)
360
- }
361
- return bytes
362
- }
363
-
364
- function dirSizeBytes(dir) {
365
- let total = 0
366
- const walk = (current) => {
367
- let names = []
368
- try { names = fs.readdirSync(current, { withFileTypes: true }) } catch { return }
369
- for (const entry of names) {
370
- const full = path.join(current, entry.name)
371
- if (entry.isDirectory()) { walk(full); continue }
372
- try { total += fs.statSync(full).size } catch {}
373
- }
374
- }
375
- walk(dir)
376
- return total
377
- }
378
-
379
- function recordProbe(version, verified) {
380
- try {
381
- const history = ensureHistory(readCurrent())
382
- const entry = history[version] || {}
383
- history[version] = {
384
- ...entry,
385
- version,
386
- probe: verified?.ok
387
- ? { ok: true, at: stamp() }
388
- : { ok: false, at: stamp(), error: String(verified?.error || 'probe failed').slice(0, 300) },
389
- commands: verified?.commands || entry.commands || null,
390
- }
391
- writeJson(HISTORY_FILE(), history)
392
- } catch {}
393
- }
394
-
395
- export function listEngineVersions({ withSize = false } = {}) {
396
- const current = readCurrent()
397
- const history = ensureHistory(current)
398
- const names = new Set([...Object.keys(history), ENGINE_VERSION])
399
- // A directory can exist without a history entry (hand-copied venv, an install
400
- // interrupted before the record), so scan the tree too.
401
- try {
402
- for (const name of fs.readdirSync(engineDir())) {
403
- if (fs.existsSync(path.join(engineDir(), name, 'venv'))) names.add(name)
404
- }
405
- } catch {}
406
- return [...names]
407
- .filter(Boolean)
408
- .map((version) => {
409
- const known = history[version]
410
- const venv = known?.venv || engineDir(version, 'venv')
411
- const python = known?.python || venvPython(venv)
412
- const installed = fs.existsSync(venv)
413
- // "installed" only means a venv directory is there. "usable" means a probe
414
- // actually ran it: a venv whose python was deleted, or whose deps were
415
- // half-installed, still passes the directory check.
416
- const probe = known?.probe || null
417
- const usable = installed ? (probe ? probe.ok === true : null) : false
418
- return {
419
- version,
420
- installed,
421
- usable,
422
- probeAt: probe?.at || null,
423
- probeError: probe && probe.ok === false ? probe.error || 'probe failed' : null,
424
- schemaVersion: known?.schemaVersion || null,
425
- sizeBytes: withSize && installed ? sizeOfVersion(version, path.dirname(venv)) : null,
426
- current: installed && current?.version === version,
427
- recommended: version === ENGINE_VERSION,
428
- installedAt: known?.installedAt || null,
429
- mirror: known?.mirror || null,
430
- commands: known?.commands || null,
431
- venv,
432
- python,
433
- }
434
- })
435
- .sort((a, b) => String(b.installedAt || '').localeCompare(String(a.installedAt || '')))
436
- }
437
-
438
- /**
439
- * Deletes old engine versions, keeping the current one, the recommended one and
440
- * the newest `keep`. A version that is running cannot be removed on Windows, so
441
- * anything locked is skipped and reported instead of failing the batch.
442
- */
443
- export function pruneEngineVersions({ keep = 3 } = {}) {
444
- const limit = Math.max(1, Math.min(10, Number(keep) || 3))
445
- const versions = listEngineVersions().filter((v) => v.installed)
446
- const protectedNames = new Set(versions.filter((v) => v.current || v.recommended).map((v) => v.version))
447
- const ordered = [...versions].sort((a, b) => String(b.installedAt || '').localeCompare(String(a.installedAt || '')))
448
- const keepNames = new Set()
449
- for (const v of ordered) {
450
- if (keepNames.size >= limit) break
451
- keepNames.add(v.version)
452
- }
453
- const removed = []
454
- const skipped = []
455
- for (const v of versions) {
456
- if (protectedNames.has(v.version) || keepNames.has(v.version)) { skipped.push(v.version); continue }
457
- try {
458
- fs.rmSync(engineDir(v.version), { recursive: true, force: true })
459
- const history = ensureHistory(readCurrent())
460
- delete history[v.version]
461
- try { writeJson(HISTORY_FILE(), history) } catch {}
462
- removed.push(v.version)
463
- } catch (error) {
464
- skipped.push(`${v.version} (${error?.code || 'locked'})`)
465
- }
466
- }
467
- return { removed, skipped, kept: [...protectedNames, ...keepNames] }
468
- }
469
-
470
- export function removeEngineVersion(version) {
471
- const target = listEngineVersions().find((v) => v.version === version)
472
- if (!target) return { ok: false, error: `unknown version: ${version}` }
473
- if (!target.installed) return { ok: false, error: `version ${version} is not installed` }
474
- if (target.current) return { ok: false, error: 'the current version cannot be removed; switch first' }
475
- if (!acquireLock()) return { ok: false, status: 'installing', error: 'another install is already running' }
476
- try {
477
- fs.rmSync(engineDir(version), { recursive: true, force: true })
478
- const history = ensureHistory(readCurrent())
479
- delete history[version]
480
- try { writeJson(HISTORY_FILE(), history) } catch {}
481
- return { ok: true }
482
- } catch (error) {
483
- return { ok: false, error: String(error?.message || error) }
484
- } finally {
485
- releaseLock()
486
- }
487
- }
488
-
489
- // ---- real-database gate -----------------------------------------------------
490
- // An empty-temp-dir probe (verifyEngine) only proves the binary starts. The
491
- // danger is switching engines while real memory databases exist that the new
492
- // binary cannot read — or silently downgrading a schema a newer engine wrote.
493
- // Before the current pointer moves, the target python must read every real
494
- // database, and a version downgrade must be forced explicitly.
495
-
496
- function realDatabases() {
497
- const dbs = []
498
- try {
499
- const globalDb = globalDbPath()
500
- if (fs.existsSync(globalDb)) dbs.push(globalDb)
501
- } catch {}
502
- try {
503
- for (const name of fs.readdirSync(librariesDir())) {
504
- if (name.endsWith('.sqlite3')) dbs.push(path.join(librariesDir(), name))
505
- }
506
- } catch {}
507
- return dbs
508
- }
509
-
510
- const ALEMBIC_SCRIPT = [
511
- 'import json, sqlite3, sys',
512
- 'db = sys.argv[1]',
513
- 'conn = sqlite3.connect(db)',
514
- 'try:',
515
- ' rows = conn.execute("select version_num from alembic_version").fetchall()',
516
- ' print(json.dumps({"versions": [r[0] for r in rows]}))',
517
- 'except Exception as e:',
518
- ' print(json.dumps({"versions": [], "error": str(e)}))',
519
- 'finally:',
520
- ' conn.close()',
521
- ].join('\n')
522
-
523
- async function schemaVersions(python, dbs) {
524
- const out = {}
525
- for (const db of dbs) {
526
- try {
527
- const res = await run(python, ['-c', ALEMBIC_SCRIPT, db], { timeoutMs: 30_000 })
528
- if (res.code !== 0) throw new Error((res.stderr || `exit ${res.code}`).trim())
529
- out[db] = JSON.parse(res.stdout.trim()).versions
530
- } catch {
531
- out[db] = null
532
- }
533
- }
534
- return out
535
- }
536
-
537
- async function smokeRealDatabases(python, { log } = {}) {
538
- const dbs = realDatabases()
539
- for (const db of dbs) {
540
- logLine(`smoke-reading ${path.basename(db)} with target engine`, log)
541
- // Read-only: list-files never writes. MEMU_MEMORY_MODE stays local so the
542
- // probe cannot touch a configured cloud backend.
543
- const res = await run(python, ['-m', 'memu', 'list-files', '--json'], {
544
- timeoutMs: 90_000,
545
- env: { MEMU_DB: db, MEMU_MEMORY_MODE: 'local' },
546
- })
547
- if (res.code !== 0) {
548
- throw new Error(`目标引擎读不了现有记忆库 ${path.basename(db)}:${(res.stderr || res.stdout || '').trim().slice(-400)}`)
549
- }
550
- }
551
- return dbs
552
- }
553
-
554
- function versionRank(v) {
555
- const m = String(v || '').match(/(\d+)\.(\d+)\.(\d+)(?:b(\d+))?/)
556
- if (!m) return null
557
- // A final release outranks its betas: 0.11.0 > 0.11.0b3.
558
- return [Number(m[1]), Number(m[2]), Number(m[3]), m[4] ? Number(m[4]) : Number.MAX_SAFE_INTEGER]
559
- }
560
-
561
- export function isVersionDowngrade(from, to) {
562
- const a = versionRank(from)
563
- const b = versionRank(to)
564
- if (!a || !b) return false
565
- for (let i = 0; i < 4; i += 1) if (a[i] !== b[i]) return a[i] < b[i]
566
- return false
567
- }
568
-
569
- // Roll back (or forward) to an already-installed version. Verified first, and the
570
- // caller's `beforeSwitch` runs before the pointer moves, so a bad target can never
571
- // become current and data is snapshotted on the way in.
572
- export async function switchEngineVersion(version, { log = null, beforeSwitch = null, force = false } = {}) {
573
- const target = listEngineVersions().find((v) => v.version === version)
574
- if (!target || !target.installed) {
575
- return { ok: false, error: `version ${version} is not installed` }
576
- }
577
- if (readCurrent()?.version === version) return { ok: true, current: readCurrent(), unchanged: true }
578
-
579
- if (!acquireLock()) return { ok: false, status: 'installing', error: 'another install is already running' }
580
- try {
581
- const verified = await verifyEngineRepaired(target.python, { log, expectedVersion: version })
582
- // Record what the probe saw, so the version list can say "usable" or "broken"
583
- // instead of guessing from the presence of a venv directory.
584
- recordProbe(version, verified)
585
- if (!verified.ok) return { ok: false, error: `目标版本自检未通过:${verified.error}` }
586
-
587
- const dbs = realDatabases()
588
- const safety = typeof beforeSwitch === 'function' ? await beforeSwitch() : null
589
- if (dbs.length && !safety) throw new Error('a verified backup is required before switching an engine with real databases')
590
- if (dbs.length > 0) {
591
- const currentMeta = readCurrent()
592
- if (!force && currentMeta && isVersionDowngrade(version, currentMeta.version)) {
593
- return {
594
- ok: false,
595
- error: `拒绝降级:现有记忆库由更新的引擎 ${currentMeta.version} 写入,切到 ${version} 可能损坏数据;如确认要降级请勾选强制`,
596
- }
597
- }
598
- const beforeSchemas = await schemaVersions(currentMeta?.python || target.python, dbs)
599
- await smokeRealDatabases(target.python, { log })
600
- const afterSchemas = await schemaVersions(target.python, dbs)
601
- for (const db of dbs) {
602
- const a = JSON.stringify(beforeSchemas[db] || [])
603
- const b = JSON.stringify(afterSchemas[db] || [])
604
- if (a !== b && !force) throw new Error(`schema revision changed: ${a} -> ${b}; backup ${safety}; explicit confirmation is required`)
605
- }
606
- }
607
-
608
- const current = {
609
- version,
610
- venv: target.venv,
611
- python: target.python,
612
- commands: verified.commands,
613
- mirror: target.mirror,
614
- installedAt: target.installedAt || stamp(),
615
- switchedAt: stamp(),
616
- }
617
- writeJson(CURRENT_FILE(), current)
618
- writeState({ status: 'ready', version, step: 'ready', error: null })
619
- logLine(`switched engine to ${version}`, log)
620
- return { ok: true, current, verified }
621
- } catch (error) {
622
- return { ok: false, error: String(error?.message || error) }
623
- } finally {
624
- releaseLock()
625
- }
626
- }
627
-
628
- /** Sizes only, for the client to fetch after the page has painted. */
629
- export function engineVersionSizes() {
630
- const sizes = {}
631
- for (const version of listEngineVersions()) {
632
- if (!version.installed) continue
633
- sizes[version.version] = sizeOfVersion(version.version, path.dirname(version.venv))
634
- }
635
- return sizes
636
- }
637
-
638
- /**
639
- * 清掉中断安装留下的临时 venv。只动 `venv.tmp-*`:正式目录(`venv-*`)可能正是
640
- * current.json 指向的可用引擎,绝不能误删。
641
- */
642
- function removeTempVenvs() {
643
- let removed = 0
644
- let names = []
645
- try { names = fs.readdirSync(engineDir(ENGINE_VERSION)) } catch { return removed }
646
- for (const name of names) {
647
- if (!name.startsWith('venv.tmp-')) continue
648
- try {
649
- fs.rmSync(path.join(engineDir(ENGINE_VERSION), name), { recursive: true, force: true })
650
- removed += 1
651
- } catch {}
652
- }
653
- return removed
654
- }
655
-
656
- /**
657
- * 给一次被中断的安装收尾。
658
- *
659
- * 安装进程被杀(宿主重启、断电、任务管理器结束进程)时,`state.json` 会永久停在
660
- * `installing`:没有 error、没有 current、临时 venv 留在盘上。界面只能显示
661
- * 「installing」,而实际上没有任何进程在装——2026-11-26 那次就这样卡了两天,语义
662
- * 召回一直静默降级成关键词,没有人看得出它其实已经死了。
663
- *
664
- * 三条判据同时成立才动手(全部满足才算「死掉」):
665
- * 1. `state.status === 'installing'`
666
- * 2. 本进程没有在装(`installInFlight`),且 `install.lock` 不存在
667
- * 3. `updatedAt` 超过 `staleMs` 没变
668
- * 动作:落成 `failed` 并写清原因,同时清理 `venv.tmp-*` 残骸,让重装从干净状态开始。
669
- *
670
- * 幂等:收尾一次后 status 不再是 installing,后续轮询直接返回。
671
- */
672
- export function reconcileInterruptedInstall({ now = Date.now(), staleMs = STALE_INSTALL_MS } = {}) {
673
- const state = readState()
674
- if (state.status !== 'installing') return { changed: false, state }
675
- if (installInFlight) return { changed: false, state }
676
- if (fs.existsSync(LOCK_FILE())) return { changed: false, state }
677
- const updated = Date.parse(state.updatedAt || state.startedAt || '')
678
- if (!Number.isFinite(updated) || now - updated < staleMs) return { changed: false, state }
679
- const removed = removeTempVenvs()
680
- const minutes = Math.round((now - updated) / 60_000)
681
- const next = writeState({
682
- status: 'failed',
683
- step: 'interrupted',
684
- error: `安装在「${state.step || '未知步骤'}」中断,已 ${minutes} 分钟无进展;已清理 ${removed} 个未完成的 venv,请重新安装`,
685
- })
686
- logLine(`interrupted install reconciled: step=${state.step || '?'} idle=${minutes}min removed=${removed}`)
687
- return { changed: true, state: next, removed }
688
- }
689
-
690
- export function engineStatus({ withSize = false } = {}) {
691
- // 每次查询先收尾一次中断安装:界面读状态时就能自愈,不必等用户点安装。
692
- reconcileInterruptedInstall()
693
- const current = readCurrent()
694
- const state = readState()
695
- return {
696
- status: current ? 'ready' : state.status || 'idle',
697
- version: current?.version || state.version || ENGINE_VERSION,
698
- installed: Boolean(current),
699
- recommendedVersion: ENGINE_VERSION,
700
- current,
701
- state,
702
- versions: listEngineVersions({ withSize }),
703
- log: INSTALL_LOG(),
704
- }
705
- }
706
-
707
- export function mirrorCandidates() {
708
- // The settings page's pipIndexes list is a real user preference and must be
709
- // honored here; env vars only add transient overrides on top.
710
- const fromSettings = Array.isArray(getSettings().pipIndexes)
711
- ? getSettings().pipIndexes.map((s) => String(s || '').trim()).filter(Boolean)
712
- : []
713
- const configured = String(process.env.DSH_MEMU_PIP_INDEXES || '')
714
- .split(',')
715
- .map((s) => s.trim())
716
- .filter(Boolean)
717
- const envIndex = String(process.env.PIP_INDEX_URL || '').trim()
718
- const list = envIndex ? [envIndex, ...fromSettings, ...configured, ...DEFAULT_INDEXES] : [...fromSettings, ...configured, ...DEFAULT_INDEXES]
719
- return [...new Set(list)]
720
- }
721
-
722
- function sleep(ms) {
723
- return new Promise((r) => setTimeout(r, ms))
724
- }
725
-
726
- function acquireLock() {
727
- ensureDir(engineDir())
728
- const file = LOCK_FILE()
729
- try {
730
- const fd = fs.openSync(file, 'wx')
731
- fs.writeFileSync(fd, JSON.stringify({ pid: process.pid, startedAt: stamp() }), 'utf8')
732
- fs.closeSync(fd)
733
- // 三个受锁流程(安装 / 切版本 / 删版本)都会走到这里,标志放在锁上最稳:
734
- // reconcile 只看「本进程有没有持锁」就能区分活干和尸体。
735
- installInFlight = true
736
- return true
737
- } catch (error) {
738
- if (error?.code !== 'EEXIST') throw error
739
- const existing = readJson(file, null)
740
- const started = existing?.startedAt ? Date.parse(existing.startedAt) : 0
741
- if (Date.now() - started > 30 * 60 * 1000) {
742
- // 过期锁用 rename 原子接管:两个进程同时发现过期时只有一个 rename 成功,
743
- // 另一个会 ENOENT 拿到 false,不会出现“先删再递归抢”被两个进程同时拿到。
744
- try {
745
- const stale = file + '.stale-' + crypto.randomUUID()
746
- fs.renameSync(file, stale)
747
- try { fs.rmSync(stale, { force: true }) } catch {}
748
- return acquireLock()
749
- } catch {
750
- return false
751
- }
752
- }
753
- return false
754
- }
755
- }
756
-
757
- function releaseLock() {
758
- installInFlight = false
759
- try { fs.rmSync(LOCK_FILE(), { force: true }) } catch {}
760
- }
761
-
762
- async function pythonVersion(cmd, prefix = []) {
763
- const res = await run(cmd, [...prefix, '-c', 'import sys; print(f"{sys.version_info[0]}.{sys.version_info[1]}.{sys.version_info[2]}")'], {
764
- timeoutMs: 15_000,
765
- })
766
- if (res.code !== 0) return null
767
- const text = res.stdout.trim().split(/\r?\n/).pop() || ''
768
- const m = /^(\d+)\.(\d+)\.(\d+)$/.exec(text)
769
- if (!m) return null
770
- return { major: Number(m[1]), minor: Number(m[2]), patch: Number(m[3]), raw: text }
771
- }
772
-
773
- async function hasPip(cmd, prefix = []) {
774
- const res = await run(cmd, [...prefix, '-m', 'pip', '--version'], { timeoutMs: 20_000 })
775
- return res.code === 0
776
- }
777
-
778
- function dshRuntimePythons() {
779
- const out = []
780
- const runtimeRoot = path.join(
781
- process.env.DSH_HOME || path.join(os.homedir(), '.dsh'),
782
- 'dsh-runtimes',
783
- )
784
- try {
785
- for (const name of fs.readdirSync(runtimeRoot)) {
786
- const base = path.join(runtimeRoot, name, 'dependencies', 'python')
787
- const exe = isWindows() ? path.join(base, 'python.exe') : path.join(base, 'bin', 'python3')
788
- if (fs.existsSync(exe)) out.push(exe)
789
- }
790
- } catch {}
791
- if (process.env.DSH_RUNTIME_PYTHON && fs.existsSync(process.env.DSH_RUNTIME_PYTHON)) {
792
- out.unshift(process.env.DSH_RUNTIME_PYTHON)
793
- }
794
- return out
795
- }
796
-
797
- async function pythonCandidate(cmd, prefix = [], source = 'path') {
798
- const version = await pythonVersion(cmd, prefix)
799
- if (!version || version.major !== 3 || version.minor < 11) return null
800
- const pip = await hasPip(cmd, prefix)
801
- return { kind: 'python', cmd, prefix, version, hasPip: pip, source }
802
- }
803
-
804
- export async function resolvePythonCandidates() {
805
- const out = []
806
- const seen = new Set()
807
- const push = (c) => {
808
- if (!c) return
809
- const key = `${c.cmd}|${c.prefix.join(' ')}`
810
- if (seen.has(key)) return
811
- seen.add(key)
812
- out.push(c)
813
- }
814
-
815
- if (process.env.DSH_MEMU_PYTHON) {
816
- push(await pythonCandidate(process.env.DSH_MEMU_PYTHON, [], 'env'))
817
- }
818
-
819
- // Prefer interpreters with reliable wheels: 3.13, 3.12, DSH bundled, then 3.14.
820
- for (const ver of ['3.13', '3.12', '3.11']) {
821
- push(await pythonCandidate('py', [`-${ver}`], `py ${ver}`))
822
- }
823
- for (const exe of dshRuntimePythons()) {
824
- push(await pythonCandidate(exe, [], 'dsh-runtime'))
825
- }
826
- for (const exe of ['python3', 'python']) {
827
- push(await pythonCandidate(exe, [], exe))
828
- }
829
- push(await pythonCandidate('py', ['-3.14'], 'py 3.14'))
830
-
831
- return out
832
- }
833
-
834
- async function cleanupDir(dir) {
835
- try { await fsp.rm(dir, { recursive: true, force: true }) } catch {}
836
- }
837
-
838
- async function cleanupDownloads() {
839
- try {
840
- const dir = downloadsDir()
841
- for (const name of await fsp.readdir(dir)) {
842
- await fsp.rm(path.join(dir, name), { recursive: true, force: true })
843
- }
844
- } catch {}
845
- }
846
-
847
- async function installIntoVenv({ base, venv, mirror, log }) {
848
- const python = venvPython(venv)
849
- if (base.uvPath) {
850
- const result = await run(base.uvPath, ['pip', 'install', '--python', python, '-r', LOCK_PATH,
851
- '--index-url', mirror, '--only-binary', ':all:', '--no-cache', '--no-progress'],
852
- { env: base.uvEnv, timeoutMs: 20 * 60 * 1000, onData: data => logLine(data.trim(), log) })
853
- if (result.code !== 0) throw new Error(`managed uv dependency install failed (exit ${result.code})`)
854
- return
855
- }
856
- if (!base.hasPip) {
857
- throw new Error(`Python ${base.cmd} ${base.prefix.join(' ')} has no pip; install pip or uv first`)
858
- }
859
- logLine(`pip install using ${mirror}`, log)
860
- const res = await run(base.cmd, [
861
- ...base.prefix,
862
- '-m', 'pip', '--python', python,
863
- 'install', '-r', LOCK_PATH,
864
- '--index-url', mirror,
865
- '--disable-pip-version-check',
866
- '--no-input',
867
- '--no-cache-dir',
868
- '--only-binary=:all:',
869
- '--timeout', '45',
870
- '--retries', '3',
871
- ], {
872
- env: { PIP_NO_CACHE_DIR: '1', PIP_DISABLE_PIP_VERSION_CHECK: '1' },
873
- timeoutMs: 20 * 60 * 1000,
874
- onData: (s) => {
875
- for (const line of s.split(/\r?\n/)) if (line.trim()) logLine(line.trim(), log)
876
- },
877
- })
878
- if (res.code !== 0) {
879
- const detail = (res.stderr || res.stdout || '').trim().split(/\r?\n/).slice(-6).join(' | ')
880
- throw new Error(`pip install failed (exit ${res.code}${res.timedOut ? ', timeout' : ''}): ${detail}`)
881
- }
882
- }
883
-
884
- async function parseMemuCommands(python) {
885
- const res = await run(python, ['-m', 'memu', '--help'], { timeoutMs: 30_000 })
886
- if (res.code !== 0) {
887
- return { ok: false, error: (res.stderr || res.stdout || 'memu --help failed').trim() }
888
- }
889
- const text = `${res.stdout}\n${res.stderr}`
890
- const commands = new Set()
891
- for (const name of [...REQUIRED_COMMANDS, ...OPTIONAL_COMMANDS]) {
892
- if (new RegExp(`(^|[\\s{,])(?:${name}|${name}\\s*\\()`, 'm').test(text)) commands.add(name)
893
- }
894
- return { ok: true, commands: [...commands], help: text }
895
- }
896
-
897
- export async function verifyEngine(python, { log, expectedVersion = null } = {}) {
898
- const versionRes = await run(python, ['-c', 'import importlib.metadata as m; print(m.version("memu-cli"))'], {
899
- timeoutMs: 30_000,
900
- })
901
- if (versionRes.code !== 0) {
902
- return { ok: false, error: `memu-cli import failed: ${(versionRes.stderr || versionRes.stdout).trim()}` }
903
- }
904
- const version = versionRes.stdout.trim().split(/\r?\n/).pop() || ''
905
- if (expectedVersion && normalizeVersion(version) !== normalizeVersion(expectedVersion)) {
906
- return { ok: false, version, error: 'memu-cli version mismatch: expected ' + expectedVersion + ', got ' + version }
907
- }
908
- const commands = await parseMemuCommands(python)
909
- if (!commands.ok) return { ok: false, version, error: commands.error }
910
- const missing = REQUIRED_COMMANDS.filter((c) => !commands.commands.includes(c))
911
- if (missing.length > 0) {
912
- return { ok: false, version, commands: commands.commands, error: `missing required commands: ${missing.join(', ')}` }
913
- }
914
- const tmpDb = path.join(os.tmpdir(), `dsh-memu-memory-smoke-${process.pid}-${Date.now()}.sqlite3`)
915
- try {
916
- const res = await run(python, ['-m', 'memu', 'list-files', '--json', '--db', tmpDb], { timeoutMs: 60_000 })
917
- if (res.code !== 0) {
918
- return { ok: false, version, commands: commands.commands, error: `list-files smoke failed: ${(res.stderr || res.stdout).trim()}` }
919
- }
920
- try { JSON.parse(res.stdout) } catch {
921
- return { ok: false, version, commands: commands.commands, error: 'list-files smoke returned non-JSON' }
922
- }
923
- } finally {
924
- try { fs.rmSync(tmpDb, { force: true }) } catch {}
925
- try { fs.rmSync(`${tmpDb}-wal`, { force: true }) } catch {}
926
- try { fs.rmSync(`${tmpDb}-shm`, { force: true }) } catch {}
927
- }
928
- logLine(`engine verified: memu-cli ${version}, commands ${commands.commands.join(',')}`, log)
929
- return { ok: true, version, commands: commands.commands }
930
- }
931
-
932
- function stateInstalling(step, extra = {}) {
933
- const previous = readState()
934
- return writeState({
935
- status: 'installing',
936
- version: ENGINE_VERSION,
937
- step,
938
- error: null,
939
- // Keep the first start time across step updates so the UI shows elapsed time
940
- // instead of restarting its clock every time the step advances.
941
- startedAt: previous.status === 'installing' && previous.startedAt ? previous.startedAt : stamp(),
942
- ...extra,
943
- })
944
- }
945
-
946
- function stateError(error, extra = {}) {
947
- const previous = readState()
948
- return writeState({
949
- status: 'error',
950
- version: ENGINE_VERSION,
951
- step: 'failed',
952
- error: String(error?.message || error),
953
- startedAt: previous.startedAt || null,
954
- finishedAt: stamp(),
955
- ...extra,
956
- })
957
- }
958
-
959
- // The installer already writes every step to ~/.dsh/dsh-memu-memory/logs/install.log.
960
- // Surfacing the tail turns "Installing…" from a black box into progress: pip's own
961
- // lines say which package it is on when a mirror stalls.
962
- export function readInstallLogTail(maxLines = 14, maxBytes = 24 * 1024) {
963
- try {
964
- const stat = fs.statSync(INSTALL_LOG())
965
- const start = Math.max(0, stat.size - maxBytes)
966
- const fd = fs.openSync(INSTALL_LOG(), 'r')
967
- const buffer = Buffer.alloc(stat.size - start)
968
- try { fs.readSync(fd, buffer, 0, buffer.length, start) } finally { fs.closeSync(fd) }
969
- return buffer.toString('utf8').split(/\r?\n/).filter((line) => line.trim()).slice(-maxLines)
970
- } catch {
971
- return []
972
- }
973
- }
974
-
975
- export async function installEngine({ force = false, log = null, beforeSwitch = null } = {}) {
976
- const current = readCurrent()
977
- if (!force && current?.version === ENGINE_VERSION) {
978
- const verified = await verifyEngineRepaired(current.python, { log })
979
- if (verified.ok) return { ok: true, current, verified }
980
- }
981
-
982
- if (!acquireLock()) {
983
- return { ok: false, status: 'installing', error: 'another install is already running' }
984
- }
985
-
986
- try {
987
- ensureDir(engineDir())
988
- ensureDir(downloadsDir())
989
- stateInstalling('resolving-python')
990
- logLine(`installing MemU engine ${ENGINE_VERSION}`, log)
991
-
992
- const candidates = await resolvePythonCandidates()
993
- if (!candidates.some(candidate => candidate.hasPip)) candidates.push(await ensureManagedPython({ run, log: line => logLine(line, log) }))
994
- logLine(`python candidates: ${candidates.map((c) => `${c.cmd} ${c.prefix.join(' ')} (${c.version.raw}${c.hasPip ? '' : ', no-pip'})`).join('; ')}`, log)
995
-
996
- const errors = []
997
- const versionDir = engineDir(ENGINE_VERSION)
998
- ensureDir(versionDir)
999
-
1000
- for (const base of candidates) {
1001
- if (!base.hasPip && !base.uvPath) continue
1002
- const tmpVenv = path.join(versionDir, `venv.tmp-${process.pid}-${Date.now()}`)
1003
- try {
1004
- stateInstalling(`creating-venv:${base.source}`)
1005
- logLine(`creating venv with ${base.cmd} ${base.prefix.join(' ')}`, log)
1006
- const venvRes = await run(base.cmd, [...base.prefix, '-m', 'venv', '--without-pip', tmpVenv], {
1007
- timeoutMs: 120_000,
1008
- onData: (s) => { for (const line of s.split(/\r?\n/)) if (line.trim()) logLine(line.trim(), log) },
1009
- })
1010
- if (venvRes.code !== 0) {
1011
- throw new Error(`venv creation failed: ${(venvRes.stderr || venvRes.stdout).trim()}`)
1012
- }
1013
-
1014
- stateInstalling(`installing-deps:${base.source}`)
1015
- let installed = false
1016
- let lastMirror = ''
1017
- for (const mirror of mirrorCandidates()) {
1018
- lastMirror = mirror
1019
- try {
1020
- await installIntoVenv({ base, venv: tmpVenv, mirror, log })
1021
- installed = true
1022
- break
1023
- } catch (error) {
1024
- errors.push(`${base.source} @ ${mirror}: ${error.message}`)
1025
- logLine(`mirror failed: ${mirror}: ${error.message}`, log)
1026
- }
1027
- }
1028
- if (!installed) throw new Error(`all mirrors failed for ${base.source}`)
1029
-
1030
- stateInstalling(`verifying:${base.source}`)
1031
- const python = venvPython(tmpVenv)
1032
- const verified = await verifyEngineRepaired(python, { log, expectedVersion: ENGINE_VERSION })
1033
- if (!verified.ok) throw new Error(`verify failed: ${verified.error}`)
1034
-
1035
- if (typeof beforeSwitch === 'function') {
1036
- stateInstalling('backing-up')
1037
- await beforeSwitch()
1038
- }
1039
- if (realDatabases().length) {
1040
- if (typeof beforeSwitch !== 'function') throw new Error('a verified backup is required before repairing an engine with real databases')
1041
- await smokeRealDatabases(python, { log })
1042
- }
1043
-
1044
- const finalVenv = fs.existsSync(path.join(versionDir, 'venv'))
1045
- ? path.join(versionDir, `venv-${Date.now()}`)
1046
- : path.join(versionDir, 'venv')
1047
- await fsp.rename(tmpVenv, finalVenv)
1048
- const finalPython = venvPython(finalVenv)
1049
- const current = {
1050
- version: ENGINE_VERSION,
1051
- venv: finalVenv,
1052
- python: finalPython,
1053
- commands: verified.commands,
1054
- mirror: lastMirror,
1055
- installedAt: stamp(),
1056
- }
1057
- writeJson(CURRENT_FILE(), current)
1058
- recordHistory(current)
1059
- writeState({ status: 'ready', version: ENGINE_VERSION, step: 'ready', error: null, mirror: lastMirror })
1060
- await cleanupDownloads()
1061
- // New engine landed: keep the version count honest without waiting for
1062
- // a manual prune. Never blocks the result.
1063
- try { pruneEngineVersions({ keep: 3 }) } catch {}
1064
- logLine(`engine ready: ${finalPython}`, log)
1065
- return { ok: true, current, verified }
1066
- } catch (error) {
1067
- await cleanupDir(tmpVenv)
1068
- errors.push(`${base.source}: ${error.message}`)
1069
- logLine(`candidate failed: ${base.source}: ${error.message}`, log)
1070
- }
1071
- }
1072
-
1073
- let message = `no Python candidate could install MemU:\n${errors.join('\n')}`
1074
- if (isMac() && errors.some((e) => isMacOSLibraryValidationError(e))) {
1075
- message += '\n(macOS 签名校验拒绝了依赖包的 .so;可对 Python 解释器执行 `codesign --force --sign - <python路径>` 后重试,或在设置里用 DSH_MEMU_PYTHON 指定 Homebrew/官方 Python)'
1076
- }
1077
- throw new Error(message)
1078
- } catch (error) {
1079
- stateError(error)
1080
- await cleanupDownloads()
1081
- logLine(`install failed: ${error.message}`, log)
1082
- return { ok: false, status: 'error', error: String(error?.message || error) }
1083
- } finally {
1084
- releaseLock()
1085
- }
1086
- }
1087
-
1088
- export async function ensureEngine({ force = false, log = null, beforeSwitch = null } = {}) {
1089
- // 带着一次死掉的安装开始新一轮,会先撞上 installing 中间态和 venv.tmp 残骸;
1090
- // 先收尾再读 current,重装才能从干净状态起跑。
1091
- reconcileInterruptedInstall()
1092
- const current = readCurrent()
1093
- if (!force && current?.version === ENGINE_VERSION) {
1094
- const verified = await verifyEngineRepaired(current.python, { log })
1095
- if (verified.ok) {
1096
- writeState({ status: 'ready', version: ENGINE_VERSION, step: 'ready', error: null })
1097
- return { ok: true, current, verified }
1098
- }
1099
- logLine(`current engine failed verification: ${verified.error}; reinstalling`, log)
1100
- }
1101
- return installEngine({ force: true, log, beforeSwitch })
1102
- }
1103
-
1
+ import fs from 'node:fs'
2
+ import fsp from 'node:fs/promises'
3
+ import os from 'node:os'
4
+ import path from 'node:path'
5
+ import crypto from 'node:crypto'
6
+ import { spawn } from 'node:child_process'
7
+ import { fileURLToPath } from 'node:url'
8
+ import {
9
+ dataDir, engineDir, downloadsDir, logsDir, librariesDir, ensureDir, readJson, writeJson, stamp, windowsSystemEnv,
10
+ } from './paths.js'
11
+ import { getSettings, globalDbPath } from './state.js'
12
+ import { ensureManagedPython } from './managed-runtime.js'
13
+
14
+ const HERE = path.dirname(fileURLToPath(import.meta.url))
15
+ const LOCK_PATH = path.join(HERE, '..', 'requirements.lock')
16
+
17
+ export const ENGINE_VERSION = '0.11.0b3'
18
+ export const REQUIRED_COMMANDS = ['retrieve', 'list-files', 'commit']
19
+ export const OPTIONAL_COMMANDS = ['search', 'memorize']
20
+
21
+ const STATE_FILE = () => path.join(engineDir(), 'state.json')
22
+ const CURRENT_FILE = () => path.join(engineDir(), 'current.json')
23
+ const LOCK_FILE = () => path.join(engineDir(), 'install.lock')
24
+ const INSTALL_LOG = () => path.join(logsDir(), 'install.log')
25
+ const AVAILABLE_FILE = () => path.join(engineDir(), 'available-versions.json')
26
+
27
+ const VERSION_CACHE_MS = 5 * 60 * 1000
28
+ // Persisted version lists are good enough to show without a network round trip.
29
+ const PERSISTED_TTL_MS = 24 * 60 * 60 * 1000
30
+ let versionCache = { at: 0, value: null }
31
+
32
+ // 本进程是否正在装引擎。`engineStatus` 每次轮询都会跑一次中断收尾,必须能把
33
+ // 「自己正在跑的安装」和「上次死掉的安装」分开,否则会把自己判成中断。
34
+ let installInFlight = false
35
+ // 多久没有进展就认定安装已死。与 acquireLock 的过期锁阈值保持一致(30 分钟),
36
+ // 这样一个僵死安装会在状态、锁、界面三处同时被判定为过期。
37
+ const STALE_INSTALL_MS = 30 * 60 * 1000
38
+
39
+ // Compare PEP 440-ish versions without a dependency. A plain release is newer
40
+ // than a pre-release of the same number (`0.11.0` > `0.11.0b3`).
41
+ export function compareVersions(a, b) {
42
+ const split = (value) => {
43
+ const text = String(value || '').trim()
44
+ const match = text.match(/^(\d+)\.(\d+)\.(\d+)(.*)$/)
45
+ if (!match) return { nums: [0, 0, 0], pre: text }
46
+ return { nums: [Number(match[1]), Number(match[2]), Number(match[3])], pre: match[4] || '' }
47
+ }
48
+ const left = split(a)
49
+ const right = split(b)
50
+ for (let i = 0; i < 3; i += 1) {
51
+ if (left.nums[i] !== right.nums[i]) return left.nums[i] - right.nums[i]
52
+ }
53
+ if (left.pre === right.pre) return 0
54
+ if (!left.pre) return 1
55
+ if (!right.pre) return -1
56
+ return left.pre.localeCompare(right.pre, undefined, { numeric: true })
57
+ }
58
+
59
+ export function normalizeVersion(raw) {
60
+ const match = String(raw || '').match(/^(\d+\.\d+\.\d+(?:[A-Za-z]+\d*)?)/)
61
+ return match ? match[1] : null
62
+ }
63
+
64
+ export function parseSimpleVersions(html) {
65
+ const found = new Set()
66
+ // The distribution is `memu-cli`, while the CLI command is `memu`. Match the
67
+ // distribution name here; matching bare `memu` picks up the unrelated MeMu
68
+ // Game Boy package that owns that PyPI name.
69
+ const re = /memu[_-]cli-(\d[0-9A-Za-z.]*[0-9A-Za-z])[-.]/g
70
+ let match
71
+ while ((match = re.exec(String(html || ''))) !== null) {
72
+ const version = normalizeVersion(match[1])
73
+ if (version) found.add(version)
74
+ }
75
+ return [...found]
76
+ }
77
+
78
+ export function readAvailableVersions() {
79
+ try {
80
+ const cached = readJson(AVAILABLE_FILE(), null)
81
+ if (cached && cached.package === 'memu-cli' && Array.isArray(cached.versions)) return cached
82
+ } catch {}
83
+ return null
84
+ }
85
+
86
+ // The plugin never silently installs the newest release (CLI/JSON changes are
87
+ // real), but it can still answer "what exists?" without the user leaving Settings.
88
+ // PyPI JSON is tried first; the mirrors only expose simple indexes, so their HTML
89
+ // is parsed as a fallback. Failures are reported, never thrown into the page.
90
+ export async function fetchAvailableVersions({ force = false, timeoutMs = 6000 } = {}) {
91
+ if (!force) {
92
+ if (versionCache.value && Date.now() - versionCache.at < VERSION_CACHE_MS) {
93
+ return { ...versionCache.value, cached: true }
94
+ }
95
+ // A cold process used to re-query PyPI every time Settings opened, and with
96
+ // pypi.org unreachable that meant waiting out every timeout in turn. A
97
+ // day-old answer is fine for a "what could I install" list.
98
+ const persisted = readAvailableVersions()
99
+ const fetchedAt = Date.parse(persisted?.fetchedAt || '') || 0
100
+ if (persisted && fetchedAt > 0 && Date.now() - fetchedAt < PERSISTED_TTL_MS) {
101
+ versionCache = { at: fetchedAt, value: persisted }
102
+ return { ...persisted, cached: true }
103
+ }
104
+ }
105
+ // Mirrors first: the package is mirrored in full, and pypi.org is the slowest
106
+ // of these from mainland China.
107
+ const sources = [
108
+ { name: 'Tsinghua', url: 'https://pypi.tuna.tsinghua.edu.cn/pypi/memu-cli/json', json: true },
109
+ { name: 'Aliyun', url: 'https://mirrors.aliyun.com/pypi/simple/memu-cli/', json: false },
110
+ { name: 'PyPI', url: 'https://pypi.org/pypi/memu-cli/json', json: true },
111
+ { name: 'Tsinghua-simple', url: 'https://pypi.tuna.tsinghua.edu.cn/simple/memu-cli/', json: false },
112
+ { name: 'PyPI-simple', url: 'https://pypi.org/simple/memu-cli/', json: false },
113
+ ]
114
+ const errors = []
115
+ for (const source of sources) {
116
+ try {
117
+ const response = await fetch(source.url, {
118
+ headers: { accept: source.json ? 'application/json' : 'text/html' },
119
+ signal: AbortSignal.timeout(timeoutMs),
120
+ })
121
+ if (!response.ok) throw new Error(`HTTP ${response.status}`)
122
+ const body = source.json ? await response.json() : await response.text()
123
+ const releases = body?.releases ?? body?.info?.releases ?? {}
124
+ const versions = source.json
125
+ ? Object.keys(releases)
126
+ : parseSimpleVersions(body)
127
+ const clean = [...new Set(versions.map(normalizeVersion).filter(Boolean))]
128
+ .sort((a, b) => compareVersions(b, a))
129
+ if (clean.length === 0) throw new Error('no versions in response')
130
+ const value = {
131
+ ok: true,
132
+ package: 'memu-cli',
133
+ source: source.name,
134
+ versions: clean.slice(0, 40),
135
+ latest: clean[0],
136
+ fetchedAt: stamp(),
137
+ }
138
+ versionCache = { at: Date.now(), value }
139
+ try { writeJson(AVAILABLE_FILE(), value) } catch {}
140
+ return { ...value, cached: false }
141
+ } catch (error) {
142
+ errors.push(`${source.name}: ${error?.message || error}`)
143
+ }
144
+ }
145
+ const persisted = readAvailableVersions()
146
+ if (persisted) return { ...persisted, ok: false, cached: true, errors }
147
+ return { ok: false, versions: [], latest: null, errors, fetchedAt: stamp() }
148
+ }
149
+
150
+ const DEFAULT_INDEXES = [
151
+ 'https://pypi.tuna.tsinghua.edu.cn/simple',
152
+ 'https://mirrors.aliyun.com/pypi/simple/',
153
+ 'https://pypi.org/simple',
154
+ ]
155
+
156
+ function isWindows() {
157
+ return process.platform === 'win32'
158
+ }
159
+
160
+ function isMac() {
161
+ return process.platform === 'darwin'
162
+ }
163
+
164
+ // macOS library validation rejects the ad-hoc-signed `.so` files inside PyPI
165
+ // wheels when the running interpreter itself is Developer-ID signed with the
166
+ // hardened runtime (python-build-standalone: the uv-managed Python and the DSH
167
+ // bundled runtime). The dlopen error names "different Team IDs"; ad-hoc
168
+ // re-signing the interpreter drops the hardened runtime flag and lets every
169
+ // wheel load. Matched against verifyEngine's error text so the repair only
170
+ // fires on real signature failures, never on unrelated import errors.
171
+ export function isMacOSLibraryValidationError(text) {
172
+ return /code signature|different Team IDs|SignatureInvalid|library validation/i.test(String(text || ''))
173
+ }
174
+
175
+ // Best-effort: codesign always exists on macOS, but re-signing an interpreter
176
+ // we don't own (Homebrew, python.org) may fail on permissions; callers treat
177
+ // `false` as "repair unavailable" and let the normal error path report.
178
+ async function resignDarwinInterpreter(python, log) {
179
+ if (!isMac()) return false
180
+ let target = python
181
+ try { target = fs.realpathSync(python) } catch {}
182
+ logLine(`re-signing interpreter ad-hoc (macOS library validation): ${target}`, log)
183
+ const res = await run('/usr/bin/codesign', ['--force', '--sign', '-', target], { timeoutMs: 60_000 })
184
+ if (res.code !== 0) {
185
+ logLine(`codesign failed: ${(res.stderr || res.stdout || '').trim().slice(-200)}`, log)
186
+ return false
187
+ }
188
+ // Files written by other tools can carry a quarantine xattr that would break
189
+ // the next exec even with a valid signature; clearing it is harmless if absent.
190
+ await run('/usr/bin/xattr', ['-d', 'com.apple.quarantine', target], { timeoutMs: 15_000 })
191
+ return true
192
+ }
193
+
194
+ // verifyEngine plus the macOS signature repair: on a signature-shaped failure,
195
+ // re-sign the venv's base interpreter once and verify again before declaring
196
+ // the candidate broken. Every verify site goes through here so existing
197
+ // installs self-heal on the next ensure/install too.
198
+ async function verifyEngineRepaired(python, { log, expectedVersion = null } = {}) {
199
+ const verified = await verifyEngine(python, { log, expectedVersion })
200
+ if (verified.ok || !isMac() || !isMacOSLibraryValidationError(verified.error)) return verified
201
+ logLine(`verify failed with a macOS code-signature error; repairing and retrying`, log)
202
+ await resignDarwinInterpreter(python, log)
203
+ return verifyEngine(python, { log, expectedVersion })
204
+ }
205
+
206
+ export function venvPython(venv) {
207
+ return isWindows()
208
+ ? path.join(venv, 'Scripts', 'python.exe')
209
+ : path.join(venv, 'bin', 'python3')
210
+ }
211
+
212
+ function run(cmd, args, opts = {}) {
213
+ return new Promise((resolve) => {
214
+ const child = spawn(cmd, args, {
215
+ cwd: opts.cwd,
216
+ env: { ...windowsSystemEnv(), ...process.env, ...(opts.env || {}) },
217
+ windowsHide: true,
218
+ stdio: ['ignore', 'pipe', 'pipe'],
219
+ })
220
+ let stdout = ''
221
+ let stderr = ''
222
+ let timedOut = false
223
+ const timer = setTimeout(() => {
224
+ timedOut = true
225
+ try { child.kill() } catch {}
226
+ }, opts.timeoutMs ?? 120_000)
227
+ child.stdout?.on('data', (d) => {
228
+ const s = d.toString()
229
+ stdout += s
230
+ opts.onData?.(s)
231
+ })
232
+ child.stderr?.on('data', (d) => {
233
+ const s = d.toString()
234
+ stderr += s
235
+ opts.onData?.(s)
236
+ })
237
+ child.on('error', (error) => {
238
+ clearTimeout(timer)
239
+ resolve({ code: -1, stdout, stderr, error, timedOut })
240
+ })
241
+ child.on('close', (code) => {
242
+ clearTimeout(timer)
243
+ resolve({ code, stdout, stderr, timedOut })
244
+ })
245
+ })
246
+ }
247
+
248
+ function logLine(message, sink) {
249
+ const line = `[${stamp()}] ${message}`
250
+ try {
251
+ ensureDir(logsDir())
252
+ fs.appendFileSync(INSTALL_LOG(), line + '\n', 'utf8')
253
+ } catch {}
254
+ try { sink?.(line) } catch {}
255
+ }
256
+
257
+ function readState() {
258
+ return readJson(STATE_FILE(), {}) || {}
259
+ }
260
+
261
+ function writeState(patch) {
262
+ const next = { ...readState(), ...patch, updatedAt: stamp() }
263
+ writeJson(STATE_FILE(), next)
264
+ return next
265
+ }
266
+
267
+ export function readCurrent() {
268
+ const current = readJson(CURRENT_FILE(), null)
269
+ if (!current || typeof current.python !== 'string' || typeof current.venv !== 'string') return null
270
+ return current
271
+ }
272
+
273
+ // Every version this machine has actually installed, kept so the engine page can
274
+ // offer a rollback target after the plugin itself is upgraded. It is a record of
275
+ // intent; `listEngineVersions` still verifies the venv is really on disk.
276
+ const HISTORY_FILE = () => engineDir('history.json')
277
+
278
+ function readHistory() {
279
+ const raw = readJson(HISTORY_FILE(), null)
280
+ return raw && typeof raw === 'object' ? raw : {}
281
+ }
282
+
283
+ function recordHistory(entry) {
284
+ const history = readHistory()
285
+ history[entry.version] = {
286
+ ...history[entry.version],
287
+ ...entry,
288
+ }
289
+ writeJson(HISTORY_FILE(), history)
290
+ return history
291
+ }
292
+
293
+ function entryFromCurrent(current) {
294
+ return {
295
+ version: current.version,
296
+ venv: current.venv,
297
+ python: current.python,
298
+ commands: current.commands || null,
299
+ mirror: current.mirror || null,
300
+ installedAt: current.installedAt || current.switchedAt || null,
301
+ }
302
+ }
303
+
304
+ // Installs made before the history file existed (or a history file removed by
305
+ // hand) otherwise render as a bare version row with no install time or mirror.
306
+ // `current.json` still has that data, so backfill it once on the next read.
307
+ function ensureHistory(current = readCurrent()) {
308
+ const history = readHistory()
309
+ if (!current) return history
310
+ const known = history[current.version]
311
+ if (known?.installedAt && known?.mirror) return history
312
+ const fresh = entryFromCurrent(current)
313
+ history[current.version] = {
314
+ ...fresh,
315
+ ...known,
316
+ installedAt: known?.installedAt || fresh.installedAt,
317
+ mirror: known?.mirror || fresh.mirror,
318
+ commands: known?.commands || fresh.commands,
319
+ venv: known?.venv || fresh.venv,
320
+ python: known?.python || fresh.python,
321
+ }
322
+ try { writeJson(HISTORY_FILE(), history) } catch {}
323
+ return history
324
+ }
325
+
326
+ // Walking a venv is thousands of stat() calls; doing it on every `getState`
327
+ // made opening Settings slow. The number is stable until the version is
328
+ // reinstalled, so it is remembered in history.json and memoised per process.
329
+ const sizeCache = new Map()
330
+ const sizedThisSession = new Set()
331
+
332
+ function rememberedSize(version) {
333
+ try {
334
+ const history = JSON.parse(fs.readFileSync(HISTORY_FILE(), 'utf8'))
335
+ const bytes = history?.[version]?.sizeBytes
336
+ return Number.isFinite(bytes) ? bytes : null
337
+ } catch {
338
+ return null
339
+ }
340
+ }
341
+
342
+ function rememberSize(version, bytes) {
343
+ try {
344
+ const history = JSON.parse(fs.readFileSync(HISTORY_FILE(), 'utf8'))
345
+ if (!history?.[version]) return
346
+ if (history[version].sizeBytes === bytes) return
347
+ history[version].sizeBytes = bytes
348
+ writeJson(HISTORY_FILE(), history)
349
+ } catch {}
350
+ }
351
+
352
+ function sizeOfVersion(version, dir) {
353
+ if (sizeCache.has(version)) return sizeCache.get(version)
354
+ const stored = rememberedSize(version)
355
+ const bytes = stored === null ? dirSizeBytes(dir) : stored
356
+ sizeCache.set(version, bytes)
357
+ if (stored === null && !sizedThisSession.has(version)) {
358
+ sizedThisSession.add(version)
359
+ rememberSize(version, bytes)
360
+ }
361
+ return bytes
362
+ }
363
+
364
+ function dirSizeBytes(dir) {
365
+ let total = 0
366
+ const walk = (current) => {
367
+ let names = []
368
+ try { names = fs.readdirSync(current, { withFileTypes: true }) } catch { return }
369
+ for (const entry of names) {
370
+ const full = path.join(current, entry.name)
371
+ if (entry.isDirectory()) { walk(full); continue }
372
+ try { total += fs.statSync(full).size } catch {}
373
+ }
374
+ }
375
+ walk(dir)
376
+ return total
377
+ }
378
+
379
+ function recordProbe(version, verified) {
380
+ try {
381
+ const history = ensureHistory(readCurrent())
382
+ const entry = history[version] || {}
383
+ history[version] = {
384
+ ...entry,
385
+ version,
386
+ probe: verified?.ok
387
+ ? { ok: true, at: stamp() }
388
+ : { ok: false, at: stamp(), error: String(verified?.error || 'probe failed').slice(0, 300) },
389
+ commands: verified?.commands || entry.commands || null,
390
+ }
391
+ writeJson(HISTORY_FILE(), history)
392
+ } catch {}
393
+ }
394
+
395
+ export function listEngineVersions({ withSize = false } = {}) {
396
+ const current = readCurrent()
397
+ const history = ensureHistory(current)
398
+ const names = new Set([...Object.keys(history), ENGINE_VERSION])
399
+ // A directory can exist without a history entry (hand-copied venv, an install
400
+ // interrupted before the record), so scan the tree too.
401
+ try {
402
+ for (const name of fs.readdirSync(engineDir())) {
403
+ if (fs.existsSync(path.join(engineDir(), name, 'venv'))) names.add(name)
404
+ }
405
+ } catch {}
406
+ return [...names]
407
+ .filter(Boolean)
408
+ .map((version) => {
409
+ const known = history[version]
410
+ const venv = known?.venv || engineDir(version, 'venv')
411
+ const python = known?.python || venvPython(venv)
412
+ const installed = fs.existsSync(venv)
413
+ // "installed" only means a venv directory is there. "usable" means a probe
414
+ // actually ran it: a venv whose python was deleted, or whose deps were
415
+ // half-installed, still passes the directory check.
416
+ const probe = known?.probe || null
417
+ const usable = installed ? (probe ? probe.ok === true : null) : false
418
+ return {
419
+ version,
420
+ installed,
421
+ usable,
422
+ probeAt: probe?.at || null,
423
+ probeError: probe && probe.ok === false ? probe.error || 'probe failed' : null,
424
+ schemaVersion: known?.schemaVersion || null,
425
+ sizeBytes: withSize && installed ? sizeOfVersion(version, path.dirname(venv)) : null,
426
+ current: installed && current?.version === version,
427
+ recommended: version === ENGINE_VERSION,
428
+ installedAt: known?.installedAt || null,
429
+ mirror: known?.mirror || null,
430
+ commands: known?.commands || null,
431
+ venv,
432
+ python,
433
+ }
434
+ })
435
+ .sort((a, b) => String(b.installedAt || '').localeCompare(String(a.installedAt || '')))
436
+ }
437
+
438
+ /**
439
+ * Deletes old engine versions, keeping the current one, the recommended one and
440
+ * the newest `keep`. A version that is running cannot be removed on Windows, so
441
+ * anything locked is skipped and reported instead of failing the batch.
442
+ */
443
+ export function pruneEngineVersions({ keep = 3 } = {}) {
444
+ const limit = Math.max(1, Math.min(10, Number(keep) || 3))
445
+ const versions = listEngineVersions().filter((v) => v.installed)
446
+ const protectedNames = new Set(versions.filter((v) => v.current || v.recommended).map((v) => v.version))
447
+ const ordered = [...versions].sort((a, b) => String(b.installedAt || '').localeCompare(String(a.installedAt || '')))
448
+ const keepNames = new Set()
449
+ for (const v of ordered) {
450
+ if (keepNames.size >= limit) break
451
+ keepNames.add(v.version)
452
+ }
453
+ const removed = []
454
+ const skipped = []
455
+ for (const v of versions) {
456
+ if (protectedNames.has(v.version) || keepNames.has(v.version)) { skipped.push(v.version); continue }
457
+ try {
458
+ fs.rmSync(engineDir(v.version), { recursive: true, force: true })
459
+ const history = ensureHistory(readCurrent())
460
+ delete history[v.version]
461
+ try { writeJson(HISTORY_FILE(), history) } catch {}
462
+ removed.push(v.version)
463
+ } catch (error) {
464
+ skipped.push(`${v.version} (${error?.code || 'locked'})`)
465
+ }
466
+ }
467
+ return { removed, skipped, kept: [...protectedNames, ...keepNames] }
468
+ }
469
+
470
+ export function removeEngineVersion(version) {
471
+ const target = listEngineVersions().find((v) => v.version === version)
472
+ if (!target) return { ok: false, error: `unknown version: ${version}` }
473
+ if (!target.installed) return { ok: false, error: `version ${version} is not installed` }
474
+ if (target.current) return { ok: false, error: 'the current version cannot be removed; switch first' }
475
+ if (!acquireLock()) return { ok: false, status: 'installing', error: 'another install is already running' }
476
+ try {
477
+ fs.rmSync(engineDir(version), { recursive: true, force: true })
478
+ const history = ensureHistory(readCurrent())
479
+ delete history[version]
480
+ try { writeJson(HISTORY_FILE(), history) } catch {}
481
+ return { ok: true }
482
+ } catch (error) {
483
+ return { ok: false, error: String(error?.message || error) }
484
+ } finally {
485
+ releaseLock()
486
+ }
487
+ }
488
+
489
+ // ---- real-database gate -----------------------------------------------------
490
+ // An empty-temp-dir probe (verifyEngine) only proves the binary starts. The
491
+ // danger is switching engines while real memory databases exist that the new
492
+ // binary cannot read — or silently downgrading a schema a newer engine wrote.
493
+ // Before the current pointer moves, the target python must read every real
494
+ // database, and a version downgrade must be forced explicitly.
495
+
496
+ function realDatabases() {
497
+ const dbs = []
498
+ try {
499
+ const globalDb = globalDbPath()
500
+ if (fs.existsSync(globalDb)) dbs.push(globalDb)
501
+ } catch {}
502
+ try {
503
+ for (const name of fs.readdirSync(librariesDir())) {
504
+ if (name.endsWith('.sqlite3')) dbs.push(path.join(librariesDir(), name))
505
+ }
506
+ } catch {}
507
+ return dbs
508
+ }
509
+
510
+ const ALEMBIC_SCRIPT = [
511
+ 'import json, sqlite3, sys',
512
+ 'db = sys.argv[1]',
513
+ 'conn = sqlite3.connect(db)',
514
+ 'try:',
515
+ ' rows = conn.execute("select version_num from alembic_version").fetchall()',
516
+ ' print(json.dumps({"versions": [r[0] for r in rows]}))',
517
+ 'except Exception as e:',
518
+ ' print(json.dumps({"versions": [], "error": str(e)}))',
519
+ 'finally:',
520
+ ' conn.close()',
521
+ ].join('\n')
522
+
523
+ async function schemaVersions(python, dbs) {
524
+ const out = {}
525
+ for (const db of dbs) {
526
+ try {
527
+ const res = await run(python, ['-c', ALEMBIC_SCRIPT, db], { timeoutMs: 30_000 })
528
+ if (res.code !== 0) throw new Error((res.stderr || `exit ${res.code}`).trim())
529
+ out[db] = JSON.parse(res.stdout.trim()).versions
530
+ } catch {
531
+ out[db] = null
532
+ }
533
+ }
534
+ return out
535
+ }
536
+
537
+ async function smokeRealDatabases(python, { log } = {}) {
538
+ const dbs = realDatabases()
539
+ for (const db of dbs) {
540
+ logLine(`smoke-reading ${path.basename(db)} with target engine`, log)
541
+ // Read-only: list-files never writes. MEMU_MEMORY_MODE stays local so the
542
+ // probe cannot touch a configured cloud backend.
543
+ const res = await run(python, ['-m', 'memu', 'list-files', '--json'], {
544
+ timeoutMs: 90_000,
545
+ env: { MEMU_DB: db, MEMU_MEMORY_MODE: 'local' },
546
+ })
547
+ if (res.code !== 0) {
548
+ throw new Error(`目标引擎读不了现有记忆库 ${path.basename(db)}:${(res.stderr || res.stdout || '').trim().slice(-400)}`)
549
+ }
550
+ }
551
+ return dbs
552
+ }
553
+
554
+ function versionRank(v) {
555
+ const m = String(v || '').match(/(\d+)\.(\d+)\.(\d+)(?:b(\d+))?/)
556
+ if (!m) return null
557
+ // A final release outranks its betas: 0.11.0 > 0.11.0b3.
558
+ return [Number(m[1]), Number(m[2]), Number(m[3]), m[4] ? Number(m[4]) : Number.MAX_SAFE_INTEGER]
559
+ }
560
+
561
+ export function isVersionDowngrade(from, to) {
562
+ const a = versionRank(from)
563
+ const b = versionRank(to)
564
+ if (!a || !b) return false
565
+ for (let i = 0; i < 4; i += 1) if (a[i] !== b[i]) return a[i] < b[i]
566
+ return false
567
+ }
568
+
569
+ // Roll back (or forward) to an already-installed version. Verified first, and the
570
+ // caller's `beforeSwitch` runs before the pointer moves, so a bad target can never
571
+ // become current and data is snapshotted on the way in.
572
+ export async function switchEngineVersion(version, { log = null, beforeSwitch = null, force = false } = {}) {
573
+ const target = listEngineVersions().find((v) => v.version === version)
574
+ if (!target || !target.installed) {
575
+ return { ok: false, error: `version ${version} is not installed` }
576
+ }
577
+ if (readCurrent()?.version === version) return { ok: true, current: readCurrent(), unchanged: true }
578
+
579
+ if (!acquireLock()) return { ok: false, status: 'installing', error: 'another install is already running' }
580
+ try {
581
+ const verified = await verifyEngineRepaired(target.python, { log, expectedVersion: version })
582
+ // Record what the probe saw, so the version list can say "usable" or "broken"
583
+ // instead of guessing from the presence of a venv directory.
584
+ recordProbe(version, verified)
585
+ if (!verified.ok) return { ok: false, error: `目标版本自检未通过:${verified.error}` }
586
+
587
+ const dbs = realDatabases()
588
+ const safety = typeof beforeSwitch === 'function' ? await beforeSwitch() : null
589
+ if (dbs.length && !safety) throw new Error('a verified backup is required before switching an engine with real databases')
590
+ if (dbs.length > 0) {
591
+ const currentMeta = readCurrent()
592
+ if (!force && currentMeta && isVersionDowngrade(version, currentMeta.version)) {
593
+ return {
594
+ ok: false,
595
+ error: `拒绝降级:现有记忆库由更新的引擎 ${currentMeta.version} 写入,切到 ${version} 可能损坏数据;如确认要降级请勾选强制`,
596
+ }
597
+ }
598
+ const beforeSchemas = await schemaVersions(currentMeta?.python || target.python, dbs)
599
+ await smokeRealDatabases(target.python, { log })
600
+ const afterSchemas = await schemaVersions(target.python, dbs)
601
+ for (const db of dbs) {
602
+ const a = JSON.stringify(beforeSchemas[db] || [])
603
+ const b = JSON.stringify(afterSchemas[db] || [])
604
+ if (a !== b && !force) throw new Error(`schema revision changed: ${a} -> ${b}; backup ${safety}; explicit confirmation is required`)
605
+ }
606
+ }
607
+
608
+ const current = {
609
+ version,
610
+ venv: target.venv,
611
+ python: target.python,
612
+ commands: verified.commands,
613
+ mirror: target.mirror,
614
+ installedAt: target.installedAt || stamp(),
615
+ switchedAt: stamp(),
616
+ }
617
+ writeJson(CURRENT_FILE(), current)
618
+ writeState({ status: 'ready', version, step: 'ready', error: null })
619
+ logLine(`switched engine to ${version}`, log)
620
+ return { ok: true, current, verified }
621
+ } catch (error) {
622
+ return { ok: false, error: String(error?.message || error) }
623
+ } finally {
624
+ releaseLock()
625
+ }
626
+ }
627
+
628
+ /** Sizes only, for the client to fetch after the page has painted. */
629
+ export function engineVersionSizes() {
630
+ const sizes = {}
631
+ for (const version of listEngineVersions()) {
632
+ if (!version.installed) continue
633
+ sizes[version.version] = sizeOfVersion(version.version, path.dirname(version.venv))
634
+ }
635
+ return sizes
636
+ }
637
+
638
+ /**
639
+ * 清掉中断安装留下的临时 venv。只动 `venv.tmp-*`:正式目录(`venv-*`)可能正是
640
+ * current.json 指向的可用引擎,绝不能误删。
641
+ */
642
+ function removeTempVenvs() {
643
+ let removed = 0
644
+ let names = []
645
+ try { names = fs.readdirSync(engineDir(ENGINE_VERSION)) } catch { return removed }
646
+ for (const name of names) {
647
+ if (!name.startsWith('venv.tmp-')) continue
648
+ try {
649
+ fs.rmSync(path.join(engineDir(ENGINE_VERSION), name), { recursive: true, force: true })
650
+ removed += 1
651
+ } catch {}
652
+ }
653
+ return removed
654
+ }
655
+
656
+ /**
657
+ * 给一次被中断的安装收尾。
658
+ *
659
+ * 安装进程被杀(宿主重启、断电、任务管理器结束进程)时,`state.json` 会永久停在
660
+ * `installing`:没有 error、没有 current、临时 venv 留在盘上。界面只能显示
661
+ * 「installing」,而实际上没有任何进程在装——2026-11-26 那次就这样卡了两天,语义
662
+ * 召回一直静默降级成关键词,没有人看得出它其实已经死了。
663
+ *
664
+ * 三条判据同时成立才动手(全部满足才算「死掉」):
665
+ * 1. `state.status === 'installing'`
666
+ * 2. 本进程没有在装(`installInFlight`),且 `install.lock` 不存在
667
+ * 3. `updatedAt` 超过 `staleMs` 没变
668
+ * 动作:落成 `failed` 并写清原因,同时清理 `venv.tmp-*` 残骸,让重装从干净状态开始。
669
+ *
670
+ * 幂等:收尾一次后 status 不再是 installing,后续轮询直接返回。
671
+ */
672
+ export function reconcileInterruptedInstall({ now = Date.now(), staleMs = STALE_INSTALL_MS } = {}) {
673
+ const state = readState()
674
+ if (state.status !== 'installing') return { changed: false, state }
675
+ if (installInFlight) return { changed: false, state }
676
+ if (fs.existsSync(LOCK_FILE())) return { changed: false, state }
677
+ const updated = Date.parse(state.updatedAt || state.startedAt || '')
678
+ if (!Number.isFinite(updated) || now - updated < staleMs) return { changed: false, state }
679
+ const removed = removeTempVenvs()
680
+ const minutes = Math.round((now - updated) / 60_000)
681
+ const next = writeState({
682
+ status: 'failed',
683
+ step: 'interrupted',
684
+ error: `安装在「${state.step || '未知步骤'}」中断,已 ${minutes} 分钟无进展;已清理 ${removed} 个未完成的 venv,请重新安装`,
685
+ })
686
+ logLine(`interrupted install reconciled: step=${state.step || '?'} idle=${minutes}min removed=${removed}`)
687
+ return { changed: true, state: next, removed }
688
+ }
689
+
690
+ export function engineStatus({ withSize = false } = {}) {
691
+ // 每次查询先收尾一次中断安装:界面读状态时就能自愈,不必等用户点安装。
692
+ reconcileInterruptedInstall()
693
+ const current = readCurrent()
694
+ const state = readState()
695
+ return {
696
+ status: current ? 'ready' : state.status || 'idle',
697
+ version: current?.version || state.version || ENGINE_VERSION,
698
+ installed: Boolean(current),
699
+ recommendedVersion: ENGINE_VERSION,
700
+ current,
701
+ state,
702
+ versions: listEngineVersions({ withSize }),
703
+ log: INSTALL_LOG(),
704
+ }
705
+ }
706
+
707
+ export function mirrorCandidates() {
708
+ // The settings page's pipIndexes list is a real user preference and must be
709
+ // honored here; env vars only add transient overrides on top.
710
+ const fromSettings = Array.isArray(getSettings().pipIndexes)
711
+ ? getSettings().pipIndexes.map((s) => String(s || '').trim()).filter(Boolean)
712
+ : []
713
+ const configured = String(process.env.DSH_MEMU_PIP_INDEXES || '')
714
+ .split(',')
715
+ .map((s) => s.trim())
716
+ .filter(Boolean)
717
+ const envIndex = String(process.env.PIP_INDEX_URL || '').trim()
718
+ const list = envIndex ? [envIndex, ...fromSettings, ...configured, ...DEFAULT_INDEXES] : [...fromSettings, ...configured, ...DEFAULT_INDEXES]
719
+ return [...new Set(list)]
720
+ }
721
+
722
+ function sleep(ms) {
723
+ return new Promise((r) => setTimeout(r, ms))
724
+ }
725
+
726
+ function acquireLock() {
727
+ ensureDir(engineDir())
728
+ const file = LOCK_FILE()
729
+ try {
730
+ const fd = fs.openSync(file, 'wx')
731
+ fs.writeFileSync(fd, JSON.stringify({ pid: process.pid, startedAt: stamp() }), 'utf8')
732
+ fs.closeSync(fd)
733
+ // 三个受锁流程(安装 / 切版本 / 删版本)都会走到这里,标志放在锁上最稳:
734
+ // reconcile 只看「本进程有没有持锁」就能区分活干和尸体。
735
+ installInFlight = true
736
+ return true
737
+ } catch (error) {
738
+ if (error?.code !== 'EEXIST') throw error
739
+ const existing = readJson(file, null)
740
+ const started = existing?.startedAt ? Date.parse(existing.startedAt) : 0
741
+ if (Date.now() - started > 30 * 60 * 1000) {
742
+ // 过期锁用 rename 原子接管:两个进程同时发现过期时只有一个 rename 成功,
743
+ // 另一个会 ENOENT 拿到 false,不会出现“先删再递归抢”被两个进程同时拿到。
744
+ try {
745
+ const stale = file + '.stale-' + crypto.randomUUID()
746
+ fs.renameSync(file, stale)
747
+ try { fs.rmSync(stale, { force: true }) } catch {}
748
+ return acquireLock()
749
+ } catch {
750
+ return false
751
+ }
752
+ }
753
+ return false
754
+ }
755
+ }
756
+
757
+ function releaseLock() {
758
+ installInFlight = false
759
+ try { fs.rmSync(LOCK_FILE(), { force: true }) } catch {}
760
+ }
761
+
762
+ async function pythonVersion(cmd, prefix = []) {
763
+ const res = await run(cmd, [...prefix, '-c', 'import sys; print(f"{sys.version_info[0]}.{sys.version_info[1]}.{sys.version_info[2]}")'], {
764
+ timeoutMs: 15_000,
765
+ })
766
+ if (res.code !== 0) return null
767
+ const text = res.stdout.trim().split(/\r?\n/).pop() || ''
768
+ const m = /^(\d+)\.(\d+)\.(\d+)$/.exec(text)
769
+ if (!m) return null
770
+ return { major: Number(m[1]), minor: Number(m[2]), patch: Number(m[3]), raw: text }
771
+ }
772
+
773
+ async function hasPip(cmd, prefix = []) {
774
+ const res = await run(cmd, [...prefix, '-m', 'pip', '--version'], { timeoutMs: 20_000 })
775
+ return res.code === 0
776
+ }
777
+
778
+ function dshRuntimePythons() {
779
+ const out = []
780
+ const runtimeRoot = path.join(
781
+ process.env.DSH_HOME || path.join(os.homedir(), '.dsh'),
782
+ 'dsh-runtimes',
783
+ )
784
+ try {
785
+ for (const name of fs.readdirSync(runtimeRoot)) {
786
+ const base = path.join(runtimeRoot, name, 'dependencies', 'python')
787
+ const exe = isWindows() ? path.join(base, 'python.exe') : path.join(base, 'bin', 'python3')
788
+ if (fs.existsSync(exe)) out.push(exe)
789
+ }
790
+ } catch {}
791
+ if (process.env.DSH_RUNTIME_PYTHON && fs.existsSync(process.env.DSH_RUNTIME_PYTHON)) {
792
+ out.unshift(process.env.DSH_RUNTIME_PYTHON)
793
+ }
794
+ return out
795
+ }
796
+
797
+ async function pythonCandidate(cmd, prefix = [], source = 'path') {
798
+ const version = await pythonVersion(cmd, prefix)
799
+ if (!version || version.major !== 3 || version.minor < 11) return null
800
+ const pip = await hasPip(cmd, prefix)
801
+ return { kind: 'python', cmd, prefix, version, hasPip: pip, source }
802
+ }
803
+
804
+ export async function resolvePythonCandidates() {
805
+ const out = []
806
+ const seen = new Set()
807
+ const push = (c) => {
808
+ if (!c) return
809
+ const key = `${c.cmd}|${c.prefix.join(' ')}`
810
+ if (seen.has(key)) return
811
+ seen.add(key)
812
+ out.push(c)
813
+ }
814
+
815
+ if (process.env.DSH_MEMU_PYTHON) {
816
+ push(await pythonCandidate(process.env.DSH_MEMU_PYTHON, [], 'env'))
817
+ }
818
+
819
+ // Prefer interpreters with reliable wheels: 3.13, 3.12, DSH bundled, then 3.14.
820
+ for (const ver of ['3.13', '3.12', '3.11']) {
821
+ push(await pythonCandidate('py', [`-${ver}`], `py ${ver}`))
822
+ }
823
+ for (const exe of dshRuntimePythons()) {
824
+ push(await pythonCandidate(exe, [], 'dsh-runtime'))
825
+ }
826
+ for (const exe of ['python3', 'python']) {
827
+ push(await pythonCandidate(exe, [], exe))
828
+ }
829
+ push(await pythonCandidate('py', ['-3.14'], 'py 3.14'))
830
+
831
+ return out
832
+ }
833
+
834
+ async function cleanupDir(dir) {
835
+ try { await fsp.rm(dir, { recursive: true, force: true }) } catch {}
836
+ }
837
+
838
+ async function cleanupDownloads() {
839
+ try {
840
+ const dir = downloadsDir()
841
+ for (const name of await fsp.readdir(dir)) {
842
+ await fsp.rm(path.join(dir, name), { recursive: true, force: true })
843
+ }
844
+ } catch {}
845
+ }
846
+
847
+ async function installIntoVenv({ base, venv, mirror, log }) {
848
+ const python = venvPython(venv)
849
+ if (base.uvPath) {
850
+ const result = await run(base.uvPath, ['pip', 'install', '--python', python, '-r', LOCK_PATH,
851
+ '--index-url', mirror, '--only-binary', ':all:', '--no-cache', '--no-progress'],
852
+ { env: base.uvEnv, timeoutMs: 20 * 60 * 1000, onData: data => logLine(data.trim(), log) })
853
+ if (result.code !== 0) throw new Error(`managed uv dependency install failed (exit ${result.code})`)
854
+ return
855
+ }
856
+ if (!base.hasPip) {
857
+ throw new Error(`Python ${base.cmd} ${base.prefix.join(' ')} has no pip; install pip or uv first`)
858
+ }
859
+ logLine(`pip install using ${mirror}`, log)
860
+ const res = await run(base.cmd, [
861
+ ...base.prefix,
862
+ '-m', 'pip', '--python', python,
863
+ 'install', '-r', LOCK_PATH,
864
+ '--index-url', mirror,
865
+ '--disable-pip-version-check',
866
+ '--no-input',
867
+ '--no-cache-dir',
868
+ '--only-binary=:all:',
869
+ '--timeout', '45',
870
+ '--retries', '3',
871
+ ], {
872
+ env: { PIP_NO_CACHE_DIR: '1', PIP_DISABLE_PIP_VERSION_CHECK: '1' },
873
+ timeoutMs: 20 * 60 * 1000,
874
+ onData: (s) => {
875
+ for (const line of s.split(/\r?\n/)) if (line.trim()) logLine(line.trim(), log)
876
+ },
877
+ })
878
+ if (res.code !== 0) {
879
+ const detail = (res.stderr || res.stdout || '').trim().split(/\r?\n/).slice(-6).join(' | ')
880
+ throw new Error(`pip install failed (exit ${res.code}${res.timedOut ? ', timeout' : ''}): ${detail}`)
881
+ }
882
+ }
883
+
884
+ async function parseMemuCommands(python) {
885
+ const res = await run(python, ['-m', 'memu', '--help'], { timeoutMs: 30_000 })
886
+ if (res.code !== 0) {
887
+ return { ok: false, error: (res.stderr || res.stdout || 'memu --help failed').trim() }
888
+ }
889
+ const text = `${res.stdout}\n${res.stderr}`
890
+ const commands = new Set()
891
+ for (const name of [...REQUIRED_COMMANDS, ...OPTIONAL_COMMANDS]) {
892
+ if (new RegExp(`(^|[\\s{,])(?:${name}|${name}\\s*\\()`, 'm').test(text)) commands.add(name)
893
+ }
894
+ return { ok: true, commands: [...commands], help: text }
895
+ }
896
+
897
+ export async function verifyEngine(python, { log, expectedVersion = null } = {}) {
898
+ const versionRes = await run(python, ['-c', 'import importlib.metadata as m; print(m.version("memu-cli"))'], {
899
+ timeoutMs: 30_000,
900
+ })
901
+ if (versionRes.code !== 0) {
902
+ return { ok: false, error: `memu-cli import failed: ${(versionRes.stderr || versionRes.stdout).trim()}` }
903
+ }
904
+ const version = versionRes.stdout.trim().split(/\r?\n/).pop() || ''
905
+ if (expectedVersion && normalizeVersion(version) !== normalizeVersion(expectedVersion)) {
906
+ return { ok: false, version, error: 'memu-cli version mismatch: expected ' + expectedVersion + ', got ' + version }
907
+ }
908
+ const commands = await parseMemuCommands(python)
909
+ if (!commands.ok) return { ok: false, version, error: commands.error }
910
+ const missing = REQUIRED_COMMANDS.filter((c) => !commands.commands.includes(c))
911
+ if (missing.length > 0) {
912
+ return { ok: false, version, commands: commands.commands, error: `missing required commands: ${missing.join(', ')}` }
913
+ }
914
+ const tmpDb = path.join(os.tmpdir(), `dsh-memu-memory-smoke-${process.pid}-${Date.now()}.sqlite3`)
915
+ try {
916
+ const res = await run(python, ['-m', 'memu', 'list-files', '--json', '--db', tmpDb], { timeoutMs: 60_000 })
917
+ if (res.code !== 0) {
918
+ return { ok: false, version, commands: commands.commands, error: `list-files smoke failed: ${(res.stderr || res.stdout).trim()}` }
919
+ }
920
+ try { JSON.parse(res.stdout) } catch {
921
+ return { ok: false, version, commands: commands.commands, error: 'list-files smoke returned non-JSON' }
922
+ }
923
+ } finally {
924
+ try { fs.rmSync(tmpDb, { force: true }) } catch {}
925
+ try { fs.rmSync(`${tmpDb}-wal`, { force: true }) } catch {}
926
+ try { fs.rmSync(`${tmpDb}-shm`, { force: true }) } catch {}
927
+ }
928
+ logLine(`engine verified: memu-cli ${version}, commands ${commands.commands.join(',')}`, log)
929
+ return { ok: true, version, commands: commands.commands }
930
+ }
931
+
932
+ function stateInstalling(step, extra = {}) {
933
+ const previous = readState()
934
+ return writeState({
935
+ status: 'installing',
936
+ version: ENGINE_VERSION,
937
+ step,
938
+ error: null,
939
+ // Keep the first start time across step updates so the UI shows elapsed time
940
+ // instead of restarting its clock every time the step advances.
941
+ startedAt: previous.status === 'installing' && previous.startedAt ? previous.startedAt : stamp(),
942
+ ...extra,
943
+ })
944
+ }
945
+
946
+ function stateError(error, extra = {}) {
947
+ const previous = readState()
948
+ return writeState({
949
+ status: 'error',
950
+ version: ENGINE_VERSION,
951
+ step: 'failed',
952
+ error: String(error?.message || error),
953
+ startedAt: previous.startedAt || null,
954
+ finishedAt: stamp(),
955
+ ...extra,
956
+ })
957
+ }
958
+
959
+ // The installer already writes every step to ~/.dsh/dsh-memu-memory/logs/install.log.
960
+ // Surfacing the tail turns "Installing…" from a black box into progress: pip's own
961
+ // lines say which package it is on when a mirror stalls.
962
+ export function readInstallLogTail(maxLines = 14, maxBytes = 24 * 1024) {
963
+ try {
964
+ const stat = fs.statSync(INSTALL_LOG())
965
+ const start = Math.max(0, stat.size - maxBytes)
966
+ const fd = fs.openSync(INSTALL_LOG(), 'r')
967
+ const buffer = Buffer.alloc(stat.size - start)
968
+ try { fs.readSync(fd, buffer, 0, buffer.length, start) } finally { fs.closeSync(fd) }
969
+ return buffer.toString('utf8').split(/\r?\n/).filter((line) => line.trim()).slice(-maxLines)
970
+ } catch {
971
+ return []
972
+ }
973
+ }
974
+
975
+ export async function installEngine({ force = false, log = null, beforeSwitch = null } = {}) {
976
+ const current = readCurrent()
977
+ if (!force && current?.version === ENGINE_VERSION) {
978
+ const verified = await verifyEngineRepaired(current.python, { log })
979
+ if (verified.ok) return { ok: true, current, verified }
980
+ }
981
+
982
+ if (!acquireLock()) {
983
+ return { ok: false, status: 'installing', error: 'another install is already running' }
984
+ }
985
+
986
+ try {
987
+ ensureDir(engineDir())
988
+ ensureDir(downloadsDir())
989
+ stateInstalling('resolving-python')
990
+ logLine(`installing MemU engine ${ENGINE_VERSION}`, log)
991
+
992
+ const candidates = await resolvePythonCandidates()
993
+ if (!candidates.some(candidate => candidate.hasPip)) candidates.push(await ensureManagedPython({ run, log: line => logLine(line, log) }))
994
+ logLine(`python candidates: ${candidates.map((c) => `${c.cmd} ${c.prefix.join(' ')} (${c.version.raw}${c.hasPip ? '' : ', no-pip'})`).join('; ')}`, log)
995
+
996
+ const errors = []
997
+ const versionDir = engineDir(ENGINE_VERSION)
998
+ ensureDir(versionDir)
999
+
1000
+ for (const base of candidates) {
1001
+ if (!base.hasPip && !base.uvPath) continue
1002
+ const tmpVenv = path.join(versionDir, `venv.tmp-${process.pid}-${Date.now()}`)
1003
+ try {
1004
+ stateInstalling(`creating-venv:${base.source}`)
1005
+ logLine(`creating venv with ${base.cmd} ${base.prefix.join(' ')}`, log)
1006
+ const venvRes = await run(base.cmd, [...base.prefix, '-m', 'venv', '--without-pip', tmpVenv], {
1007
+ timeoutMs: 120_000,
1008
+ onData: (s) => { for (const line of s.split(/\r?\n/)) if (line.trim()) logLine(line.trim(), log) },
1009
+ })
1010
+ if (venvRes.code !== 0) {
1011
+ throw new Error(`venv creation failed: ${(venvRes.stderr || venvRes.stdout).trim()}`)
1012
+ }
1013
+
1014
+ stateInstalling(`installing-deps:${base.source}`)
1015
+ let installed = false
1016
+ let lastMirror = ''
1017
+ for (const mirror of mirrorCandidates()) {
1018
+ lastMirror = mirror
1019
+ try {
1020
+ await installIntoVenv({ base, venv: tmpVenv, mirror, log })
1021
+ installed = true
1022
+ break
1023
+ } catch (error) {
1024
+ errors.push(`${base.source} @ ${mirror}: ${error.message}`)
1025
+ logLine(`mirror failed: ${mirror}: ${error.message}`, log)
1026
+ }
1027
+ }
1028
+ if (!installed) throw new Error(`all mirrors failed for ${base.source}`)
1029
+
1030
+ stateInstalling(`verifying:${base.source}`)
1031
+ const python = venvPython(tmpVenv)
1032
+ const verified = await verifyEngineRepaired(python, { log, expectedVersion: ENGINE_VERSION })
1033
+ if (!verified.ok) throw new Error(`verify failed: ${verified.error}`)
1034
+
1035
+ if (typeof beforeSwitch === 'function') {
1036
+ stateInstalling('backing-up')
1037
+ await beforeSwitch()
1038
+ }
1039
+ if (realDatabases().length) {
1040
+ if (typeof beforeSwitch !== 'function') throw new Error('a verified backup is required before repairing an engine with real databases')
1041
+ await smokeRealDatabases(python, { log })
1042
+ }
1043
+
1044
+ const finalVenv = fs.existsSync(path.join(versionDir, 'venv'))
1045
+ ? path.join(versionDir, `venv-${Date.now()}`)
1046
+ : path.join(versionDir, 'venv')
1047
+ await fsp.rename(tmpVenv, finalVenv)
1048
+ const finalPython = venvPython(finalVenv)
1049
+ const current = {
1050
+ version: ENGINE_VERSION,
1051
+ venv: finalVenv,
1052
+ python: finalPython,
1053
+ commands: verified.commands,
1054
+ mirror: lastMirror,
1055
+ installedAt: stamp(),
1056
+ }
1057
+ writeJson(CURRENT_FILE(), current)
1058
+ recordHistory(current)
1059
+ writeState({ status: 'ready', version: ENGINE_VERSION, step: 'ready', error: null, mirror: lastMirror })
1060
+ await cleanupDownloads()
1061
+ // New engine landed: keep the version count honest without waiting for
1062
+ // a manual prune. Never blocks the result.
1063
+ try { pruneEngineVersions({ keep: 3 }) } catch {}
1064
+ logLine(`engine ready: ${finalPython}`, log)
1065
+ return { ok: true, current, verified }
1066
+ } catch (error) {
1067
+ await cleanupDir(tmpVenv)
1068
+ errors.push(`${base.source}: ${error.message}`)
1069
+ logLine(`candidate failed: ${base.source}: ${error.message}`, log)
1070
+ }
1071
+ }
1072
+
1073
+ let message = `no Python candidate could install MemU:\n${errors.join('\n')}`
1074
+ if (isMac() && errors.some((e) => isMacOSLibraryValidationError(e))) {
1075
+ message += '\n(macOS 签名校验拒绝了依赖包的 .so;可对 Python 解释器执行 `codesign --force --sign - <python路径>` 后重试,或在设置里用 DSH_MEMU_PYTHON 指定 Homebrew/官方 Python)'
1076
+ }
1077
+ throw new Error(message)
1078
+ } catch (error) {
1079
+ stateError(error)
1080
+ await cleanupDownloads()
1081
+ logLine(`install failed: ${error.message}`, log)
1082
+ return { ok: false, status: 'error', error: String(error?.message || error) }
1083
+ } finally {
1084
+ releaseLock()
1085
+ }
1086
+ }
1087
+
1088
+ export async function ensureEngine({ force = false, log = null, beforeSwitch = null } = {}) {
1089
+ // 带着一次死掉的安装开始新一轮,会先撞上 installing 中间态和 venv.tmp 残骸;
1090
+ // 先收尾再读 current,重装才能从干净状态起跑。
1091
+ reconcileInterruptedInstall()
1092
+ const current = readCurrent()
1093
+ if (!force && current?.version === ENGINE_VERSION) {
1094
+ const verified = await verifyEngineRepaired(current.python, { log })
1095
+ if (verified.ok) {
1096
+ writeState({ status: 'ready', version: ENGINE_VERSION, step: 'ready', error: null })
1097
+ return { ok: true, current, verified }
1098
+ }
1099
+ logLine(`current engine failed verification: ${verified.error}; reinstalling`, log)
1100
+ }
1101
+ return installEngine({ force: true, log, beforeSwitch })
1102
+ }
1103
+