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/state.js CHANGED
@@ -1,1928 +1,1948 @@
1
- import fs from 'node:fs'
2
- import path from 'node:path'
3
- import crypto from 'node:crypto'
4
- import {
5
- dataDir, librariesDir, indexDir, backupsDir, memoryRefKey,
6
- ensureDir, readJson, readFailure, readFailuresUnder, writeJson, withFileLock, assertJsonShape, warn, stamp, shortHash, libraryIdForScope, isSafeId,
7
- } from './paths.js'
8
- import {
9
- createBackup, deleteBackupEntry, listBackupEntries, restoreFromBackup,
10
- } from './backup.js'
11
- import { migrateIndexVisibility } from './visibility.js'
12
- import { memuDbFor, memuGlobalDbFor, removeActiveLibrary } from './vector-profile.js'
13
- import { normalizeEmotion, derivedValence } from './mood.js'
14
- import { localCalendarDay } from './temporal.js'
15
-
16
- const STATE_FILE = () => path.join(dataDir(), 'state.json')
17
- const GLOBAL_DB = () => path.join(dataDir(), 'global.sqlite3')
18
- const GLOBAL_INDEX = () => path.join(indexDir(), 'global.json')
19
-
20
- // Observable outcome of the last backup action; see listBackupEntries().
21
- let lastBackupReport = null
22
-
23
- export const DEFAULT_SETTINGS = {
24
- sidebarSettings: false,
25
- visionCaptionEnabled: true,
26
- // Only these named tools may carry the explicit inbound protocol in model text.
27
- // Producer-owned tool meta is the preferred integration and needs no allowlist.
28
- inboundToolNames: [],
29
- autoInject: 'smart',
30
- // 自动关联(DESIGN §6.4):'suggest' 只出候选、不写任何边(迁移期默认),
31
- // 'deterministic' 只写由已确认实体或字段证据推出的确定性边,'off' 完全关闭。
32
- // allowWorkerAssertion 是 v3 的预留开关(worker 确认实体),本版不读取。
33
- autoLinkMode: 'suggest',
34
- allowWorkerAssertion: false,
35
- // These defaults are tuned for high-density chat — a QQ-style group where many
36
- // short messages arrive per minute, in fragments rather than sentences, and the
37
- // topic drifts every few of them. Under that cadence the failure mode is not
38
- // "too little memory", it is noise: a per-turn block sized for paragraph-long
39
- // prompts drowns the conversation it was meant to help. So the per-turn budgets
40
- // are small, and the windows that stop repetition are measured in many turns.
41
- privateTopK: 5,
42
- globalTopK: 5,
43
- // Cross-library recall: merge private candidates from other libraries that use
44
- // the same memory domain. Reading across folders changes the isolation boundary,
45
- // so it is opt-in; writes still target the bound library only.
46
- crossLibraryRecall: false,
47
- anchorTokens: 800,
48
- // 800 tokens for one recall block. A dense chat calls recall on almost every
49
- // message, so the injected block has to stay clearly smaller than the message it
50
- // serves. This is the recall budget, not the whole plugin-message ceiling.
51
- turnTokens: 800,
52
- // Whole plugin-message ceiling: anchor + recall + optional cue/texture. It must
53
- // be at least the sum of the sub-budgets the user wants to allow; the default leaves
54
- // room for the default anchor and recall blocks.
55
- injectionTotalTokens: 2000,
56
- relevanceThreshold: 0.4,
57
- // 16 turns is a couple of minutes of group traffic. The old 8 expired inside a
58
- // single burst, so the same entry came back every minute or two.
59
- dedupeTurns: 16,
60
- // Every 6 turns instead of 3: the global layer is cross-conversation and drags
61
- // foreign context in, and three turns of dense chat is nothing at all.
62
- globalEveryNTurns: 6,
63
- // 6 characters is about one short CJK clause. 12 skipped most of what a group
64
- // chat actually says — recall was off in exactly the conversations that wanted
65
- // it. "嗯" / "好" / "收到" (2-3 chars) still skip.
66
- minUserChars: 6,
67
- // 条件式时效提示(工单 D):召回块里出现可能过时的记忆时,在末尾追加一个
68
- // <memory-freshness>,让有搜索工具的模型先核实,没有就如实说明。默认开;
69
- // freshnessDays 是"写得够久"的口径,不在模块里另设默认。
70
- freshnessHint: true,
71
- freshnessDays: 30,
72
- // Keep the always-on layer tight: dense chat generates many small candidates,
73
- // and 16 pins would eat the anchor budget before the anchor starts.
74
- mustRememberCap: 12,
75
- // Short-term layer: a memory that only has to survive the arc of one
76
- // conversation. It expires rather than being deleted, so the idle
77
- // consolidation pass still gets to promote it to long_term before it goes. 72h
78
- // spans "we talked about this over the weekend"; 0 disables the layer, and a
79
- // write with layer=short_term is then refused instead of silently becoming
80
- // permanent.
81
- shortTermTtlHours: 72,
82
- // Prompt pages beyond 通用. Each one owns a set of `<key>.<domain>.md` overrides
83
- // and can be assigned to a conversation, so the list is data, not code.
84
- // All shipped pages stay enabled; a new conversation starts on RP via the
85
- // binding's domainOverride. Every enabled domain is also offered by the session
86
- // picker, so these two lists cannot drift apart.
87
- promptDomains: ['rp', 'coding', 'mixed'],
88
- // Unpin is the model's own call (see memory.js privateUnpin). These two are the
89
- // guardrails that replaced the human marker: a per-conversation quota and a
90
- // cooldown, both small on purpose.
91
- unpinBudgetPerSession: 2,
92
- unpinCooldownMinutes: 3,
93
- // Rolled once per user turn: at dense cadence 5% means a cue every ~20 turns,
94
- // which reads as constant interruption. 2% keeps it rare.
95
- randomCueChance: 0.02,
96
- newSessionPromptDismissed: false,
97
- // What "remember my choice" stores: off | auto | both.
98
- newSessionDefault: 'both',
99
- curatorModel: null,
100
- autoInstallEngine: true,
101
- pipIndexes: [],
102
- // Fresh installs start with the plugin fully alive: auto-install, the
103
- // new-session prompt, domestic texture, and idle consolidation are all on.
104
- // These stay ordinary switches, and an existing saved choice is preserved.
105
- sleepConsolidation: true,
106
- // Group chat arrives in bursts, but a burst is seconds apart and the per-turn
107
- // timestamps already cover that. Two idle minutes still separates "reading a
108
- // diff / thinking" from "gone", and keeps the per-run window small.
109
- sleepAfterIdleMinutes: 2,
110
- // 主动记忆:分数门槛、饥饿阈值(空闲超过它无条件检查)、两种抑制冷却(分钟;整理冷却默认 0,
111
- // 薄证据的重复 fork 由评分拦截,只有用户显式配置才启用硬冷却)。
112
- activeMemoryMinScore: 0.8,
113
- activeMemoryStarvationMinutes: 15,
114
- activeMemoryCooldownMinutes: 0,
115
- activeMemoryRecallCooldownMinutes: 15,
116
- // 全局提炼的审核放行(§4.10):'auto' 只暂扣冲突、缺证据与高风险改写;
117
- // 'review-all' 把全部内容操作送进复核。硬门在两档下都生效。
118
- curatorReviewMode: 'auto',
119
- autoCurateEveryHours: 0,
120
- autoCurateSessionLimit: 8,
121
- // 'local' keeps every memory on this machine; 'cloud' hands MemU's own backend
122
- // the storage, which is the vendor path and off by default.
123
- memoryMode: 'local',
124
- // Who turns a conversation into memory. 'agent' means the conversation's own
125
- // agent writes and summarizes into the JSON index, with no MemU engine and no
126
- // embedding API. 'api' hands the work to the configured remote MemU service.
127
- memoryBackend: 'agent',
128
- vectorSource: 'local',
129
- habitsInjection: true,
130
- // 一次性的带日期承诺过期之后的复提间隔(天)。带日期 + open_loop 的过期条目不走
131
- // 3 天年龄门槛,也不会因为“提过一次”永久沉默;它按这个间隔重复,直到被关闭或归档。
132
- // 它和普通 3 天腿共用每回合 limit 1,dated 过期腿优先。
133
- openLoopRemindDays: 7,
134
- // 工单 E:纪念日到点唤醒。它真的会改变宿主行为——用公开的 ctx.schedule 在绑定会话里
135
- // 开一整回合——所以默认关闭,必须由用户显式打开。salientWakeHour 是该回合的本地墙上
136
- // 时间(HH:mm);salientWakeTimeZone 为空表示跟随系统时区,非空必须是有效 IANA 区。
137
- salientWake: 'off',
138
- salientWakeHour: '09:00',
139
- salientWakeTimeZone: '',
140
- // 整理 fork 的模型选择(三模式)。'inherit' 沿用父会话的 provider/model;'host' 用
141
- // consolidationModel("<provider>/<model>",同 curatorModel 的解析口径)指名宿主已
142
- // 激活的 route;'custom' 用 consolidationCustom* 在宿主 llm 注册表挂本插件私有 route
143
- // (lib/fork-model.js CONSOLIDATION_CUSTOM_ROUTE)。fork 的 AgentOptions 没有
144
- // baseURL/apiKey 通道,自定义端点只能走注册 route,所以 custom 的连接四件套存在这里。
145
- // apiKey 落盘在 state.json(与 ~/.memu/config.env 的 0600 同一信任域),但任何 RPC
146
- // 回包只给 has/tail 打码视图——rpc.js 的 redactConsolidationSettings。
147
- consolidationModelMode: 'inherit',
148
- consolidationModel: null,
149
- // 1.3.1:整理 fork 的思考强度独立于父会话。'inherit' 保持旧行为;'off' /
150
- // 'medium' / 'low' / 'high' 直接覆盖,用于成本/质量的 A/B。
151
- consolidationReasoningEffort: 'medium',
152
- consolidationCustomBaseURL: '',
153
- consolidationCustomApiKey: '',
154
- consolidationCustomModel: '',
155
- consolidationCustomApi: 'openai-completions',
156
- // T0 构件 1(设计文档 §10.1):增量回合日志。'on'(默认)按回合实时落盘,是持久
157
- // 整理 worker 的上下文载体(缓存,不是账本);'off' 时输入退回现场 condenseEvents。
158
- consolidationTurnLog: 'on',
159
- // T1 构件(设计文档 §10.2):整理执行器。'fork'(默认)= 现状每窗新 fork,行为零
160
- // 变化;'worker' = 持久整理 worker(lib/worker-pool.js,epoch 制跨窗复用,三级试活,
161
- // 五退役条件,§4)。回滚 = 切回 'fork',数据层无依赖(turn-log 是缓存,账本才算数)。
162
- consolidationRunner: 'fork',
163
- // 工具行三档(§3.1):'none' 纯对话(默认,实测每窗 ≈3.7k);'errors' 只留错误
164
- // 结果行(≈357 字符/窗的廉价保险);'summary' 完整一行摘要(coding 域保真最高)。
165
- consolidationTurnLogTools: 'none',
166
- // A positive age marks cleanup candidates; deletion always needs a user action.
167
- purgeArchivedAfterDays: 0,
168
- // 升级后的一次性实体碎片自愈(lib/index.js startEntityRepairPass)。默认开,但它**只**合并
169
- // 可证明的那一类(窗口片段重建出正文里出现过的完整名);"只是相似"的候选永远等人工确认。
170
- // 关掉它 = 连可证明的也不动,全部留在诊断页的手动按钮上。写入前一律先备份。
171
- autoRepairEntityFragments: true,
172
- // 回合中途补充召回(inject.js midTurnPolicy):默认开。这些键必须注册在这里——
173
- // updateSettings 对 DEFAULT_SETTINGS 之外的键静默丢弃,文档里「midTurnRecall: false
174
- // 可关」的承诺只有落了默认值与白名单才成立。阈值口径见 docs/memory-semantics.md §8.4。
175
- midTurnRecall: true,
176
- midTurnMinSteps: 4,
177
- midTurnMinUnits: 3,
178
- midTurnMinChars: 6000,
179
- midTurnMaxPerTurn: 2,
180
- midTurnCooldownMs: 60000,
181
- midTurnTokens: 400,
182
- midTurnFullUnits: 6,
183
- midTurnFullChars: 15000,
184
- }
185
-
186
- function defaultState() {
187
- return {
188
- version: 1,
189
- settings: { ...DEFAULT_SETTINGS },
190
- libraries: {},
191
- sessions: {},
192
- // Per-folder memory switches. Keyed by the normalized scope key (the same key
193
- // a library uses), so a folder keeps its choice even before it has a library.
194
- workspacePolicies: {},
195
- }
196
- }
197
-
198
- function mergeState(raw) {
199
- const base = defaultState()
200
- if (!raw || typeof raw !== 'object') return base
201
- const rawSettings = raw.settings && typeof raw.settings === 'object' ? raw.settings : {}
202
- const legacyVectorSource = rawSettings.vectorSource === 'api' || rawSettings.vectorSource === 'local'
203
- ? rawSettings.vectorSource
204
- : (rawSettings.memoryMode === 'cloud' ? 'api' : 'local')
205
- return {
206
- ...base,
207
- ...raw,
208
- settings: { ...base.settings, ...rawSettings, vectorSource: legacyVectorSource },
209
- libraries: raw.libraries && typeof raw.libraries === 'object' ? raw.libraries : {},
210
- sessions: raw.sessions && typeof raw.sessions === 'object' ? raw.sessions : {},
211
- workspacePolicies: raw.workspacePolicies && typeof raw.workspacePolicies === 'object' ? raw.workspacePolicies : {},
212
- }
213
- }
214
-
215
- // A user turn touches the bookkeeping fields 6-7 times (see P0-4). Each write
216
- // used to be a full read + full rewrite of state.json. The cache below coalesces
217
- // those into one trailing write; memory indexes deliberately do NOT go through
218
- // it, because losing a memory is not the same as losing "which turn injected
219
- // what". Cache validity is checked against mtime+size so an external writer
220
- // (backup, another profile) is never silently shadowed.
221
- const FLUSH_MS = 50
222
- let cache = null
223
- let dirty = false
224
- let flushTimer = null
225
-
226
- function statOf(file) {
227
- try { return fs.statSync(file) } catch { return null }
228
- }
229
-
230
- function adoptCache(state, fromReadFailure = false, base = null) {
231
- const stat = statOf(STATE_FILE())
232
- cache = {
233
- dir: dataDir(),
234
- state,
235
- base: structuredClone(base || state),
236
- // True when this cache content is a *fallback* built from defaults because
237
- // the file could not be read — not the on-disk truth. A fallback must never
238
- // be written back: that would replace real bindings/libraries with defaults.
239
- fromReadFailure,
240
- mtimeMs: stat ? stat.mtimeMs : 0,
241
- size: stat ? stat.size : -1,
242
- }
243
- return state
244
- }
245
-
246
- export function loadState() {
247
- const dir = dataDir()
248
- if (cache && cache.dir === dir) {
249
- if (dirty) return cache.state
250
- const stat = statOf(STATE_FILE())
251
- if (!stat) {
252
- // Gone from disk while we hold a good copy: keep it and put it back.
253
- dirty = true
254
- scheduleFlush()
255
- return cache.state
256
- }
257
- // A fallback cache never satisfies the mtime check: it is not the on-disk
258
- // truth, so keep re-reading until the file reads cleanly again.
259
- if (!cache.fromReadFailure && stat.mtimeMs === cache.mtimeMs && stat.size === cache.size) return cache.state
260
- }
261
- dirty = false
262
- let raw = readJson(STATE_FILE(), null)
263
- if (raw !== null) raw = assertJsonShape(STATE_FILE(), raw, value => value && typeof value === 'object' && !Array.isArray(value)
264
- && ['libraries', 'sessions', 'settings', 'workspacePolicies'].every(key => value[key] === undefined || value[key] && typeof value[key] === 'object' && !Array.isArray(value[key])))
265
- // Distinguish "no file yet" (writing defaults is harmless) from "read failed"
266
- // (writing defaults would destroy the real state still on disk).
267
- const failed = readFailure(STATE_FILE()) !== null
268
- return adoptCache(mergeState(raw), failed)
269
- }
270
-
271
- export function saveState(state) {
272
- // Carry the fallback marker over: saving new content does not make a
273
- // previously-failed read trustworthy.
274
- const previous = cache?.dir === dataDir() ? cache : null
275
- adoptCache(state, previous?.fromReadFailure === true, previous?.base)
276
- if (previous) { cache.mtimeMs = previous.mtimeMs; cache.size = previous.size }
277
- dirty = true
278
- bumpMemoryRevision()
279
- flushState()
280
- return state
281
- }
282
-
283
- export function updateState(fn) {
284
- const state = structuredClone(loadState())
285
- const next = fn(state) || state
286
- if (cache) cache.state = next
287
- dirty = true
288
- scheduleFlush()
289
- return next
290
- }
291
-
292
- // Codes that mean "the store was momentarily unavailable", not "this write can never
293
- // succeed". Only these are re-armed; a read-only filesystem or a corrupt path would
294
- // otherwise retry forever at FLUSH_MS.
295
- const RETRYABLE_FLUSH_CODES = ['DSH_MEMU_STORE_BUSY', 'EPERM', 'EBUSY', 'EACCES']
296
-
297
- function scheduleFlush() {
298
- if (flushTimer) return
299
- flushTimer = setTimeout(() => {
300
- flushTimer = null
301
- try {
302
- flushState()
303
- } catch (error) {
304
- warnSinkSafe(`state flush failed: ${error?.message || error}`)
305
- if (RETRYABLE_FLUSH_CODES.includes(error?.code)) scheduleFlush()
306
- }
307
- }, FLUSH_MS)
308
- flushTimer.unref?.()
309
- }
310
-
311
- /** Writes any pending bookkeeping change now. Safe to call when clean. */
312
- export function flushState() {
313
- if (flushTimer) {
314
- clearTimeout(flushTimer)
315
- flushTimer = null
316
- }
317
- if (!dirty || !cache) return
318
- try {
319
- return withFileLock(STATE_FILE(), flushStateLocked)
320
- } catch (error) {
321
- // S-10: the timer was already cleared above, so a failed flush used to leave the
322
- // pending bookkeeping dirty with nothing scheduled — one busy lock was enough to
323
- // strand inbound pending / lastRecallError / sleepRetryAt in memory until the next
324
- // unrelated write (or a crash). Re-arm before rethrowing so the batch is retried;
325
- // the caller still sees the error.
326
- warnSinkSafe(`state flush failed: ${error?.message || error}`)
327
- if (RETRYABLE_FLUSH_CODES.includes(error?.code)) scheduleFlush()
328
- throw error
329
- }
330
- }
331
-
332
- function mergeChanges(base, local, disk) {
333
- if (JSON.stringify(base) === JSON.stringify(local)) return structuredClone(disk)
334
- const object = value => value !== null && typeof value === 'object' && !Array.isArray(value)
335
- if (!object(base) || !object(local) || !object(disk)) return structuredClone(local)
336
- const next = { ...disk }
337
- for (const key of new Set([...Object.keys(base), ...Object.keys(local)])) {
338
- if (JSON.stringify(base[key]) === JSON.stringify(local[key])) continue
339
- if (!Object.hasOwn(local, key)) delete next[key]
340
- else next[key] = mergeChanges(base[key], local[key], disk[key])
341
- }
342
- return next
343
- }
344
-
345
- function flushStateLocked() {
346
- if (!cache.fromReadFailure) {
347
- // A read can race another process's rename before its post-read stat.
348
- // Always merge the disk truth under the lock; mtime/size is not a transaction.
349
- const disk = readJson(STATE_FILE(), null)
350
- if (readFailure(STATE_FILE())) throw new Error('state.json changed but could not be read; pending changes retained')
351
- cache.state = mergeChanges(cache.base, cache.state, mergeState(disk))
352
- }
353
- try {
354
- writeJson(STATE_FILE(), cache.state)
355
- } catch (error) {
356
- if (error?.code !== 'dsh-memu-memory/read-failed') throw error
357
- // The write barrier is set only while the file is unreadable. Re-probe: a
358
- // successful read clears it, so a transient EBUSY does not freeze the plugin
359
- // until restart. If it is still unreadable this write throws again.
360
- const diskRaw = readJson(STATE_FILE(), null)
361
- if (readFailure(STATE_FILE()) !== null) throw error
362
- if (cache.fromReadFailure) {
363
- // The pending write was built on top of a *fallback* state, not the real
364
- // one. Writing it now would overwrite good data with defaults. Adopt the
365
- // disk truth instead and drop the pending fallback write.
366
- warn('state.json read failed earlier; discarding changes made against the fallback state to avoid overwriting real data')
367
- adoptCache(mergeState(diskRaw), false)
368
- dirty = false
369
- return
370
- }
371
- writeJson(STATE_FILE(), cache.state)
372
- }
373
- dirty = false
374
- noteMemoryWrite('state', null)
375
- const stat = statOf(STATE_FILE())
376
- cache.mtimeMs = stat ? stat.mtimeMs : 0
377
- cache.size = stat ? stat.size : -1
378
- cache.base = structuredClone(cache.state)
379
- }
380
-
381
- function warnSinkSafe(message) {
382
- warn(message)
383
- }
384
-
385
- export function getSettings() {
386
- return loadState().settings
387
- }
388
-
389
- /**
390
- * Files that failed to read and are now write-protected, plus quarantined
391
- * copies left behind. Surfaced by `memu_status` so a silent storage fault is
392
- * visible instead of becoming "my memories vanished".
393
- */
394
- export function storageHealth() {
395
- const issues = readFailuresUnder(dataDir()).map((failure) => {
396
- const relative = path.relative(dataDir(), failure.file).replace(/\\/g, '/')
397
- const { file, ...rest } = failure
398
- return { file: relative, ...rest }
399
- })
400
- const quarantined = []
401
- for (const [dir, prefix] of [[dataDir(), ''], [indexDir(), 'index/']]) {
402
- try {
403
- for (const name of fs.readdirSync(dir)) {
404
- if (name.includes('.corrupt-')) quarantined.push(`${prefix}${name}`)
405
- }
406
- } catch {}
407
- }
408
- return { issues, quarantined }
409
- }
410
-
411
- // The default is deliberately the self-contained path: a fresh install must be
412
- // able to remember without MemU, Ollama, or any vendor key.
413
- export function getMemoryBackend() {
414
- return loadState().settings?.memoryBackend === 'api' ? 'api' : 'agent'
415
- }
416
-
417
- // Single route authority for automatic memory reads and writes.
418
- export function effectiveVectorRoute(settings = loadState().settings) {
419
- if (settings?.memoryBackend !== 'api') return 'lexical'
420
- return settings?.vectorSource === 'api' ? 'remote-api' : 'managed-local'
421
- }
422
-
423
- export function vectorBackendEnabled(settings = loadState().settings) {
424
- return effectiveVectorRoute(settings) !== 'lexical'
425
- }
426
-
427
- export function updateSettings(patch) {
428
- const clean = {}
429
- const ranges = {
430
- privateTopK: [1, 20], globalTopK: [1, 20], anchorTokens: [160, 8000], turnTokens: [80, 8000],
431
- injectionTotalTokens: [160, 16000],
432
- relevanceThreshold: [0, 1], dedupeTurns: [0, 200], globalEveryNTurns: [0, 200], minUserChars: [0, 1000],
433
- freshnessDays: [1, 3650],
434
- mustRememberCap: [1, 100], randomCueChance: [0, 1], shortTermTtlHours: [0, 8760],
435
- unpinBudgetPerSession: [1, 20], unpinCooldownMinutes: [0, 1440], sleepAfterIdleMinutes: [1, 1440],
436
- openLoopRemindDays: [1, 365],
437
- autoCurateEveryHours: [0, 8760], autoCurateSessionLimit: [1, 10], purgeArchivedAfterDays: [0, 36500],
438
- activeMemoryMinScore: [0, 10], activeMemoryStarvationMinutes: [1, 1440],
439
- activeMemoryCooldownMinutes: [0, 10080], activeMemoryRecallCooldownMinutes: [0, 10080],
440
- midTurnMinSteps: [1, 64], midTurnMinUnits: [1, 200], midTurnMinChars: [0, 200000],
441
- midTurnMaxPerTurn: [1, 10], midTurnCooldownMs: [0, 600000], midTurnTokens: [120, 2000],
442
- midTurnFullUnits: [1, 200], midTurnFullChars: [0, 200000],
443
- }
444
- const enums = { autoInject: ['smart', 'anchor-only', 'per-turn', 'off'], autoLinkMode: ['suggest', 'deterministic', 'off'], memoryMode: ['local', 'cloud'], memoryBackend: ['agent', 'api'], vectorSource: ['local', 'api'], newSessionDefault: ['off', 'auto', 'global', 'both'], curatorReviewMode: ['auto', 'review-all'], salientWake: ['off', 'schedule'], consolidationModelMode: ['inherit', 'host', 'custom'], consolidationReasoningEffort: ['inherit', 'off', 'low', 'medium', 'high'], consolidationCustomApi: ['openai-completions', 'openai-responses', 'anthropic-messages'], consolidationTurnLog: ['on', 'off'], consolidationTurnLogTools: ['none', 'errors', 'summary'], consolidationRunner: ['worker', 'fork'] }
445
- for (const [key, value] of Object.entries(patch || {})) {
446
- if (!Object.hasOwn(DEFAULT_SETTINGS, key)) continue
447
- if (enums[key]) {
448
- if (!enums[key].includes(value)) throw new Error(`invalid setting ${key}`)
449
- clean[key] = value
450
- } else if (ranges[key]) {
451
- if (typeof value !== 'number' || !Number.isFinite(value)) throw new Error(`setting ${key} must be a finite number`)
452
- const [min, max] = ranges[key]
453
- clean[key] = Math.max(min, Math.min(max, value))
454
- } else if (typeof DEFAULT_SETTINGS[key] === 'boolean') {
455
- if (typeof value !== 'boolean') throw new Error(`setting ${key} must be boolean`)
456
- clean[key] = value
457
- } else if (key === 'curatorModel') {
458
- if (value !== null && (typeof value !== 'string' || value.length > 200)) throw new Error('invalid curator model')
459
- clean[key] = value
460
- } else if (key === 'consolidationModel') {
461
- // host 模式的 "<provider>/<model>"。格式本身留给 lib/fork-model.js 的解析口径
462
- // (与 curatorModel 一致:这里只挡类型与超长),写错的值会在 fork 创建时被
463
- // invalid-consolidation-model 拒绝并在活动日志里说清,设置页先存的草稿不该被卡死。
464
- if (value !== null && (typeof value !== 'string' || value.length > 200)) throw new Error('invalid consolidation model')
465
- clean[key] = value
466
- } else if (key === 'consolidationCustomBaseURL') {
467
- // custom 模式的端点。空串是「还没填」,合法;非空必须是不带内嵌凭据的 http(s)
468
- // URL——与 pipIndexes / vision endpoint 同一把尺(宿主请求头进不了带凭据的 URL)。
469
- if (typeof value !== 'string') throw new Error('setting consolidationCustomBaseURL must be a string')
470
- const trimmed = value.trim()
471
- if (trimmed) {
472
- try {
473
- const url = new URL(trimmed)
474
- if (!['http:', 'https:'].includes(url.protocol) || url.username || url.password) throw new Error('bad protocol')
475
- } catch {
476
- throw new Error('consolidationCustomBaseURL must be an HTTP(S) URL without embedded credentials')
477
- }
478
- }
479
- clean[key] = trimmed
480
- } else if (key === 'consolidationCustomApiKey') {
481
- // custom 模式选填的明文 key(本地网关可以没有)。落盘在 state.json,回包只给
482
- // 打码视图(rpc.js);这里只挡类型与荒谬长度,两头空白顺手去掉。
483
- if (typeof value !== 'string' || value.length > 500) throw new Error('invalid consolidation custom api key')
484
- clean[key] = value.trim()
485
- } else if (key === 'consolidationCustomModel') {
486
- // custom 模式必填的模型 id。允许 '/'(openrouter 风格的嵌套 id),只挡类型与长度。
487
- if (typeof value !== 'string' || value.length > 200) throw new Error('invalid consolidation custom model')
488
- clean[key] = value.trim()
489
- } else if (key === 'salientWakeHour') {
490
- // 定时唤醒的本地墙上时间。只收 HH:mm,不收 "9:00":宿主的 at 输入按 HH:mm[:ss]
491
- // 解释,少一位会被拒或读成别的时刻,宁可在设置页就拒绝。
492
- if (typeof value !== 'string' || !/^([01]\d|2[0-3]):[0-5]\d$/.test(value)) throw new Error('setting salientWakeHour must be HH:mm')
493
- clean[key] = value
494
- } else if (key === 'salientWakeTimeZone') {
495
- // 空串是"跟随系统",是合法配置,不在这里解析成具体城市;非空必须是有效 IANA 区,
496
- // 否则宿主的 at 计时会在投递时被拒(invalid_time_zone),排了也不会响。
497
- if (typeof value !== 'string' || value.length > 100) throw new Error('invalid salientWakeTimeZone')
498
- const zone = value.trim()
499
- if (zone) {
500
- try {
501
- new Intl.DateTimeFormat('en-US', { timeZone: zone })
502
- } catch {
503
- throw new Error(`invalid salientWakeTimeZone: ${zone}`)
504
- }
505
- }
506
- clean[key] = zone
507
- } else if (key === 'pipIndexes' || key === 'promptDomains' || key === 'inboundToolNames') {
508
- if (!Array.isArray(value) || value.length > 20 || value.some(item => typeof item !== 'string')) throw new Error(`invalid setting ${key}`)
509
- if (key === 'promptDomains' && value.some(item => !/^[a-z0-9][a-z0-9_-]{0,23}$/.test(item))) throw new Error('invalid domain id')
510
- if (key === 'inboundToolNames' && value.some(item => !/^[A-Za-z0-9_.:/-]{1,160}$/.test(item))) throw new Error('invalid inbound tool name')
511
- if (key === 'pipIndexes' && value.some(item => {
512
- try { const url = new URL(item); return !['http:', 'https:'].includes(url.protocol) || url.username || url.password } catch { return true }
513
- })) throw new Error('pip indexes must be HTTP(S) URLs without credentials')
514
- clean[key] = value.slice()
515
- }
516
- }
517
- return updateState((state) => {
518
- state.settings = { ...state.settings, ...clean }
519
- return state
520
- }).settings
521
- }
522
-
523
- /**
524
- * The prompt pages a user can edit and assign. Ids are used as file suffixes and
525
- * as session domains, so they are restricted to a slug alphabet; `general` is
526
- * implicit (the base prompt) and never appears here.
527
- */
528
- export function getPromptDomains() {
529
- const raw = loadState().settings?.promptDomains
530
- const list = Array.isArray(raw) ? raw : DEFAULT_SETTINGS.promptDomains
531
- const seen = new Set()
532
- const out = []
533
- for (const value of list) {
534
- const id = String(value || '').trim().toLowerCase()
535
- if (!/^[a-z0-9][a-z0-9_-]{0,23}$/.test(id) || id === 'general' || seen.has(id)) continue
536
- seen.add(id)
537
- out.push(id)
538
- }
539
- return out
540
- }
541
-
542
- export function addPromptDomain(id) {
543
- const value = String(id || '').trim().toLowerCase()
544
- if (!/^[a-z0-9][a-z0-9_-]{0,23}$/.test(value)) throw new Error('domain id must be 1-24 chars: a-z, 0-9, - or _')
545
- if (value === 'general') throw new Error('"general" is the built-in 通用 page')
546
- const list = getPromptDomains()
547
- if (list.includes(value)) return list
548
- return updateSettings({ promptDomains: [...list, value] }).promptDomains
549
- }
550
-
551
- export function removePromptDomain(id) {
552
- const value = String(id || '').trim().toLowerCase()
553
- const list = getPromptDomains()
554
- if (!list.includes(value)) return list
555
- return updateSettings({ promptDomains: list.filter((item) => item !== value) }).promptDomains
556
- }
557
-
558
- // Both switches default to on: that is the behaviour every existing folder had
559
- // before this setting existed. Turning the private switch off means "this folder
560
- // keeps no private library", not "delete the one it has" — nothing is ever deleted
561
- // by a switch.
562
- export const DEFAULT_FOLDER_POLICY = { useLibrary: true, useGlobal: true }
563
-
564
- function policyFor(state, scopeKey) {
565
- return { ...DEFAULT_FOLDER_POLICY, ...(state.workspacePolicies?.[scopeKey] || {}) }
566
- }
567
-
568
- export function getWorkspacePolicy(scopeKey) {
569
- const key = normalizeCwd(scopeKey) || '__default__'
570
- return { scopeKey: key, ...policyFor(loadState(), key) }
571
- }
572
-
573
- /**
574
- * The folder policy is a ceiling, not an initial value. `sessions[].useLibrary`
575
- * records what the user chose for that conversation; the folder decides how far
576
- * that choice can go. Storing the wish and computing the effect separately is
577
- * what lets re-enabling a folder restore each conversation's own choice instead
578
- * of flipping everything back on.
579
- */
580
- export function effectiveScope(binding, policy = null) {
581
- const folder = policy || (binding?.scopeKey ? getWorkspacePolicy(binding.scopeKey) : { ...DEFAULT_FOLDER_POLICY })
582
- const wantsLibrary = binding ? binding.useLibrary !== false : folder.useLibrary !== false
583
- const wantsGlobal = binding ? binding.useGlobal !== false : folder.useGlobal !== false
584
- return {
585
- folder,
586
- useLibrary: folder.useLibrary !== false && wantsLibrary,
587
- useGlobal: folder.useGlobal !== false && wantsGlobal,
588
- libraryBlocked: folder.useLibrary === false,
589
- globalBlocked: folder.useGlobal === false,
590
- enabled: (folder.useLibrary !== false && wantsLibrary) || (folder.useGlobal !== false && wantsGlobal),
591
- }
592
- }
593
-
594
- export function listWorkspacePolicies() {
595
- const state = loadState()
596
- return Object.entries(state.workspacePolicies || {})
597
- .map(([scopeKey, policy]) => ({ scopeKey, ...DEFAULT_FOLDER_POLICY, ...policy }))
598
- }
599
-
600
- export function setWorkspacePolicy(scopeKey, patch = {}) {
601
- const key = normalizeCwd(scopeKey) || '__default__'
602
- const state = updateState((draft) => {
603
- draft.workspacePolicies = draft.workspacePolicies || {}
604
- const next = { ...DEFAULT_FOLDER_POLICY, ...(draft.workspacePolicies[key] || {}) }
605
- for (const field of ['useLibrary', 'useGlobal']) {
606
- if (typeof patch[field] === 'boolean') next[field] = patch[field]
607
- }
608
- draft.workspacePolicies[key] = { ...next, updatedAt: stamp() }
609
- const library = Object.entries(draft.libraries)
610
- .find(([, lib]) => lib.scopeKey === key && lib.archived !== true)
611
- // Existing conversations are deliberately NOT edited: their switches record
612
- // what the user chose for that chat, and the folder policy above already
613
- // clamps them at read time. The only repair worth doing is pointing a
614
- // conversation at its folder's library once one exists again.
615
- if (patch.useLibrary === true) {
616
- for (const binding of Object.values(draft.sessions || {})) {
617
- const inFolder = binding.scopeKey === key
618
- || (binding.libraryId && draft.libraries[binding.libraryId]?.scopeKey === key)
619
- if (inFolder && !binding.libraryId && library) binding.libraryId = library[0]
620
- }
621
- }
622
- return draft
623
- })
624
- return { scopeKey: key, ...policyFor(state, key) }
625
- }
626
-
627
- export function normalizeCwd(cwd) {
628
- if (!cwd || typeof cwd !== 'string') return ''
629
- // The no-workspace placeholder is a key, not a path. Resolving it would produce
630
- // a machine-dependent scope like `d:/somewhere/__default__` and leak a junk
631
- // library into the list every time a session starts without a folder.
632
- if (cwd === '__default__') return '__default__'
633
- let resolved
634
- try { resolved = path.resolve(cwd) } catch { resolved = cwd }
635
- let text = resolved.replace(/\\/g, '/').replace(/\/+$/, '')
636
- if (process.platform === 'win32') text = text.toLowerCase()
637
- return text
638
- }
639
-
640
- export function detectDomain({ agentPreset, cwd } = {}) {
641
- const text = `${agentPreset || ''} ${cwd || ''}`.toLowerCase()
642
- if (/(roleplay|role-play|character|persona|rp[-_ ]|沉浸|角色扮演)/.test(text)) return 'rp'
643
- if (cwd) return 'coding'
644
- return 'general'
645
- }
646
-
647
- export function listLibraries() {
648
- const state = loadState()
649
- return Object.entries(state.libraries)
650
- .filter(([, lib]) => lib.archived !== true)
651
- .map(([id, lib]) => ({ id, ...lib }))
652
- .sort((a, b) => String(b.lastUsedAt || '').localeCompare(String(a.lastUsedAt || '')))
653
- }
654
-
655
- export function listLibrariesAll() {
656
- const state = loadState()
657
- return Object.entries(state.libraries).map(([id, lib]) => ({ id, ...lib }))
658
- }
659
-
660
- export function listArchivedLibraries() {
661
- const state = loadState()
662
- return Object.entries(state.libraries)
663
- .filter(([, lib]) => lib.archived === true)
664
- .map(([id, lib]) => ({ id, ...lib }))
665
- // Oldest archived first: the ones nobody revived are the deletion candidates.
666
- .sort((a, b) => String(a.archivedAt || '').localeCompare(String(b.archivedAt || '')))
667
- }
668
-
669
- // A library's scope folder is gone from disk. `__default__` has no folder to check,
670
- // so it never counts as missing.
671
- export function libraryScopeMissing(lib) {
672
- const key = lib?.scopeKey
673
- if (!key || key === '__default__') return false
674
- try {
675
- return !fs.existsSync(key)
676
- } catch {
677
- return false
678
- }
679
- }
680
-
681
- // Hard delete: the sqlite store and its sidecar index leave with the state entry.
682
- // Only ever called on an already-archived library, so the caller had to confirm twice.
683
- // `force` exists for the one legitimate case the state cannot see: the caller already
684
- // unbound every session and knows it. Without it, a library that a live conversation
685
- // still points at cannot be deleted — the sweep used to be able to put an in-use
686
- // library into the only state `deleteLibrary` accepts (2026-11-21 外部报告).
687
- export function deleteLibrary(id, { force = false } = {}) {
688
- if (!isSafeId(id)) throw new Error('invalid library id')
689
- const state = loadState()
690
- if (!state.libraries[id]) return { ok: false, error: 'library not found' }
691
- if (state.libraries[id].archived !== true) return { ok: false, error: 'archive the library before deleting it' }
692
- // 只拦「危险归档 + 仍在用」:扫描误归档的那一类才有一键删掉全部记忆的风险。
693
- // 用户主动归档仍有绑定会话时照旧允许(删除会连同绑定一起清掉,这是既有语义);
694
- // 冷数据的旧归档同理放行,否则本机 rp / 另一个工作区库 这类库会变成"永远删不掉"。
695
- if (!force && archivedWhileInUse(state.libraries[id], { inUse: inUseLibraryIds(state).has(id) })) {
696
- return { ok: false, error: 'this library was archived while a conversation still uses it; unbind or delete those sessions first (force overrides)' }
697
- }
698
- const activeVectorDb = removeActiveLibrary(id)
699
- const legacyVectorDb = path.join(librariesDir(), id + '.sqlite3')
700
- delete state.libraries[id]
701
- for (const [sessionId, binding] of Object.entries(state.sessions || {})) {
702
- if (binding?.libraryId === id) delete state.sessions[sessionId]
703
- }
704
- saveState(state)
705
- const removed = []
706
- const vectorPrefix = id + '.'
707
- const vectorGenerationFiles = fs.existsSync(librariesDir())
708
- ? fs.readdirSync(librariesDir()).filter(name => name.startsWith(vectorPrefix) && name.endsWith('.sqlite3')).map(name => path.join(librariesDir(), name))
709
- : []
710
- for (const file of [activeVectorDb, legacyVectorDb, ...vectorGenerationFiles, ...['json', 'entities.json', 'media.json', 'stats.json', 'link-suppression.json', 'anchor-candidates.json'].map(suffix => path.join(indexDir(), `${id}.${suffix}`))]) {
711
- if (!file) continue
712
- try {
713
- if (fs.existsSync(file)) { fs.rmSync(file, { force: true }); removed.push(file) }
714
- } catch {}
715
- }
716
- const attachments = path.join(dataDir(), 'attachments', id)
717
- if (!path.resolve(attachments).startsWith(path.resolve(dataDir(), 'attachments') + path.sep)) throw new Error('attachment path escaped')
718
- if (fs.existsSync(attachments)) fs.rmSync(attachments, { recursive: true, force: true })
719
- return { ok: true, id, removed }
720
- }
721
-
722
- export function getLibrary(id) {
723
- if (!id) return null
724
- const lib = loadState().libraries[id]
725
- return lib ? { id, ...lib } : null
726
- }
727
-
728
- function uniqueLibraryId(state, scopeKey) {
729
- let id = libraryIdForScope(scopeKey)
730
- if (state.libraries[id] && state.libraries[id].scopeKey !== scopeKey) {
731
- id = `${id}-${shortHash(scopeKey)}`
732
- }
733
- return id
734
- }
735
-
736
- export function createLibrary({ name, scopeKey, cwd } = {}) {
737
- const key = normalizeCwd(scopeKey || cwd || name || '__default__')
738
- const state = loadState()
739
- const id = uniqueLibraryId(state, key)
740
- if (state.libraries[id]) return { id, ...state.libraries[id] }
741
- state.libraries[id] = {
742
- name: String(name || path.basename(key) || 'Default').slice(0, 80),
743
- scopeKey: key,
744
- createdAt: stamp(),
745
- lastUsedAt: stamp(),
746
- }
747
- saveState(state)
748
- ensureDir(librariesDir())
749
- return { id, ...state.libraries[id] }
750
- }
751
-
752
- export function ensureLibraryForCwd(cwd) {
753
- const scopeKey = normalizeCwd(cwd) || '__default__'
754
- const state = loadState()
755
- const found = Object.entries(state.libraries).find(([, lib]) => lib.scopeKey === scopeKey)
756
- if (found) {
757
- found[1].lastUsedAt = stamp()
758
- // The folder came back: re-binding it revives the library instead of silently
759
- // writing new memories into an archived one.
760
- if (found[1].archived) {
761
- found[1].archived = false
762
- found[1].archivedAt = null
763
- found[1].revivedAt = stamp()
764
- }
765
- saveState(state)
766
- return { id: found[0], ...found[1] }
767
- }
768
- return createLibrary({ scopeKey, name: scopeKey === '__default__' ? 'Default' : path.basename(scopeKey) })
769
- }
770
-
771
- export function renameLibrary(id, name) {
772
- const state = loadState()
773
- if (!state.libraries[id]) return null
774
- state.libraries[id].name = String(name || '').trim().slice(0, 80) || state.libraries[id].name
775
- saveState(state)
776
- return { id, ...state.libraries[id] }
777
- }
778
-
779
- // A pre-folder build could bind a conversation before its cwd was known, leaving
780
- // one shared "Default" bucket for every workspace. The conversation is the only
781
- // place that still knows the real folder, so when it is opened with a cwd we
782
- // promote that bucket in place: same id, so its memories and index stay attached,
783
- // but the name and scope become the folder a human expects to see.
784
- export function adoptDefaultLibrary(libraryId, cwd) {
785
- const key = normalizeCwd(cwd)
786
- if (!key || key === '__default__') return null
787
- const state = loadState()
788
- const lib = state.libraries[libraryId]
789
- if (!lib || normalizeCwd(lib.scopeKey || '') !== '__default__') return null
790
- const existing = Object.entries(state.libraries)
791
- .find(([id, other]) => id !== libraryId && other.scopeKey === key && other.archived !== true)
792
- if (existing) {
793
- for (const binding of Object.values(state.sessions || {})) {
794
- if (binding.libraryId === libraryId) {
795
- binding.libraryId = existing[0]
796
- binding.scopeKey = key
797
- }
798
- }
799
- // Keep the old bucket recoverable but out of the way when nothing points at it
800
- // any more. It is never deleted: a mis-detected cwd must not destroy memories.
801
- const stillBound = Object.values(state.sessions || {}).some((b) => b.libraryId === libraryId)
802
- if (!stillBound) {
803
- lib.archived = true
804
- lib.archivedAt = stamp()
805
- lib.adoptedInto = existing[0]
806
- }
807
- saveState(state)
808
- return { id: existing[0], ...existing[1], adopted: true, reused: true }
809
- }
810
- lib.scopeKey = key
811
- lib.name = key.split(/[\\/]/).filter(Boolean).pop() || lib.name || 'Default'
812
- lib.updatedAt = stamp()
813
- for (const binding of Object.values(state.sessions || {})) {
814
- if (binding.libraryId === libraryId) binding.scopeKey = key
815
- }
816
- saveState(state)
817
- return { id: libraryId, ...lib, adopted: true }
818
- }
819
-
820
- /**
821
- * 哪些库正被真实会话使用:有存活绑定(`sessionGone !== true`)指向它即算在用。
822
- *
823
- * 为什么需要这个判据:归档扫描(cycle.js `runLibraryHousekeeping`)以前只看
824
- * workspaceRegistry 里注册的目录。IM 插件数据目录、profile 下的目录这类 scope 永远不在
825
- * 注册表里,于是「建库 → 176 秒后被归档 → 绑定会话继续读写 9 小时」这种自相矛盾的状态
826
- * 会稳定发生(2026-11-21 外部报告:归档后 172 条活动、6 次召回全部成功,而 UI 里库已经
827
- * 消失,且它恰好处于 `deleteLibrary` 唯一允许删除的状态)。
828
- *
829
- * 只认绑定关系、不掺时间窗口:过期时间会让「刚打开就被归档」在边界上复现,而绑定关系是
830
- * 确定的事实。传 state 进来是为了让 sweep 一次读盘、只算一次。
831
- */
832
- export function inUseLibraryIds(state = null) {
833
- const snapshot = state || loadState()
834
- const ids = new Set()
835
- for (const binding of Object.values(snapshot.sessions || {})) {
836
- if (!binding || binding.sessionGone === true) continue
837
- const libraryId = binding.libraryId
838
- if (!libraryId || !snapshot.libraries?.[libraryId]) continue
839
- ids.add(libraryId)
840
- }
841
- return ids
842
- }
843
-
844
- export function isLibraryInUse(id) {
845
- return Boolean(id) && inUseLibraryIds().has(id)
846
- }
847
-
848
- // 1.3.13 及更早的归档没有 `archivedBy`:分不清是用户点的归档还是老扫描误归档。
849
- // 对这类库只认「还热」的(lastUsedAt 在 14 天内),冷归档按用户意图对待。
850
- export const ARCHIVE_REVIVE_FRESH_MS = 14 * 86_400_000
851
-
852
- /**
853
- * 「归档了但其实还在用」——扫描误归档的判据,同时也是删除守卫的判据。
854
- *
855
- * 用户主动归档(`archivedBy === 'user'`)永远不算;扫描归档的(`'sweep'`)永远算;
856
- * 旧数据按 lastUsedAt 的新鲜度判。两处共用同一个函数,避免"扫描复活、删除又放行"这种
857
- * 两套口径各说各话。
858
- */
859
- export function archivedWhileInUse(lib, { inUse = false, now = Date.now() } = {}) {
860
- if (!inUse || !lib) return false
861
- if (lib.archivedBy === 'user') return false
862
- if (lib.archivedBy === 'sweep') return true
863
- const lastUsed = Date.parse(lib.lastUsedAt || '') || 0
864
- return lastUsed > 0 && now - lastUsed <= ARCHIVE_REVIVE_FRESH_MS
865
- }
866
-
867
- /** `by` 记录是谁归档的:用户的主动归档不该被扫描悄悄复活。 */
868
- export function archiveLibrary(id, { by = 'user' } = {}) {
869
- const state = loadState()
870
- if (!state.libraries[id]) return false
871
- state.libraries[id].archived = true
872
- state.libraries[id].archivedAt = stamp()
873
- state.libraries[id].archivedBy = by
874
- saveState(state)
875
- return true
876
- }
877
-
878
- // Registry presence is the signal for both directions: the sweep only calls this for
879
- // a scope that just came back into the workspace list. Checking the disk here would
880
- // contradict the archive rule (removing a workspace keeps its folder on disk, and a
881
- // folder can be absent for reasons that have nothing to do with DSH).
882
- export function restoreLibrary(id) {
883
- const state = loadState()
884
- const lib = state.libraries[id]
885
- if (!lib) return { ok: false, error: 'library not found' }
886
- lib.archived = false
887
- lib.archivedAt = null
888
- lib.archivedBy = null
889
- lib.revivedAt = stamp()
890
- lib.lastUsedAt = stamp()
891
- saveState(state)
892
- return { ok: true, id, library: { id, ...lib } }
893
- }
894
-
895
- export function getSessionBinding(sessionId) {
896
- if (!sessionId) return null
897
- const state = loadState()
898
- return state.sessions[sessionId] || null
899
- }
900
-
901
- export function setSessionBinding(sessionId, patch) {
902
- return updateState((state) => {
903
- const previous = state.sessions[sessionId] || {}
904
- const next = { ...previous, ...(patch || {}) }
905
- for (const key of ['lastInjectedUserMessageId', 'guideRulesKey', 'guideMessageAt', 'anchorPushed']) {
906
- if (!Object.hasOwn(patch || {}, key)) continue
907
- next.injectionOwners = { ...(next.injectionOwners || {}), [key]: `legacy:${crypto.randomUUID()}` }
908
- }
909
- const scopeFields = ['libraryId', 'scopeKey', 'memoryContext', 'useLibrary', 'useGlobal', 'domainOverride']
910
- if (scopeFields.some(key => Object.hasOwn(patch || {}, key) && JSON.stringify(previous[key]) !== JSON.stringify(next[key]))) {
911
- next.scopeGeneration = Number(previous.scopeGeneration || 0) + 1
912
- }
913
- state.sessions[sessionId] = next
914
- return state
915
- }).sessions[sessionId]
916
- }
917
-
918
- export function ensureSession(sessionId, { cwd, agentPreset, libraryId = null, createLibrary = true } = {}) {
919
- if (!sessionId) throw new Error('ensureSession requires a sessionId')
920
- const initial = loadState()
921
- const previous = initial.sessions[sessionId]
922
- if (previous?.libraryId && initial.libraries[previous.libraryId]) {
923
- const boundLibrary = initial.libraries[previous.libraryId]
924
- // 一个正在被这个会话读写的库不该停在 archived:归档的语义是「隐藏、准备清理」,
925
- // 而在用的库既不该消失,也不该落进 `deleteLibrary` 唯一允许删除的状态。旧版扫描
926
- // 只要 scope 不在 workspaceRegistry 就归档,而这条快路径从不复活,于是库能一边
927
- // 「归档」一边长数据 9 小时。用户主动归档(archivedBy === 'user')除外。
928
- if (boundLibrary.archived === true && boundLibrary.archivedBy !== 'user') {
929
- restoreLibrary(previous.libraryId)
930
- const revived = loadState().sessions[sessionId]
931
- if (revived) return revived
932
- }
933
- const libraryScope = normalizeCwd(boundLibrary.scopeKey || '')
934
- // Repair the old placeholder bucket as soon as the live conversation reveals
935
- // its folder. Without this, every historical Default library stays mislabelled
936
- // even though new conversations are correct.
937
- if (libraryScope === '__default__' && normalizeCwd(cwd)) {
938
- const adopted = adoptDefaultLibrary(previous.libraryId, cwd)
939
- if (adopted) {
940
- const repaired = loadState().sessions[sessionId]
941
- if (repaired) return repaired
942
- }
943
- }
944
- // A library that already knows its folder but still carries the placeholder
945
- // name should show the folder too; this is the case the old repair missed.
946
- const placeholderName = !boundLibrary.name || boundLibrary.name === 'Default' || boundLibrary.name === '__default__'
947
- if (libraryScope && libraryScope !== '__default__' && placeholderName) {
948
- boundLibrary.name = libraryScope.split(/[\\/]/).filter(Boolean).pop() || boundLibrary.name || 'Default'
949
- boundLibrary.updatedAt = stamp()
950
- }
951
- boundLibrary.lastUsedAt = stamp()
952
- saveState(initial)
953
- return previous
954
- }
955
- const scopeKey = normalizeCwd(cwd) || '__default__'
956
- const policy = policyFor(initial, scopeKey)
957
- const requested = libraryId && initial.libraries[libraryId] ? libraryId : null
958
- // A per-conversation switch is the user's choice and must survive every turn:
959
- // `ensureSession` runs on each step, so overwriting it from the folder policy
960
- // here used to reset the sidebar toggle constantly. The folder still clamps at
961
- // read time via effectiveScope().
962
- const existingBinding = initial.sessions[sessionId]
963
- const wantsLibrary = existingBinding ? existingBinding.useLibrary !== false : policy.useLibrary !== false
964
- const wantsGlobal = existingBinding ? existingBinding.useGlobal !== false : policy.useGlobal !== false
965
- let lib = null
966
- if (requested) lib = { id: requested, ...initial.libraries[requested] }
967
- // `createLibrary` governs *creating* a library, never *adopting* one. Tying both
968
- // to it meant a folder that already had a library still started every new
969
- // conversation with `libraryId === null` whenever the caller passed
970
- // `createLibrary: false` — the exact shape of "my memories are gone in a new
971
- // chat". Re-using the folder's library is not a side effect; it is the point of
972
- // the folder policy. Archived libraries are skipped here (reviving one is a
973
- // deliberate act) and creation still needs the switch.
974
- else if (policy.useLibrary && wantsLibrary) {
975
- const folder = Object.entries(initial.libraries).find(([, l]) => l.scopeKey === scopeKey && l.archived !== true)
976
- if (folder) lib = { id: folder[0], ...folder[1] }
977
- else if (createLibrary) lib = ensureLibraryForCwd(cwd || '__default__')
978
- }
979
- const state = loadState()
980
- const existing = state.sessions[sessionId]
981
- const binding = {
982
- ...(existing || {}),
983
- useLibrary: requested ? true : wantsLibrary,
984
- useGlobal: wantsGlobal,
985
- scopeKey,
986
- domain: existing?.domain || detectDomain({ agentPreset, cwd }),
987
- // 未被问过的新会话不再硬编码 RP 兜底(issue #2 缺陷 2):领域跟随 detectDomain
988
- // 的文件夹/预设判定,与上方 domain 字段同一口径。弹窗或侧栏写下的显式答案会
989
- // 覆盖这里,并留下 domainSource:'chosen' 作为「已答」的凭据。
990
- domainOverride: existing?.domainOverride ?? detectDomain({ agentPreset, cwd }),
991
- domainSource: existing?.domainSource ?? 'auto',
992
- injectedIds: existing?.injectedIds || [],
993
- injectedAt: existing?.injectedAt || {},
994
- lastInjectedTurn: existing?.lastInjectedTurn ?? 0,
995
- reinjectPending: existing?.reinjectPending || false,
996
- activeCue: existing?.activeCue || null,
997
- libraryId: existing?.libraryId && state.libraries[existing.libraryId]
998
- ? existing.libraryId
999
- : (lib?.id || null),
1000
- }
1001
- state.sessions[sessionId] = binding
1002
- saveState(state)
1003
- return binding
1004
- }
1005
-
1006
- export function deleteSessionBinding(sessionId) {
1007
- return updateState((state) => {
1008
- delete state.sessions[sessionId]
1009
- return state
1010
- })
1011
- }
1012
-
1013
- // Only typed, host-admitted records prove content identity. Legacy bare ids do not.
1014
- export function recentMemoryRefs(binding, memoryClock, dedupeTurns) {
1015
- const window = Number(dedupeTurns)
1016
- const clock = Number(memoryClock)
1017
- if (!(window > 0) || !Number.isFinite(clock)) return []
1018
- const latest = new Map()
1019
- const revoked = new Set(binding?.revokedInjectionMessages || [])
1020
- for (const record of binding?.acceptedMemoryMessages || []) {
1021
- if (record.generation !== Number(binding.scopeGeneration || 0)
1022
- || record.epoch !== Number(binding.injectionEpoch || 0) || revoked.has(record.messageId)) continue
1023
- for (const ref of record.refs || []) {
1024
- const key = memoryRefKey(ref)
1025
- const previous = latest.get(key)
1026
- if (!previous || record.memoryClock >= previous.clock) latest.set(key, { ref, clock: record.memoryClock })
1027
- }
1028
- }
1029
- return [...latest.values()].filter(item => item.clock <= clock && clock - item.clock < window)
1030
- .map(item => ({ ...item.ref }))
1031
- }
1032
-
1033
- /** Commit one immutable message after its exact body entered host history. No entry bodies. */
1034
- export function markInjectedRefs(sessionId, refs, memoryClock, options = {}) {
1035
- if (!sessionId || typeof options.messageId !== 'string' || !Number.isFinite(Number(memoryClock))) return null
1036
- let committed = null
1037
- updateState(state => {
1038
- const binding = state.sessions[sessionId]
1039
- if (!binding) return state
1040
- const records = binding.acceptedMemoryMessages || []
1041
- if (records.some(record => record.messageId === options.messageId)) return state
1042
- const generation = Number(options.generation ?? binding.scopeGeneration ?? 0)
1043
- const epoch = Number(options.epoch ?? binding.injectionEpoch ?? 0)
1044
- if (generation !== Number(binding.scopeGeneration || 0) || epoch !== Number(binding.injectionEpoch || 0)) return state
1045
- const typed = (refs || []).filter(ref => ref && ['private', 'global'].includes(ref.scope)
1046
- && typeof ref.id === 'string' && typeof ref.revision === 'string'
1047
- && (ref.scope === 'global' || typeof ref.libraryId === 'string'))
1048
- .map(ref => ({ scope: ref.scope, libraryId: ref.libraryId ?? null, id: ref.id, revision: ref.revision,
1049
- ...(ref.groupKey !== undefined ? { groupKey: ref.groupKey } : {}),
1050
- ...(ref.groupRevision !== undefined ? { groupRevision: ref.groupRevision } : {}) }))
1051
- committed = { messageId: options.messageId, hostTurn: options.hostTurn ?? null, generation, epoch,
1052
- memoryClock: Number(memoryClock), refs: typed, admittedAt: stamp() }
1053
- const next = [...records, committed]
1054
- let count = next.reduce((sum, record) => sum + record.refs.length, 0)
1055
- while (next.length > 1 && (count > 400 || next.length > 400)) count -= next.shift().refs.length
1056
- if (count > 400) committed.refs = committed.refs.slice(-400)
1057
- binding.acceptedMemoryMessages = next
1058
- // Old anchor consumers retain their compatibility view, never a typed cooldown.
1059
- const ids = typed.map(ref => ref.id)
1060
- if ((binding.injectedIds || []).includes('__anchor__')) binding.anchorPushed = true
1061
- binding.injectedIds = [...new Set([...(binding.injectedIds || []).filter(id => id !== '__anchor__'), ...ids])].slice(-400)
1062
- binding.injectedAt = { ...(binding.injectedAt || {}) }
1063
- binding.injectionOwners = { ...(binding.injectionOwners || {}) }
1064
- binding.injectionOwnerClocks = { ...(binding.injectionOwnerClocks || {}) }
1065
- committed.effects = {}
1066
- const applyEffect = (key, value, field = key, id = null) => {
1067
- const owner = binding.injectionOwners[key]
1068
- const priorClock = typeof owner === 'string' && owner.startsWith('legacy:')
1069
- ? Math.max(Number(binding.lastInjectedTurn || 0), Number(binding.inbound?.clock || 0), Number(binding.injectionOwnerClocks[key] || 0))
1070
- : binding.injectionOwnerClocks[key] ?? records.find(record => record.messageId === owner)?.memoryClock ?? -1
1071
- if (Number(priorClock) > Number(memoryClock)) return
1072
- const previous = id === null ? binding[field] : binding[field]?.[id]
1073
- committed.effects[key] = { value: structuredClone(previous), owner: binding.injectionOwners[key] ?? null,
1074
- clock: binding.injectionOwnerClocks[key] ?? null, field, id }
1075
- if (id === null) binding[field] = structuredClone(value)
1076
- else binding[field] = { ...(binding[field] || {}), [id]: structuredClone(value) }
1077
- binding.injectionOwners[key] = options.messageId
1078
- binding.injectionOwnerClocks[key] = Number(memoryClock)
1079
- }
1080
- for (const id of ids) applyEffect(`id:${id}`, Number(memoryClock), 'injectedAt', id)
1081
- const actions = structuredClone(options.actions || {})
1082
- const patch = actions.patch || {}
1083
- if (actions.anchor) { patch.anchorPushed = true; patch.reinjectPending = false }
1084
- if (actions.cue) patch.activeCue = { id: String(actions.cue.id), text: String(actions.cue.text || '').slice(0, 500),
1085
- sourceId: actions.cue.sourceId ? String(actions.cue.sourceId) : null,
1086
- recallQuery: actions.cue.recallQuery ? String(actions.cue.recallQuery).slice(0, 200) : null, createdAt: stamp() }
1087
- if (actions.lexicon?.selected?.length) patch.lexiconInjectionClock = Number(memoryClock)
1088
- for (const [key, value] of Object.entries(patch)) applyEffect(key, value)
1089
- for (const [id, day] of Object.entries(actions.anniversaries || {})) applyEffect(`anniversary:${id}`, day, 'anniversariesShown', id)
1090
- for (const id of actions.nudgeIds || []) applyEffect(`nudge:${id}`, stamp(), 'openLoopRemindedAt', id)
1091
- binding.lastInjectedTurn = Math.max(Number(binding.lastInjectedTurn || 0), Number(memoryClock))
1092
- if (typed.length || actions.anchor) binding.lastInjectedAt = stamp()
1093
- return state
1094
- })
1095
- return committed ? structuredClone(committed) : null
1096
- }
1097
-
1098
- /**
1099
- * 待接纳提案的**落盘**副本(2026-11-23)。
1100
- *
1101
- * `injectionAdmissions` 是进程内 Map:宿主重启、或同一个 home 被另一个进程观察时,
1102
- * 提案会凭空消失,于是接纳永远不会发生——qq-dm 会话 333 个回合里
1103
- * `acceptedMemoryMessages` 一次都没出现过,就是这么来的(同库的 qq-group 正常)。
1104
- * 这里只存最小的提交凭据(按消息内容 digest 匹配),观察端换进程也能补完接纳。
1105
- * 只保留最近 8 条:同一消息重投会被 digest 覆盖,过期条目自然被挤掉。
1106
- */
1107
- const PENDING_INJECTION_MAX = 8
1108
- // 凭据只为「这一轮内的跨进程补认」服务:崩溃错过 turn/end 时它可能残留,
1109
- // 同内容重投(锚点文本高度重复)会认领到最旧那条、把 turn 归属记错。
1110
- // 读取时按 30 分钟 TTL 过滤并取最新匹配;写入时顺手清扫过期项。
1111
- const PENDING_INJECTION_TTL_MS = 30 * 60 * 1000
1112
-
1113
- function pendingInjectionFresh(item, now = Date.now()) {
1114
- const at = Date.parse(item?.at || '')
1115
- return Number.isFinite(at) && now - at < PENDING_INJECTION_TTL_MS
1116
- }
1117
-
1118
- export function rememberPendingInjection(sessionId, record = {}) {
1119
- if (!sessionId || !record.digest || !record.messageId) return null
1120
- return updateState((state) => {
1121
- const binding = state.sessions[sessionId]
1122
- if (!binding) return state
1123
- const kept = (binding.pendingInjections || []).filter(item => item?.messageId !== record.messageId && pendingInjectionFresh(item))
1124
- kept.push({
1125
- digest: String(record.digest), messageId: String(record.messageId),
1126
- turn: Number(record.turn) || 0, clock: Number(record.clock) || 0,
1127
- generation: Number(record.generation) || 0, epoch: Number(record.epoch) || 0,
1128
- refs: Array.isArray(record.refs) ? record.refs : [],
1129
- actions: record.actions && typeof record.actions === 'object' ? record.actions : {},
1130
- at: stamp(),
1131
- })
1132
- binding.pendingInjections = kept.slice(-PENDING_INJECTION_MAX)
1133
- return state
1134
- })
1135
- }
1136
-
1137
- export function findPendingInjection(sessionId, digest) {
1138
- if (!sessionId || !digest) return null
1139
- const rows = (getSessionBinding(sessionId)?.pendingInjections || [])
1140
- .filter(item => item?.digest === digest && pendingInjectionFresh(item))
1141
- return rows[rows.length - 1] || null
1142
- }
1143
-
1144
- export function forgetPendingInjection(sessionId, messageId) {
1145
- if (!sessionId || !messageId) return null
1146
- return updateState((state) => {
1147
- const binding = state.sessions[sessionId]
1148
- if (!binding?.pendingInjections) return state
1149
- const kept = binding.pendingInjections.filter(item => item?.messageId !== messageId)
1150
- if (kept.length) binding.pendingInjections = kept
1151
- else delete binding.pendingInjections
1152
- return state
1153
- })
1154
- }
1155
-
1156
- export function markInjected(sessionId, ids, turn) {
1157
- if (!sessionId) return
1158
- return updateState((state) => {
1159
- const binding = state.sessions[sessionId]
1160
- if (!binding) return state
1161
- // 锚点哨兵不进 injectedIds:它是一份常驻提示,不是会被 400 条上限挤掉的记忆 id。
1162
- // 单独记 anchorPushed,避免长会话里周期性把 ~800 token 的锚点当新消息重投。
1163
- const incoming = ids || []
1164
- // 旧 binding 可能把哨兵存在 injectedIds 里:迁移为 anchorPushed,之后只按标记判断。
1165
- const anchor = incoming.includes('__anchor__') || (binding.injectedIds || []).includes('__anchor__')
1166
- const merged = [...new Set([
1167
- ...(binding.injectedIds || []).filter((id) => id !== '__anchor__'),
1168
- ...incoming.filter((id) => id !== '__anchor__'),
1169
- ])]
1170
- binding.injectedIds = merged.slice(-400)
1171
- const owner = `legacy:${crypto.randomUUID()}`
1172
- binding.injectionOwners = { ...(binding.injectionOwners || {}) }
1173
- if (anchor) { binding.anchorPushed = true; binding.injectionOwners.anchorPushed = owner }
1174
- const at = { ...(binding.injectedAt || {}) }
1175
- for (const id of incoming) {
1176
- at[id] = turn ?? Date.now()
1177
- binding.injectionOwners[`id:${id}`] = owner
1178
- }
1179
- binding.injectedAt = at
1180
- binding.lastInjectedTurn = turn ?? binding.lastInjectedTurn ?? 0
1181
- // 主动记忆抑制要一个"最近一次真正注入了记忆"的墙钟时间;turn 号不能跨会话比较。
1182
- binding.lastInjectedAt = stamp()
1183
- return state
1184
- })
1185
- }
1186
-
1187
- /**
1188
- * Records why the last per-turn recall produced nothing usable. A degraded
1189
- * recall used to be swallowed by an empty catch, which made "memory is dead"
1190
- * indistinguishable from "nothing was relevant" (P0-1).
1191
- */
1192
- export function setRecallError(sessionId, message) {
1193
- if (!sessionId) return
1194
- const next = message ? String(message).slice(0, 500) : null
1195
- return updateState((state) => {
1196
- const binding = state.sessions[sessionId]
1197
- if (!binding) return state
1198
- if (next === null) {
1199
- // Only clear when something is there, so a healthy turn costs no write.
1200
- if (binding.lastRecallError) {
1201
- delete binding.lastRecallError
1202
- delete binding.lastRecallErrorAt
1203
- }
1204
- return state
1205
- }
1206
- if (binding.lastRecallError === next) return state
1207
- binding.lastRecallError = next
1208
- binding.lastRecallErrorAt = stamp()
1209
- return state
1210
- })
1211
- }
1212
-
1213
- export function releaseInjected(sessionId) { return updateState((state) => {
1214
- const binding = state.sessions[sessionId]
1215
- if (binding) {
1216
- binding.injectedIds = []
1217
- binding.injectedAt = {}
1218
- binding.injectionEpoch = Number(binding.injectionEpoch || 0) + 1
1219
- }
1220
- return state
1221
- })
1222
- }
1223
-
1224
- export function markReinjectPending(sessionId) {
1225
- const binding = getSessionBinding(sessionId)
1226
- return setSessionBinding(sessionId, { reinjectPending: true, injectionEpoch: Number(binding?.injectionEpoch || 0) + 1 })
1227
- }
1228
-
1229
- export function clearReinjectPending(sessionId) {
1230
- return setSessionBinding(sessionId, { reinjectPending: false })
1231
- }
1232
-
1233
- export function getActiveCue(sessionId) {
1234
- const binding = getSessionBinding(sessionId)
1235
- const cue = binding?.activeCue
1236
- if (!cue || typeof cue.id !== 'string') return null
1237
- const at = Date.parse(cue.createdAt || '') || 0
1238
- if (!at || Date.now() - at > 30 * 60 * 1000) return null
1239
- return cue
1240
- }
1241
-
1242
- export function armCue(sessionId, cue) {
1243
- return setSessionBinding(sessionId, {
1244
- activeCue: {
1245
- id: String(cue.id),
1246
- text: String(cue.text || '').slice(0, 500),
1247
- // A derived cue remembers the memory it came out of. Kept on the binding so the
1248
- // source is auditable while the cue is live, and so the anti-loop rule (a cue-born
1249
- // memory never sources another cue) can be checked against what actually happened.
1250
- sourceId: cue.sourceId ? String(cue.sourceId) : null,
1251
- recallQuery: cue.recallQuery ? String(cue.recallQuery).slice(0, 200) : null,
1252
- createdAt: stamp(),
1253
- },
1254
- })
1255
- }
1256
-
1257
- export function consumeCue(sessionId, cueId) {
1258
- const binding = getSessionBinding(sessionId)
1259
- if (!binding?.activeCue || binding.activeCue.id !== cueId) return false
1260
- setSessionBinding(sessionId, { activeCue: null })
1261
- return true
1262
- }
1263
-
1264
- // The session's running mood is a retrieval lens on the binding, not a fact about
1265
- // the user: it must never be recalled as a stored memory.
1266
- export function setSessionMood(sessionId, mood) {
1267
- // 给了 emotion 就以四轴为准,valence 只是投影;只有 valence 的旧形状原样存,不反推四轴。
1268
- const emotion = normalizeEmotion(mood?.emotion ?? null)
1269
- const bounded = (raw, min, max) => Math.max(min, Math.min(max, Number.isFinite(raw) ? raw : 0)) // 显式 0 是读数的一部分,不能用 `|| 默认值`
1270
- return setSessionBinding(sessionId, { mood: {
1271
- valence: emotion ? derivedValence(emotion) : bounded(mood?.valence, -1, 1),
1272
- emotion, arousal: bounded(mood?.arousal, 0, 1), dominance: bounded(mood?.dominance, -1, 1), at: Date.now(),
1273
- } })
1274
- }
1275
-
1276
- export function getSessionMood(sessionId) {
1277
- return getSessionBinding(sessionId)?.mood || null
1278
- }
1279
-
1280
- export function setLastSleepAt(sessionId, at) {
1281
- return setSessionBinding(sessionId, { lastSleepAt: at || stamp() })
1282
- }
1283
-
1284
- export function getLastSleepAt(sessionId) {
1285
- return getSessionBinding(sessionId)?.lastSleepAt || null
1286
- }
1287
-
1288
- export function listSessionBindings() {
1289
- const state = loadState()
1290
- return Object.entries(state.sessions || {}).map(([sessionId, binding]) => ({ sessionId, ...binding }))
1291
- }
1292
-
1293
- // The idle clock that sleep consolidation measures against: the last turn the
1294
- // plugin actually saw for this session.
1295
- export function touchSession(sessionId) {
1296
- return setSessionBinding(sessionId, { lastTurnAt: stamp() })
1297
- }
1298
-
1299
- export function getCycleState() {
1300
- return loadState().cycle || {}
1301
- }
1302
-
1303
- export function setCycleState(patch) {
1304
- return updateState((state) => {
1305
- state.cycle = { ...(state.cycle || {}), ...(patch || {}) }
1306
- return state
1307
- }).cycle
1308
- }
1309
-
1310
- // An anniversary fires once per calendar day per memory, otherwise every turn of
1311
- // the day would reopen the same feeling.
1312
- export function wasAnniversaryShown(sessionId, memoryId, dayKey) {
1313
- const shown = getSessionBinding(sessionId)?.anniversariesShown
1314
- return Boolean(shown && shown[memoryId] === dayKey)
1315
- }
1316
-
1317
- export function markAnniversaryShown(sessionId, memoryId, dayKey) {
1318
- const binding = getSessionBinding(sessionId)
1319
- const shown = { ...(binding?.anniversariesShown || {}) }
1320
- // Keep only the current day's keys so the map cannot grow without bound.
1321
- const fresh = Object.fromEntries(Object.entries(shown).filter(([, v]) => v === dayKey))
1322
- fresh[memoryId] = dayKey
1323
- return setSessionBinding(sessionId, { anniversariesShown: fresh,
1324
- injectionOwners: { ...(binding?.injectionOwners || {}), [`anniversary:${memoryId}`]: `legacy:${crypto.randomUUID()}` } })
1325
- }
1326
-
1327
- // ── repeated open loops ────────────────────────────────────────────────────────
1328
- // A dated promise that has already slipped its day keeps coming back on an interval
1329
- // instead of being forgotten. The regular 3-day nudge records its ids in
1330
- // `injectedIds`, which is right for "I already mentioned this once" and wrong for
1331
- // "it was never closed"; that is why the overdue leg keeps its own clock.
1332
- //
1333
- // `openLoopRemindedAt` maps memoryId -> ISO timestamp of the last time the overdue
1334
- // nudge actually reached the prompt. Entries older than 90 days are dropped on
1335
- // write so the map cannot grow without bound (an old key would not suppress
1336
- // anything anyway — the interval has long elapsed).
1337
- const OPEN_LOOP_REMIND_PRUNE_MS = 90 * 86_400_000
1338
-
1339
- function localDayKeyOf(date) {
1340
- return localCalendarDay(date)
1341
- }
1342
-
1343
- function prunedOpenLoopReminded(sessionId, now = new Date()) {
1344
- const nowDate = now instanceof Date ? now : new Date(now)
1345
- const nowMs = nowDate.getTime()
1346
- const map = getSessionBinding(sessionId)?.openLoopRemindedAt
1347
- const fresh = {}
1348
- if (!map || typeof map !== 'object') return fresh
1349
- for (const [memoryId, iso] of Object.entries(map)) {
1350
- const at = Date.parse(String(iso || ''))
1351
- if (!Number.isFinite(at)) continue
1352
- if (nowMs - at > OPEN_LOOP_REMIND_PRUNE_MS) continue
1353
- fresh[memoryId] = map[memoryId]
1354
- }
1355
- return fresh
1356
- }
1357
-
1358
- /**
1359
- * Whether an overdue open loop was already repeated on this local calendar day.
1360
- * A session binding written before this field existed has no map: it is a first
1361
- * reminder, not an error.
1362
- */
1363
- export function wasOpenLoopRemindedToday(sessionId, memoryId, now = new Date()) {
1364
- if (!sessionId || !memoryId) return false
1365
- const iso = getSessionBinding(sessionId)?.openLoopRemindedAt?.[memoryId]
1366
- const at = Date.parse(String(iso || ''))
1367
- if (!Number.isFinite(at)) return false
1368
- return localDayKeyOf(at) === localDayKeyOf(now)
1369
- }
1370
-
1371
- export function markOpenLoopReminded(sessionId, memoryId, at = new Date()) {
1372
- if (!sessionId || !memoryId) return null
1373
- // No binding means no conversation to remind; creating a stub from here would
1374
- // write half a session into state.json.
1375
- if (!getSessionBinding(sessionId)) return null
1376
- const when = at instanceof Date ? at : new Date(at)
1377
- const reminded = prunedOpenLoopReminded(sessionId, when)
1378
- reminded[memoryId] = when.toISOString()
1379
- return setSessionBinding(sessionId, { openLoopRemindedAt: reminded,
1380
- injectionOwners: { ...(getSessionBinding(sessionId)?.injectionOwners || {}), [`nudge:${memoryId}`]: `legacy:${crypto.randomUUID()}` } })
1381
- }
1382
-
1383
- /**
1384
- * 记下"这一回合投放了哪些一次性内容",供宿主把整轮回滚时撤销记账(§3.24)。
1385
- * 同一个 hostTurn 多次调用会把 ids 并起来:一步里可能同时投了锚点、纪念日与 nudge。
1386
- */
1387
- export function recordInjectionRollback(sessionId, { hostTurn, ids = [], guideKey = null, nudgeIds = [], anniversaryIds = [] } = {}) {
1388
- const turn = Number(hostTurn)
1389
- if (!sessionId || !Number.isSafeInteger(turn) || turn < 0) return null
1390
- if (!getSessionBinding(sessionId)) return null
1391
- return updateState((state) => {
1392
- const binding = state.sessions[sessionId]
1393
- if (!binding) return state
1394
- const previous = binding.injectionRollback
1395
- const same = previous && previous.hostTurn === turn ? previous : { ids: [], nudgeIds: [], anniversaryIds: [] }
1396
- binding.injectionRollback = {
1397
- hostTurn: turn,
1398
- epoch: Number(binding.injectionEpoch || 0),
1399
- generation: Number(binding.scopeGeneration || 0),
1400
- snapshot: { owners: { ...binding.injectionOwners }, injectedAt: { ...binding.injectedAt }, anchorPushed: binding.anchorPushed,
1401
- lastInjectedUserMessageId: binding.lastInjectedUserMessageId, guideMessageAt: binding.guideMessageAt,
1402
- anniversariesShown: { ...binding.anniversariesShown }, openLoopRemindedAt: { ...binding.openLoopRemindedAt } },
1403
- ids: [...new Set([...(same.ids || []), ...ids])].slice(-400),
1404
- nudgeIds: [...new Set([...(same.nudgeIds || []), ...nudgeIds])].slice(-40),
1405
- anniversaryIds: [...new Set([...(same.anniversaryIds || []), ...anniversaryIds])].slice(-40),
1406
- guideKey: guideKey || same.guideKey || null,
1407
- }
1408
- return state
1409
- }).sessions[sessionId].injectionRollback
1410
- }
1411
-
1412
- /**
1413
- * §3.24 —— 宿主会把「请求根本没发出去」的整轮回滚(连用户消息都不留在转录里,真机实测如此),
1414
- * 可插件在"消息交回决策"之后就记账了:于是 guide 与锚点这类一次性内容**再也不会投**,整段对话
1415
- * 直到下次压缩都没有记忆总览,且一声不吭。回合失败时把那一轮写下的记账撤回来。
1416
- * 只有与 `recordInjectionRollback` 记的同一个 hostTurn 对得上才生效;「该不该撤」由调用方按
1417
- * 转录实证判定(inject.js 的 injectionAdmissions),所以走到这里的内容确实没进转录,
1418
- * 下一轮重投不会出现第二份。返回撤回了什么,供活动日志留信号。
1419
- */
1420
- export function rollbackInjectionForTurn(sessionId, hostTurn, { messageIds = [], epoch = null } = {}) {
1421
- const turn = Number(hostTurn)
1422
- if (!sessionId || !Number.isSafeInteger(turn)) return null
1423
- let rolled = null
1424
- updateState((state) => {
1425
- const binding = state.sessions[sessionId]
1426
- if (!binding) return state
1427
- // Explicit host rollback evidence can revoke individual accepted messages. A model
1428
- // request failure alone must never call this branch. Preserve immutable records.
1429
- const targets = (binding.acceptedMemoryMessages || []).filter(record => record.hostTurn === turn
1430
- && messageIds.includes(record.messageId) && (epoch === null || record.epoch === epoch))
1431
- for (const accepted of targets.reverse()) {
1432
- binding.revokedInjectionMessages = [...new Set([...(binding.revokedInjectionMessages || []), accepted.messageId])].slice(-400)
1433
- if (accepted.epoch !== Number(binding.injectionEpoch || 0) || accepted.generation !== Number(binding.scopeGeneration || 0)) continue
1434
- for (const [key, saved] of Object.entries(accepted.effects || {})) {
1435
- if (binding.injectionOwners?.[key] !== accepted.messageId) continue
1436
- let previous = saved
1437
- const visited = new Set()
1438
- while (previous.owner && binding.revokedInjectionMessages.includes(previous.owner) && !visited.has(previous.owner)) {
1439
- visited.add(previous.owner)
1440
- const revoked = (binding.acceptedMemoryMessages || []).find(record => record.messageId === previous.owner)
1441
- previous = revoked?.effects?.[key] || { ...previous, value: undefined, owner: null, clock: null }
1442
- }
1443
- const field = previous.field || key
1444
- if (previous.id !== undefined && previous.id !== null) {
1445
- if (previous.value === undefined) delete binding[field]?.[previous.id]
1446
- else binding[field] = { ...(binding[field] || {}), [previous.id]: structuredClone(previous.value) }
1447
- if (field === 'injectedAt' && previous.value === undefined) binding.injectedIds = (binding.injectedIds || []).filter(id => id !== previous.id)
1448
- } else if (previous.value === undefined) delete binding[field]
1449
- else binding[field] = structuredClone(previous.value)
1450
- if (previous.owner) binding.injectionOwners[key] = previous.owner
1451
- else delete binding.injectionOwners[key]
1452
- if (previous.clock !== undefined && previous.clock !== null) binding.injectionOwnerClocks[key] = previous.clock
1453
- else delete binding.injectionOwnerClocks?.[key]
1454
- }
1455
- for (const ref of accepted.refs) {
1456
- if (accepted.effects?.[`id:${ref.id}`] || binding.injectionOwners?.[`id:${ref.id}`] !== accepted.messageId) continue
1457
- delete binding.injectedAt?.[ref.id]
1458
- binding.injectedIds = (binding.injectedIds || []).filter(id => id !== ref.id)
1459
- delete binding.injectionOwners[`id:${ref.id}`]
1460
- }
1461
- for (const key of Object.keys(binding.injectionOwners || {})) {
1462
- if (binding.injectionOwners[key] !== accepted.messageId) continue
1463
- if (key.startsWith('anniversary:')) delete binding.anniversariesShown?.[key.slice(12)]
1464
- if (key.startsWith('nudge:')) delete binding.openLoopRemindedAt?.[key.slice(6)]
1465
- delete binding.injectionOwners[key]
1466
- }
1467
- }
1468
- if (targets.length) rolled = { ids: targets.flatMap(record => record.refs.map(ref => ref.id)), guideKey: null, anniversaries: 0, nudges: 0 }
1469
- const record = binding.injectionRollback
1470
- if (!record || record.hostTurn !== turn) return state
1471
- const snapshot = record.snapshot || {}
1472
- const owners = binding.injectionOwners || {}
1473
- const sameEpoch = record.epoch === Number(binding.injectionEpoch || 0)
1474
- && Number(record.generation || 0) === Number(binding.scopeGeneration || 0)
1475
- const owns = key => owners[key] === snapshot.owners?.[key] && (!owners[key] || owners[key].startsWith('legacy:'))
1476
- const ids = new Set((record.ids || []).filter(id => sameEpoch && owns(`id:${id}`)
1477
- && binding.injectedAt?.[id] === snapshot.injectedAt?.[id]))
1478
- binding.injectedIds = (binding.injectedIds || []).filter(id => !ids.has(id))
1479
- if (binding.injectedAt) for (const id of ids) delete binding.injectedAt[id]
1480
- if (sameEpoch && ids.has('__anchor__') && owns('anchorPushed') && binding.anchorPushed === snapshot.anchorPushed) delete binding.anchorPushed
1481
- if (sameEpoch && snapshot.lastInjectedUserMessageId !== undefined && owns('lastInjectedUserMessageId')
1482
- && binding.lastInjectedUserMessageId === snapshot.lastInjectedUserMessageId) delete binding.lastInjectedUserMessageId
1483
- if (sameEpoch && owns('guideRulesKey') && record.guideKey && binding.guideRulesKey === record.guideKey
1484
- && binding.guideMessageAt === snapshot.guideMessageAt) {
1485
- delete binding.guideRulesKey
1486
- delete binding.guideMessageAt
1487
- }
1488
- if (sameEpoch && binding.anniversariesShown) for (const id of record.anniversaryIds || []) {
1489
- if (owns(`anniversary:${id}`) && binding.anniversariesShown[id] === snapshot.anniversariesShown?.[id]) delete binding.anniversariesShown[id]
1490
- }
1491
- if (sameEpoch && binding.openLoopRemindedAt) for (const id of record.nudgeIds || []) {
1492
- if (owns(`nudge:${id}`) && binding.openLoopRemindedAt[id] === snapshot.openLoopRemindedAt?.[id]) delete binding.openLoopRemindedAt[id]
1493
- }
1494
- rolled = {
1495
- ids: [...ids],
1496
- guideKey: record.guideKey || null,
1497
- anniversaries: (record.anniversaryIds || []).length,
1498
- nudges: (record.nudgeIds || []).length,
1499
- }
1500
- delete binding.injectionRollback
1501
- return state
1502
- })
1503
- return rolled
1504
- }
1505
-
1506
- /**
1507
- * 回合收尾、但那份记账不该作废时消费掉它(正常完成,或失败时注入的消息其实已经进了转录):
1508
- * 东西已经投出去了,之后再来一条迟到的 error 事件也不该把它撤回(否则就是凭空的第二次锚点/规则消息)。
1509
- */
1510
- export function consumeInjectionRollback(sessionId, hostTurn) {
1511
- const turn = Number(hostTurn)
1512
- if (!sessionId || !Number.isSafeInteger(turn)) return false
1513
- let consumed = false
1514
- updateState((state) => {
1515
- const binding = state.sessions[sessionId]
1516
- if (!binding?.injectionRollback || binding.injectionRollback.hostTurn !== turn) return state
1517
- delete binding.injectionRollback
1518
- consumed = true
1519
- return state
1520
- })
1521
- return consumed
1522
- }
1523
-
1524
- export function memoryDbPath(libraryId) {
1525
- ensureDir(librariesDir())
1526
- return effectiveVectorRoute() === 'managed-local' ? memuDbFor(libraryId) : path.join(librariesDir(), `${libraryId}.sqlite3`)
1527
- }
1528
-
1529
- export function globalDbPath() {
1530
- ensureDir(dataDir())
1531
- return effectiveVectorRoute() === 'managed-local' ? memuGlobalDbFor() : GLOBAL_DB()
1532
- }
1533
-
1534
- // Index files are parsed on every folder in the sidebar, and the parse (full
1535
- // memory text) is the expensive part. Validity is mtime+size, so an external
1536
- // change is always picked up. Callers mutate the returned object and save it
1537
- // straight away — that is the shape every writer already had.
1538
- const indexCache = new Map()
1539
- const indexBases = new WeakMap()
1540
-
1541
- // The sidebar paints a snapshot of both indexes, and nothing used to tell it when
1542
- // that snapshot had gone stale: a memory written by a tool call, or from the
1543
- // settings pane, stayed invisible until the tab was remounted. Readers poll this
1544
- // counter and refetch only when it moves, so the cheap path is a single number —
1545
- // no entry bodies, no disk read. In-process only; it resets on restart, and that
1546
- // is fine because readers compare it against the number they last painted.
1547
- let sidebarRevision = 0
1548
-
1549
- function bumpMemoryRevision() {
1550
- sidebarRevision += 1
1551
- return sidebarRevision
1552
- }
1553
-
1554
- /** Monotonic within this process; see bumpMemoryRevision. */
1555
- export function memoryRevision() {
1556
- return sidebarRevision
1557
- }
1558
-
1559
- // Task E observability. A heartbeat is a client poll; a write event is a save that
1560
- // actually reached disk. Both are in-process timestamps (they reset with the host),
1561
- // and `memu_status` prints them so "the pane is stale" can be told apart from
1562
- // "nothing was written" and from "the pane never polled".
1563
- let lastBeatAt = null
1564
- let lastWriteEvent = null
1565
-
1566
- export function noteMemoryBeat() {
1567
- lastBeatAt = Date.now()
1568
- }
1569
-
1570
- function noteMemoryWrite(kind, libraryId) {
1571
- lastWriteEvent = { kind, libraryId: libraryId || null, at: Date.now() }
1572
- }
1573
-
1574
- export function syncActivity() {
1575
- return { lastBeatAt, lastWrite: lastWriteEvent }
1576
- }
1577
-
1578
- // The counter above is per-process, and not every write happens in this process:
1579
- // a tool call served by another module instance, a curator job, or a second window
1580
- // can save an index while this counter stays put. That is exactly how the sidebar
1581
- // ended up needing a manual Refresh — the heartbeat compared a number only the
1582
- // writer's process could move. This fingerprint is the half both processes share:
1583
- // size and mtime of every file a memory write touches. A handful of statSync calls
1584
- // is cheaper than parsing one index, and it cannot go stale.
1585
- export function memoryStamp() {
1586
- const parts = []
1587
- const add = (file, label) => {
1588
- try {
1589
- const info = fs.statSync(file)
1590
- parts.push(label + ":" + info.size + ":" + Math.round(info.mtimeMs))
1591
- } catch {
1592
- parts.push(label + ":-")
1593
- }
1594
- }
1595
- add(STATE_FILE(), "state")
1596
- add(GLOBAL_INDEX(), "global")
1597
- let names = []
1598
- try { names = fs.readdirSync(indexDir()).filter((name) => name.endsWith(".json")).sort() } catch {}
1599
- for (const name of names) add(path.join(indexDir(), name), name)
1600
- return parts.join("|")
1601
- }
1602
-
1603
- function cachedIndex(file, loader, normalize) {
1604
- const cached = indexCache.get(file)
1605
- const stat = statOf(file)
1606
- if (cached && stat && cached.mtimeMs === stat.mtimeMs && cached.size === stat.size) return indexSnapshot(cached.index, normalize)
1607
- const index = loader()
1608
- // Never cache a fallback produced by a failed read: it would keep shadowing the
1609
- // real file (whose mtime/size did not change) even after the read recovers.
1610
- if (stat && !readFailure(file)) indexCache.set(file, { mtimeMs: stat.mtimeMs, size: stat.size, index })
1611
- return indexSnapshot(index, normalize)
1612
- }
1613
-
1614
- // `normalize` upgrades the *view* (a level an older version stored), while the baseline
1615
- // stays exactly what is on disk. That split is what lets an ordinary write persist the
1616
- // upgrade: `writeIndex` diffs against the baseline, sees the change, and checks the file
1617
- // still matches what we read before accepting it.
1618
- function indexSnapshot(index, normalize) {
1619
- const baseline = structuredClone(index)
1620
- const copy = structuredClone(index)
1621
- if (normalize) normalize(copy)
1622
- indexBases.set(copy, baseline)
1623
- return copy
1624
- }
1625
-
1626
- function rememberIndex(file, index) {
1627
- const stat = statOf(file)
1628
- if (stat) indexCache.set(file, { mtimeMs: stat.mtimeMs, size: stat.size, index: structuredClone(index) })
1629
- }
1630
-
1631
- const indexWriteListeners = new Set()
1632
- export function onPrivateIndexWrite(listener) {
1633
- indexWriteListeners.add(listener)
1634
- return () => indexWriteListeners.delete(listener)
1635
- }
1636
-
1637
- function writeIndex(file, index) {
1638
- return withFileLock(file, () => {
1639
- const base = indexBases.get(index)
1640
- let next = index
1641
- if (base) {
1642
- const fresh = readJson(file, { version: 1, entries: {} })
1643
- if (!validIndex(fresh)) {
1644
- assertJsonShape(file, fresh, validIndex)
1645
- throw new Error('memory index changed to an invalid shape; restore it before writing')
1646
- }
1647
- next = { ...fresh, entries: { ...(fresh.entries || {}) } }
1648
- const before = base.entries || {}
1649
- for (const id of new Set([...Object.keys(before), ...Object.keys(index.entries || {})])) {
1650
- const value = index.entries?.[id]
1651
- if (JSON.stringify(before[id]) === JSON.stringify(value)) continue
1652
- if (JSON.stringify(before[id]) !== JSON.stringify(next.entries[id])) {
1653
- const error = new Error(`memory ${id} changed concurrently; reload and retry`)
1654
- error.code = 'DSH_MEMU_CONCURRENT_MODIFICATION'
1655
- throw error
1656
- }
1657
- if (value === undefined) delete next.entries[id]
1658
- else next.entries[id] = structuredClone(value)
1659
- }
1660
- }
1661
- writeJson(file, next)
1662
- rememberIndex(file, next)
1663
- return next
1664
- })
1665
- }
1666
-
1667
- export function loadPrivateIndex(libraryId) {
1668
- if (!isSafeId(libraryId)) throw new Error('invalid library id')
1669
- const file = path.join(indexDir(), `${libraryId}.json`)
1670
- return cachedIndex(file, () => {
1671
- let raw = readJson(file, null)
1672
- if (raw !== null) raw = assertJsonShape(file, raw, validIndex)
1673
- return raw && typeof raw === 'object' ? { version: 1, entries: raw.entries || {} } : { version: 1, entries: {} }
1674
- }, (index) => {
1675
- // An older version stored `visibility: 'session'` (a lease on one conversation).
1676
- // That level is gone; libraries written by it are read as `shared` here — the one
1677
- // chokepoint every reader and writer passes through — so no consumer has to know
1678
- // the level ever existed. Only the view is upgraded; the baseline stays the raw file
1679
- // so the next ordinary write persists the conversion (see `indexSnapshot`).
1680
- migrateIndexVisibility(index, stamp())
1681
- })
1682
- }
1683
-
1684
- /**
1685
- * Persist one library index.
1686
- *
1687
- * `bumpRevision: false` exists for writes that cannot change what recall would find:
1688
- * the injector's own bookkeeping (injectCount / lastInjectAt) runs *after* every
1689
- * successful injection, so bumping the revision there guaranteed that the next turn's
1690
- * recall and BM25 corpus both missed. The write still happens, still notifies
1691
- * listeners and still records the write event — only the "something a cached result
1692
- * depends on changed" claim is withheld, because it is not true.
1693
- */
1694
- export function savePrivateIndex(libraryId, index, { bumpRevision = true } = {}) {
1695
- if (!isSafeId(libraryId)) throw new Error('invalid library id')
1696
- if (!validIndex(index)) throw new Error('invalid memory index shape')
1697
- const file = path.join(indexDir(), `${libraryId}.json`)
1698
- const saved = writeIndex(file, index)
1699
- if (bumpRevision) bumpMemoryRevision()
1700
- noteMemoryWrite('private', libraryId)
1701
- for (const listener of indexWriteListeners) {
1702
- try { listener(libraryId, saved) } catch (error) { warn(`memory sidecar update failed: ${error?.message || error}`) }
1703
- }
1704
- }
1705
-
1706
- export function loadGlobalIndex() {
1707
- return cachedIndex(GLOBAL_INDEX(), () => {
1708
- let raw = readJson(GLOBAL_INDEX(), null)
1709
- if (raw !== null) raw = assertJsonShape(GLOBAL_INDEX(), raw, validIndex)
1710
- return raw && typeof raw === 'object' ? { version: 1, entries: raw.entries || {} } : { version: 1, entries: {} }
1711
- })
1712
- }
1713
-
1714
- function validIndex(value) {
1715
- return value && typeof value === 'object' && !Array.isArray(value) && value.entries && typeof value.entries === 'object' && !Array.isArray(value.entries)
1716
- && Object.values(value.entries).every(entry => entry && typeof entry === 'object' && !Array.isArray(entry))
1717
- }
1718
-
1719
- export function saveGlobalIndex(index, { bumpRevision = true } = {}) {
1720
- if (!validIndex(index)) throw new Error('invalid memory index shape')
1721
- writeIndex(GLOBAL_INDEX(), index)
1722
- if (bumpRevision) bumpMemoryRevision()
1723
- noteMemoryWrite('global', null)
1724
- }
1725
-
1726
- /** Counts only — no titles, no text. Cheap enough to call per folder. */
1727
- export function summarizeIndex(index) {
1728
- const entries = Object.values(index?.entries || {})
1729
- const live = entries.filter((e) => e && !['archived', 'suppressed', 'expired', 'pending_review', 'superseded'].includes(e.status)
1730
- && (!e.expiresAt || Date.parse(e.expiresAt) > Date.now()))
1731
- return {
1732
- total: entries.length,
1733
- active: live.length,
1734
- pinned: live.filter((e) => e.layer === 'must_remember').length,
1735
- marginalized: entries.filter((e) => e.marginalized === true).length,
1736
- openLoop: live.filter((e) => e.openLoop === true).length,
1737
- archived: entries.filter((e) => e.status === 'archived').length,
1738
- }
1739
- }
1740
-
1741
- /**
1742
- * Read-modify-write of one library index. The mutator is synchronous, so two
1743
- * calls can never interleave. Callers that await a backend write (MemU commit,
1744
- * a consolidation job) must reach for this *after* the await — reading before it
1745
- * and saving after is the lost-update window this exists to close (P0-4).
1746
- */
1747
- export function updatePrivateIndex(libraryId, mutator) {
1748
- if (!isSafeId(libraryId)) throw new Error('invalid library id')
1749
- return withFileLock(path.join(indexDir(), `${libraryId}.json`), () => {
1750
- indexCache.delete(path.join(indexDir(), `${libraryId}.json`))
1751
- const index = loadPrivateIndex(libraryId)
1752
- const next = mutator(index) || index
1753
- if (next?.then) throw new Error('index mutators must be synchronous')
1754
- savePrivateIndex(libraryId, next)
1755
- return next
1756
- })
1757
- }
1758
-
1759
- export function updateGlobalIndex(mutator) {
1760
- return withFileLock(GLOBAL_INDEX(), () => {
1761
- indexCache.delete(GLOBAL_INDEX())
1762
- const index = loadGlobalIndex()
1763
- const next = mutator(index) || index
1764
- if (next?.then) throw new Error('index mutators must be synchronous')
1765
- saveGlobalIndex(next)
1766
- return next
1767
- })
1768
- }
1769
-
1770
- export function newMemoryId(prefix = 'mem') {
1771
- return `${prefix}-${Date.now().toString(36)}-${crypto.randomBytes(3).toString('hex')}`
1772
- }
1773
-
1774
- /**
1775
- * Creates a managed backup of the local memory stores (plugin state, indexes,
1776
- * prompts, attachments, the vector journal and every MemU database), then keeps
1777
- * the newest BACKUP_KEEP complete ones. Retention, staging, checksums, atomic
1778
- * publish and the shared lock all live in lib/backup.js so there is exactly one
1779
- * place that decides what a backup is and which backup may be deleted.
1780
- *
1781
- * Returns the published directory: callers (engine switch, library delete,
1782
- * scripts) treat the return value as a path.
1783
- */
1784
- export async function backupDatabases(options = {}) {
1785
- // Pending bookkeeping changes live in memory for up to 50ms; a backup taken
1786
- // before a flush would silently capture the previous state.
1787
- let report
1788
- try {
1789
- report = await createBackup({ ...options, flushState })
1790
- } catch (error) {
1791
- // A refusal is the safety property working, not something to swallow: a
1792
- // database the engine could not snapshot aborts the backup, and the reason
1793
- // has to stay visible on the same channel the panel already reads.
1794
- lastBackupReport = {
1795
- at: stamp(),
1796
- action: 'create',
1797
- status: 'failed',
1798
- code: error?.code || null,
1799
- error: String(error?.message || error),
1800
- name: null,
1801
- dir: null,
1802
- files: 0,
1803
- bytes: 0,
1804
- snapshots: [],
1805
- pruned: [],
1806
- pruneFailed: [],
1807
- pendingCleanup: 0,
1808
- notice: null,
1809
- }
1810
- throw error
1811
- }
1812
- lastBackupReport = { at: stamp(), action: 'create', ...report }
1813
- return report.dir
1814
- }
1815
-
1816
- /** What the last backup/restore/prune did, so the outcome stays observable. */
1817
- export function lastBackupReportView() {
1818
- return lastBackupReport ? { ...lastBackupReport } : null
1819
- }
1820
-
1821
- /** Newest first, including entries that failed to complete (reported, never deleted). */
1822
- export function listBackups() {
1823
- return listBackupEntries()
1824
- }
1825
-
1826
- /** Removes one backup directory. The name is validated, never used as a path. */
1827
- export function deleteBackup(name) {
1828
- const result = deleteBackupEntry(name)
1829
- lastBackupReport = { at: stamp(), action: 'delete', ...result }
1830
- return { deleted: result.deleted, status: result.status }
1831
- }
1832
-
1833
- /**
1834
- * Puts a backup back. The target is leased and its whole inventory is verified
1835
- * before anything is written; the live root is saved as a safety backup next;
1836
- * only then are files replaced. Failure leaves a recovery path: the safety
1837
- * backup holds the state that was replaced and retention may not delete it.
1838
- * A backup that predates the vector journal also retires the stale live
1839
- * vector-active pointer, so recall falls back to text instead of querying
1840
- * databases that no longer match the restored index.
1841
- */
1842
- export async function restoreBackup(name, { beforeRestore = null, keep = undefined } = {}) {
1843
- const result = await restoreFromBackup(name, { beforeRestore, flushState, clearCaches, keep })
1844
- lastBackupReport = { at: stamp(), action: 'restore', ...result }
1845
- return result
1846
- }
1847
-
1848
- /** Drops the in-memory mirrors so the next read comes from disk. */
1849
- export function clearCaches() {
1850
- cache = null
1851
- dirty = false
1852
- if (flushTimer) { clearTimeout(flushTimer); flushTimer = null }
1853
- indexCache.clear()
1854
- // A restore or an external edit replaced the files under us; the sidebar must
1855
- // not keep painting what it read before.
1856
- bumpMemoryRevision()
1857
- noteMemoryWrite('restore', null)
1858
- }
1859
-
1860
- /**
1861
- * P2-5: explicit session-binding GC. Idle time is not an automatic deletion
1862
- * trigger (docs/binding-lifecycle.md); this is a dry-run-first maintenance call.
1863
- * A binding with no parseable lastTurnAt is never a candidate.
1864
- */
1865
- /**
1866
- * Session-binding garbage collection.
1867
- *
1868
- * This deletes bindings, which is not recoverable. Three guards, because the old
1869
- * version had none and a `--days 0` invocation wiped every binding in the store:
1870
- *
1871
- * · `olderThanDays` must be strictly positive. Zero/negative is a mistake, not a
1872
- * "clean everything" request, so it throws instead of quietly becoming one.
1873
- * · `isBusy(sessionId)` lets the caller veto a candidate: a session with a live
1874
- * consolidation lease is in the middle of writing, and lastTurnAt is not the only
1875
- * clock that matters.
1876
- * · the apply pass re-reads each candidate inside `updateState`. A dry-run and an
1877
- * apply are two separate loads, and a conversation that woke up in between must
1878
- * not be deleted on the strength of the earlier snapshot.
1879
- */
1880
- export function pruneSessionBindings({ olderThanDays = 30, dryRun = true, now = Date.now(), isBusy = null } = {}) {
1881
- const days = Number(olderThanDays)
1882
- if (!Number.isFinite(days) || days <= 0) throw new Error('olderThanDays must be a positive number of days')
1883
- const cutoff = Number(now) - days * 86_400_000
1884
- const state = loadState()
1885
- const candidates = []
1886
- const skipped = []
1887
- for (const [sessionId, binding] of Object.entries(state.sessions || {})) {
1888
- const at = Date.parse(String(binding?.lastTurnAt || ''))
1889
- if (!Number.isFinite(at) || at >= cutoff) continue
1890
- if (typeof isBusy === 'function') {
1891
- let busy = false
1892
- try { busy = isBusy(sessionId) === true } catch (error) {
1893
- // An unreadable lease file is not permission to delete: treat it as busy.
1894
- busy = true
1895
- warn(`prune-session-bindings: liveness check failed for ${sessionId} (${error?.message || error}); kept`)
1896
- }
1897
- if (busy) {
1898
- skipped.push({ sessionId, reason: 'a consolidation lease is still live' })
1899
- continue
1900
- }
1901
- }
1902
- candidates.push({ sessionId, lastTurnAt: binding.lastTurnAt, libraryId: binding.libraryId || null })
1903
- }
1904
- const base = {
1905
- dryRun: dryRun !== false,
1906
- olderThanDays: days,
1907
- cutoff: new Date(cutoff).toISOString(),
1908
- candidates,
1909
- skipped,
1910
- }
1911
- if (dryRun !== false || candidates.length === 0) return { ...base, removed: [] }
1912
- const removed = []
1913
- const revalidated = []
1914
- updateState((next) => {
1915
- for (const item of candidates) {
1916
- const current = next.sessions?.[item.sessionId]
1917
- if (!current) continue
1918
- const at = Date.parse(String(current.lastTurnAt || ''))
1919
- // Same predicate as the candidate pass, on the fresh copy: `at < cutoff` alone
1920
- // would still delete a binding that just came back with a stale lastTurnAt.
1921
- if (!Number.isFinite(at) || at >= cutoff) { revalidated.push(item.sessionId); continue }
1922
- delete next.sessions[item.sessionId]
1923
- removed.push(item.sessionId)
1924
- }
1925
- return next
1926
- })
1927
- return { ...base, removed, revalidated }
1928
- }
1
+ import fs from 'node:fs'
2
+ import path from 'node:path'
3
+ import crypto from 'node:crypto'
4
+ import {
5
+ dataDir, librariesDir, indexDir, backupsDir, memoryRefKey,
6
+ ensureDir, readJson, readFailure, readFailuresUnder, writeJson, withFileLock, assertJsonShape, warn, stamp, shortHash, libraryIdForScope, isSafeId,
7
+ } from './paths.js'
8
+ import {
9
+ createBackup, deleteBackupEntry, listBackupEntries, restoreFromBackup,
10
+ } from './backup.js'
11
+ import { migrateIndexVisibility } from './visibility.js'
12
+ import { memuDbFor, memuGlobalDbFor, removeActiveLibrary } from './vector-profile.js'
13
+ import { normalizeEmotion, derivedValence } from './mood.js'
14
+ import { localCalendarDay } from './temporal.js'
15
+ import { normalizeMemoryContext } from './context.js'
16
+
17
+ const STATE_FILE = () => path.join(dataDir(), 'state.json')
18
+ const GLOBAL_DB = () => path.join(dataDir(), 'global.sqlite3')
19
+ const GLOBAL_INDEX = () => path.join(indexDir(), 'global.json')
20
+
21
+ // Observable outcome of the last backup action; see listBackupEntries().
22
+ let lastBackupReport = null
23
+
24
+ export const DEFAULT_SETTINGS = {
25
+ sidebarSettings: false,
26
+ visionCaptionEnabled: true,
27
+ // Only these named tools may carry the explicit inbound protocol in model text.
28
+ // Producer-owned tool meta is the preferred integration and needs no allowlist.
29
+ inboundToolNames: [],
30
+ autoInject: 'smart',
31
+ // 自动关联(DESIGN §6.4):'suggest' 只出候选、不写任何边(迁移期默认),
32
+ // 'deterministic' 只写由已确认实体或字段证据推出的确定性边,'off' 完全关闭。
33
+ // allowWorkerAssertion 是 v3 的预留开关(worker 确认实体),本版不读取。
34
+ autoLinkMode: 'suggest',
35
+ allowWorkerAssertion: false,
36
+ // These defaults are tuned for high-density chat — a QQ-style group where many
37
+ // short messages arrive per minute, in fragments rather than sentences, and the
38
+ // topic drifts every few of them. Under that cadence the failure mode is not
39
+ // "too little memory", it is noise: a per-turn block sized for paragraph-long
40
+ // prompts drowns the conversation it was meant to help. So the per-turn budgets
41
+ // are small, and the windows that stop repetition are measured in many turns.
42
+ privateTopK: 5,
43
+ globalTopK: 5,
44
+ // Cross-library recall: merge private candidates from other libraries that use
45
+ // the same memory domain. Reading across folders changes the isolation boundary,
46
+ // so it is opt-in; writes still target the bound library only.
47
+ crossLibraryRecall: false,
48
+ anchorTokens: 800,
49
+ // 800 tokens for one recall block. A dense chat calls recall on almost every
50
+ // message, so the injected block has to stay clearly smaller than the message it
51
+ // serves. This is the recall budget, not the whole plugin-message ceiling.
52
+ turnTokens: 800,
53
+ // Whole plugin-message ceiling: anchor + recall + optional cue/texture. It must
54
+ // be at least the sum of the sub-budgets the user wants to allow; the default leaves
55
+ // room for the default anchor and recall blocks.
56
+ injectionTotalTokens: 2000,
57
+ relevanceThreshold: 0.4,
58
+ // 16 turns is a couple of minutes of group traffic. The old 8 expired inside a
59
+ // single burst, so the same entry came back every minute or two.
60
+ dedupeTurns: 16,
61
+ // Every 6 turns instead of 3: the global layer is cross-conversation and drags
62
+ // foreign context in, and three turns of dense chat is nothing at all.
63
+ globalEveryNTurns: 6,
64
+ // 6 characters is about one short CJK clause. 12 skipped most of what a group
65
+ // chat actually says — recall was off in exactly the conversations that wanted
66
+ // it. "嗯" / "好" / "收到" (2-3 chars) still skip.
67
+ minUserChars: 6,
68
+ // When recall includes potentially stale memories, append a <memory-freshness> hint
69
+ // asking models with search tools to verify them, or to say when they cannot. Enabled
70
+ // by default; freshnessDays is the sole age threshold.
71
+ freshnessHint: true,
72
+ freshnessDays: 30,
73
+ // Keep the always-on layer tight: dense chat generates many small candidates,
74
+ // and 16 pins would eat the anchor budget before the anchor starts.
75
+ mustRememberCap: 12,
76
+ // Short-term layer: a memory that only has to survive the arc of one
77
+ // conversation. It expires rather than being deleted, so the idle
78
+ // consolidation pass still gets to promote it to long_term before it goes. 72h
79
+ // spans "we talked about this over the weekend"; 0 disables the layer, and a
80
+ // write with layer=short_term is then refused instead of silently becoming
81
+ // permanent.
82
+ shortTermTtlHours: 72,
83
+ // Prompt pages beyond 通用. Each one owns a set of `<key>.<domain>.md` overrides
84
+ // and can be assigned to a conversation, so the list is data, not code.
85
+ // All shipped pages stay enabled; a new conversation starts on RP via the
86
+ // binding's domainOverride. Every enabled domain is also offered by the session
87
+ // picker, so these two lists cannot drift apart.
88
+ promptDomains: ['rp', 'coding', 'mixed'],
89
+ // Unpin is the model's own call (see memory.js privateUnpin). These two are the
90
+ // guardrails that replaced the human marker: a per-conversation quota and a
91
+ // cooldown, both small on purpose.
92
+ unpinBudgetPerSession: 2,
93
+ unpinCooldownMinutes: 3,
94
+ // Rolled once per user turn: at dense cadence 5% means a cue every ~20 turns,
95
+ // which reads as constant interruption. 2% keeps it rare.
96
+ randomCueChance: 0.02,
97
+ newSessionPromptDismissed: false,
98
+ // What "remember my choice" stores: off | auto | both.
99
+ newSessionDefault: 'both',
100
+ curatorModel: null,
101
+ autoInstallEngine: true,
102
+ pipIndexes: [],
103
+ // Fresh installs start with the plugin fully alive: auto-install, the
104
+ // new-session prompt, domestic texture, and idle consolidation are all on.
105
+ // These stay ordinary switches, and an existing saved choice is preserved.
106
+ sleepConsolidation: true,
107
+ // Group chat arrives in bursts, but a burst is seconds apart and the per-turn
108
+ // timestamps already cover that. Two idle minutes still separates "reading a
109
+ // diff / thinking" from "gone", and keeps the per-run window small.
110
+ sleepAfterIdleMinutes: 2,
111
+ // 主动记忆:分数门槛、饥饿阈值(空闲超过它无条件检查)、两种抑制冷却(分钟;整理冷却默认 0,
112
+ // 薄证据的重复 fork 由评分拦截,只有用户显式配置才启用硬冷却)。
113
+ activeMemoryMinScore: 0.8,
114
+ activeMemoryStarvationMinutes: 15,
115
+ activeMemoryCooldownMinutes: 0,
116
+ activeMemoryRecallCooldownMinutes: 15,
117
+ // 全局提炼的审核放行(§4.10):'auto' 只暂扣冲突、缺证据与高风险改写;
118
+ // 'review-all' 把全部内容操作送进复核。硬门在两档下都生效。
119
+ curatorReviewMode: 'auto',
120
+ autoCurateEveryHours: 0,
121
+ autoCurateSessionLimit: 8,
122
+ // 'local' keeps every memory on this machine; 'cloud' hands MemU's own backend
123
+ // the storage, which is the vendor path and off by default.
124
+ memoryMode: 'local',
125
+ // Who turns a conversation into memory. 'agent' means the conversation's own
126
+ // agent writes and summarizes into the JSON index, with no MemU engine and no
127
+ // embedding API. 'api' hands the work to the configured remote MemU service.
128
+ memoryBackend: 'agent',
129
+ vectorSource: 'local',
130
+ habitsInjection: true,
131
+ // 一次性的带日期承诺过期之后的复提间隔(天)。带日期 + open_loop 的过期条目不走
132
+ // 3 天年龄门槛,也不会因为“提过一次”永久沉默;它按这个间隔重复,直到被关闭或归档。
133
+ // 它和普通 3 天腿共用每回合 limit 1,dated 过期腿优先。
134
+ openLoopRemindDays: 7,
135
+ // Scheduled anniversary wake-ups start a host turn in the bound session, so they are
136
+ // disabled by default and require explicit user opt-in. salientWakeHour is local
137
+ // wall-clock time (HH:mm); an empty salientWakeTimeZone follows the system, while a
138
+ // non-empty value must be a valid IANA time zone.
139
+ salientWake: 'off',
140
+ salientWakeHour: '09:00',
141
+ salientWakeTimeZone: '',
142
+ // 整理 fork 的模型选择(三模式)。'inherit' 沿用父会话的 provider/model;'host' 用
143
+ // consolidationModel("<provider>/<model>",同 curatorModel 的解析口径)指名宿主已
144
+ // 激活的 route;'custom' 用 consolidationCustom* 在宿主 llm 注册表挂本插件私有 route
145
+ // (lib/fork-model.js CONSOLIDATION_CUSTOM_ROUTE)。fork 的 AgentOptions 没有
146
+ // baseURL/apiKey 通道,自定义端点只能走注册 route,所以 custom 的连接四件套存在这里。
147
+ // apiKey 落盘在 state.json(与 ~/.memu/config.env 的 0600 同一信任域),但任何 RPC
148
+ // 回包只给 has/tail 打码视图——rpc.js 的 redactConsolidationSettings。
149
+ consolidationModelMode: 'inherit',
150
+ consolidationModel: null,
151
+ // 1.3.1:整理 fork 的思考强度独立于父会话。'inherit' 保持旧行为;'off' /
152
+ // 'medium' / 'low' / 'high' 直接覆盖,用于成本/质量的 A/B。
153
+ consolidationReasoningEffort: 'medium',
154
+ consolidationCustomBaseURL: '',
155
+ consolidationCustomApiKey: '',
156
+ consolidationCustomModel: '',
157
+ consolidationCustomApi: 'openai-completions',
158
+ // Incremental turn log. 'on' (default) persists each turn and provides cached context
159
+ // for the persistent consolidation worker; it is not the completion ledger. When 'off',
160
+ // input falls back to condenseEvents.
161
+ consolidationTurnLog: 'on',
162
+ // Consolidation executor: 'fork' (default) starts a fresh fork per window; 'worker'
163
+ // reuses a persistent worker across windows. Switching back to 'fork' requires no data
164
+ // migration; the turn log is a cache and the ledger remains authoritative.
165
+ consolidationRunner: 'fork',
166
+ // Worker tool-log detail: 'none' stores no tool rows, 'errors' stores error results,
167
+ // and 'summary' stores one summary row.
168
+ consolidationTurnLogTools: 'none',
169
+ // A positive age marks cleanup candidates; deletion always needs a user action.
170
+ purgeArchivedAfterDays: 0,
171
+ // 升级后的一次性实体碎片自愈(lib/index.js startEntityRepairPass)。默认开,但它**只**合并
172
+ // 可证明的那一类(窗口片段重建出正文里出现过的完整名);"只是相似"的候选永远等人工确认。
173
+ // 关掉它 = 连可证明的也不动,全部留在诊断页的手动按钮上。写入前一律先备份。
174
+ autoRepairEntityFragments: true,
175
+ // 回合中途补充召回(inject.js midTurnPolicy):默认开。这些键必须注册在这里——
176
+ // updateSettings 对 DEFAULT_SETTINGS 之外的键静默丢弃,文档里「midTurnRecall: false
177
+ // 可关」的承诺只有落了默认值与白名单才成立。阈值口径见 docs/memory-semantics.md §8.4。
178
+ midTurnRecall: true,
179
+ midTurnMinSteps: 4,
180
+ midTurnMinUnits: 3,
181
+ midTurnMinChars: 6000,
182
+ midTurnMaxPerTurn: 2,
183
+ midTurnCooldownMs: 60000,
184
+ midTurnTokens: 400,
185
+ midTurnFullUnits: 6,
186
+ midTurnFullChars: 15000,
187
+ }
188
+
189
+ function defaultState() {
190
+ return {
191
+ version: 1,
192
+ settings: { ...DEFAULT_SETTINGS },
193
+ libraries: {},
194
+ sessions: {},
195
+ // Per-folder memory switches. Keyed by the normalized scope key (the same key
196
+ // a library uses), so a folder keeps its choice even before it has a library.
197
+ workspacePolicies: {},
198
+ }
199
+ }
200
+
201
+ function mergeState(raw) {
202
+ const base = defaultState()
203
+ if (!raw || typeof raw !== 'object') return base
204
+ const rawSettings = raw.settings && typeof raw.settings === 'object' ? raw.settings : {}
205
+ const legacyVectorSource = rawSettings.vectorSource === 'api' || rawSettings.vectorSource === 'local'
206
+ ? rawSettings.vectorSource
207
+ : (rawSettings.memoryMode === 'cloud' ? 'api' : 'local')
208
+ return {
209
+ ...base,
210
+ ...raw,
211
+ settings: { ...base.settings, ...rawSettings, vectorSource: legacyVectorSource },
212
+ libraries: raw.libraries && typeof raw.libraries === 'object' ? raw.libraries : {},
213
+ sessions: raw.sessions && typeof raw.sessions === 'object' ? raw.sessions : {},
214
+ workspacePolicies: raw.workspacePolicies && typeof raw.workspacePolicies === 'object' ? raw.workspacePolicies : {},
215
+ }
216
+ }
217
+
218
+ // Bookkeeping writes are coalesced to avoid repeated full state.json rewrites. Memory
219
+ // indexes deliberately bypass this cache: losing an index entry is not equivalent to
220
+ // losing injection bookkeeping. Validate the cache against mtime and size so an external
221
+ // writer, such as a backup or another profile, is never silently shadowed.
222
+ const FLUSH_MS = 50
223
+ let cache = null
224
+ let dirty = false
225
+ let flushTimer = null
226
+
227
+ function statOf(file) {
228
+ try { return fs.statSync(file) } catch { return null }
229
+ }
230
+
231
+ function adoptCache(state, fromReadFailure = false, base = null) {
232
+ const stat = statOf(STATE_FILE())
233
+ cache = {
234
+ dir: dataDir(),
235
+ state,
236
+ base: structuredClone(base || state),
237
+ // True when this cache content is a *fallback* built from defaults because
238
+ // the file could not be read — not the on-disk truth. A fallback must never
239
+ // be written back: that would replace real bindings/libraries with defaults.
240
+ fromReadFailure,
241
+ mtimeMs: stat ? stat.mtimeMs : 0,
242
+ size: stat ? stat.size : -1,
243
+ }
244
+ return state
245
+ }
246
+
247
+ export function loadState() {
248
+ const dir = dataDir()
249
+ if (cache && cache.dir === dir) {
250
+ if (dirty) return cache.state
251
+ const stat = statOf(STATE_FILE())
252
+ if (!stat) {
253
+ // Gone from disk while we hold a good copy: keep it and put it back.
254
+ dirty = true
255
+ scheduleFlush()
256
+ return cache.state
257
+ }
258
+ // A fallback cache never satisfies the mtime check: it is not the on-disk
259
+ // truth, so keep re-reading until the file reads cleanly again.
260
+ if (!cache.fromReadFailure && stat.mtimeMs === cache.mtimeMs && stat.size === cache.size) return cache.state
261
+ }
262
+ dirty = false
263
+ let raw = readJson(STATE_FILE(), null)
264
+ if (raw !== null) raw = assertJsonShape(STATE_FILE(), raw, value => value && typeof value === 'object' && !Array.isArray(value)
265
+ && ['libraries', 'sessions', 'settings', 'workspacePolicies'].every(key => value[key] === undefined || value[key] && typeof value[key] === 'object' && !Array.isArray(value[key])))
266
+ // Distinguish "no file yet" (writing defaults is harmless) from "read failed"
267
+ // (writing defaults would destroy the real state still on disk).
268
+ const failed = readFailure(STATE_FILE()) !== null
269
+ return adoptCache(mergeState(raw), failed)
270
+ }
271
+
272
+ export function saveState(state) {
273
+ // Carry the fallback marker over: saving new content does not make a
274
+ // previously-failed read trustworthy.
275
+ const previous = cache?.dir === dataDir() ? cache : null
276
+ adoptCache(state, previous?.fromReadFailure === true, previous?.base)
277
+ if (previous) { cache.mtimeMs = previous.mtimeMs; cache.size = previous.size }
278
+ dirty = true
279
+ bumpMemoryRevision()
280
+ flushState()
281
+ return state
282
+ }
283
+
284
+ export function updateState(fn) {
285
+ const state = structuredClone(loadState())
286
+ const next = fn(state) || state
287
+ if (cache) cache.state = next
288
+ dirty = true
289
+ scheduleFlush()
290
+ return next
291
+ }
292
+
293
+ // Codes that mean "the store was momentarily unavailable", not "this write can never
294
+ // succeed". Only these are re-armed; a read-only filesystem or a corrupt path would
295
+ // otherwise retry forever at FLUSH_MS.
296
+ const RETRYABLE_FLUSH_CODES = ['DSH_MEMU_STORE_BUSY', 'EPERM', 'EBUSY', 'EACCES']
297
+
298
+ function scheduleFlush() {
299
+ if (flushTimer) return
300
+ flushTimer = setTimeout(() => {
301
+ flushTimer = null
302
+ try {
303
+ flushState()
304
+ } catch (error) {
305
+ warnSinkSafe(`state flush failed: ${error?.message || error}`)
306
+ if (RETRYABLE_FLUSH_CODES.includes(error?.code)) scheduleFlush()
307
+ }
308
+ }, FLUSH_MS)
309
+ flushTimer.unref?.()
310
+ }
311
+
312
+ /** Writes any pending bookkeeping change now. Safe to call when clean. */
313
+ export function flushState() {
314
+ if (flushTimer) {
315
+ clearTimeout(flushTimer)
316
+ flushTimer = null
317
+ }
318
+ if (!dirty || !cache) return
319
+ try {
320
+ return withFileLock(STATE_FILE(), flushStateLocked)
321
+ } catch (error) {
322
+ // S-10: the timer was already cleared above, so a failed flush used to leave the
323
+ // pending bookkeeping dirty with nothing scheduled — one busy lock was enough to
324
+ // strand inbound pending / lastRecallError / sleepRetryAt in memory until the next
325
+ // unrelated write (or a crash). Re-arm before rethrowing so the batch is retried;
326
+ // the caller still sees the error.
327
+ warnSinkSafe(`state flush failed: ${error?.message || error}`)
328
+ if (RETRYABLE_FLUSH_CODES.includes(error?.code)) scheduleFlush()
329
+ throw error
330
+ }
331
+ }
332
+
333
+ function mergeChanges(base, local, disk) {
334
+ if (JSON.stringify(base) === JSON.stringify(local)) return structuredClone(disk)
335
+ const object = value => value !== null && typeof value === 'object' && !Array.isArray(value)
336
+ if (!object(base) || !object(local) || !object(disk)) return structuredClone(local)
337
+ const next = { ...disk }
338
+ for (const key of new Set([...Object.keys(base), ...Object.keys(local)])) {
339
+ if (JSON.stringify(base[key]) === JSON.stringify(local[key])) continue
340
+ if (!Object.hasOwn(local, key)) delete next[key]
341
+ else next[key] = mergeChanges(base[key], local[key], disk[key])
342
+ }
343
+ return next
344
+ }
345
+
346
+ function flushStateLocked() {
347
+ if (!cache.fromReadFailure) {
348
+ // A read can race another process's rename before its post-read stat.
349
+ // Always merge the disk truth under the lock; mtime/size is not a transaction.
350
+ const disk = readJson(STATE_FILE(), null)
351
+ if (readFailure(STATE_FILE())) throw new Error('state.json changed but could not be read; pending changes retained')
352
+ cache.state = mergeChanges(cache.base, cache.state, mergeState(disk))
353
+ }
354
+ try {
355
+ writeJson(STATE_FILE(), cache.state)
356
+ } catch (error) {
357
+ if (error?.code !== 'dsh-memu-memory/read-failed') throw error
358
+ // The write barrier is set only while the file is unreadable. Re-probe: a
359
+ // successful read clears it, so a transient EBUSY does not freeze the plugin
360
+ // until restart. If it is still unreadable this write throws again.
361
+ const diskRaw = readJson(STATE_FILE(), null)
362
+ if (readFailure(STATE_FILE()) !== null) throw error
363
+ if (cache.fromReadFailure) {
364
+ // The pending write was built on top of a *fallback* state, not the real
365
+ // one. Writing it now would overwrite good data with defaults. Adopt the
366
+ // disk truth instead and drop the pending fallback write.
367
+ warn('state.json read failed earlier; discarding changes made against the fallback state to avoid overwriting real data')
368
+ adoptCache(mergeState(diskRaw), false)
369
+ dirty = false
370
+ return
371
+ }
372
+ writeJson(STATE_FILE(), cache.state)
373
+ }
374
+ dirty = false
375
+ noteMemoryWrite('state', null)
376
+ const stat = statOf(STATE_FILE())
377
+ cache.mtimeMs = stat ? stat.mtimeMs : 0
378
+ cache.size = stat ? stat.size : -1
379
+ cache.base = structuredClone(cache.state)
380
+ }
381
+
382
+ function warnSinkSafe(message) {
383
+ warn(message)
384
+ }
385
+
386
+ export function getSettings() {
387
+ return loadState().settings
388
+ }
389
+
390
+ /**
391
+ * Files that failed to read and are now write-protected, plus quarantined
392
+ * copies left behind. Surfaced by `memu_status` so a silent storage fault is
393
+ * visible instead of becoming "my memories vanished".
394
+ */
395
+ export function storageHealth() {
396
+ const issues = readFailuresUnder(dataDir()).map((failure) => {
397
+ const relative = path.relative(dataDir(), failure.file).replace(/\\/g, '/')
398
+ const { file, ...rest } = failure
399
+ return { file: relative, ...rest }
400
+ })
401
+ const quarantined = []
402
+ for (const [dir, prefix] of [[dataDir(), ''], [indexDir(), 'index/']]) {
403
+ try {
404
+ for (const name of fs.readdirSync(dir)) {
405
+ if (name.includes('.corrupt-')) quarantined.push(`${prefix}${name}`)
406
+ }
407
+ } catch {}
408
+ }
409
+ return { issues, quarantined }
410
+ }
411
+
412
+ // The default is deliberately the self-contained path: a fresh install must be
413
+ // able to remember without MemU, Ollama, or any vendor key.
414
+ export function getMemoryBackend() {
415
+ return loadState().settings?.memoryBackend === 'api' ? 'api' : 'agent'
416
+ }
417
+
418
+ // Single route authority for automatic memory reads and writes.
419
+ export function effectiveVectorRoute(settings = loadState().settings) {
420
+ if (settings?.memoryBackend !== 'api') return 'lexical'
421
+ return settings?.vectorSource === 'api' ? 'remote-api' : 'managed-local'
422
+ }
423
+
424
+ export function vectorBackendEnabled(settings = loadState().settings) {
425
+ return effectiveVectorRoute(settings) !== 'lexical'
426
+ }
427
+
428
+ export function updateSettings(patch) {
429
+ const clean = {}
430
+ const ranges = {
431
+ privateTopK: [1, 20], globalTopK: [1, 20], anchorTokens: [160, 8000], turnTokens: [80, 8000],
432
+ injectionTotalTokens: [160, 16000],
433
+ relevanceThreshold: [0, 1], dedupeTurns: [0, 200], globalEveryNTurns: [0, 200], minUserChars: [0, 1000],
434
+ freshnessDays: [1, 3650],
435
+ mustRememberCap: [1, 100], randomCueChance: [0, 1], shortTermTtlHours: [0, 8760],
436
+ unpinBudgetPerSession: [1, 20], unpinCooldownMinutes: [0, 1440], sleepAfterIdleMinutes: [1, 1440],
437
+ openLoopRemindDays: [1, 365],
438
+ autoCurateEveryHours: [0, 8760], autoCurateSessionLimit: [1, 10], purgeArchivedAfterDays: [0, 36500],
439
+ activeMemoryMinScore: [0, 10], activeMemoryStarvationMinutes: [1, 1440],
440
+ activeMemoryCooldownMinutes: [0, 10080], activeMemoryRecallCooldownMinutes: [0, 10080],
441
+ midTurnMinSteps: [1, 64], midTurnMinUnits: [1, 200], midTurnMinChars: [0, 200000],
442
+ midTurnMaxPerTurn: [1, 10], midTurnCooldownMs: [0, 600000], midTurnTokens: [120, 2000],
443
+ midTurnFullUnits: [1, 200], midTurnFullChars: [0, 200000],
444
+ }
445
+ const enums = { autoInject: ['smart', 'anchor-only', 'per-turn', 'off'], autoLinkMode: ['suggest', 'deterministic', 'off'], memoryMode: ['local', 'cloud'], memoryBackend: ['agent', 'api'], vectorSource: ['local', 'api'], newSessionDefault: ['off', 'auto', 'global', 'both'], curatorReviewMode: ['auto', 'review-all'], salientWake: ['off', 'schedule'], consolidationModelMode: ['inherit', 'host', 'custom'], consolidationReasoningEffort: ['inherit', 'off', 'low', 'medium', 'high'], consolidationCustomApi: ['openai-completions', 'openai-responses', 'anthropic-messages'], consolidationTurnLog: ['on', 'off'], consolidationTurnLogTools: ['none', 'errors', 'summary'], consolidationRunner: ['worker', 'fork'] }
446
+ for (const [key, value] of Object.entries(patch || {})) {
447
+ if (!Object.hasOwn(DEFAULT_SETTINGS, key)) continue
448
+ if (enums[key]) {
449
+ if (!enums[key].includes(value)) throw new Error(`invalid setting ${key}`)
450
+ clean[key] = value
451
+ } else if (ranges[key]) {
452
+ if (typeof value !== 'number' || !Number.isFinite(value)) throw new Error(`setting ${key} must be a finite number`)
453
+ const [min, max] = ranges[key]
454
+ clean[key] = Math.max(min, Math.min(max, value))
455
+ } else if (typeof DEFAULT_SETTINGS[key] === 'boolean') {
456
+ if (typeof value !== 'boolean') throw new Error(`setting ${key} must be boolean`)
457
+ clean[key] = value
458
+ } else if (key === 'curatorModel') {
459
+ if (value !== null && (typeof value !== 'string' || value.length > 200)) throw new Error('invalid curator model')
460
+ clean[key] = value
461
+ } else if (key === 'consolidationModel') {
462
+ // host 模式的 "<provider>/<model>"。格式本身留给 lib/fork-model.js 的解析口径
463
+ // (与 curatorModel 一致:这里只挡类型与超长),写错的值会在 fork 创建时被
464
+ // invalid-consolidation-model 拒绝并在活动日志里说清,设置页先存的草稿不该被卡死。
465
+ if (value !== null && (typeof value !== 'string' || value.length > 200)) throw new Error('invalid consolidation model')
466
+ clean[key] = value
467
+ } else if (key === 'consolidationCustomBaseURL') {
468
+ // custom 模式的端点。空串是「还没填」,合法;非空必须是不带内嵌凭据的 http(s)
469
+ // URL——与 pipIndexes / vision endpoint 同一把尺(宿主请求头进不了带凭据的 URL)。
470
+ if (typeof value !== 'string') throw new Error('setting consolidationCustomBaseURL must be a string')
471
+ const trimmed = value.trim()
472
+ if (trimmed) {
473
+ try {
474
+ const url = new URL(trimmed)
475
+ if (!['http:', 'https:'].includes(url.protocol) || url.username || url.password) throw new Error('bad protocol')
476
+ } catch {
477
+ throw new Error('consolidationCustomBaseURL must be an HTTP(S) URL without embedded credentials')
478
+ }
479
+ }
480
+ clean[key] = trimmed
481
+ } else if (key === 'consolidationCustomApiKey') {
482
+ // custom 模式选填的明文 key(本地网关可以没有)。落盘在 state.json,回包只给
483
+ // 打码视图(rpc.js);这里只挡类型与荒谬长度,两头空白顺手去掉。
484
+ if (typeof value !== 'string' || value.length > 500) throw new Error('invalid consolidation custom api key')
485
+ clean[key] = value.trim()
486
+ } else if (key === 'consolidationCustomModel') {
487
+ // custom 模式必填的模型 id。允许 '/'(openrouter 风格的嵌套 id),只挡类型与长度。
488
+ if (typeof value !== 'string' || value.length > 200) throw new Error('invalid consolidation custom model')
489
+ clean[key] = value.trim()
490
+ } else if (key === 'salientWakeHour') {
491
+ // 定时唤醒的本地墙上时间。只收 HH:mm,不收 "9:00":宿主的 at 输入按 HH:mm[:ss]
492
+ // 解释,少一位会被拒或读成别的时刻,宁可在设置页就拒绝。
493
+ if (typeof value !== 'string' || !/^([01]\d|2[0-3]):[0-5]\d$/.test(value)) throw new Error('setting salientWakeHour must be HH:mm')
494
+ clean[key] = value
495
+ } else if (key === 'salientWakeTimeZone') {
496
+ // 空串是"跟随系统",是合法配置,不在这里解析成具体城市;非空必须是有效 IANA 区,
497
+ // 否则宿主的 at 计时会在投递时被拒(invalid_time_zone),排了也不会响。
498
+ if (typeof value !== 'string' || value.length > 100) throw new Error('invalid salientWakeTimeZone')
499
+ const zone = value.trim()
500
+ if (zone) {
501
+ try {
502
+ new Intl.DateTimeFormat('en-US', { timeZone: zone })
503
+ } catch {
504
+ throw new Error(`invalid salientWakeTimeZone: ${zone}`)
505
+ }
506
+ }
507
+ clean[key] = zone
508
+ } else if (key === 'pipIndexes' || key === 'promptDomains' || key === 'inboundToolNames') {
509
+ if (!Array.isArray(value) || value.length > 20 || value.some(item => typeof item !== 'string')) throw new Error(`invalid setting ${key}`)
510
+ if (key === 'promptDomains' && value.some(item => !/^[a-z0-9][a-z0-9_-]{0,23}$/.test(item))) throw new Error('invalid domain id')
511
+ if (key === 'inboundToolNames' && value.some(item => !/^[A-Za-z0-9_.:/-]{1,160}$/.test(item))) throw new Error('invalid inbound tool name')
512
+ if (key === 'pipIndexes' && value.some(item => {
513
+ try { const url = new URL(item); return !['http:', 'https:'].includes(url.protocol) || url.username || url.password } catch { return true }
514
+ })) throw new Error('pip indexes must be HTTP(S) URLs without credentials')
515
+ clean[key] = value.slice()
516
+ }
517
+ }
518
+ return updateState((state) => {
519
+ state.settings = { ...state.settings, ...clean }
520
+ return state
521
+ }).settings
522
+ }
523
+
524
+ /**
525
+ * The prompt pages a user can edit and assign. Ids are used as file suffixes and
526
+ * as session domains, so they are restricted to a slug alphabet; `general` is
527
+ * implicit (the base prompt) and never appears here.
528
+ */
529
+ export function getPromptDomains() {
530
+ const raw = loadState().settings?.promptDomains
531
+ const list = Array.isArray(raw) ? raw : DEFAULT_SETTINGS.promptDomains
532
+ const seen = new Set()
533
+ const out = []
534
+ for (const value of list) {
535
+ const id = String(value || '').trim().toLowerCase()
536
+ if (!/^[a-z0-9][a-z0-9_-]{0,23}$/.test(id) || id === 'general' || seen.has(id)) continue
537
+ seen.add(id)
538
+ out.push(id)
539
+ }
540
+ return out
541
+ }
542
+
543
+ export function addPromptDomain(id) {
544
+ const value = String(id || '').trim().toLowerCase()
545
+ if (!/^[a-z0-9][a-z0-9_-]{0,23}$/.test(value)) throw new Error('domain id must be 1-24 chars: a-z, 0-9, - or _')
546
+ if (value === 'general') throw new Error('"general" is the built-in 通用 page')
547
+ const list = getPromptDomains()
548
+ if (list.includes(value)) return list
549
+ return updateSettings({ promptDomains: [...list, value] }).promptDomains
550
+ }
551
+
552
+ export function removePromptDomain(id) {
553
+ const value = String(id || '').trim().toLowerCase()
554
+ const list = getPromptDomains()
555
+ if (!list.includes(value)) return list
556
+ return updateSettings({ promptDomains: list.filter((item) => item !== value) }).promptDomains
557
+ }
558
+
559
+ // Both switches default to on: that is the behaviour every existing folder had
560
+ // before this setting existed. Turning the private switch off means "this folder
561
+ // keeps no private library", not "delete the one it has" — nothing is ever deleted
562
+ // by a switch.
563
+ export const DEFAULT_FOLDER_POLICY = { useLibrary: true, useGlobal: true }
564
+
565
+ function policyFor(state, scopeKey) {
566
+ return { ...DEFAULT_FOLDER_POLICY, ...(state.workspacePolicies?.[scopeKey] || {}) }
567
+ }
568
+
569
+ export function getWorkspacePolicy(scopeKey) {
570
+ const key = normalizeCwd(scopeKey) || '__default__'
571
+ return { scopeKey: key, ...policyFor(loadState(), key) }
572
+ }
573
+
574
+ /**
575
+ * The folder policy is a ceiling, not an initial value. `sessions[].useLibrary`
576
+ * records what the user chose for that conversation; the folder decides how far
577
+ * that choice can go. Storing the wish and computing the effect separately is
578
+ * what lets re-enabling a folder restore each conversation's own choice instead
579
+ * of flipping everything back on.
580
+ */
581
+ export function effectiveScope(binding, policy = null) {
582
+ const folder = policy || (binding?.scopeKey ? getWorkspacePolicy(binding.scopeKey) : { ...DEFAULT_FOLDER_POLICY })
583
+ const wantsLibrary = binding ? binding.useLibrary !== false : folder.useLibrary !== false
584
+ const wantsGlobal = binding ? binding.useGlobal !== false : folder.useGlobal !== false
585
+ return {
586
+ folder,
587
+ useLibrary: folder.useLibrary !== false && wantsLibrary,
588
+ useGlobal: folder.useGlobal !== false && wantsGlobal,
589
+ libraryBlocked: folder.useLibrary === false,
590
+ globalBlocked: folder.useGlobal === false,
591
+ enabled: (folder.useLibrary !== false && wantsLibrary) || (folder.useGlobal !== false && wantsGlobal),
592
+ }
593
+ }
594
+
595
+ export function listWorkspacePolicies() {
596
+ const state = loadState()
597
+ return Object.entries(state.workspacePolicies || {})
598
+ .map(([scopeKey, policy]) => ({ scopeKey, ...DEFAULT_FOLDER_POLICY, ...policy }))
599
+ }
600
+
601
+ export function setWorkspacePolicy(scopeKey, patch = {}) {
602
+ const key = normalizeCwd(scopeKey) || '__default__'
603
+ const state = updateState((draft) => {
604
+ draft.workspacePolicies = draft.workspacePolicies || {}
605
+ const next = { ...DEFAULT_FOLDER_POLICY, ...(draft.workspacePolicies[key] || {}) }
606
+ for (const field of ['useLibrary', 'useGlobal']) {
607
+ if (typeof patch[field] === 'boolean') next[field] = patch[field]
608
+ }
609
+ draft.workspacePolicies[key] = { ...next, updatedAt: stamp() }
610
+ const library = Object.entries(draft.libraries)
611
+ .find(([, lib]) => lib.scopeKey === key && lib.archived !== true)
612
+ // Existing conversations are deliberately NOT edited: their switches record
613
+ // what the user chose for that chat, and the folder policy above already
614
+ // clamps them at read time. The only repair worth doing is pointing a
615
+ // conversation at its folder's library once one exists again.
616
+ if (patch.useLibrary === true) {
617
+ for (const binding of Object.values(draft.sessions || {})) {
618
+ const inFolder = binding.scopeKey === key
619
+ || (binding.libraryId && draft.libraries[binding.libraryId]?.scopeKey === key)
620
+ if (inFolder && !binding.libraryId && library) binding.libraryId = library[0]
621
+ }
622
+ }
623
+ return draft
624
+ })
625
+ return { scopeKey: key, ...policyFor(state, key) }
626
+ }
627
+
628
+ export function normalizeCwd(cwd) {
629
+ if (!cwd || typeof cwd !== 'string') return ''
630
+ // The no-workspace placeholder is a key, not a path. Resolving it would produce
631
+ // a machine-dependent scope like `d:/somewhere/__default__` and leak a junk
632
+ // library into the list every time a session starts without a folder.
633
+ if (cwd === '__default__') return '__default__'
634
+ let resolved
635
+ try { resolved = path.resolve(cwd) } catch { resolved = cwd }
636
+ let text = resolved.replace(/\\/g, '/').replace(/\/+$/, '')
637
+ if (process.platform === 'win32') text = text.toLowerCase()
638
+ return text
639
+ }
640
+
641
+ export function detectDomain({ agentPreset, cwd } = {}) {
642
+ const text = `${agentPreset || ''} ${cwd || ''}`.toLowerCase()
643
+ if (/(roleplay|role-play|character|persona|rp[-_ ]|沉浸|角色扮演)/.test(text)) return 'rp'
644
+ if (cwd) return 'coding'
645
+ return 'general'
646
+ }
647
+
648
+ export function listLibraries() {
649
+ const state = loadState()
650
+ return Object.entries(state.libraries)
651
+ .filter(([, lib]) => lib.archived !== true)
652
+ .map(([id, lib]) => ({ id, ...lib }))
653
+ .sort((a, b) => String(b.lastUsedAt || '').localeCompare(String(a.lastUsedAt || '')))
654
+ }
655
+
656
+ export function listLibrariesAll() {
657
+ const state = loadState()
658
+ return Object.entries(state.libraries).map(([id, lib]) => ({ id, ...lib }))
659
+ }
660
+
661
+ export function listArchivedLibraries() {
662
+ const state = loadState()
663
+ return Object.entries(state.libraries)
664
+ .filter(([, lib]) => lib.archived === true)
665
+ .map(([id, lib]) => ({ id, ...lib }))
666
+ // Oldest archived first: the ones nobody revived are the deletion candidates.
667
+ .sort((a, b) => String(a.archivedAt || '').localeCompare(String(b.archivedAt || '')))
668
+ }
669
+
670
+ // A library's scope folder is gone from disk. `__default__` has no folder to check,
671
+ // so it never counts as missing.
672
+ export function libraryScopeMissing(lib) {
673
+ const key = lib?.scopeKey
674
+ if (!key || key === '__default__') return false
675
+ try {
676
+ return !fs.existsSync(key)
677
+ } catch {
678
+ return false
679
+ }
680
+ }
681
+
682
+ // Hard delete: the sqlite store and its sidecar index leave with the state entry.
683
+ // Only ever called on an already-archived library, so the caller had to confirm twice.
684
+ // `force` exists for the one legitimate case the state cannot see: the caller already
685
+ // unbound every session and knows it. Without it, a library that a live conversation
686
+ // still points at cannot be deleted — the sweep used to be able to put an in-use
687
+ // library into the only state `deleteLibrary` accepts.
688
+ export function deleteLibrary(id, { force = false } = {}) {
689
+ if (!isSafeId(id)) throw new Error('invalid library id')
690
+ const state = loadState()
691
+ if (!state.libraries[id]) return { ok: false, error: 'library not found' }
692
+ if (state.libraries[id].archived !== true) return { ok: false, error: 'archive the library before deleting it' }
693
+ // 只拦「危险归档 + 仍在用」:扫描误归档的那一类才有一键删掉全部记忆的风险。
694
+ // 用户主动归档仍有绑定会话时照旧允许(删除会连同绑定一起清掉,这是既有语义);
695
+ // 冷数据的旧归档同理放行,否则本机 rp / 另一个工作区库 这类库会变成"永远删不掉"。
696
+ if (!force && archivedWhileInUse(state.libraries[id], { inUse: inUseLibraryIds(state).has(id) })) {
697
+ return { ok: false, error: 'this library was archived while a conversation still uses it; unbind or delete those sessions first (force overrides)' }
698
+ }
699
+ const activeVectorDb = removeActiveLibrary(id)
700
+ const legacyVectorDb = path.join(librariesDir(), id + '.sqlite3')
701
+ delete state.libraries[id]
702
+ for (const [sessionId, binding] of Object.entries(state.sessions || {})) {
703
+ if (binding?.libraryId === id) delete state.sessions[sessionId]
704
+ }
705
+ saveState(state)
706
+ const removed = []
707
+ const vectorPrefix = id + '.'
708
+ const vectorGenerationFiles = fs.existsSync(librariesDir())
709
+ ? fs.readdirSync(librariesDir()).filter(name => name.startsWith(vectorPrefix) && name.endsWith('.sqlite3')).map(name => path.join(librariesDir(), name))
710
+ : []
711
+ for (const file of [activeVectorDb, legacyVectorDb, ...vectorGenerationFiles, ...['json', 'entities.json', 'media.json', 'stats.json', 'link-suppression.json', 'anchor-candidates.json'].map(suffix => path.join(indexDir(), `${id}.${suffix}`))]) {
712
+ if (!file) continue
713
+ try {
714
+ if (fs.existsSync(file)) { fs.rmSync(file, { force: true }); removed.push(file) }
715
+ } catch {}
716
+ }
717
+ const attachments = path.join(dataDir(), 'attachments', id)
718
+ if (!path.resolve(attachments).startsWith(path.resolve(dataDir(), 'attachments') + path.sep)) throw new Error('attachment path escaped')
719
+ if (fs.existsSync(attachments)) fs.rmSync(attachments, { recursive: true, force: true })
720
+ return { ok: true, id, removed }
721
+ }
722
+
723
+ export function getLibrary(id) {
724
+ if (!id) return null
725
+ const lib = loadState().libraries[id]
726
+ return lib ? { id, ...lib } : null
727
+ }
728
+
729
+ function uniqueLibraryId(state, scopeKey) {
730
+ let id = libraryIdForScope(scopeKey)
731
+ if (state.libraries[id] && state.libraries[id].scopeKey !== scopeKey) {
732
+ id = `${id}-${shortHash(scopeKey)}`
733
+ }
734
+ return id
735
+ }
736
+
737
+ export function createLibrary({ name, scopeKey, cwd } = {}) {
738
+ const key = normalizeCwd(scopeKey || cwd || name || '__default__')
739
+ const state = loadState()
740
+ const id = uniqueLibraryId(state, key)
741
+ if (state.libraries[id]) return { id, ...state.libraries[id] }
742
+ state.libraries[id] = {
743
+ name: String(name || path.basename(key) || 'Default').slice(0, 80),
744
+ scopeKey: key,
745
+ createdAt: stamp(),
746
+ lastUsedAt: stamp(),
747
+ }
748
+ saveState(state)
749
+ ensureDir(librariesDir())
750
+ return { id, ...state.libraries[id] }
751
+ }
752
+
753
+ export function ensureLibraryForCwd(cwd) {
754
+ const scopeKey = normalizeCwd(cwd) || '__default__'
755
+ const state = loadState()
756
+ const found = Object.entries(state.libraries).find(([, lib]) => lib.scopeKey === scopeKey)
757
+ if (found) {
758
+ found[1].lastUsedAt = stamp()
759
+ // The folder came back: re-binding it revives the library instead of silently
760
+ // writing new memories into an archived one.
761
+ if (found[1].archived) {
762
+ found[1].archived = false
763
+ found[1].archivedAt = null
764
+ found[1].revivedAt = stamp()
765
+ }
766
+ saveState(state)
767
+ return { id: found[0], ...found[1] }
768
+ }
769
+ return createLibrary({ scopeKey, name: scopeKey === '__default__' ? 'Default' : path.basename(scopeKey) })
770
+ }
771
+
772
+ export function renameLibrary(id, name) {
773
+ const state = loadState()
774
+ if (!state.libraries[id]) return null
775
+ state.libraries[id].name = String(name || '').trim().slice(0, 80) || state.libraries[id].name
776
+ saveState(state)
777
+ return { id, ...state.libraries[id] }
778
+ }
779
+
780
+ // A pre-folder build could bind a conversation before its cwd was known, leaving
781
+ // one shared "Default" bucket for every workspace. The conversation is the only
782
+ // place that still knows the real folder, so when it is opened with a cwd we
783
+ // promote that bucket in place: same id, so its memories and index stay attached,
784
+ // but the name and scope become the folder a human expects to see.
785
+ export function adoptDefaultLibrary(libraryId, cwd) {
786
+ const key = normalizeCwd(cwd)
787
+ if (!key || key === '__default__') return null
788
+ const state = loadState()
789
+ const lib = state.libraries[libraryId]
790
+ if (!lib || normalizeCwd(lib.scopeKey || '') !== '__default__') return null
791
+ const existing = Object.entries(state.libraries)
792
+ .find(([id, other]) => id !== libraryId && other.scopeKey === key && other.archived !== true)
793
+ if (existing) {
794
+ for (const binding of Object.values(state.sessions || {})) {
795
+ if (binding.libraryId === libraryId) {
796
+ binding.libraryId = existing[0]
797
+ binding.scopeKey = key
798
+ }
799
+ }
800
+ // Keep the old bucket recoverable but out of the way when nothing points at it
801
+ // any more. It is never deleted: a mis-detected cwd must not destroy memories.
802
+ const stillBound = Object.values(state.sessions || {}).some((b) => b.libraryId === libraryId)
803
+ if (!stillBound) {
804
+ lib.archived = true
805
+ lib.archivedAt = stamp()
806
+ lib.adoptedInto = existing[0]
807
+ }
808
+ saveState(state)
809
+ return { id: existing[0], ...existing[1], adopted: true, reused: true }
810
+ }
811
+ lib.scopeKey = key
812
+ lib.name = key.split(/[\\/]/).filter(Boolean).pop() || lib.name || 'Default'
813
+ lib.updatedAt = stamp()
814
+ for (const binding of Object.values(state.sessions || {})) {
815
+ if (binding.libraryId === libraryId) binding.scopeKey = key
816
+ }
817
+ saveState(state)
818
+ return { id: libraryId, ...lib, adopted: true }
819
+ }
820
+
821
+ /**
822
+ * Returns libraries used by a live session: any binding with `sessionGone !== true`
823
+ * counts as active. Archive scans cannot rely only on workspaceRegistry because
824
+ * libraries scoped to IM plugins or profiles may not be registered there.
825
+ *
826
+ * Use binding state rather than an age window: elapsed time cannot reliably
827
+ * distinguish an idle library from one that was just opened. Passing state lets the
828
+ * sweep read it once and calculate the result once.
829
+ */
830
+ export function inUseLibraryIds(state = null) {
831
+ const snapshot = state || loadState()
832
+ const ids = new Set()
833
+ for (const binding of Object.values(snapshot.sessions || {})) {
834
+ if (!binding || binding.sessionGone === true) continue
835
+ const libraryId = binding.libraryId
836
+ if (!libraryId || !snapshot.libraries?.[libraryId]) continue
837
+ ids.add(libraryId)
838
+ }
839
+ return ids
840
+ }
841
+
842
+ export function isLibraryInUse(id) {
843
+ return Boolean(id) && inUseLibraryIds().has(id)
844
+ }
845
+
846
+ // 1.3.13 及更早的归档没有 `archivedBy`:分不清是用户点的归档还是老扫描误归档。
847
+ // 对这类库只认「还热」的(lastUsedAt 在 14 天内),冷归档按用户意图对待。
848
+ export const ARCHIVE_REVIVE_FRESH_MS = 14 * 86_400_000
849
+
850
+ /**
851
+ * 「归档了但其实还在用」——扫描误归档的判据,同时也是删除守卫的判据。
852
+ *
853
+ * 用户主动归档(`archivedBy === 'user'`)永远不算;扫描归档的(`'sweep'`)永远算;
854
+ * 旧数据按 lastUsedAt 的新鲜度判。两处共用同一个函数,避免"扫描复活、删除又放行"这种
855
+ * 两套口径各说各话。
856
+ */
857
+ export function archivedWhileInUse(lib, { inUse = false, now = Date.now() } = {}) {
858
+ if (!inUse || !lib) return false
859
+ if (lib.archivedBy === 'user') return false
860
+ if (lib.archivedBy === 'sweep') return true
861
+ const lastUsed = Date.parse(lib.lastUsedAt || '') || 0
862
+ return lastUsed > 0 && now - lastUsed <= ARCHIVE_REVIVE_FRESH_MS
863
+ }
864
+
865
+ /** `by` 记录是谁归档的:用户的主动归档不该被扫描悄悄复活。 */
866
+ export function archiveLibrary(id, { by = 'user' } = {}) {
867
+ const state = loadState()
868
+ if (!state.libraries[id]) return false
869
+ state.libraries[id].archived = true
870
+ state.libraries[id].archivedAt = stamp()
871
+ state.libraries[id].archivedBy = by
872
+ saveState(state)
873
+ return true
874
+ }
875
+
876
+ // Registry presence is the signal for both directions: the sweep only calls this for
877
+ // a scope that just came back into the workspace list. Checking the disk here would
878
+ // contradict the archive rule (removing a workspace keeps its folder on disk, and a
879
+ // folder can be absent for reasons that have nothing to do with DSH).
880
+ export function restoreLibrary(id) {
881
+ const state = loadState()
882
+ const lib = state.libraries[id]
883
+ if (!lib) return { ok: false, error: 'library not found' }
884
+ lib.archived = false
885
+ lib.archivedAt = null
886
+ lib.archivedBy = null
887
+ lib.revivedAt = stamp()
888
+ lib.lastUsedAt = stamp()
889
+ saveState(state)
890
+ return { ok: true, id, library: { id, ...lib } }
891
+ }
892
+
893
+ export function getSessionBinding(sessionId) {
894
+ if (!sessionId) return null
895
+ const state = loadState()
896
+ return state.sessions[sessionId] || null
897
+ }
898
+
899
+ export function setSessionBinding(sessionId, patch) {
900
+ return updateState((state) => {
901
+ const previous = state.sessions[sessionId] || {}
902
+ const next = { ...previous, ...(patch || {}) }
903
+ for (const key of ['lastInjectedUserMessageId', 'guideRulesKey', 'guideMessageAt', 'anchorPushed']) {
904
+ if (!Object.hasOwn(patch || {}, key)) continue
905
+ next.injectionOwners = { ...(next.injectionOwners || {}), [key]: `legacy:${crypto.randomUUID()}` }
906
+ }
907
+ const scopeFields = ['libraryId', 'scopeKey', 'memoryContext', 'useLibrary', 'useGlobal', 'domainOverride']
908
+ if (scopeFields.some(key => Object.hasOwn(patch || {}, key) && JSON.stringify(previous[key]) !== JSON.stringify(next[key]))) {
909
+ next.scopeGeneration = Number(previous.scopeGeneration || 0) + 1
910
+ }
911
+ state.sessions[sessionId] = next
912
+ return state
913
+ }).sessions[sessionId]
914
+ }
915
+
916
+ export function ensureSession(sessionId, { cwd, agentPreset, libraryId = null, createLibrary = true } = {}) {
917
+ if (!sessionId) throw new Error('ensureSession requires a sessionId')
918
+ const initial = loadState()
919
+ const previous = initial.sessions[sessionId]
920
+ if (previous?.libraryId && initial.libraries[previous.libraryId]) {
921
+ const boundLibrary = initial.libraries[previous.libraryId]
922
+ // 一个正在被这个会话读写的库不该停在 archived:归档的语义是「隐藏、准备清理」,
923
+ // 而在用的库既不该消失,也不该落进 `deleteLibrary` 唯一允许删除的状态。旧版扫描
924
+ // 只要 scope 不在 workspaceRegistry 就归档,而这条快路径从不复活,于是库能一边
925
+ // 「归档」一边长数据 9 小时。用户主动归档(archivedBy === 'user')除外。
926
+ if (boundLibrary.archived === true && boundLibrary.archivedBy !== 'user') {
927
+ restoreLibrary(previous.libraryId)
928
+ const revived = loadState().sessions[sessionId]
929
+ if (revived) return revived
930
+ }
931
+ const libraryScope = normalizeCwd(boundLibrary.scopeKey || '')
932
+ // Repair the old placeholder bucket as soon as the live conversation reveals
933
+ // its folder. Without this, every historical Default library stays mislabelled
934
+ // even though new conversations are correct.
935
+ if (libraryScope === '__default__' && normalizeCwd(cwd)) {
936
+ const adopted = adoptDefaultLibrary(previous.libraryId, cwd)
937
+ if (adopted) {
938
+ const repaired = loadState().sessions[sessionId]
939
+ if (repaired) return repaired
940
+ }
941
+ }
942
+ // A library that already knows its folder but still carries the placeholder
943
+ // name should show the folder too; this is the case the old repair missed.
944
+ const placeholderName = !boundLibrary.name || boundLibrary.name === 'Default' || boundLibrary.name === '__default__'
945
+ if (libraryScope && libraryScope !== '__default__' && placeholderName) {
946
+ boundLibrary.name = libraryScope.split(/[\\/]/).filter(Boolean).pop() || boundLibrary.name || 'Default'
947
+ boundLibrary.updatedAt = stamp()
948
+ }
949
+ boundLibrary.lastUsedAt = stamp()
950
+ saveState(initial)
951
+ return previous
952
+ }
953
+ const scopeKey = normalizeCwd(cwd) || '__default__'
954
+ const policy = policyFor(initial, scopeKey)
955
+ const requested = libraryId && initial.libraries[libraryId] ? libraryId : null
956
+ // A per-conversation switch is the user's choice and must survive every turn:
957
+ // `ensureSession` runs on each step, so overwriting it from the folder policy
958
+ // here used to reset the sidebar toggle constantly. The folder still clamps at
959
+ // read time via effectiveScope().
960
+ const existingBinding = initial.sessions[sessionId]
961
+ const wantsLibrary = existingBinding ? existingBinding.useLibrary !== false : policy.useLibrary !== false
962
+ const wantsGlobal = existingBinding ? existingBinding.useGlobal !== false : policy.useGlobal !== false
963
+ let lib = null
964
+ if (requested) lib = { id: requested, ...initial.libraries[requested] }
965
+ // `createLibrary` governs *creating* a library, never *adopting* one. Tying both
966
+ // to it meant a folder that already had a library still started every new
967
+ // conversation with `libraryId === null` whenever the caller passed
968
+ // `createLibrary: false` — the exact shape of "my memories are gone in a new
969
+ // chat". Re-using the folder's library is not a side effect; it is the point of
970
+ // the folder policy. Archived libraries are skipped here (reviving one is a
971
+ // deliberate act) and creation still needs the switch.
972
+ else if (policy.useLibrary && wantsLibrary) {
973
+ const folder = Object.entries(initial.libraries).find(([, l]) => l.scopeKey === scopeKey && l.archived !== true)
974
+ if (folder) lib = { id: folder[0], ...folder[1] }
975
+ else if (createLibrary) lib = ensureLibraryForCwd(cwd || '__default__')
976
+ }
977
+ const state = loadState()
978
+ const existing = state.sessions[sessionId]
979
+ const binding = {
980
+ ...(existing || {}),
981
+ useLibrary: requested ? true : wantsLibrary,
982
+ useGlobal: wantsGlobal,
983
+ scopeKey,
984
+ domain: existing?.domain || detectDomain({ agentPreset, cwd }),
985
+ // 未被问过的新会话不再硬编码 RP 兜底(issue #2 缺陷 2):领域跟随 detectDomain
986
+ // 的文件夹/预设判定,与上方 domain 字段同一口径。弹窗或侧栏写下的显式答案会
987
+ // 覆盖这里,并留下 domainSource:'chosen' 作为「已答」的凭据。
988
+ domainOverride: existing?.domainOverride ?? detectDomain({ agentPreset, cwd }),
989
+ domainSource: existing?.domainSource ?? 'auto',
990
+ injectedIds: existing?.injectedIds || [],
991
+ injectedAt: existing?.injectedAt || {},
992
+ lastInjectedTurn: existing?.lastInjectedTurn ?? 0,
993
+ reinjectPending: existing?.reinjectPending || false,
994
+ activeCue: existing?.activeCue || null,
995
+ libraryId: existing?.libraryId && state.libraries[existing.libraryId]
996
+ ? existing.libraryId
997
+ : (lib?.id || null),
998
+ }
999
+ state.sessions[sessionId] = binding
1000
+ saveState(state)
1001
+ return binding
1002
+ }
1003
+
1004
+ export function deleteSessionBinding(sessionId) {
1005
+ return updateState((state) => {
1006
+ delete state.sessions[sessionId]
1007
+ return state
1008
+ })
1009
+ }
1010
+
1011
+ // Only typed, host-admitted records prove content identity. Legacy bare ids do not.
1012
+ export function recentMemoryRefs(binding, memoryClock, dedupeTurns) {
1013
+ const window = Number(dedupeTurns)
1014
+ const clock = Number(memoryClock)
1015
+ if (!(window > 0) || !Number.isFinite(clock)) return []
1016
+ const latest = new Map()
1017
+ const revoked = new Set(binding?.revokedInjectionMessages || [])
1018
+ for (const record of binding?.acceptedMemoryMessages || []) {
1019
+ if (record.generation !== Number(binding.scopeGeneration || 0)
1020
+ || record.epoch !== Number(binding.injectionEpoch || 0) || revoked.has(record.messageId)) continue
1021
+ for (const ref of record.refs || []) {
1022
+ const key = memoryRefKey(ref)
1023
+ const previous = latest.get(key)
1024
+ if (!previous || record.memoryClock >= previous.clock) latest.set(key, { ref, clock: record.memoryClock })
1025
+ }
1026
+ }
1027
+ return [...latest.values()].filter(item => item.clock <= clock && clock - item.clock < window)
1028
+ .map(item => ({ ...item.ref }))
1029
+ }
1030
+
1031
+ /** Commit one immutable message after its exact body entered host history. No entry bodies. */
1032
+ export function markInjectedRefs(sessionId, refs, memoryClock, options = {}) {
1033
+ if (!sessionId || typeof options.messageId !== 'string' || !Number.isFinite(Number(memoryClock))) return null
1034
+ let committed = null
1035
+ updateState(state => {
1036
+ const binding = state.sessions[sessionId]
1037
+ if (!binding) return state
1038
+ const records = binding.acceptedMemoryMessages || []
1039
+ if (records.some(record => record.messageId === options.messageId)) return state
1040
+ const generation = Number(options.generation ?? binding.scopeGeneration ?? 0)
1041
+ const epoch = Number(options.epoch ?? binding.injectionEpoch ?? 0)
1042
+ if (generation !== Number(binding.scopeGeneration || 0) || epoch !== Number(binding.injectionEpoch || 0)) return state
1043
+ const typed = (refs || []).filter(ref => ref && ['private', 'global'].includes(ref.scope)
1044
+ && typeof ref.id === 'string' && typeof ref.revision === 'string'
1045
+ && (ref.scope === 'global' || typeof ref.libraryId === 'string'))
1046
+ .map(ref => ({ scope: ref.scope, libraryId: ref.libraryId ?? null, id: ref.id, revision: ref.revision,
1047
+ ...(ref.groupKey !== undefined ? { groupKey: ref.groupKey } : {}),
1048
+ ...(ref.groupRevision !== undefined ? { groupRevision: ref.groupRevision } : {}) }))
1049
+ committed = { messageId: options.messageId, hostTurn: options.hostTurn ?? null, generation, epoch,
1050
+ memoryClock: Number(memoryClock), refs: typed, admittedAt: stamp() }
1051
+ const next = [...records, committed]
1052
+ let count = next.reduce((sum, record) => sum + record.refs.length, 0)
1053
+ while (next.length > 1 && (count > 400 || next.length > 400)) count -= next.shift().refs.length
1054
+ if (count > 400) committed.refs = committed.refs.slice(-400)
1055
+ binding.acceptedMemoryMessages = next
1056
+ // Old anchor consumers retain their compatibility view, never a typed cooldown.
1057
+ const ids = typed.map(ref => ref.id)
1058
+ if ((binding.injectedIds || []).includes('__anchor__')) binding.anchorPushed = true
1059
+ binding.injectedIds = [...new Set([...(binding.injectedIds || []).filter(id => id !== '__anchor__'), ...ids])].slice(-400)
1060
+ binding.injectedAt = { ...(binding.injectedAt || {}) }
1061
+ binding.injectionOwners = { ...(binding.injectionOwners || {}) }
1062
+ binding.injectionOwnerClocks = { ...(binding.injectionOwnerClocks || {}) }
1063
+ committed.effects = {}
1064
+ const applyEffect = (key, value, field = key, id = null) => {
1065
+ const owner = binding.injectionOwners[key]
1066
+ const priorClock = typeof owner === 'string' && owner.startsWith('legacy:')
1067
+ ? Math.max(Number(binding.lastInjectedTurn || 0), Number(binding.inbound?.clock || 0), Number(binding.injectionOwnerClocks[key] || 0))
1068
+ : binding.injectionOwnerClocks[key] ?? records.find(record => record.messageId === owner)?.memoryClock ?? -1
1069
+ if (Number(priorClock) > Number(memoryClock)) return
1070
+ const previous = id === null ? binding[field] : binding[field]?.[id]
1071
+ committed.effects[key] = { value: structuredClone(previous), owner: binding.injectionOwners[key] ?? null,
1072
+ clock: binding.injectionOwnerClocks[key] ?? null, field, id }
1073
+ if (id === null) binding[field] = structuredClone(value)
1074
+ else binding[field] = { ...(binding[field] || {}), [id]: structuredClone(value) }
1075
+ binding.injectionOwners[key] = options.messageId
1076
+ binding.injectionOwnerClocks[key] = Number(memoryClock)
1077
+ }
1078
+ for (const id of ids) applyEffect(`id:${id}`, Number(memoryClock), 'injectedAt', id)
1079
+ const actions = structuredClone(options.actions || {})
1080
+ const patch = actions.patch || {}
1081
+ if (actions.anchor) { patch.anchorPushed = true; patch.reinjectPending = false }
1082
+ if (actions.cue) patch.activeCue = { id: String(actions.cue.id), text: String(actions.cue.text || '').slice(0, 500),
1083
+ sourceId: actions.cue.sourceId ? String(actions.cue.sourceId) : null,
1084
+ recallQuery: actions.cue.recallQuery ? String(actions.cue.recallQuery).slice(0, 200) : null, createdAt: stamp() }
1085
+ if (actions.lexicon?.selected?.length) patch.lexiconInjectionClock = Number(memoryClock)
1086
+ for (const [key, value] of Object.entries(patch)) applyEffect(key, value)
1087
+ for (const [id, day] of Object.entries(actions.anniversaries || {})) applyEffect(`anniversary:${id}`, day, 'anniversariesShown', id)
1088
+ for (const id of actions.nudgeIds || []) applyEffect(`nudge:${id}`, stamp(), 'openLoopRemindedAt', id)
1089
+ // An immutable proposal consumes only its displayed occurrences, never a SHA or snapshot queue.
1090
+ const media = actions.media
1091
+ if (media?.scope?.sessionId === sessionId && media.scope.libraryId === binding.libraryId
1092
+ && media.scope.incarnation === binding.mediaIncarnation
1093
+ && media.scope.contextKey === JSON.stringify(normalizeMemoryContext(binding.memoryContext))) {
1094
+ const ids = new Set((media.occurrenceIds || []).filter(id => typeof id === 'string'))
1095
+ const consumed = (binding.pendingMedia || []).filter(item => ids.has(item.occurrenceId)
1096
+ && JSON.stringify(item.mediaScope) === JSON.stringify(media.scope))
1097
+ committed.media = { scope: structuredClone(media.scope), occurrences: structuredClone(consumed) }
1098
+ const consumedIds = new Set(consumed.map(item => item.occurrenceId))
1099
+ binding.pendingMedia = (binding.pendingMedia || []).filter(item => !consumedIds.has(item.occurrenceId))
1100
+ }
1101
+ binding.lastInjectedTurn = Math.max(Number(binding.lastInjectedTurn || 0), Number(memoryClock))
1102
+ if (typed.length || actions.anchor) binding.lastInjectedAt = stamp()
1103
+ return state
1104
+ })
1105
+ if (committed) flushState()
1106
+ return committed ? structuredClone(committed) : null
1107
+ }
1108
+
1109
+ /**
1110
+ * A durable copy of pending admission proposals. `injectionAdmissions` is an
1111
+ * in-process Map, so proposals would be lost across host restarts or when another
1112
+ * process observes the same home. Persist only minimal commit credentials keyed by
1113
+ * message-content digest so another observer can complete admission. Keep the most
1114
+ * recent 8 entries; reposts replace matching digests and older entries are evicted.
1115
+ */
1116
+ const PENDING_INJECTION_MAX = 8
1117
+ // 凭据只为「这一轮内的跨进程补认」服务:崩溃错过 turn/end 时它可能残留,
1118
+ // 同内容重投(锚点文本高度重复)会认领到最旧那条、把 turn 归属记错。
1119
+ // 读取时按 30 分钟 TTL 过滤并取最新匹配;写入时顺手清扫过期项。
1120
+ const PENDING_INJECTION_TTL_MS = 30 * 60 * 1000
1121
+
1122
+ function pendingInjectionFresh(item, now = Date.now()) {
1123
+ const at = Date.parse(item?.at || '')
1124
+ return Number.isFinite(at) && now - at < PENDING_INJECTION_TTL_MS
1125
+ }
1126
+
1127
+ export function rememberPendingInjection(sessionId, record = {}) {
1128
+ if (!sessionId || !record.digest || !record.messageId) return null
1129
+ return updateState((state) => {
1130
+ const binding = state.sessions[sessionId]
1131
+ if (!binding) return state
1132
+ const kept = (binding.pendingInjections || []).filter(item => item?.messageId !== record.messageId && pendingInjectionFresh(item))
1133
+ kept.push({
1134
+ digest: String(record.digest), messageId: String(record.messageId),
1135
+ turn: Number(record.turn) || 0, clock: Number(record.clock) || 0,
1136
+ generation: Number(record.generation) || 0, epoch: Number(record.epoch) || 0,
1137
+ refs: Array.isArray(record.refs) ? record.refs : [],
1138
+ actions: record.actions && typeof record.actions === 'object' ? record.actions : {},
1139
+ at: stamp(),
1140
+ })
1141
+ binding.pendingInjections = kept.slice(-PENDING_INJECTION_MAX)
1142
+ return state
1143
+ })
1144
+ }
1145
+
1146
+ export function findPendingInjection(sessionId, digest, messageId = null) {
1147
+ if (!sessionId || !digest) return null
1148
+ const rows = (getSessionBinding(sessionId)?.pendingInjections || [])
1149
+ .filter(item => item?.digest === digest && pendingInjectionFresh(item)
1150
+ && (!item.actions?.media?.occurrenceIds?.length || item.messageId === messageId))
1151
+ return rows[rows.length - 1] || null
1152
+ }
1153
+
1154
+ export function forgetPendingInjection(sessionId, messageId) {
1155
+ if (!sessionId || !messageId) return null
1156
+ return updateState((state) => {
1157
+ const binding = state.sessions[sessionId]
1158
+ if (!binding?.pendingInjections) return state
1159
+ const kept = binding.pendingInjections.filter(item => item?.messageId !== messageId)
1160
+ if (kept.length) binding.pendingInjections = kept
1161
+ else delete binding.pendingInjections
1162
+ return state
1163
+ })
1164
+ }
1165
+
1166
+ export function markInjected(sessionId, ids, turn) {
1167
+ if (!sessionId) return
1168
+ return updateState((state) => {
1169
+ const binding = state.sessions[sessionId]
1170
+ if (!binding) return state
1171
+ // 锚点哨兵不进 injectedIds:它是一份常驻提示,不是会被 400 条上限挤掉的记忆 id。
1172
+ // 单独记 anchorPushed,避免长会话里周期性把 ~800 token 的锚点当新消息重投。
1173
+ const incoming = ids || []
1174
+ // 旧 binding 可能把哨兵存在 injectedIds 里:迁移为 anchorPushed,之后只按标记判断。
1175
+ const anchor = incoming.includes('__anchor__') || (binding.injectedIds || []).includes('__anchor__')
1176
+ const merged = [...new Set([
1177
+ ...(binding.injectedIds || []).filter((id) => id !== '__anchor__'),
1178
+ ...incoming.filter((id) => id !== '__anchor__'),
1179
+ ])]
1180
+ binding.injectedIds = merged.slice(-400)
1181
+ const owner = `legacy:${crypto.randomUUID()}`
1182
+ binding.injectionOwners = { ...(binding.injectionOwners || {}) }
1183
+ if (anchor) { binding.anchorPushed = true; binding.injectionOwners.anchorPushed = owner }
1184
+ const at = { ...(binding.injectedAt || {}) }
1185
+ for (const id of incoming) {
1186
+ at[id] = turn ?? Date.now()
1187
+ binding.injectionOwners[`id:${id}`] = owner
1188
+ }
1189
+ binding.injectedAt = at
1190
+ binding.lastInjectedTurn = turn ?? binding.lastInjectedTurn ?? 0
1191
+ // 主动记忆抑制要一个"最近一次真正注入了记忆"的墙钟时间;turn 号不能跨会话比较。
1192
+ binding.lastInjectedAt = stamp()
1193
+ return state
1194
+ })
1195
+ }
1196
+
1197
+ /**
1198
+ * Records why the last per-turn recall produced nothing usable. A degraded
1199
+ * recall used to be swallowed by an empty catch, which made "memory is dead"
1200
+ * indistinguishable from "nothing was relevant" (P0-1).
1201
+ */
1202
+ export function setRecallError(sessionId, message) {
1203
+ if (!sessionId) return
1204
+ const next = message ? String(message).slice(0, 500) : null
1205
+ return updateState((state) => {
1206
+ const binding = state.sessions[sessionId]
1207
+ if (!binding) return state
1208
+ if (next === null) {
1209
+ // Only clear when something is there, so a healthy turn costs no write.
1210
+ if (binding.lastRecallError) {
1211
+ delete binding.lastRecallError
1212
+ delete binding.lastRecallErrorAt
1213
+ }
1214
+ return state
1215
+ }
1216
+ if (binding.lastRecallError === next) return state
1217
+ binding.lastRecallError = next
1218
+ binding.lastRecallErrorAt = stamp()
1219
+ return state
1220
+ })
1221
+ }
1222
+
1223
+ export function releaseInjected(sessionId) { return updateState((state) => {
1224
+ const binding = state.sessions[sessionId]
1225
+ if (binding) {
1226
+ binding.injectedIds = []
1227
+ binding.injectedAt = {}
1228
+ binding.injectionEpoch = Number(binding.injectionEpoch || 0) + 1
1229
+ }
1230
+ return state
1231
+ })
1232
+ }
1233
+
1234
+ export function markReinjectPending(sessionId) {
1235
+ const binding = getSessionBinding(sessionId)
1236
+ return setSessionBinding(sessionId, { reinjectPending: true, injectionEpoch: Number(binding?.injectionEpoch || 0) + 1 })
1237
+ }
1238
+
1239
+ export function clearReinjectPending(sessionId) {
1240
+ return setSessionBinding(sessionId, { reinjectPending: false })
1241
+ }
1242
+
1243
+ export function getActiveCue(sessionId) {
1244
+ const binding = getSessionBinding(sessionId)
1245
+ const cue = binding?.activeCue
1246
+ if (!cue || typeof cue.id !== 'string') return null
1247
+ const at = Date.parse(cue.createdAt || '') || 0
1248
+ if (!at || Date.now() - at > 30 * 60 * 1000) return null
1249
+ return cue
1250
+ }
1251
+
1252
+ export function armCue(sessionId, cue) {
1253
+ return setSessionBinding(sessionId, {
1254
+ activeCue: {
1255
+ id: String(cue.id),
1256
+ text: String(cue.text || '').slice(0, 500),
1257
+ // A derived cue remembers the memory it came out of. Kept on the binding so the
1258
+ // source is auditable while the cue is live, and so the anti-loop rule (a cue-born
1259
+ // memory never sources another cue) can be checked against what actually happened.
1260
+ sourceId: cue.sourceId ? String(cue.sourceId) : null,
1261
+ recallQuery: cue.recallQuery ? String(cue.recallQuery).slice(0, 200) : null,
1262
+ createdAt: stamp(),
1263
+ },
1264
+ })
1265
+ }
1266
+
1267
+ export function consumeCue(sessionId, cueId) {
1268
+ const binding = getSessionBinding(sessionId)
1269
+ if (!binding?.activeCue || binding.activeCue.id !== cueId) return false
1270
+ setSessionBinding(sessionId, { activeCue: null })
1271
+ return true
1272
+ }
1273
+
1274
+ // The session's running mood is a retrieval lens on the binding, not a fact about
1275
+ // the user: it must never be recalled as a stored memory.
1276
+ export function setSessionMood(sessionId, mood) {
1277
+ // 给了 emotion 就以四轴为准,valence 只是投影;只有 valence 的旧形状原样存,不反推四轴。
1278
+ const emotion = normalizeEmotion(mood?.emotion ?? null)
1279
+ const bounded = (raw, min, max) => Math.max(min, Math.min(max, Number.isFinite(raw) ? raw : 0)) // 显式 0 是读数的一部分,不能用 `|| 默认值`
1280
+ return setSessionBinding(sessionId, { mood: {
1281
+ valence: emotion ? derivedValence(emotion) : bounded(mood?.valence, -1, 1),
1282
+ emotion, arousal: bounded(mood?.arousal, 0, 1), dominance: bounded(mood?.dominance, -1, 1), at: Date.now(),
1283
+ } })
1284
+ }
1285
+
1286
+ export function getSessionMood(sessionId) {
1287
+ return getSessionBinding(sessionId)?.mood || null
1288
+ }
1289
+
1290
+ export function setLastSleepAt(sessionId, at) {
1291
+ return setSessionBinding(sessionId, { lastSleepAt: at || stamp() })
1292
+ }
1293
+
1294
+ export function getLastSleepAt(sessionId) {
1295
+ return getSessionBinding(sessionId)?.lastSleepAt || null
1296
+ }
1297
+
1298
+ export function listSessionBindings() {
1299
+ const state = loadState()
1300
+ return Object.entries(state.sessions || {}).map(([sessionId, binding]) => ({ sessionId, ...binding }))
1301
+ }
1302
+
1303
+ // The idle clock that sleep consolidation measures against: the last turn the
1304
+ // plugin actually saw for this session.
1305
+ export function touchSession(sessionId) {
1306
+ return setSessionBinding(sessionId, { lastTurnAt: stamp() })
1307
+ }
1308
+
1309
+ export function getCycleState() {
1310
+ return loadState().cycle || {}
1311
+ }
1312
+
1313
+ export function setCycleState(patch) {
1314
+ return updateState((state) => {
1315
+ state.cycle = { ...(state.cycle || {}), ...(patch || {}) }
1316
+ return state
1317
+ }).cycle
1318
+ }
1319
+
1320
+ // An anniversary fires once per calendar day per memory, otherwise every turn of
1321
+ // the day would reopen the same feeling.
1322
+ export function wasAnniversaryShown(sessionId, memoryId, dayKey) {
1323
+ const shown = getSessionBinding(sessionId)?.anniversariesShown
1324
+ return Boolean(shown && shown[memoryId] === dayKey)
1325
+ }
1326
+
1327
+ export function markAnniversaryShown(sessionId, memoryId, dayKey) {
1328
+ const binding = getSessionBinding(sessionId)
1329
+ const shown = { ...(binding?.anniversariesShown || {}) }
1330
+ // Keep only the current day's keys so the map cannot grow without bound.
1331
+ const fresh = Object.fromEntries(Object.entries(shown).filter(([, v]) => v === dayKey))
1332
+ fresh[memoryId] = dayKey
1333
+ return setSessionBinding(sessionId, { anniversariesShown: fresh,
1334
+ injectionOwners: { ...(binding?.injectionOwners || {}), [`anniversary:${memoryId}`]: `legacy:${crypto.randomUUID()}` } })
1335
+ }
1336
+
1337
+ // ── repeated open loops ────────────────────────────────────────────────────────
1338
+ // A dated promise that has already slipped its day keeps coming back on an interval
1339
+ // instead of being forgotten. The regular 3-day nudge records its ids in
1340
+ // `injectedIds`, which is right for "I already mentioned this once" and wrong for
1341
+ // "it was never closed"; that is why the overdue leg keeps its own clock.
1342
+ //
1343
+ // `openLoopRemindedAt` maps memoryId -> ISO timestamp of the last time the overdue
1344
+ // nudge actually reached the prompt. Entries older than 90 days are dropped on
1345
+ // write so the map cannot grow without bound (an old key would not suppress
1346
+ // anything anyway — the interval has long elapsed).
1347
+ const OPEN_LOOP_REMIND_PRUNE_MS = 90 * 86_400_000
1348
+
1349
+ function localDayKeyOf(date) {
1350
+ return localCalendarDay(date)
1351
+ }
1352
+
1353
+ function prunedOpenLoopReminded(sessionId, now = new Date()) {
1354
+ const nowDate = now instanceof Date ? now : new Date(now)
1355
+ const nowMs = nowDate.getTime()
1356
+ const map = getSessionBinding(sessionId)?.openLoopRemindedAt
1357
+ const fresh = {}
1358
+ if (!map || typeof map !== 'object') return fresh
1359
+ for (const [memoryId, iso] of Object.entries(map)) {
1360
+ const at = Date.parse(String(iso || ''))
1361
+ if (!Number.isFinite(at)) continue
1362
+ if (nowMs - at > OPEN_LOOP_REMIND_PRUNE_MS) continue
1363
+ fresh[memoryId] = map[memoryId]
1364
+ }
1365
+ return fresh
1366
+ }
1367
+
1368
+ /**
1369
+ * Whether an overdue open loop was already repeated on this local calendar day.
1370
+ * A session binding written before this field existed has no map: it is a first
1371
+ * reminder, not an error.
1372
+ */
1373
+ export function wasOpenLoopRemindedToday(sessionId, memoryId, now = new Date()) {
1374
+ if (!sessionId || !memoryId) return false
1375
+ const iso = getSessionBinding(sessionId)?.openLoopRemindedAt?.[memoryId]
1376
+ const at = Date.parse(String(iso || ''))
1377
+ if (!Number.isFinite(at)) return false
1378
+ return localDayKeyOf(at) === localDayKeyOf(now)
1379
+ }
1380
+
1381
+ export function markOpenLoopReminded(sessionId, memoryId, at = new Date()) {
1382
+ if (!sessionId || !memoryId) return null
1383
+ // No binding means no conversation to remind; creating a stub from here would
1384
+ // write half a session into state.json.
1385
+ if (!getSessionBinding(sessionId)) return null
1386
+ const when = at instanceof Date ? at : new Date(at)
1387
+ const reminded = prunedOpenLoopReminded(sessionId, when)
1388
+ reminded[memoryId] = when.toISOString()
1389
+ return setSessionBinding(sessionId, { openLoopRemindedAt: reminded,
1390
+ injectionOwners: { ...(getSessionBinding(sessionId)?.injectionOwners || {}), [`nudge:${memoryId}`]: `legacy:${crypto.randomUUID()}` } })
1391
+ }
1392
+
1393
+ /**
1394
+ * 记下"这一回合投放了哪些一次性内容",供宿主把整轮回滚时撤销记账(§3.24)。
1395
+ * 同一个 hostTurn 多次调用会把 ids 并起来:一步里可能同时投了锚点、纪念日与 nudge。
1396
+ */
1397
+ export function recordInjectionRollback(sessionId, { hostTurn, ids = [], guideKey = null, nudgeIds = [], anniversaryIds = [] } = {}) {
1398
+ const turn = Number(hostTurn)
1399
+ if (!sessionId || !Number.isSafeInteger(turn) || turn < 0) return null
1400
+ if (!getSessionBinding(sessionId)) return null
1401
+ return updateState((state) => {
1402
+ const binding = state.sessions[sessionId]
1403
+ if (!binding) return state
1404
+ const previous = binding.injectionRollback
1405
+ const same = previous && previous.hostTurn === turn ? previous : { ids: [], nudgeIds: [], anniversaryIds: [] }
1406
+ binding.injectionRollback = {
1407
+ hostTurn: turn,
1408
+ epoch: Number(binding.injectionEpoch || 0),
1409
+ generation: Number(binding.scopeGeneration || 0),
1410
+ snapshot: { owners: { ...binding.injectionOwners }, injectedAt: { ...binding.injectedAt }, anchorPushed: binding.anchorPushed,
1411
+ lastInjectedUserMessageId: binding.lastInjectedUserMessageId, guideMessageAt: binding.guideMessageAt,
1412
+ anniversariesShown: { ...binding.anniversariesShown }, openLoopRemindedAt: { ...binding.openLoopRemindedAt } },
1413
+ ids: [...new Set([...(same.ids || []), ...ids])].slice(-400),
1414
+ nudgeIds: [...new Set([...(same.nudgeIds || []), ...nudgeIds])].slice(-40),
1415
+ anniversaryIds: [...new Set([...(same.anniversaryIds || []), ...anniversaryIds])].slice(-40),
1416
+ guideKey: guideKey || same.guideKey || null,
1417
+ }
1418
+ return state
1419
+ }).sessions[sessionId].injectionRollback
1420
+ }
1421
+
1422
+ /**
1423
+ * Roll back bookkeeping for a host turn that was returned before the request was sent.
1424
+ * The plugin records admission after handing messages to the host; a failed request
1425
+ * can therefore leave one-time guide and anchor state for messages absent from the
1426
+ * transcript. Roll back only the matching hostTurn, and only when the caller has
1427
+ * evidence from the transcript that the messages were not admitted. Return the revoked
1428
+ * records so the activity log can retain an observable signal.
1429
+ */
1430
+ export function rollbackInjectionForTurn(sessionId, hostTurn, { messageIds = [], epoch = null } = {}) {
1431
+ const turn = Number(hostTurn)
1432
+ if (!sessionId || !Number.isSafeInteger(turn)) return null
1433
+ let rolled = null
1434
+ updateState((state) => {
1435
+ const binding = state.sessions[sessionId]
1436
+ if (!binding) return state
1437
+ // Explicit host rollback evidence can revoke individual accepted messages. A model
1438
+ // request failure alone must never call this branch. Preserve immutable records.
1439
+ const targets = (binding.acceptedMemoryMessages || []).filter(record => record.hostTurn === turn
1440
+ && messageIds.includes(record.messageId) && (epoch === null || record.epoch === epoch))
1441
+ for (const accepted of targets.reverse()) {
1442
+ binding.revokedInjectionMessages = [...new Set([...(binding.revokedInjectionMessages || []), accepted.messageId])].slice(-400)
1443
+ if (accepted.epoch !== Number(binding.injectionEpoch || 0) || accepted.generation !== Number(binding.scopeGeneration || 0)) continue
1444
+ const media = accepted.media
1445
+ if (media?.scope && media.scope.incarnation === binding.mediaIncarnation && media.scope.libraryId === binding.libraryId
1446
+ && media.scope.contextKey === JSON.stringify(normalizeMemoryContext(binding.memoryContext))) {
1447
+ const pendingIds = new Set((binding.pendingMedia || []).map(item => item.occurrenceId))
1448
+ const consumedElsewhere = new Set((binding.acceptedMemoryMessages || [])
1449
+ .filter(record => !binding.revokedInjectionMessages.includes(record.messageId))
1450
+ .flatMap(record => record.media?.occurrences?.map(item => item.occurrenceId) || []))
1451
+ binding.pendingMedia = [...(media.occurrences || []).filter(item => !pendingIds.has(item.occurrenceId)
1452
+ && !consumedElsewhere.has(item.occurrenceId)), ...(binding.pendingMedia || [])]
1453
+ }
1454
+ for (const [key, saved] of Object.entries(accepted.effects || {})) {
1455
+ if (binding.injectionOwners?.[key] !== accepted.messageId) continue
1456
+ let previous = saved
1457
+ const visited = new Set()
1458
+ while (previous.owner && binding.revokedInjectionMessages.includes(previous.owner) && !visited.has(previous.owner)) {
1459
+ visited.add(previous.owner)
1460
+ const revoked = (binding.acceptedMemoryMessages || []).find(record => record.messageId === previous.owner)
1461
+ previous = revoked?.effects?.[key] || { ...previous, value: undefined, owner: null, clock: null }
1462
+ }
1463
+ const field = previous.field || key
1464
+ if (previous.id !== undefined && previous.id !== null) {
1465
+ if (previous.value === undefined) delete binding[field]?.[previous.id]
1466
+ else binding[field] = { ...(binding[field] || {}), [previous.id]: structuredClone(previous.value) }
1467
+ if (field === 'injectedAt' && previous.value === undefined) binding.injectedIds = (binding.injectedIds || []).filter(id => id !== previous.id)
1468
+ } else if (previous.value === undefined) delete binding[field]
1469
+ else binding[field] = structuredClone(previous.value)
1470
+ if (previous.owner) binding.injectionOwners[key] = previous.owner
1471
+ else delete binding.injectionOwners[key]
1472
+ if (previous.clock !== undefined && previous.clock !== null) binding.injectionOwnerClocks[key] = previous.clock
1473
+ else delete binding.injectionOwnerClocks?.[key]
1474
+ }
1475
+ for (const ref of accepted.refs) {
1476
+ if (accepted.effects?.[`id:${ref.id}`] || binding.injectionOwners?.[`id:${ref.id}`] !== accepted.messageId) continue
1477
+ delete binding.injectedAt?.[ref.id]
1478
+ binding.injectedIds = (binding.injectedIds || []).filter(id => id !== ref.id)
1479
+ delete binding.injectionOwners[`id:${ref.id}`]
1480
+ }
1481
+ for (const key of Object.keys(binding.injectionOwners || {})) {
1482
+ if (binding.injectionOwners[key] !== accepted.messageId) continue
1483
+ if (key.startsWith('anniversary:')) delete binding.anniversariesShown?.[key.slice(12)]
1484
+ if (key.startsWith('nudge:')) delete binding.openLoopRemindedAt?.[key.slice(6)]
1485
+ delete binding.injectionOwners[key]
1486
+ }
1487
+ }
1488
+ if (targets.length) rolled = { ids: targets.flatMap(record => record.refs.map(ref => ref.id)), guideKey: null, anniversaries: 0, nudges: 0 }
1489
+ const record = binding.injectionRollback
1490
+ if (!record || record.hostTurn !== turn) return state
1491
+ const snapshot = record.snapshot || {}
1492
+ const owners = binding.injectionOwners || {}
1493
+ const sameEpoch = record.epoch === Number(binding.injectionEpoch || 0)
1494
+ && Number(record.generation || 0) === Number(binding.scopeGeneration || 0)
1495
+ const owns = key => owners[key] === snapshot.owners?.[key] && (!owners[key] || owners[key].startsWith('legacy:'))
1496
+ const ids = new Set((record.ids || []).filter(id => sameEpoch && owns(`id:${id}`)
1497
+ && binding.injectedAt?.[id] === snapshot.injectedAt?.[id]))
1498
+ binding.injectedIds = (binding.injectedIds || []).filter(id => !ids.has(id))
1499
+ if (binding.injectedAt) for (const id of ids) delete binding.injectedAt[id]
1500
+ if (sameEpoch && ids.has('__anchor__') && owns('anchorPushed') && binding.anchorPushed === snapshot.anchorPushed) delete binding.anchorPushed
1501
+ if (sameEpoch && snapshot.lastInjectedUserMessageId !== undefined && owns('lastInjectedUserMessageId')
1502
+ && binding.lastInjectedUserMessageId === snapshot.lastInjectedUserMessageId) delete binding.lastInjectedUserMessageId
1503
+ if (sameEpoch && owns('guideRulesKey') && record.guideKey && binding.guideRulesKey === record.guideKey
1504
+ && binding.guideMessageAt === snapshot.guideMessageAt) {
1505
+ delete binding.guideRulesKey
1506
+ delete binding.guideMessageAt
1507
+ }
1508
+ if (sameEpoch && binding.anniversariesShown) for (const id of record.anniversaryIds || []) {
1509
+ if (owns(`anniversary:${id}`) && binding.anniversariesShown[id] === snapshot.anniversariesShown?.[id]) delete binding.anniversariesShown[id]
1510
+ }
1511
+ if (sameEpoch && binding.openLoopRemindedAt) for (const id of record.nudgeIds || []) {
1512
+ if (owns(`nudge:${id}`) && binding.openLoopRemindedAt[id] === snapshot.openLoopRemindedAt?.[id]) delete binding.openLoopRemindedAt[id]
1513
+ }
1514
+ rolled = {
1515
+ ids: [...ids],
1516
+ guideKey: record.guideKey || null,
1517
+ anniversaries: (record.anniversaryIds || []).length,
1518
+ nudges: (record.nudgeIds || []).length,
1519
+ }
1520
+ delete binding.injectionRollback
1521
+ return state
1522
+ })
1523
+ return rolled
1524
+ }
1525
+
1526
+ /**
1527
+ * 回合收尾、但那份记账不该作废时消费掉它(正常完成,或失败时注入的消息其实已经进了转录):
1528
+ * 东西已经投出去了,之后再来一条迟到的 error 事件也不该把它撤回(否则就是凭空的第二次锚点/规则消息)。
1529
+ */
1530
+ export function consumeInjectionRollback(sessionId, hostTurn) {
1531
+ const turn = Number(hostTurn)
1532
+ if (!sessionId || !Number.isSafeInteger(turn)) return false
1533
+ let consumed = false
1534
+ updateState((state) => {
1535
+ const binding = state.sessions[sessionId]
1536
+ if (!binding?.injectionRollback || binding.injectionRollback.hostTurn !== turn) return state
1537
+ delete binding.injectionRollback
1538
+ consumed = true
1539
+ return state
1540
+ })
1541
+ return consumed
1542
+ }
1543
+
1544
+ export function memoryDbPath(libraryId) {
1545
+ ensureDir(librariesDir())
1546
+ return effectiveVectorRoute() === 'managed-local' ? memuDbFor(libraryId) : path.join(librariesDir(), `${libraryId}.sqlite3`)
1547
+ }
1548
+
1549
+ export function globalDbPath() {
1550
+ ensureDir(dataDir())
1551
+ return effectiveVectorRoute() === 'managed-local' ? memuGlobalDbFor() : GLOBAL_DB()
1552
+ }
1553
+
1554
+ // Index files are parsed on every folder in the sidebar, and the parse (full
1555
+ // memory text) is the expensive part. Validity is mtime+size, so an external
1556
+ // change is always picked up. Callers mutate the returned object and save it
1557
+ // straight away — that is the shape every writer already had.
1558
+ const indexCache = new Map()
1559
+ const indexBases = new WeakMap()
1560
+
1561
+ // The sidebar paints a snapshot of both indexes, and nothing used to tell it when
1562
+ // that snapshot had gone stale: a memory written by a tool call, or from the
1563
+ // settings pane, stayed invisible until the tab was remounted. Readers poll this
1564
+ // counter and refetch only when it moves, so the cheap path is a single number —
1565
+ // no entry bodies, no disk read. In-process only; it resets on restart, and that
1566
+ // is fine because readers compare it against the number they last painted.
1567
+ let sidebarRevision = 0
1568
+
1569
+ function bumpMemoryRevision() {
1570
+ sidebarRevision += 1
1571
+ return sidebarRevision
1572
+ }
1573
+
1574
+ /** Monotonic within this process; see bumpMemoryRevision. */
1575
+ export function memoryRevision() {
1576
+ return sidebarRevision
1577
+ }
1578
+
1579
+ // Task E observability. A heartbeat is a client poll; a write event is a save that
1580
+ // actually reached disk. Both are in-process timestamps (they reset with the host),
1581
+ // and `memu_status` prints them so "the pane is stale" can be told apart from
1582
+ // "nothing was written" and from "the pane never polled".
1583
+ let lastBeatAt = null
1584
+ let lastWriteEvent = null
1585
+
1586
+ export function noteMemoryBeat() {
1587
+ lastBeatAt = Date.now()
1588
+ }
1589
+
1590
+ function noteMemoryWrite(kind, libraryId) {
1591
+ lastWriteEvent = { kind, libraryId: libraryId || null, at: Date.now() }
1592
+ }
1593
+
1594
+ export function syncActivity() {
1595
+ return { lastBeatAt, lastWrite: lastWriteEvent }
1596
+ }
1597
+
1598
+ // The counter above is per-process, and not every write happens in this process:
1599
+ // a tool call served by another module instance, a curator job, or a second window
1600
+ // can save an index while this counter stays put. That is exactly how the sidebar
1601
+ // ended up needing a manual Refresh — the heartbeat compared a number only the
1602
+ // writer's process could move. This fingerprint is the half both processes share:
1603
+ // size and mtime of every file a memory write touches. A handful of statSync calls
1604
+ // is cheaper than parsing one index, and it cannot go stale.
1605
+ export function memoryStamp() {
1606
+ const parts = []
1607
+ const add = (file, label) => {
1608
+ try {
1609
+ const info = fs.statSync(file)
1610
+ parts.push(label + ":" + info.size + ":" + Math.round(info.mtimeMs))
1611
+ } catch {
1612
+ parts.push(label + ":-")
1613
+ }
1614
+ }
1615
+ add(STATE_FILE(), "state")
1616
+ add(GLOBAL_INDEX(), "global")
1617
+ let names = []
1618
+ try { names = fs.readdirSync(indexDir()).filter((name) => name.endsWith(".json")).sort() } catch {}
1619
+ for (const name of names) add(path.join(indexDir(), name), name)
1620
+ return parts.join("|")
1621
+ }
1622
+
1623
+ function cachedIndex(file, loader, normalize) {
1624
+ const cached = indexCache.get(file)
1625
+ const stat = statOf(file)
1626
+ if (cached && stat && cached.mtimeMs === stat.mtimeMs && cached.size === stat.size) return indexSnapshot(cached.index, normalize)
1627
+ const index = loader()
1628
+ // Never cache a fallback produced by a failed read: it would keep shadowing the
1629
+ // real file (whose mtime/size did not change) even after the read recovers.
1630
+ if (stat && !readFailure(file)) indexCache.set(file, { mtimeMs: stat.mtimeMs, size: stat.size, index })
1631
+ return indexSnapshot(index, normalize)
1632
+ }
1633
+
1634
+ // `normalize` upgrades the *view* (a level an older version stored), while the baseline
1635
+ // stays exactly what is on disk. That split is what lets an ordinary write persist the
1636
+ // upgrade: `writeIndex` diffs against the baseline, sees the change, and checks the file
1637
+ // still matches what we read before accepting it.
1638
+ function indexSnapshot(index, normalize) {
1639
+ const baseline = structuredClone(index)
1640
+ const copy = structuredClone(index)
1641
+ if (normalize) normalize(copy)
1642
+ indexBases.set(copy, baseline)
1643
+ return copy
1644
+ }
1645
+
1646
+ function rememberIndex(file, index) {
1647
+ const stat = statOf(file)
1648
+ if (stat) indexCache.set(file, { mtimeMs: stat.mtimeMs, size: stat.size, index: structuredClone(index) })
1649
+ }
1650
+
1651
+ const indexWriteListeners = new Set()
1652
+ export function onPrivateIndexWrite(listener) {
1653
+ indexWriteListeners.add(listener)
1654
+ return () => indexWriteListeners.delete(listener)
1655
+ }
1656
+
1657
+ function writeIndex(file, index) {
1658
+ return withFileLock(file, () => {
1659
+ const base = indexBases.get(index)
1660
+ let next = index
1661
+ if (base) {
1662
+ const fresh = readJson(file, { version: 1, entries: {} })
1663
+ if (!validIndex(fresh)) {
1664
+ assertJsonShape(file, fresh, validIndex)
1665
+ throw new Error('memory index changed to an invalid shape; restore it before writing')
1666
+ }
1667
+ next = { ...fresh, entries: { ...(fresh.entries || {}) } }
1668
+ const before = base.entries || {}
1669
+ for (const id of new Set([...Object.keys(before), ...Object.keys(index.entries || {})])) {
1670
+ const value = index.entries?.[id]
1671
+ if (JSON.stringify(before[id]) === JSON.stringify(value)) continue
1672
+ if (JSON.stringify(before[id]) !== JSON.stringify(next.entries[id])) {
1673
+ const error = new Error(`memory ${id} changed concurrently; reload and retry`)
1674
+ error.code = 'DSH_MEMU_CONCURRENT_MODIFICATION'
1675
+ throw error
1676
+ }
1677
+ if (value === undefined) delete next.entries[id]
1678
+ else next.entries[id] = structuredClone(value)
1679
+ }
1680
+ }
1681
+ writeJson(file, next)
1682
+ rememberIndex(file, next)
1683
+ return next
1684
+ })
1685
+ }
1686
+
1687
+ export function loadPrivateIndex(libraryId) {
1688
+ if (!isSafeId(libraryId)) throw new Error('invalid library id')
1689
+ const file = path.join(indexDir(), `${libraryId}.json`)
1690
+ return cachedIndex(file, () => {
1691
+ let raw = readJson(file, null)
1692
+ if (raw !== null) raw = assertJsonShape(file, raw, validIndex)
1693
+ return raw && typeof raw === 'object' ? { version: 1, entries: raw.entries || {} } : { version: 1, entries: {} }
1694
+ }, (index) => {
1695
+ // An older version stored `visibility: 'session'` (a lease on one conversation).
1696
+ // That level is gone; libraries written by it are read as `shared` here — the one
1697
+ // chokepoint every reader and writer passes through — so no consumer has to know
1698
+ // the level ever existed. Only the view is upgraded; the baseline stays the raw file
1699
+ // so the next ordinary write persists the conversion (see `indexSnapshot`).
1700
+ migrateIndexVisibility(index, stamp())
1701
+ })
1702
+ }
1703
+
1704
+ /**
1705
+ * Persist one library index.
1706
+ *
1707
+ * `bumpRevision: false` exists for writes that cannot change what recall would find:
1708
+ * the injector's own bookkeeping (injectCount / lastInjectAt) runs *after* every
1709
+ * successful injection, so bumping the revision there guaranteed that the next turn's
1710
+ * recall and BM25 corpus both missed. The write still happens, still notifies
1711
+ * listeners and still records the write event — only the "something a cached result
1712
+ * depends on changed" claim is withheld, because it is not true.
1713
+ */
1714
+ export function savePrivateIndex(libraryId, index, { bumpRevision = true } = {}) {
1715
+ if (!isSafeId(libraryId)) throw new Error('invalid library id')
1716
+ if (!validIndex(index)) throw new Error('invalid memory index shape')
1717
+ const file = path.join(indexDir(), `${libraryId}.json`)
1718
+ const saved = writeIndex(file, index)
1719
+ if (bumpRevision) bumpMemoryRevision()
1720
+ noteMemoryWrite('private', libraryId)
1721
+ for (const listener of indexWriteListeners) {
1722
+ try { listener(libraryId, saved) } catch (error) { warn(`memory sidecar update failed: ${error?.message || error}`) }
1723
+ }
1724
+ }
1725
+
1726
+ export function loadGlobalIndex() {
1727
+ return cachedIndex(GLOBAL_INDEX(), () => {
1728
+ let raw = readJson(GLOBAL_INDEX(), null)
1729
+ if (raw !== null) raw = assertJsonShape(GLOBAL_INDEX(), raw, validIndex)
1730
+ return raw && typeof raw === 'object' ? { version: 1, entries: raw.entries || {} } : { version: 1, entries: {} }
1731
+ })
1732
+ }
1733
+
1734
+ function validIndex(value) {
1735
+ return value && typeof value === 'object' && !Array.isArray(value) && value.entries && typeof value.entries === 'object' && !Array.isArray(value.entries)
1736
+ && Object.values(value.entries).every(entry => entry && typeof entry === 'object' && !Array.isArray(entry))
1737
+ }
1738
+
1739
+ export function saveGlobalIndex(index, { bumpRevision = true } = {}) {
1740
+ if (!validIndex(index)) throw new Error('invalid memory index shape')
1741
+ writeIndex(GLOBAL_INDEX(), index)
1742
+ if (bumpRevision) bumpMemoryRevision()
1743
+ noteMemoryWrite('global', null)
1744
+ }
1745
+
1746
+ /** Counts only — no titles, no text. Cheap enough to call per folder. */
1747
+ export function summarizeIndex(index) {
1748
+ const entries = Object.values(index?.entries || {})
1749
+ const live = entries.filter((e) => e && !['archived', 'suppressed', 'expired', 'pending_review', 'superseded'].includes(e.status)
1750
+ && (!e.expiresAt || Date.parse(e.expiresAt) > Date.now()))
1751
+ return {
1752
+ total: entries.length,
1753
+ active: live.length,
1754
+ pinned: live.filter((e) => e.layer === 'must_remember').length,
1755
+ marginalized: entries.filter((e) => e.marginalized === true).length,
1756
+ openLoop: live.filter((e) => e.openLoop === true).length,
1757
+ archived: entries.filter((e) => e.status === 'archived').length,
1758
+ }
1759
+ }
1760
+
1761
+ /**
1762
+ * Read-modify-write of one library index. The mutator is synchronous, so two
1763
+ * calls can never interleave. Callers that await a backend write (MemU commit,
1764
+ * a consolidation job) must reach for this *after* the await — reading before it
1765
+ * and saving afterward leaves a lost-update window this lock closes.
1766
+ */
1767
+ export function updatePrivateIndex(libraryId, mutator) {
1768
+ if (!isSafeId(libraryId)) throw new Error('invalid library id')
1769
+ return withFileLock(path.join(indexDir(), `${libraryId}.json`), () => {
1770
+ indexCache.delete(path.join(indexDir(), `${libraryId}.json`))
1771
+ const index = loadPrivateIndex(libraryId)
1772
+ const next = mutator(index) || index
1773
+ if (next?.then) throw new Error('index mutators must be synchronous')
1774
+ savePrivateIndex(libraryId, next)
1775
+ return next
1776
+ })
1777
+ }
1778
+
1779
+ export function updateGlobalIndex(mutator) {
1780
+ return withFileLock(GLOBAL_INDEX(), () => {
1781
+ indexCache.delete(GLOBAL_INDEX())
1782
+ const index = loadGlobalIndex()
1783
+ const next = mutator(index) || index
1784
+ if (next?.then) throw new Error('index mutators must be synchronous')
1785
+ saveGlobalIndex(next)
1786
+ return next
1787
+ })
1788
+ }
1789
+
1790
+ export function newMemoryId(prefix = 'mem') {
1791
+ return `${prefix}-${Date.now().toString(36)}-${crypto.randomBytes(3).toString('hex')}`
1792
+ }
1793
+
1794
+ /**
1795
+ * Creates a managed backup of the local memory stores (plugin state, indexes,
1796
+ * prompts, attachments, the vector journal and every MemU database), then keeps
1797
+ * the newest BACKUP_KEEP complete ones. Retention, staging, checksums, atomic
1798
+ * publish and the shared lock all live in lib/backup.js so there is exactly one
1799
+ * place that decides what a backup is and which backup may be deleted.
1800
+ *
1801
+ * Returns the published directory: callers (engine switch, library delete,
1802
+ * scripts) treat the return value as a path.
1803
+ */
1804
+ export async function backupDatabases(options = {}) {
1805
+ // Pending bookkeeping changes live in memory for up to 50ms; a backup taken
1806
+ // before a flush would silently capture the previous state.
1807
+ let report
1808
+ try {
1809
+ report = await createBackup({ ...options, flushState })
1810
+ } catch (error) {
1811
+ // A refusal is the safety property working, not something to swallow: a
1812
+ // database the engine could not snapshot aborts the backup, and the reason
1813
+ // has to stay visible on the same channel the panel already reads.
1814
+ lastBackupReport = {
1815
+ at: stamp(),
1816
+ action: 'create',
1817
+ status: 'failed',
1818
+ code: error?.code || null,
1819
+ error: String(error?.message || error),
1820
+ name: null,
1821
+ dir: null,
1822
+ files: 0,
1823
+ bytes: 0,
1824
+ snapshots: [],
1825
+ pruned: [],
1826
+ pruneFailed: [],
1827
+ pendingCleanup: 0,
1828
+ notice: null,
1829
+ }
1830
+ throw error
1831
+ }
1832
+ lastBackupReport = { at: stamp(), action: 'create', ...report }
1833
+ return report.dir
1834
+ }
1835
+
1836
+ /** What the last backup/restore/prune did, so the outcome stays observable. */
1837
+ export function lastBackupReportView() {
1838
+ return lastBackupReport ? { ...lastBackupReport } : null
1839
+ }
1840
+
1841
+ /** Newest first, including entries that failed to complete (reported, never deleted). */
1842
+ export function listBackups() {
1843
+ return listBackupEntries()
1844
+ }
1845
+
1846
+ /** Removes one backup directory. The name is validated, never used as a path. */
1847
+ export function deleteBackup(name) {
1848
+ const result = deleteBackupEntry(name)
1849
+ lastBackupReport = { at: stamp(), action: 'delete', ...result }
1850
+ return { deleted: result.deleted, status: result.status }
1851
+ }
1852
+
1853
+ /**
1854
+ * Puts a backup back. The target is leased and its whole inventory is verified
1855
+ * before anything is written; the live root is saved as a safety backup next;
1856
+ * only then are files replaced. Failure leaves a recovery path: the safety
1857
+ * backup holds the state that was replaced and retention may not delete it.
1858
+ * A backup that predates the vector journal also retires the stale live
1859
+ * vector-active pointer, so recall falls back to text instead of querying
1860
+ * databases that no longer match the restored index.
1861
+ */
1862
+ export async function restoreBackup(name, { beforeRestore = null, keep = undefined } = {}) {
1863
+ const result = await restoreFromBackup(name, { beforeRestore, flushState, clearCaches, keep })
1864
+ lastBackupReport = { at: stamp(), action: 'restore', ...result }
1865
+ return result
1866
+ }
1867
+
1868
+ /** Drops the in-memory mirrors so the next read comes from disk. */
1869
+ export function clearCaches() {
1870
+ cache = null
1871
+ dirty = false
1872
+ if (flushTimer) { clearTimeout(flushTimer); flushTimer = null }
1873
+ indexCache.clear()
1874
+ // A restore or an external edit replaced the files under us; the sidebar must
1875
+ // not keep painting what it read before.
1876
+ bumpMemoryRevision()
1877
+ noteMemoryWrite('restore', null)
1878
+ }
1879
+
1880
+ /**
1881
+ * Explicit session-binding cleanup. Idle time is not an automatic deletion trigger;
1882
+ * this is a dry-run-first maintenance call. A binding with no parseable lastTurnAt
1883
+ * is never a candidate.
1884
+ */
1885
+ /**
1886
+ * Session-binding garbage collection.
1887
+ *
1888
+ * This deletes bindings, which is not recoverable. Three guards, because the old
1889
+ * version had none and a `--days 0` invocation wiped every binding in the store:
1890
+ *
1891
+ * · `olderThanDays` must be strictly positive. Zero/negative is a mistake, not a
1892
+ * "clean everything" request, so it throws instead of quietly becoming one.
1893
+ * · `isBusy(sessionId)` lets the caller veto a candidate: a session with a live
1894
+ * consolidation lease is in the middle of writing, and lastTurnAt is not the only
1895
+ * clock that matters.
1896
+ * · the apply pass re-reads each candidate inside `updateState`. A dry-run and an
1897
+ * apply are two separate loads, and a conversation that woke up in between must
1898
+ * not be deleted on the strength of the earlier snapshot.
1899
+ */
1900
+ export function pruneSessionBindings({ olderThanDays = 30, dryRun = true, now = Date.now(), isBusy = null } = {}) {
1901
+ const days = Number(olderThanDays)
1902
+ if (!Number.isFinite(days) || days <= 0) throw new Error('olderThanDays must be a positive number of days')
1903
+ const cutoff = Number(now) - days * 86_400_000
1904
+ const state = loadState()
1905
+ const candidates = []
1906
+ const skipped = []
1907
+ for (const [sessionId, binding] of Object.entries(state.sessions || {})) {
1908
+ const at = Date.parse(String(binding?.lastTurnAt || ''))
1909
+ if (!Number.isFinite(at) || at >= cutoff) continue
1910
+ if (typeof isBusy === 'function') {
1911
+ let busy = false
1912
+ try { busy = isBusy(sessionId) === true } catch (error) {
1913
+ // An unreadable lease file is not permission to delete: treat it as busy.
1914
+ busy = true
1915
+ warn(`prune-session-bindings: liveness check failed for ${sessionId} (${error?.message || error}); kept`)
1916
+ }
1917
+ if (busy) {
1918
+ skipped.push({ sessionId, reason: 'a consolidation lease is still live' })
1919
+ continue
1920
+ }
1921
+ }
1922
+ candidates.push({ sessionId, lastTurnAt: binding.lastTurnAt, libraryId: binding.libraryId || null })
1923
+ }
1924
+ const base = {
1925
+ dryRun: dryRun !== false,
1926
+ olderThanDays: days,
1927
+ cutoff: new Date(cutoff).toISOString(),
1928
+ candidates,
1929
+ skipped,
1930
+ }
1931
+ if (dryRun !== false || candidates.length === 0) return { ...base, removed: [] }
1932
+ const removed = []
1933
+ const revalidated = []
1934
+ updateState((next) => {
1935
+ for (const item of candidates) {
1936
+ const current = next.sessions?.[item.sessionId]
1937
+ if (!current) continue
1938
+ const at = Date.parse(String(current.lastTurnAt || ''))
1939
+ // Same predicate as the candidate pass, on the fresh copy: `at < cutoff` alone
1940
+ // would still delete a binding that just came back with a stale lastTurnAt.
1941
+ if (!Number.isFinite(at) || at >= cutoff) { revalidated.push(item.sessionId); continue }
1942
+ delete next.sessions[item.sessionId]
1943
+ removed.push(item.sessionId)
1944
+ }
1945
+ return next
1946
+ })
1947
+ return { ...base, removed, revalidated }
1948
+ }