dsh-memu-memory 1.4.2 → 1.4.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (389) hide show
  1. package/AGENTS.md +108 -110
  2. package/CHANGELOG.md +173 -868
  3. package/LICENSE +21 -21
  4. package/README.md +368 -374
  5. package/README.zh.md +354 -360
  6. package/assets/icon.svg +7 -7
  7. package/cordis.patch.yml +8 -8
  8. package/docs/active-memory-ab.md +279 -385
  9. package/docs/binding-lifecycle.md +99 -99
  10. package/docs/client-conventions.md +75 -75
  11. package/docs/contributing.md +217 -217
  12. package/docs/emotion-model-spec.md +247 -281
  13. package/docs/env-and-commands.md +149 -152
  14. package/docs/host-adaptation.md +339 -360
  15. package/docs/host-api.md +131 -137
  16. package/docs/host-versions.md +117 -120
  17. package/docs/mcp-porting.md +146 -146
  18. package/docs/memory-semantics.md +271 -259
  19. package/docs/pending-work.md +44 -51
  20. package/docs/troubleshooting.md +909 -854
  21. package/lib/active-memory.js +160 -165
  22. package/lib/activity-log.js +207 -207
  23. package/lib/auto-link/apply.js +248 -249
  24. package/lib/auto-link/candidates.js +163 -163
  25. package/lib/auto-link/decide.js +300 -300
  26. package/lib/auto-link/normalize.js +99 -99
  27. package/lib/auto-link/policy.js +42 -42
  28. package/lib/auto-link/suppression.js +101 -101
  29. package/lib/auto-link/terminology.js +311 -311
  30. package/lib/backup.js +1254 -1254
  31. package/lib/binding-diagnostics.js +634 -634
  32. package/lib/budget.js +118 -118
  33. package/lib/client.js +9820 -9751
  34. package/lib/commitment.js +178 -138
  35. package/lib/consolidation-ledger.js +434 -438
  36. package/lib/consolidation-receipt.js +386 -387
  37. package/lib/consolidation-snapshot.js +420 -405
  38. package/lib/consolidation-worker.js +240 -241
  39. package/lib/context.js +33 -33
  40. package/lib/curator-evidence.js +131 -131
  41. package/lib/curator-policy.js +198 -202
  42. package/lib/curator.js +1813 -1811
  43. package/lib/cycle.js +524 -513
  44. package/lib/diagnostics.js +524 -524
  45. package/lib/embedding-catalog.js +1051 -1055
  46. package/lib/embedding-download.js +637 -607
  47. package/lib/embedding-runtime.js +946 -946
  48. package/lib/engine.js +1103 -1103
  49. package/lib/entity-repair.js +285 -285
  50. package/lib/environment-check.js +394 -394
  51. package/lib/fork-model.js +312 -312
  52. package/lib/freshness.js +128 -121
  53. package/lib/global-graph.js +389 -389
  54. package/lib/graph.js +1193 -1193
  55. package/lib/host-surface.js +30 -30
  56. package/lib/inbound.js +284 -281
  57. package/lib/index.js +506 -511
  58. package/lib/inject.js +2639 -2619
  59. package/lib/lexicon-scope.js +143 -143
  60. package/lib/lexicon.js +1183 -1192
  61. package/lib/lifecycle-audit.js +37 -0
  62. package/lib/local-embedding-entry.js +145 -145
  63. package/lib/local-embedding-manager.js +306 -306
  64. package/lib/local-embedding-protocol.js +210 -210
  65. package/lib/local-embedding-worker.js +682 -682
  66. package/lib/local-vector-service.js +506 -453
  67. package/lib/maintenance-ledger.js +138 -0
  68. package/lib/maintenance-review.js +103 -0
  69. package/lib/maintenance-runner.js +267 -0
  70. package/lib/managed-runtime.js +118 -118
  71. package/lib/media.js +607 -513
  72. package/lib/memory.js +5035 -4941
  73. package/lib/memu-config.js +213 -213
  74. package/lib/memu.js +565 -565
  75. package/lib/migrate.js +200 -200
  76. package/lib/mood.js +300 -300
  77. package/lib/paths.js +453 -457
  78. package/lib/port-surface.js +82 -82
  79. package/lib/preset-mount.js +85 -0
  80. package/lib/preset-scope.js +126 -126
  81. package/lib/private-links.js +567 -567
  82. package/lib/private.js +2198 -2209
  83. package/lib/prompts/global-curator.md +135 -135
  84. package/lib/prompts/image-caption.md +1 -1
  85. package/lib/prompts/private-consolidation.coding.md +39 -39
  86. package/lib/prompts/private-consolidation.md +32 -32
  87. package/lib/prompts/private-consolidation.mixed.md +37 -37
  88. package/lib/prompts/private-consolidation.rp.md +47 -47
  89. package/lib/prompts/private-policy.coding.md +35 -35
  90. package/lib/prompts/private-policy.md +36 -36
  91. package/lib/prompts/private-policy.mixed.md +29 -29
  92. package/lib/prompts/private-policy.rp.md +43 -43
  93. package/lib/prompts/system-guide.coding.md +20 -20
  94. package/lib/prompts/system-guide.md +25 -25
  95. package/lib/prompts/system-guide.mixed.md +22 -22
  96. package/lib/prompts/system-guide.rp.md +23 -23
  97. package/lib/prompts.js +331 -331
  98. package/lib/recall-cache.js +212 -212
  99. package/lib/remote-summary.js +123 -123
  100. package/lib/rpc.js +2531 -2532
  101. package/lib/salient-wake.js +438 -438
  102. package/lib/snippet.js +125 -125
  103. package/lib/state.js +1948 -1928
  104. package/lib/stats.js +236 -236
  105. package/lib/temporal.js +345 -348
  106. package/lib/text-retrieval.js +992 -1001
  107. package/lib/text-similarity.js +305 -305
  108. package/lib/tokenizer-v2.js +271 -271
  109. package/lib/tools.js +1098 -1091
  110. package/lib/turn-log.js +545 -545
  111. package/lib/vector-migration.js +928 -930
  112. package/lib/vector-profile.js +1353 -1359
  113. package/lib/visibility.js +59 -59
  114. package/lib/webui/graph-LICENSE.txt +1 -1
  115. package/lib/webui/graph-view.bundle.js +2 -2
  116. package/lib/webui/graph-view.js +1171 -1175
  117. package/lib/webui/mark.svg +7 -7
  118. package/lib/webui/standalone.css +1178 -1178
  119. package/lib/webui/standalone.js +238 -238
  120. package/lib/webui.js +136 -136
  121. package/lib/worker-pool.js +1020 -979
  122. package/package.json +153 -153
  123. package/requirements.lock +34 -34
  124. package/scripts/acceptance-local.mjs +946 -946
  125. package/scripts/active-memory-ab-live.mjs +653 -655
  126. package/scripts/active-memory-ab.mjs +1302 -1302
  127. package/scripts/audit-memory-lifecycle.mjs +55 -0
  128. package/scripts/bench-recall.mjs +142 -142
  129. package/scripts/build-graph.mjs +44 -45
  130. package/scripts/chain-matrix.mjs +541 -541
  131. package/scripts/check-all.mjs +68 -74
  132. package/scripts/check-doc-drift.mjs +547 -547
  133. package/scripts/check-graph-browser.mjs +261 -261
  134. package/scripts/check-i18n.mjs +81 -83
  135. package/scripts/check-idle-compositing.mjs +61 -61
  136. package/scripts/check-seed-compat.mjs +115 -118
  137. package/scripts/check-text-format.mjs +55 -0
  138. package/scripts/curator-pair-calibrate.mjs +259 -259
  139. package/scripts/diagnose-bindings.mjs +176 -176
  140. package/scripts/drive-session.mjs +863 -864
  141. package/scripts/engine-smoke.mjs +69 -69
  142. package/scripts/entity-dedupe.mjs +110 -110
  143. package/scripts/lexicon-calibrate.mjs +230 -230
  144. package/scripts/lexicon-dedupe.mjs +318 -318
  145. package/scripts/local-runtime-install.mjs +142 -142
  146. package/scripts/local-runtime-verify.mjs +56 -56
  147. package/scripts/local-vector-verify.mjs +93 -93
  148. package/scripts/make-readme-shots.mjs +59 -59
  149. package/scripts/migrate-visibility.mjs +94 -94
  150. package/scripts/mock-llm.mjs +938 -903
  151. package/scripts/preview.mjs +58 -58
  152. package/scripts/prune-sessions.mjs +31 -34
  153. package/scripts/prune-turnlogs.mjs +29 -30
  154. package/scripts/prune-vectors.mjs +24 -24
  155. package/scripts/rebuild-auto-links.mjs +252 -252
  156. package/scripts/recall-bench.mjs +820 -820
  157. package/scripts/repetition-ab-scenarios.mjs +93 -93
  158. package/scripts/repetition-detector-snapshot.mjs +314 -314
  159. package/scripts/repetition-eval-live.mjs +360 -360
  160. package/scripts/repetition-eval.mjs +702 -702
  161. package/scripts/replay.mjs +705 -575
  162. package/scripts/setup.mjs +46 -46
  163. package/scripts/simulate-injection.mjs +299 -301
  164. package/tests/absorb-review.test.mjs +354 -354
  165. package/tests/activation.test.mjs +89 -89
  166. package/tests/active-memory-ab.test.mjs +745 -745
  167. package/tests/active-memory.test.mjs +129 -129
  168. package/tests/activity-log.test.mjs +126 -126
  169. package/tests/activity-wiring.test.mjs +155 -155
  170. package/tests/appendix-b.test.mjs +217 -217
  171. package/tests/appendix-b2.test.mjs +166 -166
  172. package/tests/audit-batch3.test.mjs +247 -247
  173. package/tests/audit-regression.test.mjs +275 -275
  174. package/tests/audit-safety.test.mjs +227 -227
  175. package/tests/auto-link-candidates.test.mjs +245 -245
  176. package/tests/auto-link-decide.test.mjs +512 -512
  177. package/tests/auto-link-migration.test.mjs +133 -133
  178. package/tests/backend-compensation.test.mjs +272 -272
  179. package/tests/backup.test.mjs +793 -793
  180. package/tests/binding-diagnostics.test.mjs +720 -720
  181. package/tests/browser.test.mjs +476 -476
  182. package/tests/client-export.test.mjs +521 -521
  183. package/tests/client-render.test.mjs +2008 -1728
  184. package/tests/coalesce.test.mjs +113 -113
  185. package/tests/commitment.test.mjs +243 -144
  186. package/tests/config.test.mjs +159 -159
  187. package/tests/consolidation-credential.test.mjs +330 -330
  188. package/tests/consolidation-feed.test.mjs +122 -122
  189. package/tests/consolidation-fork.test.mjs +1587 -1539
  190. package/tests/consolidation-ledger.test.mjs +389 -389
  191. package/tests/consolidation-snapshot.test.mjs +567 -505
  192. package/tests/consolidation-value.test.mjs +89 -89
  193. package/tests/context-scope.test.mjs +40 -40
  194. package/tests/cross-library-recall.test.mjs +269 -269
  195. package/tests/cue.test.mjs +58 -58
  196. package/tests/curator-absorb.test.mjs +444 -444
  197. package/tests/curator-calibrate.test.mjs +173 -173
  198. package/tests/curator-clusters.test.mjs +306 -306
  199. package/tests/curator-commit.test.mjs +325 -325
  200. package/tests/curator-contract.test.mjs +191 -191
  201. package/tests/curator-evidence.test.mjs +102 -102
  202. package/tests/curator-link.test.mjs +317 -317
  203. package/tests/curator-pairing.test.mjs +339 -339
  204. package/tests/curator-probe.test.mjs +490 -490
  205. package/tests/curator-review-mode.test.mjs +315 -315
  206. package/tests/curator.test.mjs +152 -152
  207. package/tests/cycle.test.mjs +567 -568
  208. package/tests/diagnostics.test.mjs +278 -278
  209. package/tests/disclosure.test.mjs +249 -249
  210. package/tests/doc-drift.test.mjs +342 -342
  211. package/tests/drive-session.test.mjs +152 -152
  212. package/tests/dynamic-rrf.test.mjs +182 -182
  213. package/tests/dynamic-threshold.test.mjs +52 -52
  214. package/tests/embedding-catalog.test.mjs +374 -374
  215. package/tests/embedding-download.test.mjs +529 -486
  216. package/tests/embedding-runtime.test.mjs +449 -449
  217. package/tests/emotion-chain.test.mjs +84 -84
  218. package/tests/emotion-contract.test.mjs +445 -445
  219. package/tests/engine.test.mjs +108 -108
  220. package/tests/entity-merge.test.mjs +278 -278
  221. package/tests/environment-check.test.mjs +187 -187
  222. package/tests/fact-version.test.mjs +146 -146
  223. package/tests/fixtures/active-memory-ab/README.md +56 -56
  224. package/tests/fixtures/active-memory-ab/cases/01-clean-dense-turn.json +351 -351
  225. package/tests/fixtures/active-memory-ab/cases/02-clean-thin-turn.json +122 -122
  226. package/tests/fixtures/active-memory-ab/cases/03-clean-starved-small.json +125 -125
  227. package/tests/fixtures/active-memory-ab/cases/04-clean-large-thin.json +137 -137
  228. package/tests/fixtures/active-memory-ab/cases/05-clean-half-step.json +166 -166
  229. package/tests/fixtures/active-memory-ab/cases/06-clean-duplicate-reread.json +197 -197
  230. package/tests/fixtures/active-memory-ab/cases/07-clean-recent-recall.json +125 -125
  231. package/tests/fixtures/active-memory-ab/cases/08-global-relevant.json +111 -111
  232. package/tests/fixtures/active-memory-ab/cases/09-global-irrelevant-conflict.json +158 -158
  233. package/tests/fixtures/active-memory-ab/cases/10-no-human-turn.json +97 -97
  234. package/tests/fixtures/active-memory-ab/cases/11-clean-scale-100.json +137 -137
  235. package/tests/fixtures/active-memory-ab/cases/12-clean-scale-1000.json +137 -137
  236. package/tests/fixtures/active-memory-ab/cases/13-clean-scale-5000.json +137 -137
  237. package/tests/fixtures/active-memory-ab/cases/14-clean-scale-20000.json +137 -137
  238. package/tests/fixtures/active-memory-ab/lead-ai-reviewed-reference.json +191 -191
  239. package/tests/fixtures/active-memory-ab/manifest.json +199 -199
  240. package/tests/fixtures/curator-pairs/labeled.v1.jsonl +90 -90
  241. package/tests/fixtures/lexicon-stub-hooks.mjs +15 -15
  242. package/tests/fixtures/lexicon-stub.mjs +284 -284
  243. package/tests/fixtures/mock-llm/reply.txt +1 -1
  244. package/tests/fixtures/recall-bench/01-paraphrase.json +183 -183
  245. package/tests/fixtures/recall-bench/02-exact.json +152 -152
  246. package/tests/fixtures/recall-bench/03-negation.json +172 -172
  247. package/tests/fixtures/recall-bench/04-no-answer.json +161 -161
  248. package/tests/fixtures/recall-bench/05-conflict.json +193 -193
  249. package/tests/fixtures/recall-bench/06-boundary.json +272 -272
  250. package/tests/fixtures/recall-bench/07-secret.json +190 -190
  251. package/tests/fixtures/recall-bench/08-coding.json +163 -163
  252. package/tests/fixtures/recall-bench-gold-candidates/01-paraphrase.json +193 -193
  253. package/tests/fixtures/recall-bench-gold-candidates/02-exact.json +197 -197
  254. package/tests/fixtures/recall-bench-gold-candidates/03-negation.json +244 -244
  255. package/tests/fixtures/recall-bench-gold-candidates/04-no-answer.json +189 -189
  256. package/tests/fixtures/recall-bench-gold-candidates/05-conflict.json +245 -245
  257. package/tests/fixtures/recall-bench-gold-candidates/06-boundary.json +279 -279
  258. package/tests/fixtures/recall-bench-gold-candidates/07-secret.json +224 -224
  259. package/tests/fixtures/recall-bench-gold-candidates/08-coding.json +218 -218
  260. package/tests/fixtures/repetition-eval/01-zh-rp.json +92 -92
  261. package/tests/fixtures/repetition-eval/02-en.json +96 -96
  262. package/tests/fixtures/repetition-eval/03-code.json +90 -90
  263. package/tests/fixtures/repetition-eval/04-names.json +115 -115
  264. package/tests/fixtures/repetition-eval/05-user-quote.json +95 -95
  265. package/tests/fixtures/repetition-eval/06-agreement.json +85 -85
  266. package/tests/fixtures/tokenizer-cases.mjs +27 -27
  267. package/tests/fork-model.test.mjs +345 -345
  268. package/tests/freshness.test.mjs +140 -140
  269. package/tests/global-graph.test.mjs +106 -106
  270. package/tests/global-lifecycle.test.mjs +149 -149
  271. package/tests/graph-cascade.test.mjs +363 -363
  272. package/tests/graph-view.test.mjs +414 -414
  273. package/tests/graph.test.mjs +371 -371
  274. package/tests/help-page.test.mjs +416 -416
  275. package/tests/hook-order.test.mjs +72 -72
  276. package/tests/humanlike.test.mjs +232 -232
  277. package/tests/hybrid-recall.test.mjs +610 -610
  278. package/tests/inbound.test.mjs +441 -441
  279. package/tests/inject-conflict.test.mjs +173 -173
  280. package/tests/inject-guide.test.mjs +513 -513
  281. package/tests/inject.test.mjs +384 -384
  282. package/tests/injection-budget-settings.test.mjs +35 -35
  283. package/tests/injection-budget.test.mjs +165 -165
  284. package/tests/injection-chain.test.mjs +442 -442
  285. package/tests/injection-intent-budget.test.mjs +92 -92
  286. package/tests/injection-rollback.test.mjs +428 -428
  287. package/tests/issue2-chain.test.mjs +169 -169
  288. package/tests/lexical-bm25.test.mjs +171 -171
  289. package/tests/lexicon-calibrate.test.mjs +48 -48
  290. package/tests/lexicon-dedupe.test.mjs +171 -171
  291. package/tests/lexicon-frequency.test.mjs +195 -195
  292. package/tests/lexicon-inject.test.mjs +459 -459
  293. package/tests/lexicon-perf.test.mjs +464 -464
  294. package/tests/lexicon-scope.test.mjs +256 -256
  295. package/tests/lexicon-ui.test.mjs +667 -667
  296. package/tests/lexicon.test.mjs +922 -922
  297. package/tests/lifecycle-audit.test.mjs +56 -0
  298. package/tests/loader-register.mjs +3 -3
  299. package/tests/loader.mjs +17 -17
  300. package/tests/local-embedding-entry.test.mjs +95 -95
  301. package/tests/local-embedding-env.test.mjs +51 -51
  302. package/tests/local-embedding-manager.test.mjs +494 -494
  303. package/tests/local-embedding-protocol.test.mjs +121 -121
  304. package/tests/local-embedding-worker.test.mjs +440 -440
  305. package/tests/local-vector-service.test.mjs +41 -0
  306. package/tests/maintenance-status.test.mjs +77 -0
  307. package/tests/maintenance.test.mjs +438 -0
  308. package/tests/managed-memory.test.mjs +1234 -1234
  309. package/tests/managed-runtime.test.mjs +72 -72
  310. package/tests/media-injection.test.mjs +225 -0
  311. package/tests/media.test.mjs +135 -135
  312. package/tests/memory-chain.test.mjs +169 -169
  313. package/tests/memory-fields.test.mjs +134 -134
  314. package/tests/memu-resident-route.test.mjs +130 -130
  315. package/tests/memu-resident.test.mjs +33 -33
  316. package/tests/migration-payload.test.mjs +40 -42
  317. package/tests/mock-llm.test.mjs +263 -225
  318. package/tests/mood.test.mjs +109 -109
  319. package/tests/multiprocess.test.mjs +29 -29
  320. package/tests/negation-polarity.test.mjs +135 -135
  321. package/tests/new-session-gate.test.mjs +617 -617
  322. package/tests/open-loop-date.test.mjs +416 -416
  323. package/tests/ops-hardening.test.mjs +209 -209
  324. package/tests/package-shipping.test.mjs +88 -88
  325. package/tests/pending-injection.test.mjs +107 -107
  326. package/tests/port-surface.test.mjs +138 -138
  327. package/tests/preset-mount.test.mjs +132 -0
  328. package/tests/preset-scope.test.mjs +212 -212
  329. package/tests/private-links.test.mjs +493 -493
  330. package/tests/prompt-semantics.test.mjs +51 -51
  331. package/tests/prompts.test.mjs +315 -315
  332. package/tests/query-decompose.test.mjs +62 -62
  333. package/tests/react-snapshot.test.mjs +24 -24
  334. package/tests/recall-bench.test.mjs +317 -317
  335. package/tests/recall-cache.test.mjs +292 -292
  336. package/tests/recall-corpus-eligibility.test.mjs +51 -51
  337. package/tests/recall-dedup.test.mjs +446 -446
  338. package/tests/recall-intent.test.mjs +172 -172
  339. package/tests/regression-sweep.test.mjs +311 -311
  340. package/tests/reminder-fairness.test.mjs +55 -0
  341. package/tests/remote.test.mjs +140 -140
  342. package/tests/rename.test.mjs +30 -30
  343. package/tests/repetition-detector-snapshot.test.mjs +231 -231
  344. package/tests/repetition-eval-live.test.mjs +177 -177
  345. package/tests/repetition-eval.test.mjs +373 -373
  346. package/tests/salience-domain.test.mjs +173 -173
  347. package/tests/salient-date.test.mjs +142 -142
  348. package/tests/salient-wake.test.mjs +389 -389
  349. package/tests/settings-beat.test.mjs +222 -222
  350. package/tests/settings-coverage.test.mjs +97 -97
  351. package/tests/settings-plumbing.test.mjs +79 -79
  352. package/tests/short-term.test.mjs +182 -166
  353. package/tests/sidebar-beat.test.mjs +213 -213
  354. package/tests/sidebar-refresh.test.mjs +123 -123
  355. package/tests/sidebar.test.mjs +102 -74
  356. package/tests/simulate-injection.test.mjs +76 -76
  357. package/tests/slot-similarity.test.mjs +153 -153
  358. package/tests/snippet.test.mjs +79 -79
  359. package/tests/source-kind.test.mjs +52 -52
  360. package/tests/speaker-provenance.test.mjs +120 -120
  361. package/tests/stale-maintenance.test.mjs +206 -131
  362. package/tests/state-gc.test.mjs +34 -34
  363. package/tests/state.test.mjs +155 -155
  364. package/tests/stats.test.mjs +112 -112
  365. package/tests/storage.test.mjs +125 -125
  366. package/tests/stubs/child-process-spy.mjs +14 -14
  367. package/tests/stubs/dsh-llm-pi-ai.js +13 -13
  368. package/tests/stubs/dsh-llm.js +5 -5
  369. package/tests/stubs/dsh-schedule.js +140 -140
  370. package/tests/stubs/dsh-session-query.js +26 -26
  371. package/tests/stubs/dsh-session.js +7 -7
  372. package/tests/stubs/dsh-tools.js +101 -101
  373. package/tests/temporal-repair.test.mjs +78 -0
  374. package/tests/temporal.test.mjs +124 -124
  375. package/tests/text-format.test.mjs +24 -0
  376. package/tests/tokenizer-v2.test.mjs +142 -142
  377. package/tests/tool-schema.test.mjs +126 -126
  378. package/tests/tools.test.mjs +810 -810
  379. package/tests/turn-log.test.mjs +487 -487
  380. package/tests/ui-defaults.test.mjs +57 -57
  381. package/tests/update-fields.test.mjs +138 -138
  382. package/tests/vector-gc.test.mjs +37 -37
  383. package/tests/vector-migration.test.mjs +810 -810
  384. package/tests/vector-profile.test.mjs +449 -449
  385. package/tests/visibility-migration.test.mjs +152 -152
  386. package/tests/webui-auth.test.mjs +963 -963
  387. package/tests/webui.test.mjs +421 -421
  388. package/tests/windows-env.test.mjs +89 -89
  389. package/tests/worker-lifecycle.test.mjs +1522 -1429
package/lib/cycle.js CHANGED
@@ -1,513 +1,524 @@
1
- import {
2
- getSettings, listSessionBindings, getLastSleepAt, setLastSleepAt,
3
- getCycleState, setCycleState, listLibrariesAll, archiveLibrary, setSessionBinding,
4
- deleteLibrary, restoreLibrary, normalizeCwd, inUseLibraryIds, archivedWhileInUse,
5
- } from './state.js'
6
- import { expireShortTerm, archiveExpiredDrafts, overdueOpenCommitments, EXPIRED_DRAFT_RETENTION_DAYS } from './memory.js'
7
- import { requestPrivateConsolidation, archivedSessionIdsOf, CONSOLIDATION_BACKLOG_EVENTS, CONSOLIDATION_PROBE_MINUTES } from './private.js'
8
- import { gcTurnLogs } from './turn-log.js'
9
- import { startGlobalCuration } from './curator.js'
10
- import { runVisibilityMigrationPass } from './migrate.js'
11
- import { runSalientWakePass } from './salient-wake.js'
12
- import { record } from './activity-log.js'
13
- import { ACTIVE_MEMORY_POLICY, suppressionReason } from './active-memory.js'
14
- import { clearSessionState, loadLedger, sessionState } from './consolidation-ledger.js'
15
-
16
- const SWEEP_MS = 5 * 60 * 1000
17
- // Long enough that the host has restored its session list and the agent objects
18
- // the fork needs, short enough that a user who opens the app and reads for a minute
19
- // still gets the catch-up before they type their next message.
20
- const STARTUP_SWEEP_MS = 8000
21
- // 「inbound 队列非空就跳过整理」只该挡住「会话马上要进下一回合」的抢跑(issue #5)。
22
- // 队列只在用户再次发言时才被排空(inject.js 在召回错误/abort/超预算时都会留下
23
- // pending + 30s retryAt),一次召回异常 + 用户从此不再发言 = pending 永久残留。
24
- // 所以只有队列非空 **且** 最近一次入站活动在热窗内才让路;凉掉的残骸不再永久阻断。
25
- const INBOUND_PENDING_HOT_MS = 15 * 60 * 1000
26
-
27
- function liveAgent(ctx, sessionId) {
28
- try {
29
- const agents = ctx.get?.('agents')
30
- return agents?.get?.(sessionId) || null
31
- } catch {
32
- return null
33
- }
34
- }
35
-
36
- function older(a, b) {
37
- const ta = Date.parse(a || '') || 0
38
- const tb = Date.parse(b || '') || 0
39
- return ta - tb
40
- }
41
-
42
- // Short-term expiry. Runs before the sleep pass on purpose: a draft that is already
43
- // past its deadline must not be offered to consolidation as something worth keeping,
44
- // and promoting a dead entry would resurrect text nobody asked for again.
45
- // 过期之后的保留期也在同一趟里结算:超期草稿改标 archived(不删除),
46
- // 免得"第二机会"变成永久占位。
47
- export function runShortTermPass(_ctx, { now = Date.now(), log = () => {} } = {}) {
48
- try {
49
- const result = expireShortTerm({ now })
50
- if (result.expired.length > 0) {
51
- log(`expired ${result.expired.length} short-term memor${result.expired.length === 1 ? 'y' : 'ies'} in ${result.libraries.length} library(ies)`)
52
- }
53
- let archived = { archived: [], libraries: [], skipped: 0 }
54
- try {
55
- archived = archiveExpiredDrafts({ now })
56
- if (archived.archived.length > 0) {
57
- log(`archived ${archived.archived.length} expired draft(s) past the retention window`)
58
- record({
59
- kind: 'check',
60
- scope: 'private',
61
- ok: true,
62
- message: `过期草稿归档 · ${archived.archived.length} 条(保留期 ${EXPIRED_DRAFT_RETENTION_DAYS} 天,不删除正文)`,
63
- detail: { ids: archived.archived.map((row) => row.id), libraries: archived.libraries },
64
- })
65
- }
66
- } catch (error) {
67
- log(`expired draft archiving failed: ${error?.message || error}`)
68
- }
69
- return { ...result, archived }
70
- } catch (error) {
71
- log(`short-term expiry failed: ${error?.message || error}`)
72
- return { expired: [], libraries: [], skipped: 0, archived: { archived: [], libraries: [], skipped: 0 }, error: String(error?.message || error) }
73
- }
74
- }
75
-
76
- // 逾期承诺的周期提醒:只写一条活动日志提示"该结案了",绝不改 status。
77
- // 承诺有没有兑现要靠转录证据(由整理任务书交给 worker),清理策略不替人裁决。
78
- // 同一条承诺 7 天内只提示一次,避免每天刷屏。
79
- const OVERDUE_REVIEW_DAYS = 7
80
- const OVERDUE_REVIEW_REPEAT_MS = 7 * 86_400_000
81
- const OVERDUE_REVIEW_KEYS = 500
82
-
83
- export function runOverdueReviewPass(_ctx, { now = Date.now(), log = () => {} } = {}) {
84
- try {
85
- const seen = { ...(getCycleState().overdueReviewAt || {}) }
86
- const noted = []
87
- const liveKeys = new Set()
88
- for (const lib of listLibrariesAll()) {
89
- if (lib.archived === true) continue
90
- const rows = overdueOpenCommitments({ libraryId: lib.id, now, minOverdueDays: OVERDUE_REVIEW_DAYS })
91
- for (const row of rows) liveKeys.add(`${lib.id}:${row.id}`)
92
- const due = rows.filter((row) => {
93
- const last = Date.parse(seen[`${lib.id}:${row.id}`] || '') || 0
94
- return !last || now - last >= OVERDUE_REVIEW_REPEAT_MS
95
- })
96
- if (due.length === 0) continue
97
- const at = new Date(now).toISOString()
98
- for (const row of due) {
99
- seen[`${lib.id}:${row.id}`] = at
100
- noted.push({ libraryId: lib.id, id: row.id, daysOverdue: row.daysOverdue })
101
- }
102
- record({
103
- kind: 'check',
104
- scope: 'private',
105
- libraryId: lib.id,
106
- ok: true,
107
- message: `欠账待结案 · ${due.length} 条承诺逾期 ≥${OVERDUE_REVIEW_DAYS} 天(整理时按证据结案)`,
108
- detail: { ids: due.map((row) => row.id), daysOverdue: due.map((row) => row.daysOverdue) },
109
- })
110
- log(`overdue commitments in ${lib.id}: ${due.length} past ${OVERDUE_REVIEW_DAYS} days`)
111
- }
112
- // 标记表只留还欠着的 + 60 天内的记录,上限 500,避免无限长。
113
- const cutoff = now - 60 * 86_400_000
114
- const kept = Object.entries(seen)
115
- .filter(([key, at]) => liveKeys.has(key) || (Date.parse(at) || 0) >= cutoff)
116
- .sort((a, b) => (Date.parse(b[1]) || 0) - (Date.parse(a[1]) || 0))
117
- .slice(0, OVERDUE_REVIEW_KEYS)
118
- if (noted.length > 0 || kept.length !== Object.keys(seen).length) {
119
- setCycleState({ overdueReviewAt: Object.fromEntries(kept) })
120
- }
121
- return { noted: noted.length, rows: noted }
122
- } catch (error) {
123
- log(`overdue commitment review failed: ${error?.message || error}`)
124
- return { noted: 0, rows: [], error: String(error?.message || error) }
125
- }
126
- }
127
-
128
- // The host's answer when a conversation has been deleted: `session "<id>" not
129
- // found`. It is not transient — retrying it is how a dead session used to be woken
130
- // up once an hour forever.
131
- //
132
- // `ENOENT` is deliberately not part of this list. A missing file is what a failed
133
- // *read* looks like, and captureSessionSnapshot marks every read failure retryable on
134
- // purpose (`consolidation-snapshot.js` failed(): "读失败,可重试" → retryable: true).
135
- // Matching the bare word here turned one unreadable transcript into `sessionGone`,
136
- // and the sweep then skips that conversation (`if (binding.sessionGone) continue`)
137
- // until `lib/inbound.js` clears the mark on some later human message — so a
138
- // quiet-but-alive conversation silently stopped being consolidated.
139
- export function isGoneSessionError(message) {
140
- return /session[^"]*".*" not found|no such session|session .*does not exist/i.test(String(message || ''))
141
- }
142
-
143
- // Sleep consolidation: after a conversation has been quiet for a while, the agent
144
- // gets one instruction to tidy the library it wrote during it. Failed attempts
145
- // back off, but never pretend that an unread transcript was consolidated.
146
- //
147
- // Two things this pass must not do. It must not wake a conversation that no longer
148
- // exists: the host answers "session not found" for it forever, and the retry curve
149
- // tops out at one hour, so one deleted chat used to be retried for the life of the
150
- // install. And it must not read "there are new turns" as "there is something worth
151
- // remembering" — `assessConsolidationValue` inspects the transcript first, and a
152
- // session that only exchanged greetings is marked asleep instead of being forked.
153
- export async function runSleepPass(ctx, { now = Date.now(), log = () => {}, limit = 2 } = {}) {
154
- const settings = getSettings()
155
- if (settings.sleepConsolidation !== true) return { ran: 0, skipped: 'disabled' }
156
- const idleMs = Math.max(1, Number(settings.sleepAfterIdleMinutes) || 2) * 60_000
157
- const probeMs = Math.max(1, Number(CONSOLIDATION_PROBE_MINUTES) || 15) * 60_000
158
- // One ledger read per sweep: pending backlog is the cheap水位 signal that does
159
- // not need a transcript read.
160
- let ledger = null
161
- try { ledger = loadLedger() } catch { ledger = null }
162
- // 归档会话事前跳过(issue #4 缺陷 3):宿主会在 agent/pre-step 拒绝祖先含归档会话
163
- // 的 subagent("the fork turn ended blocked"),撞两次就踩中 snapshot-failed 冻结。
164
- // 在候选阶段直接 continue:不占 budget 名额、不计失败、不推进游标。空注册表 =
165
- // 无成员信息,与 rpc.js 的读法一致,不当成「全是归档」。
166
- const archived = archivedSessionIdsOf(ctx)
167
- // 归档库同样不该再整理:宿主侧 archivedSessionIds 只覆盖「会话被归档」,拿不到
168
- // workspaceRegistry 时它为空集,等于完全不过滤;库被归档后仍照旧整理,会把新内容
169
- // 写进一个用户以为已经收起来的库(本机实测有这种会话在整理)。
170
- const libraries = new Map(listLibrariesAll().map(lib => [lib.id, lib]))
171
- const candidates = []
172
- for (const binding of listSessionBindings()) {
173
- if (binding.consolidationFork || !binding.lastTurnAt) continue
174
- if (binding.sessionGone) continue
175
- if (binding.libraryId && libraries.get(binding.libraryId)?.archived === true) continue
176
- if (archived?.size && archived.has(String(binding.sessionId))) continue
177
- const lastSleepAt = getLastSleepAt(binding.sessionId)
178
- const activeAt = Math.max(Date.parse(binding.lastTurnAt) || 0, Date.parse(binding.lastInboundAt) || 0, Date.parse(binding.lastAgentIdleAt) || 0)
179
- const idle = now - activeAt >= idleMs
180
- const newActivity = older(lastSleepAt, binding.lastTurnAt) < 0
181
- const state = ledger ? sessionState(binding.sessionId, ledger) : null
182
- // The ledger's backoff used to be write-only: failJob stored retryAt and nothing
183
- // ever read it, so a session that failed three times was retried on the very next
184
- // sweep, five minutes later, forever. `sleepRetryAt` below is a different clock —
185
- // that one delays the next *window*, this one delays the retry after a *failure*.
186
- if ((Date.parse(state?.retryAt || '') || 0) > now) continue
187
- const pendingEvents = state?.pending && (!state.checked || state.pending.throughSeq > state.checked.throughSeq)
188
- ? Number(state.pending.throughSeq) - (Number.isSafeInteger(Number(state.checked?.throughSeq)) ? Number(state.checked.throughSeq) : -1)
189
- : 0
190
- const backlog = pendingEvents >= CONSOLIDATION_BACKLOG_EVENTS
191
- const neverSlept = !lastSleepAt
192
- const lastProbe = Date.parse(binding.lastConsolidationProbeAt || '') || 0
193
- const probeDue = newActivity && now - lastProbe >= probeMs
194
- // Idle time alone is not new evidence: after a successful window the sleep
195
- // stamp already covers the transcript, so a quiet idle sweep must not fork it again.
196
- if (!newActivity && !backlog) continue
197
- // Three independent reasons to look: idle (normal), a real pending backlog
198
- // (watermark), or a bounded probe when new activity has arrived but not enough
199
- // to know its size yet. The probe reads the transcript and decides without a
200
- // fork, so it costs CPU, not tokens.
201
- if (!idle && !backlog && !neverSlept && !probeDue) continue
202
- // Running includes a long-lived asynchronous tool. Waiting is not proof that
203
- // the conversation ended, and a fork should not race its active agent.
204
- if (liveAgent(ctx, binding.sessionId)?.status === 'running') continue
205
- // Fresh inbound queue = a step may be about to race the fork. A queue that has
206
- // gone cold (no inbound activity within INBOUND_PENDING_HOT_MS) is residue from
207
- // a recall error that only the user's next message would drain — it must not
208
- // block idle consolidation forever (issue #5).
209
- const inboundFreshAt = Math.max(Date.parse(binding.lastInboundAt) || 0, Date.parse(binding.lastInboundOutcome?.at) || 0)
210
- if (binding.inbound?.pending?.length && now - inboundFreshAt < INBOUND_PENDING_HOT_MS) continue
211
- if ((Date.parse(binding.sleepRetryAt || '') || 0) > now) continue
212
- // 冻结退避(1.3.10):snapshot-failed 熔断期不再每扫重读快照/种子、不占 budget 名额。
213
- // 但冻结后来了新真人回合(lastTurnAt 越过 frozenAt)立刻让路——新事件改快照哈希、
214
- // 闸门本就会放行;退避只挡「无新活动的重复扫入」,不惩罚新活动。独立字段,不碰
215
- // sleepRetryAt(后者不因新消息清零,复用它会挡死冻结期新活动)。
216
- const frozenUntil = Date.parse(binding.sleepFrozenUntil || '') || 0
217
- if (frozenUntil > now && (Date.parse(binding.lastTurnAt) || 0) <= (Date.parse(binding.sleepFrozenAt) || 0)) continue
218
- // Backlog first, then real idle, then cheap probes: a sweep with a limited
219
- // budget must not let probe-only sessions crowd out work that is actually due.
220
- candidates.push({ binding, activeAt, trigger: idle ? 'idle' : 'backlog', priority: backlog ? 3 : idle ? 2 : 1 })
221
- }
222
- // Newest first within the same priority: a catch-up run after the app was closed
223
- // should tidy what the user just lived through, not a week-old chat that has
224
- // already waited this long.
225
- candidates.sort((a, b) => (b.priority - a.priority) || (b.activeAt - a.activeAt))
226
- const budget = Math.max(1, Math.min(10, Number(limit) || 2))
227
- let ran = 0
228
- for (const { binding, trigger } of candidates.slice(0, budget)) {
229
- if (binding.useLibrary === false) {
230
- setLastSleepAt(binding.sessionId)
231
- continue
232
- }
233
- // One path for every session: both backends now read the transcript
234
- // themselves and neither touches the user's own chat — remote through the
235
- // configured endpoint, agent through a seeded fork (requestHistoricalConsolidation).
236
- // A live session used to be consolidated in place, which is exactly what put
237
- // a queued draft above the user's composer and then left a housekeeping turn
238
- // in their transcript for good.
239
- const suppression = suppressionReason({
240
- now,
241
- lastSleepAt: getLastSleepAt(binding.sessionId),
242
- lastInjectedAt: binding.lastInjectedAt || null,
243
- consolidatedCooldownMinutes: Number(settings.activeMemoryCooldownMinutes ?? ACTIVE_MEMORY_POLICY.consolidatedCooldownMinutes),
244
- recallCooldownMinutes: Number(settings.activeMemoryRecallCooldownMinutes ?? ACTIVE_MEMORY_POLICY.recallCooldownMinutes),
245
- })
246
- // 「刚注入过记忆」只压空闲收尾,不压水位/探针:后者先读转录再决定,不合并不 fork。
247
- const blocked = suppression && !(trigger === 'backlog' && suppression === 'recent-recall')
248
- if (blocked) {
249
- log(`sleep consolidation suppressed for ${binding.sessionId}: ${suppression}`)
250
- record({
251
- kind: 'check', scope: 'private', sessionId: binding.sessionId, libraryId: binding.libraryId || null, ok: true,
252
- message: '闲时检查抑制:' + suppression,
253
- detail: { trigger, reason: suppression, lastSleepAt: getLastSleepAt(binding.sessionId), lastInjectedAt: binding.lastInjectedAt || null },
254
- })
255
- continue
256
- }
257
- try {
258
- const result = await requestPrivateConsolidation(ctx, binding.sessionId, { trigger })
259
- if (result?.ok) {
260
- // 证据不足(low-score)不是"已整理":不推进游标、不计数,等空闲越过饥饿阈值
261
- // 或后续证据变多再检查。否则这句话会被永久跳过。
262
- if (result.settled === false) {
263
- // 任何没结算的结果都要记探针时间,不只是「水位不足」那两种:low-score 也
264
- // 会读一遍转录并打分,不记就会在每次 5 分钟扫描里把同一段重读一遍。
265
- const patch = { lastConsolidationProbeAt: new Date(now).toISOString(), sleepFrozenUntil: null, sleepFrozenAt: null }
266
- // snapshot-failed 冻结:写独立退避字段,候选阶段守卫据此跳过无新活动的重复
267
- // 扫入;新真人回合到来即让路。非冻结的 deferral 顺手清掉可能残留的冻结字段。
268
- if (result.reasonCode === 'snapshot-failed-too-many' && result.cooldownUntil) {
269
- patch.sleepFrozenUntil = result.cooldownUntil
270
- patch.sleepFrozenAt = result.frozenAt || null
271
- }
272
- setSessionBinding(binding.sessionId, patch)
273
- log(`sleep consolidation deferred for ${binding.sessionId}: ${result.skipped || 'not settled'}`)
274
- continue
275
- }
276
- // Only cover activity this pass began with, not new messages during it.
277
- // 多窗收口(issue #4 缺陷 2):`settled` 是「本窗完成」的语义,ledger 的
278
- // lastSleepSeq 已随本窗回执推进(private.js advanceSleepCursor),不会重扫;
279
- // 但粗游标 lastSleepAt 只有在整段(remaining === 0)扫完时才推平——否则
280
- // 尾段 < 200 事件(backlog 够不着)的会话会在候选阶段 `!newActivity && !backlog` 处被永久跳过。
281
- if (!(Number(result.remaining) > 0)) {
282
- setLastSleepAt(binding.sessionId, binding.lastTurnAt)
283
- }
284
- setSessionBinding(binding.sessionId, {
285
- sleepRetryAt: null, sleepAttempts: 0, lastSleepError: null,
286
- sleepFrozenUntil: null, sleepFrozenAt: null,
287
- lastConsolidationProbeAt: new Date(now).toISOString(),
288
- })
289
- // A terminal policy skip (greetings, no new events) advances the sleep stamp
290
- // but is not a verified worker run; `ran` must keep that distinction.
291
- if (!result.skipped) ran += 1
292
- } else if (isGoneSessionError(result?.error)) {
293
- setSessionBinding(binding.sessionId, { sessionGone: true, sessionGoneAt: new Date(now).toISOString(), sleepRetryAt: null, sleepAttempts: 0, sleepFrozenUntil: null, sleepFrozenAt: null, lastSleepError: String(result.error) })
294
- try { clearSessionState(binding.sessionId) } catch {}
295
- log(`sleep consolidation dropped ${binding.sessionId}: the conversation no longer exists`)
296
- } else {
297
- const attempts = Number(binding.sleepAttempts || 0) + 1
298
- setSessionBinding(binding.sessionId, { sleepAttempts: attempts, lastSleepError: result?.error || 'not settled', sleepRetryAt: new Date(now + Math.min(60, 2 ** Math.min(attempts, 6)) * 60_000).toISOString() })
299
- log(`sleep consolidation skipped for ${binding.sessionId}: ${result?.error || 'not queued'}`)
300
- }
301
- } catch (error) {
302
- if (isGoneSessionError(error?.message)) {
303
- setSessionBinding(binding.sessionId, { sessionGone: true, sessionGoneAt: new Date(now).toISOString(), sleepRetryAt: null, sleepAttempts: 0, sleepFrozenUntil: null, sleepFrozenAt: null, lastSleepError: String(error.message) })
304
- try { clearSessionState(binding.sessionId) } catch {}
305
- continue
306
- }
307
- // A missing service or transient file failure can heal without a new turn.
308
- const attempts = Number(binding.sleepAttempts || 0) + 1
309
- setSessionBinding(binding.sessionId, { sleepAttempts: attempts, lastSleepError: String(error?.message || error), sleepRetryAt: new Date(now + Math.min(60, 2 ** Math.min(attempts, 6)) * 60_000).toISOString() })
310
- log(`sleep consolidation failed for ${binding.sessionId}: ${error?.message || error}`)
311
- }
312
- }
313
- return { ran, considered: candidates.length }
314
- }
315
-
316
- // 休眠 GC 的 turn-log 分配(设计文档 §3.4):对每个绑定做两条件检查——日志无未结算
317
- // 增量(max seqEnd ≤ lastSleepSeq)且会话 ≥30 天无任何活动 → 删缓存文件。便宜检查:
318
- // 只读绑定表 + 文件 stat/mtime,仅对已闲置满期的少数绑定才读日志内容找 max seqEnd;
319
- // 没有日志文件的绑定直接跳过。异常只 warn,绝不绊倒 sweep 的其他 pass。
320
- export function runTurnLogGcPass(_ctx, { now = Date.now(), log = () => {} } = {}) {
321
- try {
322
- const result = gcTurnLogs(listSessionBindings(), { now })
323
- if (result.deleted.length > 0) log(`turn-log gc deleted ${result.deleted.length} idle turn log(s)`)
324
- return result
325
- } catch (error) {
326
- log(`turn-log gc failed: ${error?.message || error}`)
327
- return { deleted: [], kept: [], error: String(error?.message || error) }
328
- }
329
- }
330
-
331
- // Background global curation: turn the conversations that happened since the last
332
- // run into shared memory, using whichever session is live as the curator's parent.
333
- export async function runCurationPass(ctx, { now = Date.now(), log = () => {} } = {}) {
334
- const settings = getSettings()
335
- const hours = Number(settings.autoCurateEveryHours) || 0
336
- if (!(hours > 0)) return { ran: 0, skipped: 'disabled' }
337
- const lastRunAt = Date.parse(getCycleState().lastCurateAt || '') || 0
338
- if (now - lastRunAt < hours * 3_600_000) return { ran: 0, skipped: 'not-due' }
339
-
340
- const limit = Math.max(1, Math.min(30, Number(settings.autoCurateSessionLimit) || 8))
341
- const due = listSessionBindings()
342
- .filter((b) => !b.consolidationFork && b.lastTurnAt && older(b.lastTurnAt, new Date(lastRunAt).toISOString()) > 0)
343
- .sort((a, b) => String(b.lastTurnAt).localeCompare(String(a.lastTurnAt)))
344
- .slice(0, limit)
345
- .map((b) => b.sessionId)
346
- if (due.length === 0) return { ran: 0, skipped: 'no-new-sessions' }
347
-
348
- const parent = due.find((id) => liveAgent(ctx, id))
349
- || listSessionBindings().filter((b) => !b.consolidationFork).map((b) => b.sessionId).find((id) => liveAgent(ctx, id))
350
- if (!parent) {
351
- // Deliberately not recording the attempt: the next sweep retries, and a run
352
- // that never started must not push the schedule forward.
353
- log('auto curation waiting for a live session to host the curator')
354
- return { ran: 0, skipped: 'no-live-parent' }
355
- }
356
- try {
357
- const job = await startGlobalCuration(ctx, { sessionIds: due, parentSessionId: parent, model: settings.curatorModel })
358
- setCycleState({ lastCurateAt: new Date(now).toISOString(), lastCurateJob: job?.id || null })
359
- record({ kind: 'curate', scope: 'global', ok: true, message: `自动提炼启动:${due.length} 个会话`, detail: { sessions: due.length, jobId: job?.id || null, parent } })
360
- return { ran: due.length, job }
361
- } catch (error) {
362
- log(`auto curation failed: ${error?.message || error}`)
363
- record({ kind: 'curate', scope: 'global', ok: false, level: 'error', message: '自动提炼失败:' + String(error?.message || error), detail: { sessions: due.length } })
364
- return { ran: 0, error: String(error?.message || error) }
365
- }
366
- }
367
-
368
- // A library leaves daily use when its workspace is removed from DSH — which is a
369
- // pure unregister: the folder and every session log stay on disk. So the trigger is
370
- // the workspace registry, never `fs.existsSync`. A deleted folder is not "removed
371
- // from DSH", and a folder taken out of the sidebar still exists.
372
- function registeredScopes(ctx) {
373
- let registry = null
374
- try { registry = ctx.get?.('workspaceRegistry') } catch { return null }
375
- if (!registry || typeof registry.list !== 'function') return null
376
- let list
377
- try { list = registry.list() } catch { return null }
378
- if (!Array.isArray(list)) return null
379
- // An empty registry is not trusted: a fresh install with no workspace yet must not
380
- // archive every library ever created.
381
- const scopes = list.map((ws) => normalizeCwd(ws?.path)).filter(Boolean)
382
- return { scopes: new Set(scopes), trustworthy: scopes.length > 0 }
383
- }
384
-
385
- // 同一个库每 5 分钟重复一条「因为在用所以没归档」只会把宿主日志淹掉,说一次就够;
386
- // 归档或复活都会清掉这个标记。
387
- const inUseSkipNotified = new Set()
388
-
389
- function noteInUseSkip(libraryId, scopeKey, log) {
390
- if (inUseSkipNotified.has(libraryId)) return
391
- inUseSkipNotified.add(libraryId)
392
- log(`kept library ${libraryId}: workspace ${scopeKey} is not in the DSH registry, but a live conversation still uses it`)
393
- }
394
-
395
- export function runLibraryHousekeeping(ctx, { now = Date.now(), log = () => {} } = {}) {
396
- const settings = getSettings()
397
- const archived = []
398
- const revived = []
399
- const purged = []
400
- const skippedInUse = []
401
- const purgeCandidates = []
402
- const registry = registeredScopes(ctx)
403
- // 一次读盘算出「哪些库还有存活绑定」。这是归档判定缺的那一半:注册表只回答
404
- // 「这个目录是不是 DSH 工作区」,不回答「这个库还有没有人用」。
405
- const inUse = inUseLibraryIds()
406
-
407
- for (const lib of listLibrariesAll()) {
408
- const used = inUse.has(lib.id)
409
- if (lib.archived === true) {
410
- const scopeBack = Boolean(registry?.trustworthy && registry.scopes.has(lib.scopeKey))
411
- // 误归档(旧版扫描把在用的非工作区库归档了):库还在被读取写入,就该回到列表。
412
- // 用户主动归档(archivedBy === 'user')不动——那是用户的决定。
413
- const misArchived = archivedWhileInUse(lib, { inUse: used, now })
414
- if (scopeBack || misArchived) {
415
- if (restoreLibrary(lib.id).ok) {
416
- revived.push(lib.id)
417
- inUseSkipNotified.delete(lib.id)
418
- if (misArchived && !scopeBack) log(`revived library ${lib.id}: a live conversation still uses it`)
419
- }
420
- continue
421
- }
422
- const days = Number(settings.purgeArchivedAfterDays) || 0
423
- // 在用的库永不进入清理候选:purge 只看年龄,一旦把活跃库算进去就是数据丢失。
424
- if (days > 0 && !used && lib.archivedAt && (now - (Date.parse(lib.archivedAt) || now)) / 86_400_000 >= days) {
425
- purgeCandidates.push(lib.id)
426
- }
427
- continue
428
- }
429
- if (!registry?.trustworthy) continue
430
- if (!lib.scopeKey || lib.scopeKey === '__default__') continue
431
- if (!registry.scopes.has(lib.scopeKey)) {
432
- // 关键判据:不在工作区注册表 ≠ 没人用。IM 插件数据目录、profile 下的目录都不在
433
- // 注册表里,却可能有会话正在高频读写(2026-11-21 报告:建成 176 秒被归档,之后
434
- // 9 小时 172 条活动、6 次召回全成功,而 UI 里库已消失)。
435
- if (used) {
436
- skippedInUse.push(lib.id)
437
- noteInUseSkip(lib.id, lib.scopeKey, log)
438
- continue
439
- }
440
- archiveLibrary(lib.id, { by: 'sweep' })
441
- inUseSkipNotified.delete(lib.id)
442
- archived.push(lib.id)
443
- log(`archived library ${lib.id}: workspace ${lib.scopeKey} is no longer registered in DSH`)
444
- }
445
- }
446
- return { archived, revived, purged, purgeCandidates, skippedInUse, registrySeen: Boolean(registry?.trustworthy) }
447
- }
448
-
449
- export async function runCyclePasses(ctx, options = {}) {
450
- const shortTerm = runShortTermPass(ctx, options)
451
- const overdue = runOverdueReviewPass(ctx, options)
452
- // turn-log GC 挂在 sweep 顺带跑(§3.4),只做 stat/绑定表级别的便宜检查。
453
- const turnLogs = runTurnLogGcPass(ctx, options)
454
- const sleep = await runSleepPass(ctx, options)
455
- const curate = await runCurationPass(ctx, options)
456
- const libraries = runLibraryHousekeeping(ctx, options)
457
- // A library can still be on disk in the removed `session` format when the plugin
458
- // updated mid-flight. Reads are already normalized, so this only keeps the files in
459
- // step with the code (see lib/migrate.js); it is cheap and idempotent.
460
- const migrated = runVisibilityMigrationPass({ log: options.log })
461
- // 工单 E:纪念日到点唤醒。放在最后:它是唯一会碰宿主 schedule 服务的 pass,宿主没
462
- // 这个服务时只返回 `{skipped:'service'}`;即使它整体失败,上面的短期过期、睡眠整理、
463
- // 自动提炼和库迁移已经跑完,下一次 sweep 照常重试。
464
- const salientWake = await runSalientWakePass(ctx, { now: options.now ?? new Date(), log: options.log }).catch((error) => {
465
- try { options.log?.(`salient wake pass failed: ${error?.message || error}`) } catch {}
466
- return { created: 0, cleaned: 0, skipped: 0, errors: 1 }
467
- })
468
- return { shortTerm, overdue, turnLogs, sleep, curate, libraries, migrated, salientWake }
469
- }
470
-
471
- // DSH has no host scheduler a plugin can register a *global* job with
472
- // (`ctx.schedule` is session-bound and delivers a prompt into that session, which
473
- // is the wrong shape for a plugin-wide sweep), so this owns a plain interval.
474
- // Cordis' own `ctx.interval` is preferred because the host disposes it with the
475
- // plugin scope; the raw fallback is unref'd so a plugin timer can never be the
476
- // reason the app stays alive. Everything this reads is a persisted timestamp, so a
477
- // missed sweep is recovered on the next one.
478
- export function registerCycle(ctx, { log = () => {} } = {}) {
479
- let running = false
480
- const tick = async () => {
481
- if (running) return
482
- running = true
483
- try {
484
- await runCyclePasses(ctx, { log })
485
- } catch (error) {
486
- log(`cycle sweep failed: ${error?.message || error}`)
487
- } finally {
488
- running = false
489
- }
490
- }
491
- // One catch-up sweep shortly after load. The sweep timer only exists while the app
492
- // is open, so a conversation that ended while it was closed used to wait for the
493
- // next idle window — and the next message always resets that clock, which is how a
494
- // whole evening could pass without a single consolidation. The delay lets the host
495
- // finish restoring sessions and agents first; the pass itself is bounded (two
496
- // sessions) so a long list of stale bindings cannot turn startup into a stampede.
497
- const startup = setTimeout(() => { void tick() }, STARTUP_SWEEP_MS)
498
- startup.unref?.()
499
- // Property access on an uninjected service throws in cordis, so the probe itself
500
- // is guarded; a host without the timer service falls back instead of failing.
501
- let scoped = null
502
- try { scoped = typeof ctx.interval === 'function' ? ctx : null } catch { scoped = null }
503
- if (scoped) {
504
- // cordis' ctx.interval returns a *disposer function*, not a Node timer id —
505
- // clearInterval() on it is a silent no-op and the sweep would keep running
506
- // after plugin unload/HMR. Call the disposer.
507
- const dispose = scoped.interval(() => { void tick() }, SWEEP_MS)
508
- return () => { try { clearTimeout(startup) } catch {} try { dispose?.() } catch {} }
509
- }
510
- const timer = setInterval(() => { void tick() }, SWEEP_MS)
511
- timer.unref?.()
512
- return () => { clearTimeout(startup); clearInterval(timer) }
513
- }
1
+ import {
2
+ getSettings, listSessionBindings, getLastSleepAt, setLastSleepAt,
3
+ getCycleState, setCycleState, listLibrariesAll, archiveLibrary, setSessionBinding,
4
+ deleteLibrary, restoreLibrary, normalizeCwd, inUseLibraryIds, archivedWhileInUse,
5
+ } from './state.js'
6
+ import { expireShortTerm, archiveExpiredDrafts, overdueOpenCommitments, EXPIRED_DRAFT_RETENTION_DAYS } from './memory.js'
7
+ import { requestPrivateConsolidation, archivedSessionIdsOf, CONSOLIDATION_BACKLOG_EVENTS, CONSOLIDATION_PROBE_MINUTES } from './private.js'
8
+ import { gcTurnLogs } from './turn-log.js'
9
+ import { startGlobalCuration } from './curator.js'
10
+ import { runVisibilityMigrationPass } from './migrate.js'
11
+ import { runSalientWakePass } from './salient-wake.js'
12
+ import { runMaintenancePass } from './maintenance-runner.js'
13
+ export { runMaintenancePass } from './maintenance-runner.js'
14
+ import { record } from './activity-log.js'
15
+ import { ACTIVE_MEMORY_POLICY, suppressionReason } from './active-memory.js'
16
+ import { clearSessionState, loadLedger, sessionState } from './consolidation-ledger.js'
17
+
18
+ const SWEEP_MS = 5 * 60 * 1000
19
+ // Long enough that the host has restored its session list and the agent objects
20
+ // the fork needs, short enough that a user who opens the app and reads for a minute
21
+ // still gets the catch-up before they type their next message.
22
+ const STARTUP_SWEEP_MS = 8000
23
+ // 「inbound 队列非空就跳过整理」只该挡住「会话马上要进下一回合」的抢跑(issue #5)。
24
+ // 队列只在用户再次发言时才被排空(inject.js 在召回错误/abort/超预算时都会留下
25
+ // pending + 30s retryAt),一次召回异常 + 用户从此不再发言 = pending 永久残留。
26
+ // 所以只有队列非空 **且** 最近一次入站活动在热窗内才让路;凉掉的残骸不再永久阻断。
27
+ const INBOUND_PENDING_HOT_MS = 15 * 60 * 1000
28
+
29
+ function liveAgent(ctx, sessionId) {
30
+ try {
31
+ const agents = ctx.get?.('agents')
32
+ return agents?.get?.(sessionId) || null
33
+ } catch {
34
+ return null
35
+ }
36
+ }
37
+
38
+ function older(a, b) {
39
+ const ta = Date.parse(a || '') || 0
40
+ const tb = Date.parse(b || '') || 0
41
+ return ta - tb
42
+ }
43
+
44
+ // Short-term expiry. Runs before the sleep pass on purpose: a draft that is already
45
+ // past its deadline must not be offered to consolidation as something worth keeping,
46
+ // and promoting a dead entry would resurrect text nobody asked for again.
47
+ // 过期之后的保留期也在同一趟里结算:超期草稿改标 archived(不删除),
48
+ // 免得"第二机会"变成永久占位。
49
+ export function runShortTermPass(_ctx, { now = Date.now(), log = () => {} } = {}) {
50
+ try {
51
+ const result = expireShortTerm({ now })
52
+ if (result.expired.length > 0) {
53
+ log(`expired ${result.expired.length} short-term memor${result.expired.length === 1 ? 'y' : 'ies'} in ${result.libraries.length} library(ies)`)
54
+ }
55
+ let archived = { archived: [], libraries: [], skipped: 0 }
56
+ try {
57
+ archived = archiveExpiredDrafts({ now })
58
+ if (archived.archived.length > 0) {
59
+ log(`archived ${archived.archived.length} expired draft(s) past the retention window`)
60
+ record({
61
+ kind: 'check',
62
+ scope: 'private',
63
+ ok: true,
64
+ message: `过期草稿归档 · ${archived.archived.length} 条(保留期 ${EXPIRED_DRAFT_RETENTION_DAYS} 天,不删除正文)`,
65
+ detail: { ids: archived.archived.map((row) => row.id), libraries: archived.libraries },
66
+ })
67
+ }
68
+ } catch (error) {
69
+ log(`expired draft archiving failed: ${error?.message || error}`)
70
+ }
71
+ return { ...result, archived }
72
+ } catch (error) {
73
+ log(`short-term expiry failed: ${error?.message || error}`)
74
+ return { expired: [], libraries: [], skipped: 0, archived: { archived: [], libraries: [], skipped: 0 }, error: String(error?.message || error) }
75
+ }
76
+ }
77
+
78
+ // 逾期承诺的周期提醒:只写一条活动日志提示"该结案了",绝不改 status。
79
+ // 承诺有没有兑现要靠转录证据(由整理任务书交给 worker),清理策略不替人裁决。
80
+ // 同一条承诺 7 天内只提示一次,避免每天刷屏。
81
+ const OVERDUE_REVIEW_DAYS = 7
82
+ const OVERDUE_REVIEW_REPEAT_MS = 7 * 86_400_000
83
+ const OVERDUE_REVIEW_KEYS = 500
84
+
85
+ export function runOverdueReviewPass(_ctx, { now = Date.now(), log = () => {} } = {}) {
86
+ try {
87
+ const seen = { ...(getCycleState().overdueReviewAt || {}) }
88
+ const cursors = { ...(getCycleState().overdueReviewCursor || {}) }
89
+ const noted = []
90
+ const liveKeys = new Set()
91
+ for (const lib of listLibrariesAll()) {
92
+ if (lib.archived === true) continue
93
+ const rows = overdueOpenCommitments({ libraryId: lib.id, now, minOverdueDays: OVERDUE_REVIEW_DAYS, allCandidates: true })
94
+ .sort((a, b) => a.id.localeCompare(b.id))
95
+ for (const row of rows) liveKeys.add(`${lib.id}:${row.id}`)
96
+ let cursor = cursors[lib.id] || {}
97
+ // The traversal survives the capped seen table without repeating prefixes.
98
+ if (cursor.completedAt && now - Date.parse(cursor.completedAt) < OVERDUE_REVIEW_REPEAT_MS) continue
99
+ if (cursor.completedAt) cursor = {}
100
+ const remaining = rows.filter(row => !cursor.lastId || row.id.localeCompare(cursor.lastId) > 0)
101
+ const due = remaining.filter((row) => {
102
+ const last = Date.parse(seen[`${lib.id}:${row.id}`] || '') || 0
103
+ return !last || now - last >= OVERDUE_REVIEW_REPEAT_MS
104
+ }).slice(0, 20)
105
+ const lastId = due.at(-1)?.id || cursor.lastId || null
106
+ cursors[lib.id] = { lastId, completedAt: !due.length || !rows.some(row => lastId && row.id.localeCompare(lastId) > 0) ? new Date(now).toISOString() : null }
107
+ if (due.length === 0) continue
108
+ const at = new Date(now).toISOString()
109
+ for (const row of due) {
110
+ seen[`${lib.id}:${row.id}`] = at
111
+ noted.push({ libraryId: lib.id, id: row.id, daysOverdue: row.daysOverdue })
112
+ }
113
+ record({
114
+ kind: 'check',
115
+ scope: 'private',
116
+ libraryId: lib.id,
117
+ ok: true,
118
+ message: `欠账待结案 · ${due.length} 条承诺逾期 ≥${OVERDUE_REVIEW_DAYS} 天(整理时按证据结案)`,
119
+ detail: { ids: due.map((row) => row.id), daysOverdue: due.map((row) => row.daysOverdue) },
120
+ })
121
+ log(`overdue commitments in ${lib.id}: ${due.length} past ${OVERDUE_REVIEW_DAYS} days`)
122
+ }
123
+ // 标记表只留还欠着的 + 60 天内的记录,上限 500,避免无限长。
124
+ const cutoff = now - 60 * 86_400_000
125
+ const kept = Object.entries(seen)
126
+ .filter(([key, at]) => liveKeys.has(key) || (Date.parse(at) || 0) >= cutoff)
127
+ .sort((a, b) => (Date.parse(b[1]) || 0) - (Date.parse(a[1]) || 0))
128
+ .slice(0, OVERDUE_REVIEW_KEYS)
129
+ if (noted.length > 0 || kept.length !== Object.keys(seen).length || JSON.stringify(cursors) !== JSON.stringify(getCycleState().overdueReviewCursor || {})) {
130
+ setCycleState({ overdueReviewAt: Object.fromEntries(kept), overdueReviewCursor: cursors })
131
+ }
132
+ return { noted: noted.length, rows: noted }
133
+ } catch (error) {
134
+ log(`overdue commitment review failed: ${error?.message || error}`)
135
+ return { noted: 0, rows: [], error: String(error?.message || error) }
136
+ }
137
+ }
138
+
139
+ // The host's answer when a conversation has been deleted: `session "<id>" not
140
+ // found`. It is not transient — retrying it is how a dead session used to be woken
141
+ // up once an hour forever.
142
+ //
143
+ // `ENOENT` is deliberately not part of this list. A missing file is what a failed
144
+ // *read* looks like, and captureSessionSnapshot marks every read failure retryable on
145
+ // purpose (`consolidation-snapshot.js` failed(): "读失败,可重试" → retryable: true).
146
+ // Matching the bare word here turned one unreadable transcript into `sessionGone`,
147
+ // and the sweep then skips that conversation (`if (binding.sessionGone) continue`)
148
+ // until `lib/inbound.js` clears the mark on some later human message — so a
149
+ // quiet-but-alive conversation silently stopped being consolidated.
150
+ export function isGoneSessionError(message) {
151
+ return /session[^"]*".*" not found|no such session|session .*does not exist/i.test(String(message || ''))
152
+ }
153
+
154
+ // Sleep consolidation: after a conversation has been quiet for a while, the agent
155
+ // gets one instruction to tidy the library it wrote during it. Failed attempts
156
+ // back off, but never pretend that an unread transcript was consolidated.
157
+ //
158
+ // Two things this pass must not do. It must not wake a conversation that no longer
159
+ // exists: the host answers "session not found" for it forever, and the retry curve
160
+ // tops out at one hour, so one deleted chat used to be retried for the life of the
161
+ // install. And it must not read "there are new turns" as "there is something worth
162
+ // remembering" — `assessConsolidationValue` inspects the transcript first, and a
163
+ // session that only exchanged greetings is marked asleep instead of being forked.
164
+ export async function runSleepPass(ctx, { now = Date.now(), log = () => {}, limit = 2 } = {}) {
165
+ const settings = getSettings()
166
+ if (settings.sleepConsolidation !== true) return { ran: 0, skipped: 'disabled' }
167
+ const idleMs = Math.max(1, Number(settings.sleepAfterIdleMinutes) || 2) * 60_000
168
+ const probeMs = Math.max(1, Number(CONSOLIDATION_PROBE_MINUTES) || 15) * 60_000
169
+ // One ledger read per sweep: pending backlog is the cheap水位 signal that does
170
+ // not need a transcript read.
171
+ let ledger = null
172
+ try { ledger = loadLedger() } catch { ledger = null }
173
+ // 宿主会在 agent/pre-step 拒绝祖先含归档会话的 subagent;提前过滤,
174
+ // 避免将确定不可执行的整理记为 snapshot-failed。
175
+ // 在候选阶段直接 continue:不占 budget 名额、不计失败、不推进游标。空注册表 =
176
+ // 无成员信息,与 rpc.js 的读法一致,不当成「全是归档」。
177
+ const archived = archivedSessionIdsOf(ctx)
178
+ // 归档库同样不该再整理:宿主侧 archivedSessionIds 只覆盖「会话被归档」,拿不到
179
+ // workspaceRegistry 时它为空集,因此还需检查库的归档状态,防止向归档库继续写入。
180
+ const libraries = new Map(listLibrariesAll().map(lib => [lib.id, lib]))
181
+ const candidates = []
182
+ for (const binding of listSessionBindings()) {
183
+ if (binding.consolidationFork || !binding.lastTurnAt) continue
184
+ if (binding.sessionGone) continue
185
+ if (binding.libraryId && libraries.get(binding.libraryId)?.archived === true) continue
186
+ if (archived?.size && archived.has(String(binding.sessionId))) continue
187
+ const lastSleepAt = getLastSleepAt(binding.sessionId)
188
+ const activeAt = Math.max(Date.parse(binding.lastTurnAt) || 0, Date.parse(binding.lastInboundAt) || 0, Date.parse(binding.lastAgentIdleAt) || 0)
189
+ const idle = now - activeAt >= idleMs
190
+ const newActivity = older(lastSleepAt, binding.lastTurnAt) < 0
191
+ const state = ledger ? sessionState(binding.sessionId, ledger) : null
192
+ // The ledger's backoff used to be write-only: failJob stored retryAt and nothing
193
+ // ever read it, so a session that failed three times was retried on the very next
194
+ // sweep, five minutes later, forever. `sleepRetryAt` below is a different clock —
195
+ // that one delays the next *window*, this one delays the retry after a *failure*.
196
+ if ((Date.parse(state?.retryAt || '') || 0) > now) continue
197
+ const pendingEvents = state?.pending && (!state.checked || state.pending.throughSeq > state.checked.throughSeq)
198
+ ? Number(state.pending.throughSeq) - (Number.isSafeInteger(Number(state.checked?.throughSeq)) ? Number(state.checked.throughSeq) : -1)
199
+ : 0
200
+ const backlog = pendingEvents >= CONSOLIDATION_BACKLOG_EVENTS
201
+ const neverSlept = !lastSleepAt
202
+ const lastProbe = Date.parse(binding.lastConsolidationProbeAt || '') || 0
203
+ const probeDue = newActivity && now - lastProbe >= probeMs
204
+ // Idle time alone is not new evidence: after a successful window the sleep
205
+ // stamp already covers the transcript, so a quiet idle sweep must not fork it again.
206
+ if (!newActivity && !backlog) continue
207
+ // Three independent reasons to look: idle (normal), a real pending backlog
208
+ // (watermark), or a bounded probe when new activity has arrived but not enough
209
+ // to know its size yet. The probe reads the transcript and decides without a
210
+ // fork, so it costs CPU, not tokens.
211
+ if (!idle && !backlog && !neverSlept && !probeDue) continue
212
+ // Running includes a long-lived asynchronous tool. Waiting is not proof that
213
+ // the conversation ended, and a fork should not race its active agent.
214
+ if (liveAgent(ctx, binding.sessionId)?.status === 'running') continue
215
+ // Fresh inbound queue = a step may be about to race the fork. A queue that has
216
+ // gone cold (no inbound activity within INBOUND_PENDING_HOT_MS) is residue from
217
+ // a recall error that only the user's next message would drain — it must not
218
+ // block idle consolidation forever (issue #5).
219
+ const inboundFreshAt = Math.max(Date.parse(binding.lastInboundAt) || 0, Date.parse(binding.lastInboundOutcome?.at) || 0)
220
+ if (binding.inbound?.pending?.length && now - inboundFreshAt < INBOUND_PENDING_HOT_MS) continue
221
+ if ((Date.parse(binding.sleepRetryAt || '') || 0) > now) continue
222
+ // 冻结退避(1.3.10):snapshot-failed 熔断期不再每扫重读快照/种子、不占 budget 名额。
223
+ // 但冻结后来了新真人回合(lastTurnAt 越过 frozenAt)立刻让路——新事件改快照哈希、
224
+ // 闸门本就会放行;退避只挡「无新活动的重复扫入」,不惩罚新活动。独立字段,不碰
225
+ // sleepRetryAt(后者不因新消息清零,复用它会挡死冻结期新活动)。
226
+ const frozenUntil = Date.parse(binding.sleepFrozenUntil || '') || 0
227
+ if (frozenUntil > now && (Date.parse(binding.lastTurnAt) || 0) <= (Date.parse(binding.sleepFrozenAt) || 0)) continue
228
+ // Backlog first, then real idle, then cheap probes: a sweep with a limited
229
+ // budget must not let probe-only sessions crowd out work that is actually due.
230
+ candidates.push({ binding, activeAt, trigger: idle ? 'idle' : 'backlog', priority: backlog ? 3 : idle ? 2 : 1 })
231
+ }
232
+ // Newest first within the same priority: a catch-up run after the app was closed
233
+ // should tidy what the user just lived through, not a week-old chat that has
234
+ // already waited this long.
235
+ candidates.sort((a, b) => (b.priority - a.priority) || (b.activeAt - a.activeAt))
236
+ const budget = Math.max(1, Math.min(10, Number(limit) || 2))
237
+ let ran = 0
238
+ for (const { binding, trigger } of candidates.slice(0, budget)) {
239
+ if (binding.useLibrary === false) {
240
+ setLastSleepAt(binding.sessionId)
241
+ continue
242
+ }
243
+ // One path for every session: both backends now read the transcript
244
+ // themselves and neither touches the user's own chat — remote through the
245
+ // configured endpoint, agent through a seeded fork (requestHistoricalConsolidation).
246
+ // A live session used to be consolidated in place, which is exactly what put
247
+ // a queued draft above the user's composer and then left a housekeeping turn
248
+ // in their transcript for good.
249
+ const suppression = suppressionReason({
250
+ now,
251
+ lastSleepAt: getLastSleepAt(binding.sessionId),
252
+ lastInjectedAt: binding.lastInjectedAt || null,
253
+ consolidatedCooldownMinutes: Number(settings.activeMemoryCooldownMinutes ?? ACTIVE_MEMORY_POLICY.consolidatedCooldownMinutes),
254
+ recallCooldownMinutes: Number(settings.activeMemoryRecallCooldownMinutes ?? ACTIVE_MEMORY_POLICY.recallCooldownMinutes),
255
+ })
256
+ // 「刚注入过记忆」只压空闲收尾,不压水位/探针:后者先读转录再决定,不合并不 fork。
257
+ const blocked = suppression && !(trigger === 'backlog' && suppression === 'recent-recall')
258
+ if (blocked) {
259
+ log(`sleep consolidation suppressed for ${binding.sessionId}: ${suppression}`)
260
+ record({
261
+ kind: 'check', scope: 'private', sessionId: binding.sessionId, libraryId: binding.libraryId || null, ok: true,
262
+ message: '闲时检查抑制:' + suppression,
263
+ detail: { trigger, reason: suppression, lastSleepAt: getLastSleepAt(binding.sessionId), lastInjectedAt: binding.lastInjectedAt || null },
264
+ })
265
+ continue
266
+ }
267
+ try {
268
+ const result = await requestPrivateConsolidation(ctx, binding.sessionId, { trigger })
269
+ if (result?.ok) {
270
+ // 证据不足(low-score)不是"已整理":不推进游标、不计数,等空闲越过饥饿阈值
271
+ // 或后续证据变多再检查。否则这句话会被永久跳过。
272
+ if (result.settled === false) {
273
+ // 任何没结算的结果都要记探针时间,不只是「水位不足」那两种:low-score 也
274
+ // 会读一遍转录并打分,不记就会在每次 5 分钟扫描里把同一段重读一遍。
275
+ const patch = { lastConsolidationProbeAt: new Date(now).toISOString(), sleepFrozenUntil: null, sleepFrozenAt: null }
276
+ // snapshot-failed 冻结:写独立退避字段,候选阶段守卫据此跳过无新活动的重复
277
+ // 扫入;新真人回合到来即让路。非冻结的 deferral 顺手清掉可能残留的冻结字段。
278
+ if (result.reasonCode === 'snapshot-failed-too-many' && result.cooldownUntil) {
279
+ patch.sleepFrozenUntil = result.cooldownUntil
280
+ patch.sleepFrozenAt = result.frozenAt || null
281
+ }
282
+ setSessionBinding(binding.sessionId, patch)
283
+ log(`sleep consolidation deferred for ${binding.sessionId}: ${result.skipped || 'not settled'}`)
284
+ continue
285
+ }
286
+ // Only cover activity this pass began with, not new messages during it.
287
+ // 多窗收口(issue #4 缺陷 2):`settled` 是「本窗完成」的语义,ledger 的
288
+ // lastSleepSeq 已随本窗回执推进(private.js advanceSleepCursor),不会重扫;
289
+ // 但粗游标 lastSleepAt 只有在整段(remaining === 0)扫完时才推平——否则
290
+ // 尾段 < 200 事件(backlog 够不着)的会话会在候选阶段 `!newActivity && !backlog` 处被永久跳过。
291
+ if (!(Number(result.remaining) > 0)) {
292
+ setLastSleepAt(binding.sessionId, binding.lastTurnAt)
293
+ }
294
+ setSessionBinding(binding.sessionId, {
295
+ sleepRetryAt: null, sleepAttempts: 0, lastSleepError: null,
296
+ sleepFrozenUntil: null, sleepFrozenAt: null,
297
+ lastConsolidationProbeAt: new Date(now).toISOString(),
298
+ })
299
+ // A terminal policy skip (greetings, no new events) advances the sleep stamp
300
+ // but is not a verified worker run; `ran` must keep that distinction.
301
+ if (!result.skipped) ran += 1
302
+ } else if (isGoneSessionError(result?.error)) {
303
+ setSessionBinding(binding.sessionId, { sessionGone: true, sessionGoneAt: new Date(now).toISOString(), sleepRetryAt: null, sleepAttempts: 0, sleepFrozenUntil: null, sleepFrozenAt: null, lastSleepError: String(result.error) })
304
+ try { clearSessionState(binding.sessionId) } catch {}
305
+ log(`sleep consolidation dropped ${binding.sessionId}: the conversation no longer exists`)
306
+ } else {
307
+ const attempts = Number(binding.sleepAttempts || 0) + 1
308
+ setSessionBinding(binding.sessionId, { sleepAttempts: attempts, lastSleepError: result?.error || 'not settled', sleepRetryAt: new Date(now + Math.min(60, 2 ** Math.min(attempts, 6)) * 60_000).toISOString() })
309
+ log(`sleep consolidation skipped for ${binding.sessionId}: ${result?.error || 'not queued'}`)
310
+ }
311
+ } catch (error) {
312
+ if (isGoneSessionError(error?.message)) {
313
+ setSessionBinding(binding.sessionId, { sessionGone: true, sessionGoneAt: new Date(now).toISOString(), sleepRetryAt: null, sleepAttempts: 0, sleepFrozenUntil: null, sleepFrozenAt: null, lastSleepError: String(error.message) })
314
+ try { clearSessionState(binding.sessionId) } catch {}
315
+ continue
316
+ }
317
+ // A missing service or transient file failure can heal without a new turn.
318
+ const attempts = Number(binding.sleepAttempts || 0) + 1
319
+ setSessionBinding(binding.sessionId, { sleepAttempts: attempts, lastSleepError: String(error?.message || error), sleepRetryAt: new Date(now + Math.min(60, 2 ** Math.min(attempts, 6)) * 60_000).toISOString() })
320
+ log(`sleep consolidation failed for ${binding.sessionId}: ${error?.message || error}`)
321
+ }
322
+ }
323
+ return { ran, considered: candidates.length }
324
+ }
325
+
326
+ // 休眠 GC 的 turn-log 分配(设计文档 §3.4):对每个绑定做两条件检查——日志无未结算
327
+ // 增量(max seqEnd ≤ lastSleepSeq)且会话 ≥30 天无任何活动 → 删缓存文件。便宜检查:
328
+ // 只读绑定表 + 文件 stat/mtime,仅对已闲置满期的少数绑定才读日志内容找 max seqEnd;
329
+ // 没有日志文件的绑定直接跳过。异常只 warn,绝不绊倒 sweep 的其他 pass。
330
+ export function runTurnLogGcPass(_ctx, { now = Date.now(), log = () => {} } = {}) {
331
+ try {
332
+ const result = gcTurnLogs(listSessionBindings(), { now })
333
+ if (result.deleted.length > 0) log(`turn-log gc deleted ${result.deleted.length} idle turn log(s)`)
334
+ return result
335
+ } catch (error) {
336
+ log(`turn-log gc failed: ${error?.message || error}`)
337
+ return { deleted: [], kept: [], error: String(error?.message || error) }
338
+ }
339
+ }
340
+
341
+ // Background global curation: turn the conversations that happened since the last
342
+ // run into shared memory, using whichever session is live as the curator's parent.
343
+ export async function runCurationPass(ctx, { now = Date.now(), log = () => {} } = {}) {
344
+ const settings = getSettings()
345
+ const hours = Number(settings.autoCurateEveryHours) || 0
346
+ if (!(hours > 0)) return { ran: 0, skipped: 'disabled' }
347
+ const lastRunAt = Date.parse(getCycleState().lastCurateAt || '') || 0
348
+ if (now - lastRunAt < hours * 3_600_000) return { ran: 0, skipped: 'not-due' }
349
+
350
+ const limit = Math.max(1, Math.min(30, Number(settings.autoCurateSessionLimit) || 8))
351
+ const due = listSessionBindings()
352
+ .filter((b) => !b.consolidationFork && b.lastTurnAt && older(b.lastTurnAt, new Date(lastRunAt).toISOString()) > 0)
353
+ .sort((a, b) => String(b.lastTurnAt).localeCompare(String(a.lastTurnAt)))
354
+ .slice(0, limit)
355
+ .map((b) => b.sessionId)
356
+ if (due.length === 0) return { ran: 0, skipped: 'no-new-sessions' }
357
+
358
+ const parent = due.find((id) => liveAgent(ctx, id))
359
+ || listSessionBindings().filter((b) => !b.consolidationFork).map((b) => b.sessionId).find((id) => liveAgent(ctx, id))
360
+ if (!parent) {
361
+ // Deliberately not recording the attempt: the next sweep retries, and a run
362
+ // that never started must not push the schedule forward.
363
+ log('auto curation waiting for a live session to host the curator')
364
+ return { ran: 0, skipped: 'no-live-parent' }
365
+ }
366
+ try {
367
+ const job = await startGlobalCuration(ctx, { sessionIds: due, parentSessionId: parent, model: settings.curatorModel })
368
+ setCycleState({ lastCurateAt: new Date(now).toISOString(), lastCurateJob: job?.id || null })
369
+ record({ kind: 'curate', scope: 'global', ok: true, message: `自动提炼启动:${due.length} 个会话`, detail: { sessions: due.length, jobId: job?.id || null, parent } })
370
+ return { ran: due.length, job }
371
+ } catch (error) {
372
+ log(`auto curation failed: ${error?.message || error}`)
373
+ record({ kind: 'curate', scope: 'global', ok: false, level: 'error', message: '自动提炼失败:' + String(error?.message || error), detail: { sessions: due.length } })
374
+ return { ran: 0, error: String(error?.message || error) }
375
+ }
376
+ }
377
+
378
+ // A library leaves daily use when its workspace is removed from DSH — which is a
379
+ // pure unregister: the folder and every session log stay on disk. So the trigger is
380
+ // the workspace registry, never `fs.existsSync`. A deleted folder is not "removed
381
+ // from DSH", and a folder taken out of the sidebar still exists.
382
+ function registeredScopes(ctx) {
383
+ let registry = null
384
+ try { registry = ctx.get?.('workspaceRegistry') } catch { return null }
385
+ if (!registry || typeof registry.list !== 'function') return null
386
+ let list
387
+ try { list = registry.list() } catch { return null }
388
+ if (!Array.isArray(list)) return null
389
+ // An empty registry is not trusted: a fresh install with no workspace yet must not
390
+ // archive every library ever created.
391
+ const scopes = list.map((ws) => normalizeCwd(ws?.path)).filter(Boolean)
392
+ return { scopes: new Set(scopes), trustworthy: scopes.length > 0 }
393
+ }
394
+
395
+ // 同一个库每 5 分钟重复一条「因为在用所以没归档」只会把宿主日志淹掉,说一次就够;
396
+ // 归档或复活都会清掉这个标记。
397
+ const inUseSkipNotified = new Set()
398
+
399
+ function noteInUseSkip(libraryId, scopeKey, log) {
400
+ if (inUseSkipNotified.has(libraryId)) return
401
+ inUseSkipNotified.add(libraryId)
402
+ log(`kept library ${libraryId}: workspace ${scopeKey} is not in the DSH registry, but a live conversation still uses it`)
403
+ }
404
+
405
+ export function runLibraryHousekeeping(ctx, { now = Date.now(), log = () => {} } = {}) {
406
+ const settings = getSettings()
407
+ const archived = []
408
+ const revived = []
409
+ const purged = []
410
+ const skippedInUse = []
411
+ const purgeCandidates = []
412
+ const registry = registeredScopes(ctx)
413
+ // 一次读盘算出「哪些库还有存活绑定」。这是归档判定缺的那一半:注册表只回答
414
+ // 「这个目录是不是 DSH 工作区」,不回答「这个库还有没有人用」。
415
+ const inUse = inUseLibraryIds()
416
+
417
+ for (const lib of listLibrariesAll()) {
418
+ const used = inUse.has(lib.id)
419
+ if (lib.archived === true) {
420
+ const scopeBack = Boolean(registry?.trustworthy && registry.scopes.has(lib.scopeKey))
421
+ // 误归档(旧版扫描把在用的非工作区库归档了):库还在被读取写入,就该回到列表。
422
+ // 用户主动归档(archivedBy === 'user')不动——那是用户的决定。
423
+ const misArchived = archivedWhileInUse(lib, { inUse: used, now })
424
+ if (scopeBack || misArchived) {
425
+ if (restoreLibrary(lib.id).ok) {
426
+ revived.push(lib.id)
427
+ inUseSkipNotified.delete(lib.id)
428
+ if (misArchived && !scopeBack) log(`revived library ${lib.id}: a live conversation still uses it`)
429
+ }
430
+ continue
431
+ }
432
+ const days = Number(settings.purgeArchivedAfterDays) || 0
433
+ // 在用的库永不进入清理候选:purge 只看年龄,一旦把活跃库算进去就是数据丢失。
434
+ if (days > 0 && !used && lib.archivedAt && (now - (Date.parse(lib.archivedAt) || now)) / 86_400_000 >= days) {
435
+ purgeCandidates.push(lib.id)
436
+ }
437
+ continue
438
+ }
439
+ if (!registry?.trustworthy) continue
440
+ if (!lib.scopeKey || lib.scopeKey === '__default__') continue
441
+ if (!registry.scopes.has(lib.scopeKey)) {
442
+ // 关键判据:不在工作区注册表 ≠ 没人用。IM 插件数据目录、profile 下的目录都不在
443
+ // 注册表里,却可能有会话正在高频读写(2026-11-21 报告:建成 176 秒被归档,之后
444
+ // 9 小时 172 条活动、6 次召回全成功,而 UI 里库已消失)。
445
+ if (used) {
446
+ skippedInUse.push(lib.id)
447
+ noteInUseSkip(lib.id, lib.scopeKey, log)
448
+ continue
449
+ }
450
+ archiveLibrary(lib.id, { by: 'sweep' })
451
+ inUseSkipNotified.delete(lib.id)
452
+ archived.push(lib.id)
453
+ log(`archived library ${lib.id}: workspace ${lib.scopeKey} is no longer registered in DSH`)
454
+ }
455
+ }
456
+ return { archived, revived, purged, purgeCandidates, skippedInUse, registrySeen: Boolean(registry?.trustworthy) }
457
+ }
458
+
459
+ export async function runCyclePasses(ctx, options = {}) {
460
+ const shortTerm = runShortTermPass(ctx, options)
461
+ const overdue = runOverdueReviewPass(ctx, options)
462
+ // turn-log GC 挂在 sweep 顺带跑(§3.4),只做 stat/绑定表级别的便宜检查。
463
+ const turnLogs = runTurnLogGcPass(ctx, options)
464
+ const maintenance = await runMaintenancePass(ctx, options)
465
+ const sleep = await runSleepPass(ctx, options)
466
+ const curate = await runCurationPass(ctx, options)
467
+ const libraries = runLibraryHousekeeping(ctx, options)
468
+ // A library can still be on disk in the removed `session` format when the plugin
469
+ // updated mid-flight. Reads are already normalized, so this only keeps the files in
470
+ // step with the code (see lib/migrate.js); it is cheap and idempotent.
471
+ const migrated = runVisibilityMigrationPass({ log: options.log })
472
+ // 日期唤醒放在最后:它使用可选的宿主 schedule 服务,宿主没有
473
+ // 这个服务时只返回 `{skipped:'service'}`;即使它整体失败,上面的短期过期、睡眠整理、
474
+ // 自动提炼和库迁移已经跑完,下一次 sweep 照常重试。
475
+ const salientWake = await runSalientWakePass(ctx, { now: options.now ?? new Date(), log: options.log }).catch((error) => {
476
+ try { options.log?.(`salient wake pass failed: ${error?.message || error}`) } catch {}
477
+ return { created: 0, cleaned: 0, skipped: 0, errors: 1 }
478
+ })
479
+ return { shortTerm, overdue, turnLogs, maintenance, sleep, curate, libraries, migrated, salientWake }
480
+ }
481
+
482
+ // DSH has no host scheduler a plugin can register a *global* job with
483
+ // (`ctx.schedule` is session-bound and delivers a prompt into that session, which
484
+ // is the wrong shape for a plugin-wide sweep), so this owns a plain interval.
485
+ // Cordis' own `ctx.interval` is preferred because the host disposes it with the
486
+ // plugin scope; the raw fallback is unref'd so a plugin timer can never be the
487
+ // reason the app stays alive. Everything this reads is a persisted timestamp, so a
488
+ // missed sweep is recovered on the next one.
489
+ export function registerCycle(ctx, { log = () => {} } = {}) {
490
+ let running = false
491
+ const tick = async () => {
492
+ if (running) return
493
+ running = true
494
+ try {
495
+ await runCyclePasses(ctx, { log })
496
+ } catch (error) {
497
+ log(`cycle sweep failed: ${error?.message || error}`)
498
+ } finally {
499
+ running = false
500
+ }
501
+ }
502
+ // One catch-up sweep shortly after load. The sweep timer only exists while the app
503
+ // is open, so a conversation that ended while it was closed used to wait for the
504
+ // next idle window — and the next message always resets that clock, which is how a
505
+ // whole evening could pass without a single consolidation. The delay lets the host
506
+ // finish restoring sessions and agents first; the pass itself is bounded (two
507
+ // sessions) so a long list of stale bindings cannot turn startup into a stampede.
508
+ const startup = setTimeout(() => { void tick() }, STARTUP_SWEEP_MS)
509
+ startup.unref?.()
510
+ // Property access on an uninjected service throws in cordis, so the probe itself
511
+ // is guarded; a host without the timer service falls back instead of failing.
512
+ let scoped = null
513
+ try { scoped = typeof ctx.interval === 'function' ? ctx : null } catch { scoped = null }
514
+ if (scoped) {
515
+ // cordis' ctx.interval returns a *disposer function*, not a Node timer id —
516
+ // clearInterval() on it is a silent no-op and the sweep would keep running
517
+ // after plugin unload/HMR. Call the disposer.
518
+ const dispose = scoped.interval(() => { void tick() }, SWEEP_MS)
519
+ return () => { try { clearTimeout(startup) } catch {} try { dispose?.() } catch {} }
520
+ }
521
+ const timer = setInterval(() => { void tick() }, SWEEP_MS)
522
+ timer.unref?.()
523
+ return () => { clearTimeout(startup); clearInterval(timer) }
524
+ }