dsh-memu-memory 1.4.2 → 1.4.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (389) hide show
  1. package/AGENTS.md +108 -110
  2. package/CHANGELOG.md +173 -868
  3. package/LICENSE +21 -21
  4. package/README.md +368 -374
  5. package/README.zh.md +354 -360
  6. package/assets/icon.svg +7 -7
  7. package/cordis.patch.yml +8 -8
  8. package/docs/active-memory-ab.md +279 -385
  9. package/docs/binding-lifecycle.md +99 -99
  10. package/docs/client-conventions.md +75 -75
  11. package/docs/contributing.md +217 -217
  12. package/docs/emotion-model-spec.md +247 -281
  13. package/docs/env-and-commands.md +149 -152
  14. package/docs/host-adaptation.md +339 -360
  15. package/docs/host-api.md +131 -137
  16. package/docs/host-versions.md +117 -120
  17. package/docs/mcp-porting.md +146 -146
  18. package/docs/memory-semantics.md +271 -259
  19. package/docs/pending-work.md +44 -51
  20. package/docs/troubleshooting.md +909 -854
  21. package/lib/active-memory.js +160 -165
  22. package/lib/activity-log.js +207 -207
  23. package/lib/auto-link/apply.js +248 -249
  24. package/lib/auto-link/candidates.js +163 -163
  25. package/lib/auto-link/decide.js +300 -300
  26. package/lib/auto-link/normalize.js +99 -99
  27. package/lib/auto-link/policy.js +42 -42
  28. package/lib/auto-link/suppression.js +101 -101
  29. package/lib/auto-link/terminology.js +311 -311
  30. package/lib/backup.js +1254 -1254
  31. package/lib/binding-diagnostics.js +634 -634
  32. package/lib/budget.js +118 -118
  33. package/lib/client.js +9820 -9751
  34. package/lib/commitment.js +178 -138
  35. package/lib/consolidation-ledger.js +434 -438
  36. package/lib/consolidation-receipt.js +386 -387
  37. package/lib/consolidation-snapshot.js +420 -405
  38. package/lib/consolidation-worker.js +240 -241
  39. package/lib/context.js +33 -33
  40. package/lib/curator-evidence.js +131 -131
  41. package/lib/curator-policy.js +198 -202
  42. package/lib/curator.js +1813 -1811
  43. package/lib/cycle.js +524 -513
  44. package/lib/diagnostics.js +524 -524
  45. package/lib/embedding-catalog.js +1051 -1055
  46. package/lib/embedding-download.js +637 -607
  47. package/lib/embedding-runtime.js +946 -946
  48. package/lib/engine.js +1103 -1103
  49. package/lib/entity-repair.js +285 -285
  50. package/lib/environment-check.js +394 -394
  51. package/lib/fork-model.js +312 -312
  52. package/lib/freshness.js +128 -121
  53. package/lib/global-graph.js +389 -389
  54. package/lib/graph.js +1193 -1193
  55. package/lib/host-surface.js +30 -30
  56. package/lib/inbound.js +284 -281
  57. package/lib/index.js +506 -511
  58. package/lib/inject.js +2639 -2619
  59. package/lib/lexicon-scope.js +143 -143
  60. package/lib/lexicon.js +1183 -1192
  61. package/lib/lifecycle-audit.js +37 -0
  62. package/lib/local-embedding-entry.js +145 -145
  63. package/lib/local-embedding-manager.js +306 -306
  64. package/lib/local-embedding-protocol.js +210 -210
  65. package/lib/local-embedding-worker.js +682 -682
  66. package/lib/local-vector-service.js +506 -453
  67. package/lib/maintenance-ledger.js +138 -0
  68. package/lib/maintenance-review.js +103 -0
  69. package/lib/maintenance-runner.js +267 -0
  70. package/lib/managed-runtime.js +118 -118
  71. package/lib/media.js +607 -513
  72. package/lib/memory.js +5035 -4941
  73. package/lib/memu-config.js +213 -213
  74. package/lib/memu.js +565 -565
  75. package/lib/migrate.js +200 -200
  76. package/lib/mood.js +300 -300
  77. package/lib/paths.js +453 -457
  78. package/lib/port-surface.js +82 -82
  79. package/lib/preset-mount.js +85 -0
  80. package/lib/preset-scope.js +126 -126
  81. package/lib/private-links.js +567 -567
  82. package/lib/private.js +2198 -2209
  83. package/lib/prompts/global-curator.md +135 -135
  84. package/lib/prompts/image-caption.md +1 -1
  85. package/lib/prompts/private-consolidation.coding.md +39 -39
  86. package/lib/prompts/private-consolidation.md +32 -32
  87. package/lib/prompts/private-consolidation.mixed.md +37 -37
  88. package/lib/prompts/private-consolidation.rp.md +47 -47
  89. package/lib/prompts/private-policy.coding.md +35 -35
  90. package/lib/prompts/private-policy.md +36 -36
  91. package/lib/prompts/private-policy.mixed.md +29 -29
  92. package/lib/prompts/private-policy.rp.md +43 -43
  93. package/lib/prompts/system-guide.coding.md +20 -20
  94. package/lib/prompts/system-guide.md +25 -25
  95. package/lib/prompts/system-guide.mixed.md +22 -22
  96. package/lib/prompts/system-guide.rp.md +23 -23
  97. package/lib/prompts.js +331 -331
  98. package/lib/recall-cache.js +212 -212
  99. package/lib/remote-summary.js +123 -123
  100. package/lib/rpc.js +2531 -2532
  101. package/lib/salient-wake.js +438 -438
  102. package/lib/snippet.js +125 -125
  103. package/lib/state.js +1948 -1928
  104. package/lib/stats.js +236 -236
  105. package/lib/temporal.js +345 -348
  106. package/lib/text-retrieval.js +992 -1001
  107. package/lib/text-similarity.js +305 -305
  108. package/lib/tokenizer-v2.js +271 -271
  109. package/lib/tools.js +1098 -1091
  110. package/lib/turn-log.js +545 -545
  111. package/lib/vector-migration.js +928 -930
  112. package/lib/vector-profile.js +1353 -1359
  113. package/lib/visibility.js +59 -59
  114. package/lib/webui/graph-LICENSE.txt +1 -1
  115. package/lib/webui/graph-view.bundle.js +2 -2
  116. package/lib/webui/graph-view.js +1171 -1175
  117. package/lib/webui/mark.svg +7 -7
  118. package/lib/webui/standalone.css +1178 -1178
  119. package/lib/webui/standalone.js +238 -238
  120. package/lib/webui.js +136 -136
  121. package/lib/worker-pool.js +1020 -979
  122. package/package.json +153 -153
  123. package/requirements.lock +34 -34
  124. package/scripts/acceptance-local.mjs +946 -946
  125. package/scripts/active-memory-ab-live.mjs +653 -655
  126. package/scripts/active-memory-ab.mjs +1302 -1302
  127. package/scripts/audit-memory-lifecycle.mjs +55 -0
  128. package/scripts/bench-recall.mjs +142 -142
  129. package/scripts/build-graph.mjs +44 -45
  130. package/scripts/chain-matrix.mjs +541 -541
  131. package/scripts/check-all.mjs +68 -74
  132. package/scripts/check-doc-drift.mjs +547 -547
  133. package/scripts/check-graph-browser.mjs +261 -261
  134. package/scripts/check-i18n.mjs +81 -83
  135. package/scripts/check-idle-compositing.mjs +61 -61
  136. package/scripts/check-seed-compat.mjs +115 -118
  137. package/scripts/check-text-format.mjs +55 -0
  138. package/scripts/curator-pair-calibrate.mjs +259 -259
  139. package/scripts/diagnose-bindings.mjs +176 -176
  140. package/scripts/drive-session.mjs +863 -864
  141. package/scripts/engine-smoke.mjs +69 -69
  142. package/scripts/entity-dedupe.mjs +110 -110
  143. package/scripts/lexicon-calibrate.mjs +230 -230
  144. package/scripts/lexicon-dedupe.mjs +318 -318
  145. package/scripts/local-runtime-install.mjs +142 -142
  146. package/scripts/local-runtime-verify.mjs +56 -56
  147. package/scripts/local-vector-verify.mjs +93 -93
  148. package/scripts/make-readme-shots.mjs +59 -59
  149. package/scripts/migrate-visibility.mjs +94 -94
  150. package/scripts/mock-llm.mjs +938 -903
  151. package/scripts/preview.mjs +58 -58
  152. package/scripts/prune-sessions.mjs +31 -34
  153. package/scripts/prune-turnlogs.mjs +29 -30
  154. package/scripts/prune-vectors.mjs +24 -24
  155. package/scripts/rebuild-auto-links.mjs +252 -252
  156. package/scripts/recall-bench.mjs +820 -820
  157. package/scripts/repetition-ab-scenarios.mjs +93 -93
  158. package/scripts/repetition-detector-snapshot.mjs +314 -314
  159. package/scripts/repetition-eval-live.mjs +360 -360
  160. package/scripts/repetition-eval.mjs +702 -702
  161. package/scripts/replay.mjs +705 -575
  162. package/scripts/setup.mjs +46 -46
  163. package/scripts/simulate-injection.mjs +299 -301
  164. package/tests/absorb-review.test.mjs +354 -354
  165. package/tests/activation.test.mjs +89 -89
  166. package/tests/active-memory-ab.test.mjs +745 -745
  167. package/tests/active-memory.test.mjs +129 -129
  168. package/tests/activity-log.test.mjs +126 -126
  169. package/tests/activity-wiring.test.mjs +155 -155
  170. package/tests/appendix-b.test.mjs +217 -217
  171. package/tests/appendix-b2.test.mjs +166 -166
  172. package/tests/audit-batch3.test.mjs +247 -247
  173. package/tests/audit-regression.test.mjs +275 -275
  174. package/tests/audit-safety.test.mjs +227 -227
  175. package/tests/auto-link-candidates.test.mjs +245 -245
  176. package/tests/auto-link-decide.test.mjs +512 -512
  177. package/tests/auto-link-migration.test.mjs +133 -133
  178. package/tests/backend-compensation.test.mjs +272 -272
  179. package/tests/backup.test.mjs +793 -793
  180. package/tests/binding-diagnostics.test.mjs +720 -720
  181. package/tests/browser.test.mjs +476 -476
  182. package/tests/client-export.test.mjs +521 -521
  183. package/tests/client-render.test.mjs +2008 -1728
  184. package/tests/coalesce.test.mjs +113 -113
  185. package/tests/commitment.test.mjs +243 -144
  186. package/tests/config.test.mjs +159 -159
  187. package/tests/consolidation-credential.test.mjs +330 -330
  188. package/tests/consolidation-feed.test.mjs +122 -122
  189. package/tests/consolidation-fork.test.mjs +1587 -1539
  190. package/tests/consolidation-ledger.test.mjs +389 -389
  191. package/tests/consolidation-snapshot.test.mjs +567 -505
  192. package/tests/consolidation-value.test.mjs +89 -89
  193. package/tests/context-scope.test.mjs +40 -40
  194. package/tests/cross-library-recall.test.mjs +269 -269
  195. package/tests/cue.test.mjs +58 -58
  196. package/tests/curator-absorb.test.mjs +444 -444
  197. package/tests/curator-calibrate.test.mjs +173 -173
  198. package/tests/curator-clusters.test.mjs +306 -306
  199. package/tests/curator-commit.test.mjs +325 -325
  200. package/tests/curator-contract.test.mjs +191 -191
  201. package/tests/curator-evidence.test.mjs +102 -102
  202. package/tests/curator-link.test.mjs +317 -317
  203. package/tests/curator-pairing.test.mjs +339 -339
  204. package/tests/curator-probe.test.mjs +490 -490
  205. package/tests/curator-review-mode.test.mjs +315 -315
  206. package/tests/curator.test.mjs +152 -152
  207. package/tests/cycle.test.mjs +567 -568
  208. package/tests/diagnostics.test.mjs +278 -278
  209. package/tests/disclosure.test.mjs +249 -249
  210. package/tests/doc-drift.test.mjs +342 -342
  211. package/tests/drive-session.test.mjs +152 -152
  212. package/tests/dynamic-rrf.test.mjs +182 -182
  213. package/tests/dynamic-threshold.test.mjs +52 -52
  214. package/tests/embedding-catalog.test.mjs +374 -374
  215. package/tests/embedding-download.test.mjs +529 -486
  216. package/tests/embedding-runtime.test.mjs +449 -449
  217. package/tests/emotion-chain.test.mjs +84 -84
  218. package/tests/emotion-contract.test.mjs +445 -445
  219. package/tests/engine.test.mjs +108 -108
  220. package/tests/entity-merge.test.mjs +278 -278
  221. package/tests/environment-check.test.mjs +187 -187
  222. package/tests/fact-version.test.mjs +146 -146
  223. package/tests/fixtures/active-memory-ab/README.md +56 -56
  224. package/tests/fixtures/active-memory-ab/cases/01-clean-dense-turn.json +351 -351
  225. package/tests/fixtures/active-memory-ab/cases/02-clean-thin-turn.json +122 -122
  226. package/tests/fixtures/active-memory-ab/cases/03-clean-starved-small.json +125 -125
  227. package/tests/fixtures/active-memory-ab/cases/04-clean-large-thin.json +137 -137
  228. package/tests/fixtures/active-memory-ab/cases/05-clean-half-step.json +166 -166
  229. package/tests/fixtures/active-memory-ab/cases/06-clean-duplicate-reread.json +197 -197
  230. package/tests/fixtures/active-memory-ab/cases/07-clean-recent-recall.json +125 -125
  231. package/tests/fixtures/active-memory-ab/cases/08-global-relevant.json +111 -111
  232. package/tests/fixtures/active-memory-ab/cases/09-global-irrelevant-conflict.json +158 -158
  233. package/tests/fixtures/active-memory-ab/cases/10-no-human-turn.json +97 -97
  234. package/tests/fixtures/active-memory-ab/cases/11-clean-scale-100.json +137 -137
  235. package/tests/fixtures/active-memory-ab/cases/12-clean-scale-1000.json +137 -137
  236. package/tests/fixtures/active-memory-ab/cases/13-clean-scale-5000.json +137 -137
  237. package/tests/fixtures/active-memory-ab/cases/14-clean-scale-20000.json +137 -137
  238. package/tests/fixtures/active-memory-ab/lead-ai-reviewed-reference.json +191 -191
  239. package/tests/fixtures/active-memory-ab/manifest.json +199 -199
  240. package/tests/fixtures/curator-pairs/labeled.v1.jsonl +90 -90
  241. package/tests/fixtures/lexicon-stub-hooks.mjs +15 -15
  242. package/tests/fixtures/lexicon-stub.mjs +284 -284
  243. package/tests/fixtures/mock-llm/reply.txt +1 -1
  244. package/tests/fixtures/recall-bench/01-paraphrase.json +183 -183
  245. package/tests/fixtures/recall-bench/02-exact.json +152 -152
  246. package/tests/fixtures/recall-bench/03-negation.json +172 -172
  247. package/tests/fixtures/recall-bench/04-no-answer.json +161 -161
  248. package/tests/fixtures/recall-bench/05-conflict.json +193 -193
  249. package/tests/fixtures/recall-bench/06-boundary.json +272 -272
  250. package/tests/fixtures/recall-bench/07-secret.json +190 -190
  251. package/tests/fixtures/recall-bench/08-coding.json +163 -163
  252. package/tests/fixtures/recall-bench-gold-candidates/01-paraphrase.json +193 -193
  253. package/tests/fixtures/recall-bench-gold-candidates/02-exact.json +197 -197
  254. package/tests/fixtures/recall-bench-gold-candidates/03-negation.json +244 -244
  255. package/tests/fixtures/recall-bench-gold-candidates/04-no-answer.json +189 -189
  256. package/tests/fixtures/recall-bench-gold-candidates/05-conflict.json +245 -245
  257. package/tests/fixtures/recall-bench-gold-candidates/06-boundary.json +279 -279
  258. package/tests/fixtures/recall-bench-gold-candidates/07-secret.json +224 -224
  259. package/tests/fixtures/recall-bench-gold-candidates/08-coding.json +218 -218
  260. package/tests/fixtures/repetition-eval/01-zh-rp.json +92 -92
  261. package/tests/fixtures/repetition-eval/02-en.json +96 -96
  262. package/tests/fixtures/repetition-eval/03-code.json +90 -90
  263. package/tests/fixtures/repetition-eval/04-names.json +115 -115
  264. package/tests/fixtures/repetition-eval/05-user-quote.json +95 -95
  265. package/tests/fixtures/repetition-eval/06-agreement.json +85 -85
  266. package/tests/fixtures/tokenizer-cases.mjs +27 -27
  267. package/tests/fork-model.test.mjs +345 -345
  268. package/tests/freshness.test.mjs +140 -140
  269. package/tests/global-graph.test.mjs +106 -106
  270. package/tests/global-lifecycle.test.mjs +149 -149
  271. package/tests/graph-cascade.test.mjs +363 -363
  272. package/tests/graph-view.test.mjs +414 -414
  273. package/tests/graph.test.mjs +371 -371
  274. package/tests/help-page.test.mjs +416 -416
  275. package/tests/hook-order.test.mjs +72 -72
  276. package/tests/humanlike.test.mjs +232 -232
  277. package/tests/hybrid-recall.test.mjs +610 -610
  278. package/tests/inbound.test.mjs +441 -441
  279. package/tests/inject-conflict.test.mjs +173 -173
  280. package/tests/inject-guide.test.mjs +513 -513
  281. package/tests/inject.test.mjs +384 -384
  282. package/tests/injection-budget-settings.test.mjs +35 -35
  283. package/tests/injection-budget.test.mjs +165 -165
  284. package/tests/injection-chain.test.mjs +442 -442
  285. package/tests/injection-intent-budget.test.mjs +92 -92
  286. package/tests/injection-rollback.test.mjs +428 -428
  287. package/tests/issue2-chain.test.mjs +169 -169
  288. package/tests/lexical-bm25.test.mjs +171 -171
  289. package/tests/lexicon-calibrate.test.mjs +48 -48
  290. package/tests/lexicon-dedupe.test.mjs +171 -171
  291. package/tests/lexicon-frequency.test.mjs +195 -195
  292. package/tests/lexicon-inject.test.mjs +459 -459
  293. package/tests/lexicon-perf.test.mjs +464 -464
  294. package/tests/lexicon-scope.test.mjs +256 -256
  295. package/tests/lexicon-ui.test.mjs +667 -667
  296. package/tests/lexicon.test.mjs +922 -922
  297. package/tests/lifecycle-audit.test.mjs +56 -0
  298. package/tests/loader-register.mjs +3 -3
  299. package/tests/loader.mjs +17 -17
  300. package/tests/local-embedding-entry.test.mjs +95 -95
  301. package/tests/local-embedding-env.test.mjs +51 -51
  302. package/tests/local-embedding-manager.test.mjs +494 -494
  303. package/tests/local-embedding-protocol.test.mjs +121 -121
  304. package/tests/local-embedding-worker.test.mjs +440 -440
  305. package/tests/local-vector-service.test.mjs +41 -0
  306. package/tests/maintenance-status.test.mjs +77 -0
  307. package/tests/maintenance.test.mjs +438 -0
  308. package/tests/managed-memory.test.mjs +1234 -1234
  309. package/tests/managed-runtime.test.mjs +72 -72
  310. package/tests/media-injection.test.mjs +225 -0
  311. package/tests/media.test.mjs +135 -135
  312. package/tests/memory-chain.test.mjs +169 -169
  313. package/tests/memory-fields.test.mjs +134 -134
  314. package/tests/memu-resident-route.test.mjs +130 -130
  315. package/tests/memu-resident.test.mjs +33 -33
  316. package/tests/migration-payload.test.mjs +40 -42
  317. package/tests/mock-llm.test.mjs +263 -225
  318. package/tests/mood.test.mjs +109 -109
  319. package/tests/multiprocess.test.mjs +29 -29
  320. package/tests/negation-polarity.test.mjs +135 -135
  321. package/tests/new-session-gate.test.mjs +617 -617
  322. package/tests/open-loop-date.test.mjs +416 -416
  323. package/tests/ops-hardening.test.mjs +209 -209
  324. package/tests/package-shipping.test.mjs +88 -88
  325. package/tests/pending-injection.test.mjs +107 -107
  326. package/tests/port-surface.test.mjs +138 -138
  327. package/tests/preset-mount.test.mjs +132 -0
  328. package/tests/preset-scope.test.mjs +212 -212
  329. package/tests/private-links.test.mjs +493 -493
  330. package/tests/prompt-semantics.test.mjs +51 -51
  331. package/tests/prompts.test.mjs +315 -315
  332. package/tests/query-decompose.test.mjs +62 -62
  333. package/tests/react-snapshot.test.mjs +24 -24
  334. package/tests/recall-bench.test.mjs +317 -317
  335. package/tests/recall-cache.test.mjs +292 -292
  336. package/tests/recall-corpus-eligibility.test.mjs +51 -51
  337. package/tests/recall-dedup.test.mjs +446 -446
  338. package/tests/recall-intent.test.mjs +172 -172
  339. package/tests/regression-sweep.test.mjs +311 -311
  340. package/tests/reminder-fairness.test.mjs +55 -0
  341. package/tests/remote.test.mjs +140 -140
  342. package/tests/rename.test.mjs +30 -30
  343. package/tests/repetition-detector-snapshot.test.mjs +231 -231
  344. package/tests/repetition-eval-live.test.mjs +177 -177
  345. package/tests/repetition-eval.test.mjs +373 -373
  346. package/tests/salience-domain.test.mjs +173 -173
  347. package/tests/salient-date.test.mjs +142 -142
  348. package/tests/salient-wake.test.mjs +389 -389
  349. package/tests/settings-beat.test.mjs +222 -222
  350. package/tests/settings-coverage.test.mjs +97 -97
  351. package/tests/settings-plumbing.test.mjs +79 -79
  352. package/tests/short-term.test.mjs +182 -166
  353. package/tests/sidebar-beat.test.mjs +213 -213
  354. package/tests/sidebar-refresh.test.mjs +123 -123
  355. package/tests/sidebar.test.mjs +102 -74
  356. package/tests/simulate-injection.test.mjs +76 -76
  357. package/tests/slot-similarity.test.mjs +153 -153
  358. package/tests/snippet.test.mjs +79 -79
  359. package/tests/source-kind.test.mjs +52 -52
  360. package/tests/speaker-provenance.test.mjs +120 -120
  361. package/tests/stale-maintenance.test.mjs +206 -131
  362. package/tests/state-gc.test.mjs +34 -34
  363. package/tests/state.test.mjs +155 -155
  364. package/tests/stats.test.mjs +112 -112
  365. package/tests/storage.test.mjs +125 -125
  366. package/tests/stubs/child-process-spy.mjs +14 -14
  367. package/tests/stubs/dsh-llm-pi-ai.js +13 -13
  368. package/tests/stubs/dsh-llm.js +5 -5
  369. package/tests/stubs/dsh-schedule.js +140 -140
  370. package/tests/stubs/dsh-session-query.js +26 -26
  371. package/tests/stubs/dsh-session.js +7 -7
  372. package/tests/stubs/dsh-tools.js +101 -101
  373. package/tests/temporal-repair.test.mjs +78 -0
  374. package/tests/temporal.test.mjs +124 -124
  375. package/tests/text-format.test.mjs +24 -0
  376. package/tests/tokenizer-v2.test.mjs +142 -142
  377. package/tests/tool-schema.test.mjs +126 -126
  378. package/tests/tools.test.mjs +810 -810
  379. package/tests/turn-log.test.mjs +487 -487
  380. package/tests/ui-defaults.test.mjs +57 -57
  381. package/tests/update-fields.test.mjs +138 -138
  382. package/tests/vector-gc.test.mjs +37 -37
  383. package/tests/vector-migration.test.mjs +810 -810
  384. package/tests/vector-profile.test.mjs +449 -449
  385. package/tests/visibility-migration.test.mjs +152 -152
  386. package/tests/webui-auth.test.mjs +963 -963
  387. package/tests/webui.test.mjs +421 -421
  388. package/tests/windows-env.test.mjs +89 -89
  389. package/tests/worker-lifecycle.test.mjs +1522 -1429
package/lib/paths.js CHANGED
@@ -1,457 +1,453 @@
1
- import fs from 'node:fs'
2
- import os from 'node:os'
3
- import path from 'node:path'
4
- import crypto from 'node:crypto'
5
-
6
- export function dshHome() {
7
- return process.env.DSH_HOME || path.join(os.homedir(), '.dsh')
8
- }
9
-
10
- export function dataDir() {
11
- if (process.env.DSH_MEMU_MEMORY_HOME || process.env.DSH_MEMU_HOME) return process.env.DSH_MEMU_MEMORY_HOME || process.env.DSH_MEMU_HOME
12
- const legacy = path.join(dshHome(), 'dsh-memu')
13
- const current = path.join(dshHome(), 'dsh-memu-memory')
14
- // Existing installations keep their data in place; renaming a package is not a migration.
15
- return fs.existsSync(path.join(current, 'state.json')) || !fs.existsSync(legacy) ? current : legacy
16
- }
17
-
18
- export function engineDir(...parts) {
19
- return path.join(dataDir(), 'engine', ...parts)
20
- }
21
-
22
- export function logsDir() {
23
- return path.join(dataDir(), 'logs')
24
- }
25
-
26
- export function librariesDir() {
27
- return path.join(dataDir(), 'libraries')
28
- }
29
-
30
- export function indexDir() {
31
- return path.join(dataDir(), 'index')
32
- }
33
-
34
- export function downloadsDir() {
35
- return path.join(dataDir(), 'downloads')
36
- }
37
-
38
- export function backupsDir() {
39
- return path.join(dataDir(), 'backups')
40
- }
41
-
42
- export function ensureDir(dir) {
43
- fs.mkdirSync(dir, { recursive: true })
44
- return dir
45
- }
46
-
47
- // A swallow-all read is what turns one transient failure into permanent data
48
- // loss: every writer here does load -> mutate -> save, so returning "empty" for
49
- // "unreadable" makes the next save atomically replace a whole library with
50
- // nothing. Read failures are therefore classified, and a file we could not read
51
- // is never written over. See docs/troubleshooting.md 2.3 (a read failure must never be saved back).
52
- const readFailures = new Map()
53
- let warnSink = null
54
-
55
- export function setWarnSink(fn) {
56
- warnSink = typeof fn === 'function' ? fn : null
57
- }
58
-
59
- export function warn(message) {
60
- try { warnSink?.(redactSecrets(message)) } catch {}
61
- }
62
-
63
- export function redactSecrets(value, secrets = []) {
64
- let text = String(value || '')
65
- for (const secret of secrets) if (typeof secret === 'string' && secret.length >= 8) text = text.split(secret).join('[REDACTED_KEY]')
66
- return text.replace(/\bsk-[A-Za-z0-9_-]{12,}\b/g, '[REDACTED_KEY]')
67
- .replace(/\bBearer\s+[A-Za-z0-9._-]{12,}/gi, 'Bearer [REDACTED_KEY]')
68
- .replace(/((?:api[_-]?key|access[_-]?token)\s*["']?\s*[:=]\s*["']?)[^\s"',;&]{8,}/gi, '$1[REDACTED_KEY]')
69
- .replace(/(https?:\/\/)[^/@\s]+:[^/@\s]+@/g, '$1[REDACTED]@')
70
- }
71
-
72
- export function memoryRefKey({ scope, libraryId = null, id }) {
73
- return JSON.stringify([scope, libraryId, id])
74
- }
75
-
76
- export function memoryContentRevision(entry) {
77
- const content = {
78
- title: redactSecrets(entry?.title || ''),
79
- body: redactSecrets(entry?.content || ''),
80
- source: entry?.source || 'inferred', sourceKind: entry?.source_kind || null,
81
- disclosure: entry?.disclosure || 'can_tell', visibility: entry?.visibility || 'shared',
82
- owner: entry?.owner || null, layer: entry?.layer || 'long_term',
83
- speakerId: entry?.speaker_id || null, absoluteDate: entry?.absolute_date || null,
84
- confidence: entry?.confidence ?? null, conflictsWith: entry?.conflicts_with || null,
85
- context: entry?.context || null, knownBy: entry?.known_by || null,
86
- links: entry?.links || [],
87
- attachments: (entry?.attachments || []).map(item => [item.sha256 || null, redactSecrets(item.caption || ''), item.kind || null]),
88
- }
89
- return crypto.createHash('sha256').update(JSON.stringify(content)).digest('hex')
90
- }
91
-
92
- export function memoryRef({ scope, libraryId = null, id, entry }) {
93
- return { scope, libraryId: scope === 'global' ? null : libraryId, id, revision: memoryContentRevision(entry) }
94
- }
95
-
96
- export function readJsonStrict(file) {
97
- let raw
98
- try {
99
- raw = fs.readFileSync(file, 'utf8')
100
- } catch (error) {
101
- if (error?.code === 'ENOENT') return { ok: false, missing: true }
102
- return { ok: false, missing: false, kind: 'io', error }
103
- }
104
- try {
105
- return { ok: true, value: JSON.parse(raw) }
106
- } catch (error) {
107
- return { ok: false, missing: false, kind: 'corrupt', error }
108
- }
109
- }
110
-
111
- // Safe to move a corrupt file aside because every writer uses temp+rename: a
112
- // reader can never observe a torn write, so a parse failure means the bytes on
113
- // disk are genuinely bad rather than mid-write.
114
- function quarantine(file) {
115
- const dest = `${file}.corrupt-${stamp().replace(/[:.]/g, '-')}`
116
- try {
117
- fs.renameSync(file, dest)
118
- return dest
119
- } catch {
120
- return null
121
- }
122
- }
123
-
124
- export function readJson(file, fallback = null) {
125
- const key = path.resolve(file)
126
- const result = readJsonStrict(file)
127
- if (result.ok) {
128
- readFailures.delete(key)
129
- return result.value
130
- }
131
- if (result.missing) {
132
- if (readFailures.get(key)?.kind === 'corrupt') return fallback
133
- readFailures.delete(key)
134
- return fallback
135
- }
136
- if (result.kind === 'corrupt') {
137
- const dest = quarantine(file)
138
- if (dest) {
139
- readFailures.set(key, { at: stamp(), kind: 'corrupt', quarantine: dest, code: 'INVALID_JSON', message: 'quarantined; restore a valid file before writing' })
140
- warn(`${file} is not valid JSON; kept as ${path.basename(dest)}; writes are blocked until a valid file is restored`)
141
- return fallback
142
- }
143
- }
144
- readFailures.set(key, { at: stamp(), kind: result.kind, code: result.error?.code || '', message: result.kind === 'corrupt' ? 'invalid JSON; quarantine failed' : String(result.error?.code || 'read failed') })
145
- warn(`cannot read ${file} (${result.error?.code || result.error}); writes are blocked until it reads cleanly again`)
146
- return fallback
147
- }
148
-
149
- /** Non-null when the file could not be read and is therefore write-protected. */
150
- export function readFailure(file) {
151
- const key = path.resolve(file)
152
- if (!readFailures.has(key) && !fs.existsSync(file)) {
153
- try {
154
- const prefix = path.basename(file) + '.corrupt-'
155
- const kept = fs.readdirSync(path.dirname(file)).find(name => name.startsWith(prefix))
156
- if (kept) readFailures.set(key, { at: stamp(), kind: 'corrupt', code: 'INVALID_JSON', quarantine: path.join(path.dirname(file), kept), message: 'quarantined; restore a valid file before writing' })
157
- } catch {}
158
- }
159
- return readFailures.get(key) || null
160
- }
161
-
162
- /** Every file under `dir` currently write-protected by a failed read. */
163
- export function readFailuresUnder(dir) {
164
- const root = path.resolve(dir) + path.sep
165
- const out = []
166
- for (const [file, failure] of readFailures) {
167
- if (file.startsWith(root)) out.push({ file, ...failure })
168
- }
169
- return out
170
- }
171
-
172
- export function assertWritable(file) {
173
- const failure = readFailure(file)
174
- if (!failure) return
175
- const error = new Error(`refusing to overwrite ${path.basename(file)}: an earlier read failed (${failure.code || failure.message})`)
176
- error.code = 'dsh-memu-memory/read-failed'
177
- throw error
178
- }
179
-
180
- export function assertJsonShape(file, value, valid) {
181
- if (valid(value)) return value
182
- const dest = quarantine(file)
183
- readFailures.set(path.resolve(file), { at: stamp(), kind: 'corrupt', code: 'INVALID_SHAPE', quarantine: dest, message: 'invalid JSON schema; restore a valid file before writing' })
184
- warn(`${path.basename(file)} has an invalid data shape; writes are blocked`)
185
- return null
186
- }
187
-
188
- export function writeJson(file, value) {
189
- assertWritable(file)
190
- ensureDir(path.dirname(file))
191
- const tmp = `${file}.tmp-${process.pid}-${crypto.randomUUID()}`
192
- try {
193
- fs.writeFileSync(tmp, JSON.stringify(value, null, 2), { encoding: 'utf8', flag: 'wx', mode: 0o600 })
194
- const fd = fs.openSync(tmp, 'r+')
195
- try { fs.fsyncSync(fd) } finally { fs.closeSync(fd) }
196
- for (let attempt = 0; ; attempt++) {
197
- try { fs.renameSync(tmp, file); break } catch (error) {
198
- if (!['EPERM', 'EBUSY', 'EACCES'].includes(error?.code) || attempt >= 5) throw error
199
- Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 8 * (attempt + 1))
200
- }
201
- }
202
- } catch (error) {
203
- try { fs.rmSync(tmp, { force: true }) } catch {}
204
- throw error
205
- }
206
- }
207
-
208
- const heldLocks = new Set()
209
-
210
- // 遗留锁判定阈值(2026-11-21 现场)。这里全部是"同步事务锁":action 只做同步文件 IO,
211
- // 绝不跨 await(见 docs/contributing.md §5 锁顺序不变式),所以任何锁都不该长寿。
212
- //
213
- // 旧实现的致命口子:EEXIST 时把锁内容当 pid 读,只有 `Number.isSafeInteger(owner) && owner > 0`
214
- // 才进清理分支。一个 0 字节的遗留锁(进程在 openSync 与 writeFileSync 之间被杀)于是永远
215
- // 清不掉——500ms 后抛 DSH_MEMU_STORE_BUSY,被 safeLedger 吞成 "the consolidation lease could
216
- // not be persisted",整理任务连坏 84 次而没人知道为什么。
217
- const LOCK_ACQUIRE_BUDGET_MS = 500
218
- const LOCK_EMPTY_STALE_MS = 10_000
219
- const LOCK_MAX_AGE_MS = 60_000
220
-
221
- // paths.js 不 import diagnostics.js(否则成环):锁事件扔给 sink,方向永远单向。
222
- let lockEventSink = null
223
-
224
- export function setLockEventSink(fn) {
225
- lockEventSink = typeof fn === 'function' ? fn : null
226
- }
227
-
228
- function lockEvent(event) {
229
- try { lockEventSink?.(event) } catch {}
230
- }
231
-
232
- /** 锁载荷 = `pid\nISO 时间\n`。旧锁只有一行裸 pid,解析器两种都认。 */
233
- function parseLockOwner(raw) {
234
- const lines = String(raw || '').split(/\r?\n/).map(line => line.trim()).filter(Boolean)
235
- const pid = Number(lines[0])
236
- const at = lines[1] && Number.isFinite(Date.parse(lines[1])) ? Date.parse(lines[1]) : null
237
- return { pid: Number.isSafeInteger(pid) && pid > 0 ? pid : null, at, raw: lines[0] || '' }
238
- }
239
-
240
- function lockAgeMs(lockPath, now = Date.now()) {
241
- try { return Math.max(0, now - fs.statSync(lockPath).mtimeMs) } catch { return null }
242
- }
243
-
244
- /**
245
- * 判断一个已存在的锁是不是遗留物;是则返回原因,否则 null(= 真有主,继续等)。
246
- *
247
- * 三档判据,都不依赖"锁内容必须像 pid":
248
- * - 载荷里没有合法 pid(0 字节、被截断、别的格式):扛过 LOCK_EMPTY_STALE_MS 就算遗弃,
249
- * 因为 open 与 write 之间只有毫秒级窗口;
250
- * - pid 存活探测:ESRCH 即死主,立刻清;
251
- * - pid 是本进程但当前没有事务持有它(heldLocks 无记录):说明是上一轮同 pid 进程的残骸;
252
- * - 任何锁超过 LOCK_MAX_AGE_MS:同步事务不可能持锁这么久,按遗弃处理。
253
- */
254
- export function inspectLock(lockPath, now = Date.now()) {
255
- const ageMs = lockAgeMs(lockPath, now)
256
- if (ageMs === null) return null
257
- let raw = ''
258
- try { raw = fs.readFileSync(lockPath, 'utf8') } catch {}
259
- const owner = parseLockOwner(raw)
260
- const detail = { lockPath, owner: owner.pid, raw: owner.raw.slice(0, 40), ageMs }
261
- if (owner.pid === null) {
262
- return ageMs >= LOCK_EMPTY_STALE_MS ? { reason: 'unparseable-owner', detail } : null
263
- }
264
- // 自己 pid 但内存里没有对应事务:可能是本地遗留,也可能是同一进程里的另一个插件
265
- // 副本正持有它。只有前者可以破,所以再等 LOCK_EMPTY_STALE_MS 才认——立刻破会把
266
- // 另一个副本正在写的事务拆掉。
267
- if (owner.pid === process.pid && !heldLocks.has(lockPath)) {
268
- return ageMs >= LOCK_EMPTY_STALE_MS ? { reason: 'own-pid-without-transaction', detail } : null
269
- }
270
- if (owner.pid !== process.pid) {
271
- try { process.kill(owner.pid, 0) } catch (probe) {
272
- if (probe?.code === 'ESRCH') return { reason: 'dead-owner', detail }
273
- }
274
- }
275
- if (ageMs >= LOCK_MAX_AGE_MS) return { reason: 'aged-out', detail }
276
- return null
277
- }
278
-
279
- /** 扫描数据目录下的全部 *.lock(深度 3:index/、libraries/ 一层就到)。 */
280
- export function scanMemoryLocks({ root = dataDir(), maxDepth = 3, now = Date.now() } = {}) {
281
- const found = []
282
- const walk = (dir, depth) => {
283
- if (depth > maxDepth) return
284
- let entries = []
285
- try { entries = fs.readdirSync(dir, { withFileTypes: true }) } catch { return }
286
- for (const entry of entries) {
287
- const abs = path.join(dir, entry.name)
288
- let isDir = entry.isDirectory()
289
- // 符号链接按"不跟随"处理:数据目录里没有需要跟进去的锁。
290
- if (entry.isSymbolicLink()) continue
291
- if (isDir) { walk(abs, depth + 1); continue }
292
- if (!entry.name.endsWith('.lock')) continue
293
- const stale = inspectLock(abs, now)
294
- const ageMs = lockAgeMs(abs, now)
295
- let raw = ''
296
- try { raw = fs.readFileSync(abs, 'utf8') } catch {}
297
- found.push({
298
- path: abs,
299
- rel: path.relative(root, abs),
300
- bytes: Buffer.byteLength(raw),
301
- owner: parseLockOwner(raw).pid,
302
- ageMs,
303
- stale: Boolean(stale),
304
- reason: stale?.reason || null,
305
- })
306
- }
307
- }
308
- walk(root, 1)
309
- return found
310
- }
311
-
312
- /**
313
- * 释放遗留锁。force=true 时连"看不出遗弃"的锁也一并清(手动修复入口用它,调用方必须
314
- * 是显式确认过的操作);默认只清 inspectLock 判定为遗弃的那些。
315
- */
316
- export function releaseStaleLocks({ force = false, root, now = Date.now() } = {}) {
317
- const scanned = scanMemoryLocks({ root, now })
318
- const released = []
319
- const kept = []
320
- for (const lock of scanned) {
321
- if (!lock.stale && !force) { kept.push(lock); continue }
322
- try {
323
- fs.unlinkSync(lock.path)
324
- released.push({ ...lock, reason: lock.reason || 'forced' })
325
- lockEvent({
326
- level: 'info',
327
- code: 'MEMU_LOCK_RELEASED',
328
- message: `released a stale memory store lock (${lock.reason || 'forced'}): ${lock.rel}`,
329
- detail: { lockPath: lock.path, reason: lock.reason || 'forced', owner: lock.owner, ageMs: lock.ageMs },
330
- repair: 'release-stale-locks',
331
- })
332
- } catch (error) {
333
- kept.push({ ...lock, error: error?.code || String(error?.message || error) })
334
- }
335
- }
336
- return { scanned: scanned.length, released, kept }
337
- }
338
-
339
- export async function retryStoreWrite(action, attempts = 4) {
340
- for (let attempt = 0; ; attempt++) {
341
- try { return action() } catch (error) {
342
- if (!['DSH_MEMU_STORE_BUSY', 'EPERM', 'EBUSY', 'EACCES'].includes(error?.code) || attempt >= attempts - 1) throw error
343
- await new Promise(resolve => setTimeout(resolve, 25 * (attempt + 1)))
344
- }
345
- }
346
- }
347
-
348
- /** Synchronous transactions never hold this lock across a backend/network await. */
349
- export function withFileLock(file, action) {
350
- const lock = `${path.resolve(file)}.lock`
351
- if (heldLocks.has(lock)) return action()
352
- ensureDir(path.dirname(lock))
353
- const until = Date.now() + LOCK_ACQUIRE_BUDGET_MS
354
- let fd
355
- while (fd === undefined) {
356
- try {
357
- fd = fs.openSync(lock, 'wx', 0o600)
358
- // pid 写在第一行:旧版本只用一行裸 pid,两种载荷的解析器是同一个 parseLockOwner。
359
- fs.writeFileSync(fd, `${process.pid}\n${new Date().toISOString()}\n`)
360
- } catch (error) {
361
- if (error?.code !== 'EEXIST') throw error
362
- const stale = inspectLock(lock)
363
- if (stale) {
364
- // 遗弃锁就地释放并重试:这是"死锁自愈",不需要调用方重来一遍。
365
- try { fs.unlinkSync(lock) } catch {}
366
- lockEvent({
367
- level: 'warn',
368
- code: 'MEMU_LOCK_BROKEN',
369
- reason: stale.reason,
370
- message: `released a stale memory store lock (${stale.reason}): ${path.basename(lock)}`,
371
- detail: stale.detail,
372
- hint: 'A lock whose owner process no longer exists (or whose payload was never written) is abandoned. Releasing it is safe: a live owner is never touched.',
373
- repair: 'release-stale-locks',
374
- })
375
- continue
376
- }
377
- if (Date.now() >= until) {
378
- const busy = new Error(`memory store is busy: ${path.basename(file)}; retry the operation`)
379
- busy.code = 'DSH_MEMU_STORE_BUSY'
380
- // 诊断要能回答"谁占着、占了多久",光有一句 busy 查不动。
381
- let owner = null
382
- try { owner = parseLockOwner(fs.readFileSync(lock, 'utf8')).pid } catch {}
383
- busy.lockPath = lock
384
- busy.owner = owner
385
- busy.ageMs = lockAgeMs(lock)
386
- throw busy
387
- }
388
- Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 10)
389
- }
390
- }
391
- heldLocks.add(lock)
392
- try { return action() } finally {
393
- heldLocks.delete(lock)
394
- fs.closeSync(fd)
395
- for (let attempt = 0; ; attempt++) {
396
- try { fs.unlinkSync(lock); break } catch (error) {
397
- if (error.code === 'ENOENT') break
398
- if (['EPERM', 'EBUSY', 'EACCES'].includes(error.code) && attempt < 5) {
399
- Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 5 * (attempt + 1))
400
- continue
401
- }
402
- warn(`could not release memory store lock: ${path.basename(lock)} (${error.code || 'IO error'})`)
403
- break
404
- }
405
- }
406
- }
407
- }
408
-
409
- export function stamp() {
410
- return new Date().toISOString()
411
- }
412
-
413
- /**
414
- * Windows 子进程的系统变量补齐。
415
- *
416
- * 宿主在工具化执行里把 `process.env` 清空后(docs/env-and-commands.md §9.1),注入进程的
417
- * 组件(输入法云缓存、DirectWrite 字体缓存)用 `%SystemDrive%\ProgramData\...` 拼路径时会
418
- * 展开失败,于是整串被当成相对路径写进**当前工作目录** —— 仓库里出现过字面量
419
- * `%SystemDrive%/ProgramData/...` 就是这么来的。
420
- *
421
- * 只补缺失的键:宿主给了正确的值就绝不覆盖。返回的是 overlay,调用方按
422
- * `{ ...overlay, ...process.env, ...explicit }` 的顺序合并。
423
- */
424
- export function windowsSystemEnv(platform = process.platform, env = process.env) {
425
- if (platform !== 'win32') return {}
426
- const source = env || {}
427
- const drive = String(source.SystemDrive || source.HOMEDRIVE || 'C:')
428
- const root = String(source.SystemRoot || source.windir || source.WINDIR || (drive.replace(/\\$/, '') + '\\Windows')).replace(/\\/g, '/')
429
- const overlay = {}
430
- if (!source.SystemDrive) overlay.SystemDrive = drive
431
- if (!source.SystemRoot) overlay.SystemRoot = root
432
- if (!source.windir && !source.WINDIR) overlay.windir = root
433
- if (!source.PATH && !source.Path) overlay.PATH = root + '/system32'
434
- return overlay
435
- }
436
-
437
- export function isSafeId(value) {
438
- return typeof value === 'string' && /^[A-Za-z0-9._-]{1,128}$/.test(value) && value !== '.' && value !== '..'
439
- }
440
-
441
- export function libraryIdForScope(scopeKey) {
442
- let hash = 2166136261
443
- for (let i = 0; i < scopeKey.length; i++) {
444
- hash ^= scopeKey.charCodeAt(i)
445
- hash = Math.imul(hash, 16777619)
446
- }
447
- return `lib_${(hash >>> 0).toString(16)}`
448
- }
449
-
450
- export function shortHash(value) {
451
- let hash = 2166136261
452
- for (let i = 0; i < value.length; i++) {
453
- hash ^= value.charCodeAt(i)
454
- hash = Math.imul(hash, 16777619)
455
- }
456
- return (hash >>> 0).toString(16).padStart(8, '0')
457
- }
1
+ import fs from 'node:fs'
2
+ import os from 'node:os'
3
+ import path from 'node:path'
4
+ import crypto from 'node:crypto'
5
+
6
+ export function dshHome() {
7
+ return process.env.DSH_HOME || path.join(os.homedir(), '.dsh')
8
+ }
9
+
10
+ export function dataDir() {
11
+ if (process.env.DSH_MEMU_MEMORY_HOME || process.env.DSH_MEMU_HOME) return process.env.DSH_MEMU_MEMORY_HOME || process.env.DSH_MEMU_HOME
12
+ const legacy = path.join(dshHome(), 'dsh-memu')
13
+ const current = path.join(dshHome(), 'dsh-memu-memory')
14
+ // Existing installations keep their data in place; renaming a package is not a migration.
15
+ return fs.existsSync(path.join(current, 'state.json')) || !fs.existsSync(legacy) ? current : legacy
16
+ }
17
+
18
+ export function engineDir(...parts) {
19
+ return path.join(dataDir(), 'engine', ...parts)
20
+ }
21
+
22
+ export function logsDir() {
23
+ return path.join(dataDir(), 'logs')
24
+ }
25
+
26
+ export function librariesDir() {
27
+ return path.join(dataDir(), 'libraries')
28
+ }
29
+
30
+ export function indexDir() {
31
+ return path.join(dataDir(), 'index')
32
+ }
33
+
34
+ export function downloadsDir() {
35
+ return path.join(dataDir(), 'downloads')
36
+ }
37
+
38
+ export function backupsDir() {
39
+ return path.join(dataDir(), 'backups')
40
+ }
41
+
42
+ export function ensureDir(dir) {
43
+ fs.mkdirSync(dir, { recursive: true })
44
+ return dir
45
+ }
46
+
47
+ // A swallow-all read is what turns one transient failure into permanent data
48
+ // loss: every writer here does load -> mutate -> save, so returning "empty" for
49
+ // "unreadable" makes the next save atomically replace a whole library with
50
+ // nothing. Read failures are therefore classified, and a file we could not read
51
+ // is never written over. See docs/troubleshooting.md 2.3 (a read failure must never be saved back).
52
+ const readFailures = new Map()
53
+ let warnSink = null
54
+
55
+ export function setWarnSink(fn) {
56
+ warnSink = typeof fn === 'function' ? fn : null
57
+ }
58
+
59
+ export function warn(message) {
60
+ try { warnSink?.(redactSecrets(message)) } catch {}
61
+ }
62
+
63
+ export function redactSecrets(value, secrets = []) {
64
+ let text = String(value || '')
65
+ for (const secret of secrets) if (typeof secret === 'string' && secret.length >= 8) text = text.split(secret).join('[REDACTED_KEY]')
66
+ return text.replace(/\bsk-[A-Za-z0-9_-]{12,}\b/g, '[REDACTED_KEY]')
67
+ .replace(/\bBearer\s+[A-Za-z0-9._-]{12,}/gi, 'Bearer [REDACTED_KEY]')
68
+ .replace(/((?:api[_-]?key|access[_-]?token)\s*["']?\s*[:=]\s*["']?)[^\s"',;&]{8,}/gi, '$1[REDACTED_KEY]')
69
+ .replace(/(https?:\/\/)[^/@\s]+:[^/@\s]+@/g, '$1[REDACTED]@')
70
+ }
71
+
72
+ export function memoryRefKey({ scope, libraryId = null, id }) {
73
+ return JSON.stringify([scope, libraryId, id])
74
+ }
75
+
76
+ export function memoryContentRevision(entry) {
77
+ const content = {
78
+ title: redactSecrets(entry?.title || ''),
79
+ body: redactSecrets(entry?.content || ''),
80
+ source: entry?.source || 'inferred', sourceKind: entry?.source_kind || null,
81
+ disclosure: entry?.disclosure || 'can_tell', visibility: entry?.visibility || 'shared',
82
+ owner: entry?.owner || null, layer: entry?.layer || 'long_term',
83
+ speakerId: entry?.speaker_id || null, absoluteDate: entry?.absolute_date || null,
84
+ confidence: entry?.confidence ?? null, conflictsWith: entry?.conflicts_with || null,
85
+ context: entry?.context || null, knownBy: entry?.known_by || null,
86
+ links: entry?.links || [],
87
+ attachments: (entry?.attachments || []).map(item => [item.sha256 || null, redactSecrets(item.caption || ''), item.kind || null]),
88
+ }
89
+ return crypto.createHash('sha256').update(JSON.stringify(content)).digest('hex')
90
+ }
91
+
92
+ export function memoryRef({ scope, libraryId = null, id, entry }) {
93
+ return { scope, libraryId: scope === 'global' ? null : libraryId, id, revision: memoryContentRevision(entry) }
94
+ }
95
+
96
+ export function readJsonStrict(file) {
97
+ let raw
98
+ try {
99
+ raw = fs.readFileSync(file, 'utf8')
100
+ } catch (error) {
101
+ if (error?.code === 'ENOENT') return { ok: false, missing: true }
102
+ return { ok: false, missing: false, kind: 'io', error }
103
+ }
104
+ try {
105
+ return { ok: true, value: JSON.parse(raw) }
106
+ } catch (error) {
107
+ return { ok: false, missing: false, kind: 'corrupt', error }
108
+ }
109
+ }
110
+
111
+ // Safe to move a corrupt file aside because every writer uses temp+rename: a
112
+ // reader can never observe a torn write, so a parse failure means the bytes on
113
+ // disk are genuinely bad rather than mid-write.
114
+ function quarantine(file) {
115
+ const dest = `${file}.corrupt-${stamp().replace(/[:.]/g, '-')}`
116
+ try {
117
+ fs.renameSync(file, dest)
118
+ return dest
119
+ } catch {
120
+ return null
121
+ }
122
+ }
123
+
124
+ export function readJson(file, fallback = null) {
125
+ const key = path.resolve(file)
126
+ const result = readJsonStrict(file)
127
+ if (result.ok) {
128
+ readFailures.delete(key)
129
+ return result.value
130
+ }
131
+ if (result.missing) {
132
+ if (readFailures.get(key)?.kind === 'corrupt') return fallback
133
+ readFailures.delete(key)
134
+ return fallback
135
+ }
136
+ if (result.kind === 'corrupt') {
137
+ const dest = quarantine(file)
138
+ if (dest) {
139
+ readFailures.set(key, { at: stamp(), kind: 'corrupt', quarantine: dest, code: 'INVALID_JSON', message: 'quarantined; restore a valid file before writing' })
140
+ warn(`${file} is not valid JSON; kept as ${path.basename(dest)}; writes are blocked until a valid file is restored`)
141
+ return fallback
142
+ }
143
+ }
144
+ readFailures.set(key, { at: stamp(), kind: result.kind, code: result.error?.code || '', message: result.kind === 'corrupt' ? 'invalid JSON; quarantine failed' : String(result.error?.code || 'read failed') })
145
+ warn(`cannot read ${file} (${result.error?.code || result.error}); writes are blocked until it reads cleanly again`)
146
+ return fallback
147
+ }
148
+
149
+ /** Non-null when the file could not be read and is therefore write-protected. */
150
+ export function readFailure(file) {
151
+ const key = path.resolve(file)
152
+ if (!readFailures.has(key) && !fs.existsSync(file)) {
153
+ try {
154
+ const prefix = path.basename(file) + '.corrupt-'
155
+ const kept = fs.readdirSync(path.dirname(file)).find(name => name.startsWith(prefix))
156
+ if (kept) readFailures.set(key, { at: stamp(), kind: 'corrupt', code: 'INVALID_JSON', quarantine: path.join(path.dirname(file), kept), message: 'quarantined; restore a valid file before writing' })
157
+ } catch {}
158
+ }
159
+ return readFailures.get(key) || null
160
+ }
161
+
162
+ /** Every file under `dir` currently write-protected by a failed read. */
163
+ export function readFailuresUnder(dir) {
164
+ const root = path.resolve(dir) + path.sep
165
+ const out = []
166
+ for (const [file, failure] of readFailures) {
167
+ if (file.startsWith(root)) out.push({ file, ...failure })
168
+ }
169
+ return out
170
+ }
171
+
172
+ export function assertWritable(file) {
173
+ const failure = readFailure(file)
174
+ if (!failure) return
175
+ const error = new Error(`refusing to overwrite ${path.basename(file)}: an earlier read failed (${failure.code || failure.message})`)
176
+ error.code = 'dsh-memu-memory/read-failed'
177
+ throw error
178
+ }
179
+
180
+ export function assertJsonShape(file, value, valid) {
181
+ if (valid(value)) return value
182
+ const dest = quarantine(file)
183
+ readFailures.set(path.resolve(file), { at: stamp(), kind: 'corrupt', code: 'INVALID_SHAPE', quarantine: dest, message: 'invalid JSON schema; restore a valid file before writing' })
184
+ warn(`${path.basename(file)} has an invalid data shape; writes are blocked`)
185
+ return null
186
+ }
187
+
188
+ export function writeJson(file, value) {
189
+ assertWritable(file)
190
+ ensureDir(path.dirname(file))
191
+ const tmp = `${file}.tmp-${process.pid}-${crypto.randomUUID()}`
192
+ try {
193
+ fs.writeFileSync(tmp, JSON.stringify(value, null, 2), { encoding: 'utf8', flag: 'wx', mode: 0o600 })
194
+ const fd = fs.openSync(tmp, 'r+')
195
+ try { fs.fsyncSync(fd) } finally { fs.closeSync(fd) }
196
+ for (let attempt = 0; ; attempt++) {
197
+ try { fs.renameSync(tmp, file); break } catch (error) {
198
+ if (!['EPERM', 'EBUSY', 'EACCES'].includes(error?.code) || attempt >= 5) throw error
199
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 8 * (attempt + 1))
200
+ }
201
+ }
202
+ } catch (error) {
203
+ try { fs.rmSync(tmp, { force: true }) } catch {}
204
+ throw error
205
+ }
206
+ }
207
+
208
+ const heldLocks = new Set()
209
+
210
+ // 遗留锁判定阈值。锁内 action 只执行同步文件 IO,不跨 await
211
+ // (见 docs/contributing.md 的锁顺序约束),因此可以使用有界的存续时间。
212
+ // 进程可能在创建锁后、写入 pid 前退出,空锁也需要按年龄回收,避免永久阻止写入。
213
+ const LOCK_ACQUIRE_BUDGET_MS = 500
214
+ const LOCK_EMPTY_STALE_MS = 10_000
215
+ const LOCK_MAX_AGE_MS = 60_000
216
+
217
+ // paths.js 不 import diagnostics.js(否则成环):锁事件扔给 sink,方向永远单向。
218
+ let lockEventSink = null
219
+
220
+ export function setLockEventSink(fn) {
221
+ lockEventSink = typeof fn === 'function' ? fn : null
222
+ }
223
+
224
+ function lockEvent(event) {
225
+ try { lockEventSink?.(event) } catch {}
226
+ }
227
+
228
+ /** 锁载荷 = `pid\nISO 时间\n`。旧锁只有一行裸 pid,解析器两种都认。 */
229
+ function parseLockOwner(raw) {
230
+ const lines = String(raw || '').split(/\r?\n/).map(line => line.trim()).filter(Boolean)
231
+ const pid = Number(lines[0])
232
+ const at = lines[1] && Number.isFinite(Date.parse(lines[1])) ? Date.parse(lines[1]) : null
233
+ return { pid: Number.isSafeInteger(pid) && pid > 0 ? pid : null, at, raw: lines[0] || '' }
234
+ }
235
+
236
+ function lockAgeMs(lockPath, now = Date.now()) {
237
+ try { return Math.max(0, now - fs.statSync(lockPath).mtimeMs) } catch { return null }
238
+ }
239
+
240
+ /**
241
+ * 判断一个已存在的锁是不是遗留物;是则返回原因,否则 null(= 真有主,继续等)。
242
+ *
243
+ * 三档判据,都不依赖"锁内容必须像 pid":
244
+ * - 载荷里没有合法 pid(0 字节、被截断、别的格式):扛过 LOCK_EMPTY_STALE_MS 就算遗弃,
245
+ * 因为 open 与 write 之间只有毫秒级窗口;
246
+ * - pid 存活探测:ESRCH 即死主,立刻清;
247
+ * - pid 是本进程但当前没有事务持有它(heldLocks 无记录):说明是上一轮同 pid 进程的残骸;
248
+ * - 任何锁超过 LOCK_MAX_AGE_MS:同步事务不可能持锁这么久,按遗弃处理。
249
+ */
250
+ export function inspectLock(lockPath, now = Date.now()) {
251
+ const ageMs = lockAgeMs(lockPath, now)
252
+ if (ageMs === null) return null
253
+ let raw = ''
254
+ try { raw = fs.readFileSync(lockPath, 'utf8') } catch {}
255
+ const owner = parseLockOwner(raw)
256
+ const detail = { lockPath, owner: owner.pid, raw: owner.raw.slice(0, 40), ageMs }
257
+ if (owner.pid === null) {
258
+ return ageMs >= LOCK_EMPTY_STALE_MS ? { reason: 'unparseable-owner', detail } : null
259
+ }
260
+ // 自己 pid 但内存里没有对应事务:可能是本地遗留,也可能是同一进程里的另一个插件
261
+ // 副本正持有它。只有前者可以破,所以再等 LOCK_EMPTY_STALE_MS 才认——立刻破会把
262
+ // 另一个副本正在写的事务拆掉。
263
+ if (owner.pid === process.pid && !heldLocks.has(lockPath)) {
264
+ return ageMs >= LOCK_EMPTY_STALE_MS ? { reason: 'own-pid-without-transaction', detail } : null
265
+ }
266
+ if (owner.pid !== process.pid) {
267
+ try { process.kill(owner.pid, 0) } catch (probe) {
268
+ if (probe?.code === 'ESRCH') return { reason: 'dead-owner', detail }
269
+ }
270
+ }
271
+ if (ageMs >= LOCK_MAX_AGE_MS) return { reason: 'aged-out', detail }
272
+ return null
273
+ }
274
+
275
+ /** 扫描数据目录下的全部 *.lock(深度 3:index/、libraries/ 一层就到)。 */
276
+ export function scanMemoryLocks({ root = dataDir(), maxDepth = 3, now = Date.now() } = {}) {
277
+ const found = []
278
+ const walk = (dir, depth) => {
279
+ if (depth > maxDepth) return
280
+ let entries = []
281
+ try { entries = fs.readdirSync(dir, { withFileTypes: true }) } catch { return }
282
+ for (const entry of entries) {
283
+ const abs = path.join(dir, entry.name)
284
+ let isDir = entry.isDirectory()
285
+ // 符号链接按"不跟随"处理:数据目录里没有需要跟进去的锁。
286
+ if (entry.isSymbolicLink()) continue
287
+ if (isDir) { walk(abs, depth + 1); continue }
288
+ if (!entry.name.endsWith('.lock')) continue
289
+ const stale = inspectLock(abs, now)
290
+ const ageMs = lockAgeMs(abs, now)
291
+ let raw = ''
292
+ try { raw = fs.readFileSync(abs, 'utf8') } catch {}
293
+ found.push({
294
+ path: abs,
295
+ rel: path.relative(root, abs),
296
+ bytes: Buffer.byteLength(raw),
297
+ owner: parseLockOwner(raw).pid,
298
+ ageMs,
299
+ stale: Boolean(stale),
300
+ reason: stale?.reason || null,
301
+ })
302
+ }
303
+ }
304
+ walk(root, 1)
305
+ return found
306
+ }
307
+
308
+ /**
309
+ * 释放遗留锁。force=true 时连"看不出遗弃"的锁也一并清(手动修复入口用它,调用方必须
310
+ * 是显式确认过的操作);默认只清 inspectLock 判定为遗弃的那些。
311
+ */
312
+ export function releaseStaleLocks({ force = false, root, now = Date.now() } = {}) {
313
+ const scanned = scanMemoryLocks({ root, now })
314
+ const released = []
315
+ const kept = []
316
+ for (const lock of scanned) {
317
+ if (!lock.stale && !force) { kept.push(lock); continue }
318
+ try {
319
+ fs.unlinkSync(lock.path)
320
+ released.push({ ...lock, reason: lock.reason || 'forced' })
321
+ lockEvent({
322
+ level: 'info',
323
+ code: 'MEMU_LOCK_RELEASED',
324
+ message: `released a stale memory store lock (${lock.reason || 'forced'}): ${lock.rel}`,
325
+ detail: { lockPath: lock.path, reason: lock.reason || 'forced', owner: lock.owner, ageMs: lock.ageMs },
326
+ repair: 'release-stale-locks',
327
+ })
328
+ } catch (error) {
329
+ kept.push({ ...lock, error: error?.code || String(error?.message || error) })
330
+ }
331
+ }
332
+ return { scanned: scanned.length, released, kept }
333
+ }
334
+
335
+ export async function retryStoreWrite(action, attempts = 4) {
336
+ for (let attempt = 0; ; attempt++) {
337
+ try { return action() } catch (error) {
338
+ if (!['DSH_MEMU_STORE_BUSY', 'EPERM', 'EBUSY', 'EACCES'].includes(error?.code) || attempt >= attempts - 1) throw error
339
+ await new Promise(resolve => setTimeout(resolve, 25 * (attempt + 1)))
340
+ }
341
+ }
342
+ }
343
+
344
+ /** Synchronous transactions never hold this lock across a backend/network await. */
345
+ export function withFileLock(file, action) {
346
+ const lock = `${path.resolve(file)}.lock`
347
+ if (heldLocks.has(lock)) return action()
348
+ ensureDir(path.dirname(lock))
349
+ const until = Date.now() + LOCK_ACQUIRE_BUDGET_MS
350
+ let fd
351
+ while (fd === undefined) {
352
+ try {
353
+ fd = fs.openSync(lock, 'wx', 0o600)
354
+ // pid 写在第一行:旧版本只用一行裸 pid,两种载荷的解析器是同一个 parseLockOwner。
355
+ fs.writeFileSync(fd, `${process.pid}\n${new Date().toISOString()}\n`)
356
+ } catch (error) {
357
+ if (error?.code !== 'EEXIST') throw error
358
+ const stale = inspectLock(lock)
359
+ if (stale) {
360
+ // 遗弃锁就地释放并重试:这是"死锁自愈",不需要调用方重来一遍。
361
+ try { fs.unlinkSync(lock) } catch {}
362
+ lockEvent({
363
+ level: 'warn',
364
+ code: 'MEMU_LOCK_BROKEN',
365
+ reason: stale.reason,
366
+ message: `released a stale memory store lock (${stale.reason}): ${path.basename(lock)}`,
367
+ detail: stale.detail,
368
+ hint: 'A lock whose owner process no longer exists (or whose payload was never written) is abandoned. Releasing it is safe: a live owner is never touched.',
369
+ repair: 'release-stale-locks',
370
+ })
371
+ continue
372
+ }
373
+ if (Date.now() >= until) {
374
+ const busy = new Error(`memory store is busy: ${path.basename(file)}; retry the operation`)
375
+ busy.code = 'DSH_MEMU_STORE_BUSY'
376
+ // 诊断要能回答"谁占着、占了多久",光有一句 busy 查不动。
377
+ let owner = null
378
+ try { owner = parseLockOwner(fs.readFileSync(lock, 'utf8')).pid } catch {}
379
+ busy.lockPath = lock
380
+ busy.owner = owner
381
+ busy.ageMs = lockAgeMs(lock)
382
+ throw busy
383
+ }
384
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 10)
385
+ }
386
+ }
387
+ heldLocks.add(lock)
388
+ try { return action() } finally {
389
+ heldLocks.delete(lock)
390
+ fs.closeSync(fd)
391
+ for (let attempt = 0; ; attempt++) {
392
+ try { fs.unlinkSync(lock); break } catch (error) {
393
+ if (error.code === 'ENOENT') break
394
+ if (['EPERM', 'EBUSY', 'EACCES'].includes(error.code) && attempt < 5) {
395
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 5 * (attempt + 1))
396
+ continue
397
+ }
398
+ warn(`could not release memory store lock: ${path.basename(lock)} (${error.code || 'IO error'})`)
399
+ break
400
+ }
401
+ }
402
+ }
403
+ }
404
+
405
+ export function stamp() {
406
+ return new Date().toISOString()
407
+ }
408
+
409
+ /**
410
+ * Windows 子进程的系统变量补齐。
411
+ *
412
+ * 宿主在工具化执行里把 `process.env` 清空后(docs/env-and-commands.md §9.1),注入进程的
413
+ * 组件(输入法云缓存、DirectWrite 字体缓存)用 `%SystemDrive%\ProgramData\...` 拼路径时会
414
+ * 展开失败,于是整串被当成相对路径写进**当前工作目录** —— 仓库里出现过字面量
415
+ * `%SystemDrive%/ProgramData/...` 就是这么来的。
416
+ *
417
+ * 只补缺失的键:宿主给了正确的值就绝不覆盖。返回的是 overlay,调用方按
418
+ * `{ ...overlay, ...process.env, ...explicit }` 的顺序合并。
419
+ */
420
+ export function windowsSystemEnv(platform = process.platform, env = process.env) {
421
+ if (platform !== 'win32') return {}
422
+ const source = env || {}
423
+ const drive = String(source.SystemDrive || source.HOMEDRIVE || 'C:')
424
+ const root = String(source.SystemRoot || source.windir || source.WINDIR || (drive.replace(/\\$/, '') + '\\Windows')).replace(/\\/g, '/')
425
+ const overlay = {}
426
+ if (!source.SystemDrive) overlay.SystemDrive = drive
427
+ if (!source.SystemRoot) overlay.SystemRoot = root
428
+ if (!source.windir && !source.WINDIR) overlay.windir = root
429
+ if (!source.PATH && !source.Path) overlay.PATH = root + '/system32'
430
+ return overlay
431
+ }
432
+
433
+ export function isSafeId(value) {
434
+ return typeof value === 'string' && /^[A-Za-z0-9._-]{1,128}$/.test(value) && value !== '.' && value !== '..'
435
+ }
436
+
437
+ export function libraryIdForScope(scopeKey) {
438
+ let hash = 2166136261
439
+ for (let i = 0; i < scopeKey.length; i++) {
440
+ hash ^= scopeKey.charCodeAt(i)
441
+ hash = Math.imul(hash, 16777619)
442
+ }
443
+ return `lib_${(hash >>> 0).toString(16)}`
444
+ }
445
+
446
+ export function shortHash(value) {
447
+ let hash = 2166136261
448
+ for (let i = 0; i < value.length; i++) {
449
+ hash ^= value.charCodeAt(i)
450
+ hash = Math.imul(hash, 16777619)
451
+ }
452
+ return (hash >>> 0).toString(16).padStart(8, '0')
453
+ }