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
@@ -1,568 +1,567 @@
1
- import test from 'node:test'
2
- import assert from 'node:assert/strict'
3
- import fs from 'node:fs'
4
- import os from 'node:os'
5
- import path from 'node:path'
6
-
7
- const home = fs.mkdtempSync(path.join(os.tmpdir(), 'dsh-memu-memory-cycle-'))
8
- process.env.DSH_MEMU_HOME = home
9
-
10
- const state = await import('../lib/state.js')
11
- const cycle = await import('../lib/cycle.js')
12
-
13
- test.after(() => {
14
- try { fs.rmSync(home, { recursive: true, force: true }) } catch {}
15
- })
16
-
17
- // A ctx stand-in for a host that can read a transcript and fork it. Consolidation
18
- // never asks `agents.get` for anything any more, so the recorder counts both sides:
19
- // followups handed to the user's own live agent (must stay 0) and followups handed
20
- // to a scratch fork (must be 1 per consolidated session).
21
- function fakeCtx({ live = [], forkable = null, gone = [], transcript = null, parentOptions = { provider: 'test-provider', model: 'test-model' }, turnReason = { kind: 'completed' } } = {}) {
22
- const liveSet = new Set(live)
23
- const forkSet = new Set(forkable || live)
24
- const goneSet = new Set(gone)
25
- const created = []
26
- const disposed = []
27
- const liveFollowups = []
28
- const forkFollowups = []
29
- const seeds = []
30
- const sessionHandlers = []
31
- // A transcript that actually contains a person: the value gate reads it before a
32
- // fork exists, so a fixture with bare `{seq}` markers would be judged empty.
33
- const events = transcript || [
34
- { seq: 0, type: 'user/message', data: { source: { kind: 'user' }, content: [{ type: 'text', text: '帮我看一下这个插件为什么空闲整理从来没跑过,日志里只有 skip 一行' }] } },
35
- { seq: 1, type: 'assistant/message', data: { message: { content: [{ type: 'tool-call', name: 'read', arguments: '{}' }] } } },
36
- ]
37
- const ctx = {
38
- created, disposed, liveFollowups, forkFollowups, seeds,
39
- on: (name, handler) => {
40
- if (name !== 'session/event') return () => {}
41
- sessionHandlers.push(handler)
42
- return () => {
43
- const index = sessionHandlers.indexOf(handler)
44
- if (index >= 0) sessionHandlers.splice(index, 1)
45
- }
46
- },
47
- get: (name) => {
48
- if (name === 'agents') {
49
- return {
50
- get: (id) => (liveSet.has(id)
51
- ? { followup: (message) => liveFollowups.push({ id, message }), options: parentOptions }
52
- : undefined),
53
- create: async (spec) => {
54
- created.push(spec)
55
- seeds.push(spec.seed)
56
- const childSession = { id: spec.sessionId }
57
- return {
58
- agent: {
59
- session: childSession,
60
- followup: (message) => {
61
- forkFollowups.push({ child: spec.sessionId, message })
62
- const proof = { version: 1, jobId: state.getSessionBinding(spec.sessionId).jobId, snapshotHash: state.getSessionBinding(spec.sessionId).snapshotHash, status: 'completed', outcome: 'no_value', checkedRange: { fromSeq: 0, throughSeq: events.at(-1).seq }, createdIds: [], updatedIds: [], heldIds: [] }
63
- const tick = String.fromCharCode(96).repeat(3)
64
- for (const handler of sessionHandlers) {
65
- handler(childSession, { type: 'assistant/message', seq: 99, data: { message: { content: [{ type: 'text', text: tick + 'memu-consolidation-receipt\n' + JSON.stringify(proof) + '\n' + tick }] } } })
66
- handler(childSession, { type: 'turn/end', seq: 100, data: { turn: 1, reason: turnReason } })
67
- }
68
- },
69
- whenIdle: async () => {},
70
- },
71
- dispose: async () => { disposed.push(spec.sessionId) },
72
- }
73
- },
74
- }
75
- }
76
- if (name === 'sessionQuery') {
77
- return {
78
- readSession: async (id) => {
79
- if (goneSet.has(id)) throw new Error(`session "${id}" not found`)
80
- return forkSet.has(id) ? { events, session: { cwd: path.join(home, 'p'), agentPreset: 'rp' } } : { events: [] }
81
- },
82
- }
83
- }
84
- return undefined
85
- },
86
- }
87
- return ctx
88
- }
89
-
90
- function touchAgo(sessionId, minutesAgo) {
91
- state.setSessionBinding(sessionId, { lastTurnAt: new Date(Date.now() - minutesAgo * 60_000).toISOString() })
92
- }
93
-
94
- test('sleep pass does nothing unless it is turned on', async () => {
95
- // Fresh installs now default this on, so turn it off explicitly to test the
96
- // disabled branch without depending on the default.
97
- state.updateSettings({ sleepConsolidation: false })
98
- const binding = state.ensureSession('cycle-off', { cwd: path.join(home, 'p-off'), agentPreset: 'rp' })
99
- touchAgo('cycle-off', 120)
100
- const out = await cycle.runSleepPass(fakeCtx({ live: ['cycle-off'] }))
101
- assert.equal(out.skipped, 'disabled')
102
- assert.equal(state.getLastSleepAt('cycle-off'), null)
103
- })
104
-
105
- test('an idle live session is consolidated in a fork, never in its own chat', async () => {
106
- state.updateSettings({ sleepConsolidation: true, sleepAfterIdleMinutes: 10 })
107
- const binding = state.ensureSession('cycle-idle', { cwd: path.join(home, 'p-idle'), agentPreset: 'rp' })
108
- touchAgo('cycle-idle', 30)
109
-
110
- const ctx = fakeCtx({ live: ['cycle-idle'] })
111
- const first = await cycle.runSleepPass(ctx)
112
- assert.equal(first.ran, 1)
113
- assert.ok(state.getLastSleepAt('cycle-idle'))
114
-
115
- // The reason this whole path exists: a consolidation prompt queued on the chat
116
- // the user is looking at shows up as a pending draft above the composer and then
117
- // lives in that transcript forever. The live agent must never be handed one.
118
- assert.equal(ctx.liveFollowups.length, 0, 'the live session must not get a queued draft')
119
- assert.equal(ctx.created.length, 1, 'exactly one scratch fork')
120
- assert.equal(ctx.forkFollowups.length, 1, 'the fork is what carries the work')
121
- assert.equal(ctx.disposed.length, 1, 'the fork is thrown away afterwards')
122
- const child = ctx.created[0].sessionId
123
- assert.match(child, /^memu-consolidate-/)
124
- assert.equal(ctx.created[0].meta.origin, 'subagent', 'a subagent fork stays out of the window list and the injection path')
125
- assert.equal(ctx.created[0].meta.parentSession, 'cycle-idle')
126
- assert.equal(ctx.seeds[0].lastSeq, 1, 'the seed is the parent transcript')
127
- assert.equal(state.getSessionBinding(child), null, 'worker binding is removed after disposal')
128
-
129
- const second = await cycle.runSleepPass(fakeCtx({ live: ['cycle-idle'] }))
130
- assert.equal(second.ran, 0)
131
- assert.equal(second.skipped, undefined)
132
- })
133
-
134
- test('a session that was not idle long enough is left alone', async () => {
135
- state.updateSettings({ sleepConsolidation: true, sleepAfterIdleMinutes: 30 })
136
- state.ensureSession('cycle-recent', { cwd: path.join(home, 'p-recent'), agentPreset: 'rp' })
137
- touchAgo('cycle-recent', 2)
138
- const out = await cycle.runSleepPass(fakeCtx({ live: ['cycle-recent'] }))
139
- assert.equal(out.ran, 0)
140
- assert.equal(state.getLastSleepAt('cycle-recent'), null)
141
- })
142
-
143
- test('an unreadable transcript backs off without claiming a completed sleep', async () => {
144
- state.updateSettings({ sleepConsolidation: true, sleepAfterIdleMinutes: 5 })
145
- state.ensureSession('cycle-dead', { cwd: path.join(home, 'p-dead'), agentPreset: 'rp' })
146
- touchAgo('cycle-dead', 60)
147
- const logs = []
148
- await cycle.runSleepPass({ get: () => undefined }, { log: (m) => logs.push(m) })
149
- assert.equal(state.getLastSleepAt('cycle-dead'), null)
150
- const failed = state.getSessionBinding('cycle-dead')
151
- assert.ok(Date.parse(failed.sleepRetryAt) > Date.now())
152
- assert.equal(failed.sleepAttempts, 1)
153
- await cycle.runSleepPass({ get: () => undefined })
154
- assert.equal(state.getSessionBinding('cycle-dead').sleepAttempts, 1, 'backoff suppresses immediate retries')
155
- assert.ok(logs.some((m) => /consolidation skipped for cycle-dead/.test(m)), 'skip logged: ' + logs.join(' | '))
156
- state.setSessionBinding('cycle-dead', { sleepRetryAt: new Date(0).toISOString() })
157
- await cycle.runSleepPass(fakeCtx({ live: ['cycle-dead'] }))
158
- assert.ok(state.getLastSleepAt('cycle-dead'), 'a recovered host retries without another user turn')
159
- assert.equal(state.getSessionBinding('cycle-dead').lastSleepError, null)
160
- })
161
-
162
- test('a fork that cannot be created is logged, not dropped silently', async () => {
163
- state.updateSettings({ sleepConsolidation: true, sleepAfterIdleMinutes: 5 })
164
- state.ensureSession('cycle-hist', { cwd: path.join(home, 'p-hist'), agentPreset: 'rp' })
165
- touchAgo('cycle-hist', 60)
166
- const logs = []
167
- const ctx = {
168
- get: (name) => {
169
- if (name === 'sessionQuery') return { readSession: async () => ({ events: [
170
- { seq: 0, type: 'user/message', data: { source: { kind: 'user' }, content: [{ type: 'text', text: '这个 fork 一直建不起来,帮我看下为什么,日志里只有 skipped 一行' }] } },
171
- ], session: {} }) }
172
- if (name === 'agents') return {
173
- get: () => ({ options: { provider: 'test-provider', model: 'test-model' } }),
174
- create: async () => { throw new Error('no fork in test env') },
175
- }
176
- return undefined
177
- },
178
- }
179
- await cycle.runSleepPass(ctx, { log: (m) => logs.push(m) })
180
- assert.ok(logs.some((m) => /consolidation skipped for cycle-hist: .*no fork in test env/.test(m)), 'attempt logged: ' + logs.join(' | '))
181
- assert.equal(state.getLastSleepAt('cycle-hist'), null)
182
- assert.match(state.getSessionBinding('cycle-hist').lastSleepError, /no fork/)
183
- })
184
-
185
- test('a fork whose turn errors is backed off, not marked asleep', async () => {
186
- state.updateSettings({ sleepConsolidation: true, sleepAfterIdleMinutes: 5 })
187
- state.ensureSession('cycle-fork-error', { cwd: path.join(home, 'p-fork-error'), agentPreset: 'rp' })
188
- touchAgo('cycle-fork-error', 60)
189
- const out = await cycle.runSleepPass(fakeCtx({
190
- live: ['cycle-fork-error'],
191
- turnReason: { kind: 'error', error: { message: 'prompt variable "{{model}}" has no value' } },
192
- }))
193
- assert.equal(out.ran, 0)
194
- assert.equal(state.getLastSleepAt('cycle-fork-error'), null, 'a failed turn is still unslept')
195
- const failed = state.getSessionBinding('cycle-fork-error')
196
- assert.equal(failed.sleepAttempts, 1)
197
- assert.match(failed.lastSleepError, /fork turn ended error/)
198
- assert.ok(Date.parse(failed.sleepRetryAt) > Date.now(), 'the scheduler backs off instead of losing the work')
199
- })
200
-
201
- test('a turn newer than the last sleep makes the session eligible again', async () => {
202
- state.updateSettings({ sleepConsolidation: true, sleepAfterIdleMinutes: 5 })
203
- state.ensureSession('cycle-again', { cwd: path.join(home, 'p-again'), agentPreset: 'rp' })
204
- // Slept 40 minutes ago, then the conversation continued 15 minutes ago: the
205
- // earlier sleep is stale and a new one is due.
206
- state.setLastSleepAt('cycle-again', new Date(Date.now() - 40 * 60_000).toISOString())
207
- touchAgo('cycle-again', 15)
208
-
209
- const out = await cycle.runSleepPass(fakeCtx({ live: ['cycle-again'] }))
210
- assert.equal(out.ran, 1)
211
- assert.ok(Date.parse(state.getLastSleepAt('cycle-again')) > Date.parse(new Date(Date.now() - 15 * 60_000).toISOString()) - 60_000)
212
- })
213
-
214
- test('a conversation the host says is gone is marked once and never retried', async () => {
215
- state.updateSettings({ sleepConsolidation: true, sleepAfterIdleMinutes: 5 })
216
- state.ensureSession('cycle-ghost', { cwd: path.join(home, 'p-ghost'), agentPreset: 'rp' })
217
- touchAgo('cycle-ghost', 120)
218
- const logs = []
219
- const out = await cycle.runSleepPass(fakeCtx({ live: ['cycle-ghost'], gone: ['cycle-ghost'] }), { log: (m) => logs.push(m) })
220
- assert.equal(out.ran, 0)
221
- const binding = state.getSessionBinding('cycle-ghost')
222
- assert.equal(binding.sessionGone, true, 'the mark is what stops the hourly retry')
223
- assert.equal(binding.sleepAttempts, 0, 'a deleted session is not a transient failure')
224
- assert.equal(binding.sleepRetryAt, null, 'nothing to retry later')
225
- assert.ok(logs.some((m) => /no longer exists/.test(m)), 'explained once: ' + logs.join(' | '))
226
- const quiet = await cycle.runSleepPass(fakeCtx({ live: ['cycle-ghost'] }))
227
- assert.equal(quiet.ran, 0, 'the next sweep does not consolidate a deleted session again')
228
- })
229
-
230
- test('a policy greeting skip does not claim a completed worker check', async () => {
231
- state.updateSettings({ sleepConsolidation: true, sleepAfterIdleMinutes: 5 })
232
- state.ensureSession('cycle-smalltalk', { cwd: path.join(home, 'p-small'), agentPreset: 'rp' })
233
- touchAgo('cycle-smalltalk', 20)
234
- const ctx = fakeCtx({ live: ['cycle-smalltalk'], transcript: [
235
- { seq: 0, type: 'user/message', data: { source: { kind: 'user' }, content: [{ type: 'text', text: '谢谢' }] } },
236
- { seq: 1, type: 'assistant/message', data: { message: { content: [{ type: 'text', text: '不客气' }] } } },
237
- ] })
238
- const out = await cycle.runSleepPass(ctx)
239
- assert.equal(out.ran, 0, 'a policy skip is not a verified worker receipt')
240
- assert.equal(ctx.created.length, 0, 'no fork for small talk')
241
- assert.ok(state.getLastSleepAt('cycle-smalltalk'), 'a terminal skip is recorded so the same greetings are not re-read every sweep')
242
- })
243
-
244
- test('auto curation stays off unless an interval is set', async () => {
245
- const out = await cycle.runCurationPass(fakeCtx({ live: ['cycle-idle'] }))
246
- assert.equal(out.skipped, 'disabled')
247
- })
248
-
249
- test('auto curation waits for a live parent and does not advance the schedule', async () => {
250
- state.updateSettings({ autoCurateEveryHours: 1, autoCurateSessionLimit: 5 })
251
- state.setCycleState({ lastCurateAt: null })
252
- state.ensureSession('cycle-curate', { cwd: path.join(home, 'p-curate'), agentPreset: 'rp' })
253
- touchAgo('cycle-curate', 5)
254
-
255
- const out = await cycle.runCurationPass(fakeCtx({ live: [] }))
256
- assert.equal(out.skipped, 'no-live-parent')
257
- assert.equal(out.ran, 0)
258
- assert.ok(!state.getCycleState().lastCurateAt, 'a run that never started must not reschedule')
259
- })
260
-
261
- function registryCtx(paths) {
262
- return {
263
- get: (name) => (name === 'workspaceRegistry' ? { list: () => paths.map((p) => ({ path: p })) } : undefined),
264
- }
265
- }
266
-
267
- test('a library is archived only when its workspace leaves the DSH registry', () => {
268
- const lib = state.createLibrary({ name: 'cycle-ws', cwd: '/work/cycle-ws' })
269
- assert.ok(state.listLibraries().some((l) => l.id === lib.id), 'starts active')
270
-
271
- // Registered: this library must not be touched (other leftovers from earlier
272
- // tests may legitimately archive in the same sweep, so assert only about ours).
273
- const stillThere = cycle.runLibraryHousekeeping(registryCtx(['/work/cycle-ws', '/work/other']))
274
- assert.ok(!stillThere.archived.includes(lib.id))
275
-
276
- // Unregistered (but still on disk): archived.
277
- const removed = cycle.runLibraryHousekeeping(registryCtx(['/work/other']))
278
- assert.ok(removed.archived.includes(lib.id), 'library should archive when its workspace is unregistered')
279
- assert.ok(state.listArchivedLibraries().map((l) => l.id).includes(lib.id))
280
- assert.ok(state.listLibraries().every((l) => l.id !== lib.id), 'archived libraries leave the active list')
281
- })
282
-
283
- test('an absent or empty registry archives nothing (fail-open)', () => {
284
- const lib = state.createLibrary({ name: 'cycle-safe', cwd: '/work/cycle-safe' })
285
- // No workspaceRegistry service at all.
286
- const noService = cycle.runLibraryHousekeeping({ get: () => undefined })
287
- assert.deepEqual(noService.archived, [])
288
- assert.deepEqual(noService.revived, [])
289
- // Registry present but empty — a fresh install must not wipe the library list.
290
- const empty = cycle.runLibraryHousekeeping(registryCtx([]))
291
- assert.deepEqual(empty.archived, [])
292
- assert.ok(state.getLibrary(lib.id))
293
- })
294
-
295
- test('a workspace coming back revives its library', () => {
296
- const lib = state.createLibrary({ name: 'cycle-revive', cwd: '/work/cycle-revive' })
297
- cycle.runLibraryHousekeeping(registryCtx(['/work/other']))
298
- assert.ok(state.listArchivedLibraries().some((l) => l.id === lib.id), 'should have been archived')
299
- const back = cycle.runLibraryHousekeeping(registryCtx(['/work/cycle-revive']))
300
- assert.ok(back.revived.includes(lib.id))
301
- assert.ok(state.listLibraries().some((l) => l.id === lib.id), 'should be active again')
302
- })
303
-
304
- test('archived libraries are kept forever unless an age is set', () => {
305
- const lib = state.createLibrary({ name: 'cycle-keep', cwd: '/work/cycle-keep' })
306
- state.archiveLibrary(lib.id)
307
- state.updateSettings({ purgeArchivedAfterDays: 0 })
308
- const manual = cycle.runLibraryHousekeeping(registryCtx(['/work/somewhere-else']))
309
- assert.deepEqual(manual.purged, [])
310
- assert.ok(state.getLibrary(lib.id), 'manual mode must not delete')
311
-
312
- // Now make it old and turn on purging.
313
- const st = state.loadState()
314
- st.libraries[lib.id].archivedAt = new Date(Date.now() - 40 * 86_400_000).toISOString()
315
- state.saveState(st)
316
- state.updateSettings({ purgeArchivedAfterDays: 30 })
317
- const purged = cycle.runLibraryHousekeeping(registryCtx(['/work/somewhere-else']))
318
- assert.deepEqual(purged.purged, [])
319
- assert.ok(purged.purgeCandidates.includes(lib.id))
320
- assert.ok(state.getLibrary(lib.id), 'age produces a review candidate, never an automatic library deletion')
321
- })
322
-
323
- test('deleting an un-archived library is refused', () => {
324
- const lib = state.createLibrary({ name: 'cycle-nodelete', cwd: '/work/cycle-nodelete' })
325
- const result = state.deleteLibrary(lib.id)
326
- assert.equal(result.ok, false)
327
- assert.match(result.error, /archive the library before deleting/)
328
- assert.ok(state.getLibrary(lib.id))
329
- })
330
-
331
- test('auto curation is not due yet', async () => {
332
- state.updateSettings({ autoCurateEveryHours: 6 })
333
- state.setCycleState({ lastCurateAt: new Date().toISOString() })
334
- const out = await cycle.runCurationPass(fakeCtx({ live: ['cycle-curate'] }))
335
- assert.equal(out.skipped, 'not-due')
336
- })
337
- test('a thin turn shortly after a consolidation waits for real evidence', async () => {
338
- state.updateSettings({ sleepConsolidation: true, sleepAfterIdleMinutes: 3 })
339
- state.ensureSession('cycle-cooldown', { cwd: path.join(home, 'p-cooldown'), agentPreset: 'rp' })
340
- // 刚整理过(20 分钟前),5 分钟前只补了一句很短的话:再 fork 一次要把整段转录
341
- // 重新种进去,纯粹浪费 token。评分门槛会把它压到饥饿阈值之后。
342
- state.setSessionBinding('cycle-cooldown', { lastTurnAt: new Date(Date.now() - 5 * 60_000).toISOString() })
343
- state.setLastSleepAt('cycle-cooldown', new Date(Date.now() - 20 * 60_000).toISOString())
344
- const ctx = fakeCtx({ live: ['cycle-cooldown'] })
345
- const out = await cycle.runSleepPass(ctx)
346
- assert.equal(out.ran, 0)
347
- assert.equal(ctx.created.length, 0, 'a thin follow-up must not buy another full-transcript fork')
348
- // 收尾:把它标记为已睡,避免候选泄漏到后续用例。
349
- state.setLastSleepAt('cycle-cooldown', new Date().toISOString())
350
- })
351
-
352
- test('a session that just injected memory is left alone by the idle sweep', async () => {
353
- state.updateSettings({ sleepConsolidation: true, sleepAfterIdleMinutes: 3 })
354
- state.ensureSession('cycle-recall', { cwd: path.join(home, 'p-recall'), agentPreset: 'rp' })
355
- state.setSessionBinding('cycle-recall', {
356
- // 空闲已过饥饿阈值,按评分本会 fork;但 5 分钟前刚注入了记忆,抑制优先。
357
- lastTurnAt: new Date(Date.now() - 20 * 60_000).toISOString(),
358
- lastInjectedAt: new Date(Date.now() - 5 * 60_000).toISOString(),
359
- })
360
- const ctx = fakeCtx({ live: ['cycle-recall'] })
361
- const out = await cycle.runSleepPass(ctx)
362
- assert.equal(out.ran, 0)
363
- assert.equal(ctx.created.length, 0, 'a session with fresh memory context does not need a fork')
364
- state.setLastSleepAt('cycle-recall', new Date().toISOString())
365
- })
366
-
367
- // H5: a missing file is not the host saying the conversation was deleted.
368
- // captureSessionSnapshot marks a failed read retryable on purpose ("读失败,可重试"),
369
- // but the bare word ENOENT in isGoneSessionError used to turn that into sessionGone —
370
- // and the sweep skips a marked session until some later human message clears it.
371
- test('a transcript that cannot be read is retried, not marked as a deleted conversation', async () => {
372
- state.updateSettings({ sleepConsolidation: true, sleepAfterIdleMinutes: 5 })
373
- state.ensureSession('cycle-enoent', { cwd: path.join(home, 'p-enoent'), agentPreset: 'rp' })
374
- // 6 minutes: still idle under the 5-minute threshold, but the sweep takes the two
375
- // newest candidates and this file shares one state directory across its tests.
376
- touchAgo('cycle-enoent', 6)
377
- const logs = []
378
- const ctx = {
379
- get: (name) => {
380
- if (name === 'sessionQuery') {
381
- return {
382
- readSession: async () => {
383
- const error = new Error("ENOENT: no such file or directory, open 'D:/home/sessions/cycle-enoent/log.jsonl'")
384
- error.code = 'ENOENT'
385
- throw error
386
- },
387
- }
388
- }
389
- if (name === 'agents') {
390
- return { get: () => ({}), create: async () => { throw new Error('a session that cannot be read must not be forked') } }
391
- }
392
- return undefined
393
- },
394
- }
395
- await cycle.runSleepPass(ctx, { log: (message) => logs.push(message), limit: 10 })
396
- const binding = state.getSessionBinding('cycle-enoent')
397
- assert.ok(!binding.sessionGone, 'a transient read failure is not the host reporting a deletion')
398
- assert.equal(binding.sleepAttempts, 1, 'it backs off like any other failure')
399
- assert.ok(Date.parse(binding.sleepRetryAt) > Date.now(), 'it is retried later')
400
- assert.match(binding.lastSleepError, /ENOENT/)
401
- assert.ok(logs.some((message) => /consolidation skipped for cycle-enoent/.test(message)), 'stated once: ' + logs.join(' | '))
402
- assert.equal(state.getLastSleepAt('cycle-enoent'), null, 'nothing was consolidated, so nothing is marked asleep')
403
- })
404
-
405
- test('only the host saying the conversation is gone counts as deleted', () => {
406
- assert.equal(cycle.isGoneSessionError('session "abc" not found'), true)
407
- assert.equal(cycle.isGoneSessionError('no such session: abc'), true)
408
- assert.equal(cycle.isGoneSessionError('this session does not exist any more'), true)
409
- assert.equal(cycle.isGoneSessionError("ENOENT: no such file or directory, open 'D:/x/log.jsonl'"), false)
410
- assert.equal(cycle.isGoneSessionError('EACCES: permission denied, open D:/x'), false)
411
- })
412
- // ---------------------------------------------------------------- 归档 vs 在用(2026-11-21 外部报告)
413
-
414
- // 报告里的真实形态:IM 插件数据目录不是 DSH 工作区,库建好后 176 秒被扫描归档,
415
- // 而绑定会话继续写 9 小时。这里把那条时间线压成三轮 sweep。
416
-
417
- test('a library bound to a live conversation is never archived for an unregistered scope', () => {
418
- const cwd = path.join(home, 'im-in-use')
419
- state.ensureSession('cycle-im', { cwd })
420
- const binding = state.getSessionBinding('cycle-im')
421
- const libId = binding.libraryId
422
- assert.ok(libId, 'the session created a library')
423
-
424
- const first = cycle.runLibraryHousekeeping(registryCtx(['/work/unrelated']))
425
- assert.ok(!first.archived.includes(libId), 'an in-use library must not be archived')
426
- assert.ok(first.skippedInUse.includes(libId), 'the sweep must report why it skipped')
427
- assert.ok(state.listLibraries().some((lib) => lib.id === libId), 'it stays in the active list')
428
-
429
- // 连续三轮(≈15 分钟的真实节奏)都不能翻车。
430
- const second = cycle.runLibraryHousekeeping(registryCtx(['/work/unrelated']))
431
- const third = cycle.runLibraryHousekeeping(registryCtx(['/work/unrelated']))
432
- for (const pass of [second, third]) assert.ok(!pass.archived.includes(libId))
433
- const lib = state.getLibrary(libId)
434
- assert.equal(lib.archived, undefined, 'never archived')
435
- assert.equal(lib.archivedAt, undefined)
436
- })
437
-
438
- test('an unbound library with an unregistered scope still archives (the cleanup keeps working)', () => {
439
- const lib = state.createLibrary({ name: 'cycle-unused', cwd: '/work/cycle-unused' })
440
- const pass = cycle.runLibraryHousekeeping(registryCtx(['/work/unrelated']))
441
- assert.ok(pass.archived.includes(lib.id), 'nobody uses it, so the old behaviour stands')
442
- assert.equal(state.getLibrary(lib.id).archivedBy, 'sweep', 'the sweep records that it did the archiving')
443
- })
444
-
445
- test('a library the old sweep archived while in use comes back instead of staying hidden', () => {
446
- const cwd = path.join(home, 'im-misarchived')
447
- state.ensureSession('cycle-im-revive', { cwd })
448
- const libId = state.getSessionBinding('cycle-im-revive').libraryId
449
- // 复现旧版:扫描把在用的库归档,且当时还没有 archivedBy 字段。
450
- state.archiveLibrary(libId, { by: 'sweep' })
451
- assert.ok(state.listArchivedLibraries().some((lib) => lib.id === libId))
452
-
453
- const pass = cycle.runLibraryHousekeeping(registryCtx(['/work/unrelated']))
454
- assert.ok(pass.revived.includes(libId), 'an in-use archive is a bug and must self-heal')
455
- assert.ok(state.listLibraries().some((lib) => lib.id === libId))
456
- assert.ok(!pass.archived.includes(libId), 'and it must not be archived again in the same pass')
457
- })
458
-
459
- test('a user-archived library is respected even while a conversation still points at it', () => {
460
- const cwd = path.join(home, 'im-user-archived')
461
- state.ensureSession('cycle-user-archive', { cwd })
462
- const libId = state.getSessionBinding('cycle-user-archive').libraryId
463
- state.archiveLibrary(libId) // 默认 by: 'user'
464
- const pass = cycle.runLibraryHousekeeping(registryCtx(['/work/unrelated']))
465
- assert.ok(!pass.revived.includes(libId), 'the sweep must not undo a deliberate archive')
466
- assert.ok(state.listArchivedLibraries().some((lib) => lib.id === libId))
467
- })
468
-
469
- test('purging never proposes an archived library that is still in use', () => {
470
- const cwd = path.join(home, 'im-purge')
471
- state.ensureSession('cycle-purge', { cwd })
472
- const libId = state.getSessionBinding('cycle-purge').libraryId
473
- state.archiveLibrary(libId)
474
- const st = state.loadState()
475
- st.libraries[libId].archivedAt = new Date(Date.now() - 40 * 86_400_000).toISOString()
476
- state.saveState(st)
477
- state.updateSettings({ purgeArchivedAfterDays: 30 })
478
- const pass = cycle.runLibraryHousekeeping(registryCtx(['/work/unrelated']))
479
- assert.ok(!pass.purgeCandidates.includes(libId), 'age alone must not queue a live library for deletion')
480
- })
481
-
482
- test('deleting a library the sweep archived while still in use is refused', () => {
483
- const cwd = path.join(home, 'im-delete')
484
- state.ensureSession('cycle-delete', { cwd })
485
- const libId = state.getSessionBinding('cycle-delete').libraryId
486
- // 危险类:旧版扫描归档的库(archivedBy='sweep')仍在被会话使用,一次误点就会删掉全部记忆。
487
- state.archiveLibrary(libId, { by: 'sweep' })
488
- const refused = state.deleteLibrary(libId)
489
- assert.equal(refused.ok, false)
490
- assert.match(refused.error, /still uses it|live conversations/)
491
- assert.ok(state.getLibrary(libId), 'the refusal leaves the data alone')
492
-
493
- // 解绑之后不再是「在用」,同一个调用就放行——这正是正常删除流程。
494
- state.deleteSessionBinding('cycle-delete')
495
- const allowed = state.deleteLibrary(libId)
496
- assert.equal(allowed.ok, true, allowed.error || '')
497
- assert.equal(state.getLibrary(libId), null)
498
- })
499
-
500
- test('a user-archived library can still be deleted while a conversation points at it', () => {
501
- const cwd = path.join(home, 'im-user-delete')
502
- state.ensureSession('cycle-user-delete', { cwd })
503
- const libId = state.getSessionBinding('cycle-user-delete').libraryId
504
- state.archiveLibrary(libId) // by: 'user'
505
- const result = state.deleteLibrary(libId)
506
- assert.equal(result.ok, true, result.error || 'the user asked for this; the bindings go with it')
507
- assert.equal(state.getLibrary(libId), null)
508
- })
509
-
510
- test('a session arriving at an archived library revives it through the fast path', () => {
511
- const cwd = path.join(home, 'im-fastpath')
512
- state.ensureSession('cycle-fastpath', { cwd })
513
- const libId = state.getSessionBinding('cycle-fastpath').libraryId
514
- state.archiveLibrary(libId, { by: 'sweep' })
515
- // 快路径 = 已绑定会话再来一轮。旧版只刷新 lastUsedAt,库永远停在归档。
516
- const again = state.ensureSession('cycle-fastpath', { cwd })
517
- assert.equal(again.libraryId, libId, 'the binding is unchanged')
518
- const lib = state.getLibrary(libId)
519
- assert.notEqual(lib.archived, true, 'an in-use library must not stay archived')
520
- assert.ok(lib.revivedAt)
521
- })
522
-
523
- test('a legacy archive with no recorded source is not revived just because an old binding exists', () => {
524
- // 本机实测:rp(14 个绑定)、另一个工作区库(4 个)都是「归档 + 还有旧绑定」,但 lastUsed 三周前。
525
- // 旧数据分不清是用户归档还是老扫描误归档,所以只复活「还热」的;冷的不动。
526
- const lib = state.createLibrary({ name: 'legacy-cold', cwd: path.join(home, 'legacy-cold') })
527
- const st = state.loadState()
528
- st.libraries[lib.id].archived = true
529
- st.libraries[lib.id].archivedAt = new Date(Date.now() - 40 * 86_400_000).toISOString()
530
- st.libraries[lib.id].lastUsedAt = new Date(Date.now() - 30 * 86_400_000).toISOString()
531
- delete st.libraries[lib.id].archivedBy
532
- st.sessions['cycle-legacy'] = { libraryId: lib.id, scopeKey: path.join(home, 'legacy-cold') }
533
- state.saveState(st)
534
-
535
- const pass = cycle.runLibraryHousekeeping(registryCtx(['/work/unrelated']))
536
- assert.ok(!pass.revived.includes(lib.id), 'a cold legacy archive stays archived')
537
- assert.ok(state.listArchivedLibraries().some((row) => row.id === lib.id))
538
- })
539
-
540
- test('a warm legacy archive (no source recorded, used minutes ago) is revived', () => {
541
- const lib = state.createLibrary({ name: 'legacy-warm', cwd: path.join(home, 'legacy-warm') })
542
- const st = state.loadState()
543
- st.libraries[lib.id].archived = true
544
- st.libraries[lib.id].archivedAt = new Date(Date.now() - 60_000).toISOString()
545
- st.libraries[lib.id].lastUsedAt = new Date(Date.now() - 60_000).toISOString()
546
- delete st.libraries[lib.id].archivedBy
547
- st.sessions['cycle-warm'] = { libraryId: lib.id, scopeKey: path.join(home, 'legacy-warm') }
548
- state.saveState(st)
549
-
550
- const pass = cycle.runLibraryHousekeeping(registryCtx(['/work/unrelated']))
551
- assert.ok(pass.revived.includes(lib.id), 'a library still being written minutes ago must not stay hidden')
552
- assert.ok(state.listLibraries().some((row) => row.id === lib.id))
553
- })
554
-
555
- test('a cold legacy archive with an old binding can still be deleted', () => {
556
- // 本机 rp / 另一个工作区库 形态:很久以前归档、仍留着旧绑定、lastUsed 三周前。
557
- // 它不是扫描误归档(那类会被自愈),也不该因为“有旧绑定”变成永远删不掉。
558
- const lib = state.createLibrary({ name: 'legacy-deletable', cwd: path.join(home, 'legacy-deletable') })
559
- const st = state.loadState()
560
- st.libraries[lib.id].archived = true
561
- st.libraries[lib.id].archivedAt = new Date(Date.now() - 40 * 86_400_000).toISOString()
562
- st.libraries[lib.id].lastUsedAt = new Date(Date.now() - 30 * 86_400_000).toISOString()
563
- delete st.libraries[lib.id].archivedBy
564
- st.sessions['cycle-legacy-del'] = { libraryId: lib.id, scopeKey: path.join(home, 'legacy-deletable') }
565
- state.saveState(st)
566
- const result = state.deleteLibrary(lib.id)
567
- assert.equal(result.ok, true, result.error || '')
568
- })
1
+ import test from 'node:test'
2
+ import assert from 'node:assert/strict'
3
+ import fs from 'node:fs'
4
+ import os from 'node:os'
5
+ import path from 'node:path'
6
+
7
+ const home = fs.mkdtempSync(path.join(os.tmpdir(), 'dsh-memu-memory-cycle-'))
8
+ process.env.DSH_MEMU_HOME = home
9
+
10
+ const state = await import('../lib/state.js')
11
+ const cycle = await import('../lib/cycle.js')
12
+
13
+ test.after(() => {
14
+ try { fs.rmSync(home, { recursive: true, force: true }) } catch {}
15
+ })
16
+
17
+ // A ctx stand-in for a host that can read a transcript and fork it. Consolidation
18
+ // never asks `agents.get` for anything any more, so the recorder counts both sides:
19
+ // followups handed to the user's own live agent (must stay 0) and followups handed
20
+ // to a scratch fork (must be 1 per consolidated session).
21
+ function fakeCtx({ live = [], forkable = null, gone = [], transcript = null, parentOptions = { provider: 'test-provider', model: 'test-model' }, turnReason = { kind: 'completed' } } = {}) {
22
+ const liveSet = new Set(live)
23
+ const forkSet = new Set(forkable || live)
24
+ const goneSet = new Set(gone)
25
+ const created = []
26
+ const disposed = []
27
+ const liveFollowups = []
28
+ const forkFollowups = []
29
+ const seeds = []
30
+ const sessionHandlers = []
31
+ // A transcript that actually contains a person: the value gate reads it before a
32
+ // fork exists, so a fixture with bare `{seq}` markers would be judged empty.
33
+ const events = transcript || [
34
+ { seq: 0, type: 'user/message', data: { source: { kind: 'user' }, content: [{ type: 'text', text: '帮我看一下这个插件为什么空闲整理从来没跑过,日志里只有 skip 一行' }] } },
35
+ { seq: 1, type: 'assistant/message', data: { message: { content: [{ type: 'tool-call', name: 'read', arguments: '{}' }] } } },
36
+ ]
37
+ const ctx = {
38
+ created, disposed, liveFollowups, forkFollowups, seeds,
39
+ on: (name, handler) => {
40
+ if (name !== 'session/event') return () => {}
41
+ sessionHandlers.push(handler)
42
+ return () => {
43
+ const index = sessionHandlers.indexOf(handler)
44
+ if (index >= 0) sessionHandlers.splice(index, 1)
45
+ }
46
+ },
47
+ get: (name) => {
48
+ if (name === 'agents') {
49
+ return {
50
+ get: (id) => (liveSet.has(id)
51
+ ? { followup: (message) => liveFollowups.push({ id, message }), options: parentOptions }
52
+ : undefined),
53
+ create: async (spec) => {
54
+ created.push(spec)
55
+ seeds.push(spec.seed)
56
+ const childSession = { id: spec.sessionId }
57
+ return {
58
+ agent: {
59
+ session: childSession,
60
+ followup: (message) => {
61
+ forkFollowups.push({ child: spec.sessionId, message })
62
+ const proof = { version: 1, jobId: state.getSessionBinding(spec.sessionId).jobId, snapshotHash: state.getSessionBinding(spec.sessionId).snapshotHash, status: 'completed', outcome: 'no_value', checkedRange: { fromSeq: 0, throughSeq: events.at(-1).seq }, createdIds: [], updatedIds: [], heldIds: [] }
63
+ const tick = String.fromCharCode(96).repeat(3)
64
+ for (const handler of sessionHandlers) {
65
+ handler(childSession, { type: 'assistant/message', seq: 99, data: { message: { content: [{ type: 'text', text: tick + 'memu-consolidation-receipt\n' + JSON.stringify(proof) + '\n' + tick }] } } })
66
+ handler(childSession, { type: 'turn/end', seq: 100, data: { turn: 1, reason: turnReason } })
67
+ }
68
+ },
69
+ whenIdle: async () => {},
70
+ },
71
+ dispose: async () => { disposed.push(spec.sessionId) },
72
+ }
73
+ },
74
+ }
75
+ }
76
+ if (name === 'sessionQuery') {
77
+ return {
78
+ readSession: async (id) => {
79
+ if (goneSet.has(id)) throw new Error(`session "${id}" not found`)
80
+ return forkSet.has(id) ? { events, session: { cwd: path.join(home, 'p'), agentPreset: 'rp' } } : { events: [] }
81
+ },
82
+ }
83
+ }
84
+ return undefined
85
+ },
86
+ }
87
+ return ctx
88
+ }
89
+
90
+ function touchAgo(sessionId, minutesAgo) {
91
+ state.setSessionBinding(sessionId, { lastTurnAt: new Date(Date.now() - minutesAgo * 60_000).toISOString() })
92
+ }
93
+
94
+ test('sleep pass does nothing unless it is turned on', async () => {
95
+ // Fresh installs now default this on, so turn it off explicitly to test the
96
+ // disabled branch without depending on the default.
97
+ state.updateSettings({ sleepConsolidation: false })
98
+ const binding = state.ensureSession('cycle-off', { cwd: path.join(home, 'p-off'), agentPreset: 'rp' })
99
+ touchAgo('cycle-off', 120)
100
+ const out = await cycle.runSleepPass(fakeCtx({ live: ['cycle-off'] }))
101
+ assert.equal(out.skipped, 'disabled')
102
+ assert.equal(state.getLastSleepAt('cycle-off'), null)
103
+ })
104
+
105
+ test('an idle live session is consolidated in a fork, never in its own chat', async () => {
106
+ state.updateSettings({ sleepConsolidation: true, sleepAfterIdleMinutes: 10 })
107
+ const binding = state.ensureSession('cycle-idle', { cwd: path.join(home, 'p-idle'), agentPreset: 'rp' })
108
+ touchAgo('cycle-idle', 30)
109
+
110
+ const ctx = fakeCtx({ live: ['cycle-idle'] })
111
+ const first = await cycle.runSleepPass(ctx)
112
+ assert.equal(first.ran, 1)
113
+ assert.ok(state.getLastSleepAt('cycle-idle'))
114
+
115
+ // The reason this whole path exists: a consolidation prompt queued on the chat
116
+ // the user is looking at shows up as a pending draft above the composer and then
117
+ // lives in that transcript forever. The live agent must never be handed one.
118
+ assert.equal(ctx.liveFollowups.length, 0, 'the live session must not get a queued draft')
119
+ assert.equal(ctx.created.length, 1, 'exactly one scratch fork')
120
+ assert.equal(ctx.forkFollowups.length, 1, 'the fork is what carries the work')
121
+ assert.equal(ctx.disposed.length, 1, 'the fork is thrown away afterwards')
122
+ const child = ctx.created[0].sessionId
123
+ assert.match(child, /^memu-consolidate-/)
124
+ assert.equal(ctx.created[0].meta.origin, 'subagent', 'a subagent fork stays out of the window list and the injection path')
125
+ assert.equal(ctx.created[0].meta.parentSession, 'cycle-idle')
126
+ assert.equal(ctx.seeds[0].lastSeq, 1, 'the seed is the parent transcript')
127
+ assert.equal(state.getSessionBinding(child), null, 'worker binding is removed after disposal')
128
+
129
+ const second = await cycle.runSleepPass(fakeCtx({ live: ['cycle-idle'] }))
130
+ assert.equal(second.ran, 0)
131
+ assert.equal(second.skipped, undefined)
132
+ })
133
+
134
+ test('a session that was not idle long enough is left alone', async () => {
135
+ state.updateSettings({ sleepConsolidation: true, sleepAfterIdleMinutes: 30 })
136
+ state.ensureSession('cycle-recent', { cwd: path.join(home, 'p-recent'), agentPreset: 'rp' })
137
+ touchAgo('cycle-recent', 2)
138
+ const out = await cycle.runSleepPass(fakeCtx({ live: ['cycle-recent'] }))
139
+ assert.equal(out.ran, 0)
140
+ assert.equal(state.getLastSleepAt('cycle-recent'), null)
141
+ })
142
+
143
+ test('an unreadable transcript backs off without claiming a completed sleep', async () => {
144
+ state.updateSettings({ sleepConsolidation: true, sleepAfterIdleMinutes: 5 })
145
+ state.ensureSession('cycle-dead', { cwd: path.join(home, 'p-dead'), agentPreset: 'rp' })
146
+ touchAgo('cycle-dead', 60)
147
+ const logs = []
148
+ await cycle.runSleepPass({ get: () => undefined }, { log: (m) => logs.push(m) })
149
+ assert.equal(state.getLastSleepAt('cycle-dead'), null)
150
+ const failed = state.getSessionBinding('cycle-dead')
151
+ assert.ok(Date.parse(failed.sleepRetryAt) > Date.now())
152
+ assert.equal(failed.sleepAttempts, 1)
153
+ await cycle.runSleepPass({ get: () => undefined })
154
+ assert.equal(state.getSessionBinding('cycle-dead').sleepAttempts, 1, 'backoff suppresses immediate retries')
155
+ assert.ok(logs.some((m) => /consolidation skipped for cycle-dead/.test(m)), 'skip logged: ' + logs.join(' | '))
156
+ state.setSessionBinding('cycle-dead', { sleepRetryAt: new Date(0).toISOString() })
157
+ await cycle.runSleepPass(fakeCtx({ live: ['cycle-dead'] }))
158
+ assert.ok(state.getLastSleepAt('cycle-dead'), 'a recovered host retries without another user turn')
159
+ assert.equal(state.getSessionBinding('cycle-dead').lastSleepError, null)
160
+ })
161
+
162
+ test('a fork that cannot be created is logged, not dropped silently', async () => {
163
+ state.updateSettings({ sleepConsolidation: true, sleepAfterIdleMinutes: 5 })
164
+ state.ensureSession('cycle-hist', { cwd: path.join(home, 'p-hist'), agentPreset: 'rp' })
165
+ touchAgo('cycle-hist', 60)
166
+ const logs = []
167
+ const ctx = {
168
+ get: (name) => {
169
+ if (name === 'sessionQuery') return { readSession: async () => ({ events: [
170
+ { seq: 0, type: 'user/message', data: { source: { kind: 'user' }, content: [{ type: 'text', text: '这个 fork 一直建不起来,帮我看下为什么,日志里只有 skipped 一行' }] } },
171
+ ], session: {} }) }
172
+ if (name === 'agents') return {
173
+ get: () => ({ options: { provider: 'test-provider', model: 'test-model' } }),
174
+ create: async () => { throw new Error('no fork in test env') },
175
+ }
176
+ return undefined
177
+ },
178
+ }
179
+ await cycle.runSleepPass(ctx, { log: (m) => logs.push(m) })
180
+ assert.ok(logs.some((m) => /consolidation skipped for cycle-hist: .*no fork in test env/.test(m)), 'attempt logged: ' + logs.join(' | '))
181
+ assert.equal(state.getLastSleepAt('cycle-hist'), null)
182
+ assert.match(state.getSessionBinding('cycle-hist').lastSleepError, /no fork/)
183
+ })
184
+
185
+ test('a fork whose turn errors is backed off, not marked asleep', async () => {
186
+ state.updateSettings({ sleepConsolidation: true, sleepAfterIdleMinutes: 5 })
187
+ state.ensureSession('cycle-fork-error', { cwd: path.join(home, 'p-fork-error'), agentPreset: 'rp' })
188
+ touchAgo('cycle-fork-error', 60)
189
+ const out = await cycle.runSleepPass(fakeCtx({
190
+ live: ['cycle-fork-error'],
191
+ turnReason: { kind: 'error', error: { message: 'prompt variable "{{model}}" has no value' } },
192
+ }))
193
+ assert.equal(out.ran, 0)
194
+ assert.equal(state.getLastSleepAt('cycle-fork-error'), null, 'a failed turn is still unslept')
195
+ const failed = state.getSessionBinding('cycle-fork-error')
196
+ assert.equal(failed.sleepAttempts, 1)
197
+ assert.match(failed.lastSleepError, /fork turn ended error/)
198
+ assert.ok(Date.parse(failed.sleepRetryAt) > Date.now(), 'the scheduler backs off instead of losing the work')
199
+ })
200
+
201
+ test('a turn newer than the last sleep makes the session eligible again', async () => {
202
+ state.updateSettings({ sleepConsolidation: true, sleepAfterIdleMinutes: 5 })
203
+ state.ensureSession('cycle-again', { cwd: path.join(home, 'p-again'), agentPreset: 'rp' })
204
+ // Slept 40 minutes ago, then the conversation continued 15 minutes ago: the
205
+ // earlier sleep is stale and a new one is due.
206
+ state.setLastSleepAt('cycle-again', new Date(Date.now() - 40 * 60_000).toISOString())
207
+ touchAgo('cycle-again', 15)
208
+
209
+ const out = await cycle.runSleepPass(fakeCtx({ live: ['cycle-again'] }))
210
+ assert.equal(out.ran, 1)
211
+ assert.ok(Date.parse(state.getLastSleepAt('cycle-again')) > Date.parse(new Date(Date.now() - 15 * 60_000).toISOString()) - 60_000)
212
+ })
213
+
214
+ test('a conversation the host says is gone is marked once and never retried', async () => {
215
+ state.updateSettings({ sleepConsolidation: true, sleepAfterIdleMinutes: 5 })
216
+ state.ensureSession('cycle-ghost', { cwd: path.join(home, 'p-ghost'), agentPreset: 'rp' })
217
+ touchAgo('cycle-ghost', 120)
218
+ const logs = []
219
+ const out = await cycle.runSleepPass(fakeCtx({ live: ['cycle-ghost'], gone: ['cycle-ghost'] }), { log: (m) => logs.push(m) })
220
+ assert.equal(out.ran, 0)
221
+ const binding = state.getSessionBinding('cycle-ghost')
222
+ assert.equal(binding.sessionGone, true, 'the mark is what stops the hourly retry')
223
+ assert.equal(binding.sleepAttempts, 0, 'a deleted session is not a transient failure')
224
+ assert.equal(binding.sleepRetryAt, null, 'nothing to retry later')
225
+ assert.ok(logs.some((m) => /no longer exists/.test(m)), 'explained once: ' + logs.join(' | '))
226
+ const quiet = await cycle.runSleepPass(fakeCtx({ live: ['cycle-ghost'] }))
227
+ assert.equal(quiet.ran, 0, 'the next sweep does not consolidate a deleted session again')
228
+ })
229
+
230
+ test('a policy greeting skip does not claim a completed worker check', async () => {
231
+ state.updateSettings({ sleepConsolidation: true, sleepAfterIdleMinutes: 5 })
232
+ state.ensureSession('cycle-smalltalk', { cwd: path.join(home, 'p-small'), agentPreset: 'rp' })
233
+ touchAgo('cycle-smalltalk', 20)
234
+ const ctx = fakeCtx({ live: ['cycle-smalltalk'], transcript: [
235
+ { seq: 0, type: 'user/message', data: { source: { kind: 'user' }, content: [{ type: 'text', text: '谢谢' }] } },
236
+ { seq: 1, type: 'assistant/message', data: { message: { content: [{ type: 'text', text: '不客气' }] } } },
237
+ ] })
238
+ const out = await cycle.runSleepPass(ctx)
239
+ assert.equal(out.ran, 0, 'a policy skip is not a verified worker receipt')
240
+ assert.equal(ctx.created.length, 0, 'no fork for small talk')
241
+ assert.ok(state.getLastSleepAt('cycle-smalltalk'), 'a terminal skip is recorded so the same greetings are not re-read every sweep')
242
+ })
243
+
244
+ test('auto curation stays off unless an interval is set', async () => {
245
+ const out = await cycle.runCurationPass(fakeCtx({ live: ['cycle-idle'] }))
246
+ assert.equal(out.skipped, 'disabled')
247
+ })
248
+
249
+ test('auto curation waits for a live parent and does not advance the schedule', async () => {
250
+ state.updateSettings({ autoCurateEveryHours: 1, autoCurateSessionLimit: 5 })
251
+ state.setCycleState({ lastCurateAt: null })
252
+ state.ensureSession('cycle-curate', { cwd: path.join(home, 'p-curate'), agentPreset: 'rp' })
253
+ touchAgo('cycle-curate', 5)
254
+
255
+ const out = await cycle.runCurationPass(fakeCtx({ live: [] }))
256
+ assert.equal(out.skipped, 'no-live-parent')
257
+ assert.equal(out.ran, 0)
258
+ assert.ok(!state.getCycleState().lastCurateAt, 'a run that never started must not reschedule')
259
+ })
260
+
261
+ function registryCtx(paths) {
262
+ return {
263
+ get: (name) => (name === 'workspaceRegistry' ? { list: () => paths.map((p) => ({ path: p })) } : undefined),
264
+ }
265
+ }
266
+
267
+ test('a library is archived only when its workspace leaves the DSH registry', () => {
268
+ const lib = state.createLibrary({ name: 'cycle-ws', cwd: '/work/cycle-ws' })
269
+ assert.ok(state.listLibraries().some((l) => l.id === lib.id), 'starts active')
270
+
271
+ // Registered: this library must not be touched (other leftovers from earlier
272
+ // tests may legitimately archive in the same sweep, so assert only about ours).
273
+ const stillThere = cycle.runLibraryHousekeeping(registryCtx(['/work/cycle-ws', '/work/other']))
274
+ assert.ok(!stillThere.archived.includes(lib.id))
275
+
276
+ // Unregistered (but still on disk): archived.
277
+ const removed = cycle.runLibraryHousekeeping(registryCtx(['/work/other']))
278
+ assert.ok(removed.archived.includes(lib.id), 'library should archive when its workspace is unregistered')
279
+ assert.ok(state.listArchivedLibraries().map((l) => l.id).includes(lib.id))
280
+ assert.ok(state.listLibraries().every((l) => l.id !== lib.id), 'archived libraries leave the active list')
281
+ })
282
+
283
+ test('an absent or empty registry archives nothing (fail-open)', () => {
284
+ const lib = state.createLibrary({ name: 'cycle-safe', cwd: '/work/cycle-safe' })
285
+ // No workspaceRegistry service at all.
286
+ const noService = cycle.runLibraryHousekeeping({ get: () => undefined })
287
+ assert.deepEqual(noService.archived, [])
288
+ assert.deepEqual(noService.revived, [])
289
+ // Registry present but empty — a fresh install must not wipe the library list.
290
+ const empty = cycle.runLibraryHousekeeping(registryCtx([]))
291
+ assert.deepEqual(empty.archived, [])
292
+ assert.ok(state.getLibrary(lib.id))
293
+ })
294
+
295
+ test('a workspace coming back revives its library', () => {
296
+ const lib = state.createLibrary({ name: 'cycle-revive', cwd: '/work/cycle-revive' })
297
+ cycle.runLibraryHousekeeping(registryCtx(['/work/other']))
298
+ assert.ok(state.listArchivedLibraries().some((l) => l.id === lib.id), 'should have been archived')
299
+ const back = cycle.runLibraryHousekeeping(registryCtx(['/work/cycle-revive']))
300
+ assert.ok(back.revived.includes(lib.id))
301
+ assert.ok(state.listLibraries().some((l) => l.id === lib.id), 'should be active again')
302
+ })
303
+
304
+ test('archived libraries are kept forever unless an age is set', () => {
305
+ const lib = state.createLibrary({ name: 'cycle-keep', cwd: '/work/cycle-keep' })
306
+ state.archiveLibrary(lib.id)
307
+ state.updateSettings({ purgeArchivedAfterDays: 0 })
308
+ const manual = cycle.runLibraryHousekeeping(registryCtx(['/work/somewhere-else']))
309
+ assert.deepEqual(manual.purged, [])
310
+ assert.ok(state.getLibrary(lib.id), 'manual mode must not delete')
311
+
312
+ // Now make it old and turn on purging.
313
+ const st = state.loadState()
314
+ st.libraries[lib.id].archivedAt = new Date(Date.now() - 40 * 86_400_000).toISOString()
315
+ state.saveState(st)
316
+ state.updateSettings({ purgeArchivedAfterDays: 30 })
317
+ const purged = cycle.runLibraryHousekeeping(registryCtx(['/work/somewhere-else']))
318
+ assert.deepEqual(purged.purged, [])
319
+ assert.ok(purged.purgeCandidates.includes(lib.id))
320
+ assert.ok(state.getLibrary(lib.id), 'age produces a review candidate, never an automatic library deletion')
321
+ })
322
+
323
+ test('deleting an un-archived library is refused', () => {
324
+ const lib = state.createLibrary({ name: 'cycle-nodelete', cwd: '/work/cycle-nodelete' })
325
+ const result = state.deleteLibrary(lib.id)
326
+ assert.equal(result.ok, false)
327
+ assert.match(result.error, /archive the library before deleting/)
328
+ assert.ok(state.getLibrary(lib.id))
329
+ })
330
+
331
+ test('auto curation is not due yet', async () => {
332
+ state.updateSettings({ autoCurateEveryHours: 6 })
333
+ state.setCycleState({ lastCurateAt: new Date().toISOString() })
334
+ const out = await cycle.runCurationPass(fakeCtx({ live: ['cycle-curate'] }))
335
+ assert.equal(out.skipped, 'not-due')
336
+ })
337
+ test('a thin turn shortly after a consolidation waits for real evidence', async () => {
338
+ state.updateSettings({ sleepConsolidation: true, sleepAfterIdleMinutes: 3 })
339
+ state.ensureSession('cycle-cooldown', { cwd: path.join(home, 'p-cooldown'), agentPreset: 'rp' })
340
+ // 刚整理过(20 分钟前),5 分钟前只补了一句很短的话:再 fork 一次要把整段转录
341
+ // 重新种进去,纯粹浪费 token。评分门槛会把它压到饥饿阈值之后。
342
+ state.setSessionBinding('cycle-cooldown', { lastTurnAt: new Date(Date.now() - 5 * 60_000).toISOString() })
343
+ state.setLastSleepAt('cycle-cooldown', new Date(Date.now() - 20 * 60_000).toISOString())
344
+ const ctx = fakeCtx({ live: ['cycle-cooldown'] })
345
+ const out = await cycle.runSleepPass(ctx)
346
+ assert.equal(out.ran, 0)
347
+ assert.equal(ctx.created.length, 0, 'a thin follow-up must not buy another full-transcript fork')
348
+ // 收尾:把它标记为已睡,避免候选泄漏到后续用例。
349
+ state.setLastSleepAt('cycle-cooldown', new Date().toISOString())
350
+ })
351
+
352
+ test('a session that just injected memory is left alone by the idle sweep', async () => {
353
+ state.updateSettings({ sleepConsolidation: true, sleepAfterIdleMinutes: 3 })
354
+ state.ensureSession('cycle-recall', { cwd: path.join(home, 'p-recall'), agentPreset: 'rp' })
355
+ state.setSessionBinding('cycle-recall', {
356
+ // 空闲已过饥饿阈值,按评分本会 fork;但 5 分钟前刚注入了记忆,抑制优先。
357
+ lastTurnAt: new Date(Date.now() - 20 * 60_000).toISOString(),
358
+ lastInjectedAt: new Date(Date.now() - 5 * 60_000).toISOString(),
359
+ })
360
+ const ctx = fakeCtx({ live: ['cycle-recall'] })
361
+ const out = await cycle.runSleepPass(ctx)
362
+ assert.equal(out.ran, 0)
363
+ assert.equal(ctx.created.length, 0, 'a session with fresh memory context does not need a fork')
364
+ state.setLastSleepAt('cycle-recall', new Date().toISOString())
365
+ })
366
+
367
+ // H5: a missing file is not the host saying the conversation was deleted.
368
+ // captureSessionSnapshot marks a failed read retryable on purpose ("读失败,可重试"),
369
+ // but the bare word ENOENT in isGoneSessionError used to turn that into sessionGone —
370
+ // and the sweep skips a marked session until some later human message clears it.
371
+ test('a transcript that cannot be read is retried, not marked as a deleted conversation', async () => {
372
+ state.updateSettings({ sleepConsolidation: true, sleepAfterIdleMinutes: 5 })
373
+ state.ensureSession('cycle-enoent', { cwd: path.join(home, 'p-enoent'), agentPreset: 'rp' })
374
+ // 6 minutes: still idle under the 5-minute threshold, but the sweep takes the two
375
+ // newest candidates and this file shares one state directory across its tests.
376
+ touchAgo('cycle-enoent', 6)
377
+ const logs = []
378
+ const ctx = {
379
+ get: (name) => {
380
+ if (name === 'sessionQuery') {
381
+ return {
382
+ readSession: async () => {
383
+ const error = new Error("ENOENT: no such file or directory, open 'D:/home/sessions/cycle-enoent/log.jsonl'")
384
+ error.code = 'ENOENT'
385
+ throw error
386
+ },
387
+ }
388
+ }
389
+ if (name === 'agents') {
390
+ return { get: () => ({}), create: async () => { throw new Error('a session that cannot be read must not be forked') } }
391
+ }
392
+ return undefined
393
+ },
394
+ }
395
+ await cycle.runSleepPass(ctx, { log: (message) => logs.push(message), limit: 10 })
396
+ const binding = state.getSessionBinding('cycle-enoent')
397
+ assert.ok(!binding.sessionGone, 'a transient read failure is not the host reporting a deletion')
398
+ assert.equal(binding.sleepAttempts, 1, 'it backs off like any other failure')
399
+ assert.ok(Date.parse(binding.sleepRetryAt) > Date.now(), 'it is retried later')
400
+ assert.match(binding.lastSleepError, /ENOENT/)
401
+ assert.ok(logs.some((message) => /consolidation skipped for cycle-enoent/.test(message)), 'stated once: ' + logs.join(' | '))
402
+ assert.equal(state.getLastSleepAt('cycle-enoent'), null, 'nothing was consolidated, so nothing is marked asleep')
403
+ })
404
+
405
+ test('only the host saying the conversation is gone counts as deleted', () => {
406
+ assert.equal(cycle.isGoneSessionError('session "abc" not found'), true)
407
+ assert.equal(cycle.isGoneSessionError('no such session: abc'), true)
408
+ assert.equal(cycle.isGoneSessionError('this session does not exist any more'), true)
409
+ assert.equal(cycle.isGoneSessionError("ENOENT: no such file or directory, open 'D:/x/log.jsonl'"), false)
410
+ assert.equal(cycle.isGoneSessionError('EACCES: permission denied, open D:/x'), false)
411
+ })
412
+ // ---------------------------------------------------------------- 归档 vs 在用
413
+
414
+ // 未注册的工作区路径不应影响绑定会话继续使用库;这里将该时序压成三轮 sweep。
415
+
416
+ test('a library bound to a live conversation is never archived for an unregistered scope', () => {
417
+ const cwd = path.join(home, 'im-in-use')
418
+ state.ensureSession('cycle-im', { cwd })
419
+ const binding = state.getSessionBinding('cycle-im')
420
+ const libId = binding.libraryId
421
+ assert.ok(libId, 'the session created a library')
422
+
423
+ const first = cycle.runLibraryHousekeeping(registryCtx(['/work/unrelated']))
424
+ assert.ok(!first.archived.includes(libId), 'an in-use library must not be archived')
425
+ assert.ok(first.skippedInUse.includes(libId), 'the sweep must report why it skipped')
426
+ assert.ok(state.listLibraries().some((lib) => lib.id === libId), 'it stays in the active list')
427
+
428
+ // 连续三轮(≈15 分钟的真实节奏)都不能翻车。
429
+ const second = cycle.runLibraryHousekeeping(registryCtx(['/work/unrelated']))
430
+ const third = cycle.runLibraryHousekeeping(registryCtx(['/work/unrelated']))
431
+ for (const pass of [second, third]) assert.ok(!pass.archived.includes(libId))
432
+ const lib = state.getLibrary(libId)
433
+ assert.equal(lib.archived, undefined, 'never archived')
434
+ assert.equal(lib.archivedAt, undefined)
435
+ })
436
+
437
+ test('an unbound library with an unregistered scope still archives (the cleanup keeps working)', () => {
438
+ const lib = state.createLibrary({ name: 'cycle-unused', cwd: '/work/cycle-unused' })
439
+ const pass = cycle.runLibraryHousekeeping(registryCtx(['/work/unrelated']))
440
+ assert.ok(pass.archived.includes(lib.id), 'nobody uses it, so the old behaviour stands')
441
+ assert.equal(state.getLibrary(lib.id).archivedBy, 'sweep', 'the sweep records that it did the archiving')
442
+ })
443
+
444
+ test('a library the old sweep archived while in use comes back instead of staying hidden', () => {
445
+ const cwd = path.join(home, 'im-misarchived')
446
+ state.ensureSession('cycle-im-revive', { cwd })
447
+ const libId = state.getSessionBinding('cycle-im-revive').libraryId
448
+ // 复现旧版:扫描把在用的库归档,且当时还没有 archivedBy 字段。
449
+ state.archiveLibrary(libId, { by: 'sweep' })
450
+ assert.ok(state.listArchivedLibraries().some((lib) => lib.id === libId))
451
+
452
+ const pass = cycle.runLibraryHousekeeping(registryCtx(['/work/unrelated']))
453
+ assert.ok(pass.revived.includes(libId), 'an in-use archive is a bug and must self-heal')
454
+ assert.ok(state.listLibraries().some((lib) => lib.id === libId))
455
+ assert.ok(!pass.archived.includes(libId), 'and it must not be archived again in the same pass')
456
+ })
457
+
458
+ test('a user-archived library is respected even while a conversation still points at it', () => {
459
+ const cwd = path.join(home, 'im-user-archived')
460
+ state.ensureSession('cycle-user-archive', { cwd })
461
+ const libId = state.getSessionBinding('cycle-user-archive').libraryId
462
+ state.archiveLibrary(libId) // 默认 by: 'user'
463
+ const pass = cycle.runLibraryHousekeeping(registryCtx(['/work/unrelated']))
464
+ assert.ok(!pass.revived.includes(libId), 'the sweep must not undo a deliberate archive')
465
+ assert.ok(state.listArchivedLibraries().some((lib) => lib.id === libId))
466
+ })
467
+
468
+ test('purging never proposes an archived library that is still in use', () => {
469
+ const cwd = path.join(home, 'im-purge')
470
+ state.ensureSession('cycle-purge', { cwd })
471
+ const libId = state.getSessionBinding('cycle-purge').libraryId
472
+ state.archiveLibrary(libId)
473
+ const st = state.loadState()
474
+ st.libraries[libId].archivedAt = new Date(Date.now() - 40 * 86_400_000).toISOString()
475
+ state.saveState(st)
476
+ state.updateSettings({ purgeArchivedAfterDays: 30 })
477
+ const pass = cycle.runLibraryHousekeeping(registryCtx(['/work/unrelated']))
478
+ assert.ok(!pass.purgeCandidates.includes(libId), 'age alone must not queue a live library for deletion')
479
+ })
480
+
481
+ test('deleting a library the sweep archived while still in use is refused', () => {
482
+ const cwd = path.join(home, 'im-delete')
483
+ state.ensureSession('cycle-delete', { cwd })
484
+ const libId = state.getSessionBinding('cycle-delete').libraryId
485
+ // 危险类:旧版扫描归档的库(archivedBy='sweep')仍在被会话使用,一次误点就会删掉全部记忆。
486
+ state.archiveLibrary(libId, { by: 'sweep' })
487
+ const refused = state.deleteLibrary(libId)
488
+ assert.equal(refused.ok, false)
489
+ assert.match(refused.error, /still uses it|live conversations/)
490
+ assert.ok(state.getLibrary(libId), 'the refusal leaves the data alone')
491
+
492
+ // 解绑之后不再是「在用」,同一个调用就放行——这正是正常删除流程。
493
+ state.deleteSessionBinding('cycle-delete')
494
+ const allowed = state.deleteLibrary(libId)
495
+ assert.equal(allowed.ok, true, allowed.error || '')
496
+ assert.equal(state.getLibrary(libId), null)
497
+ })
498
+
499
+ test('a user-archived library can still be deleted while a conversation points at it', () => {
500
+ const cwd = path.join(home, 'im-user-delete')
501
+ state.ensureSession('cycle-user-delete', { cwd })
502
+ const libId = state.getSessionBinding('cycle-user-delete').libraryId
503
+ state.archiveLibrary(libId) // by: 'user'
504
+ const result = state.deleteLibrary(libId)
505
+ assert.equal(result.ok, true, result.error || 'the user asked for this; the bindings go with it')
506
+ assert.equal(state.getLibrary(libId), null)
507
+ })
508
+
509
+ test('a session arriving at an archived library revives it through the fast path', () => {
510
+ const cwd = path.join(home, 'im-fastpath')
511
+ state.ensureSession('cycle-fastpath', { cwd })
512
+ const libId = state.getSessionBinding('cycle-fastpath').libraryId
513
+ state.archiveLibrary(libId, { by: 'sweep' })
514
+ // 快路径 = 已绑定会话再来一轮。旧版只刷新 lastUsedAt,库永远停在归档。
515
+ const again = state.ensureSession('cycle-fastpath', { cwd })
516
+ assert.equal(again.libraryId, libId, 'the binding is unchanged')
517
+ const lib = state.getLibrary(libId)
518
+ assert.notEqual(lib.archived, true, 'an in-use library must not stay archived')
519
+ assert.ok(lib.revivedAt)
520
+ })
521
+
522
+ test('a legacy archive with no recorded source is not revived just because an old binding exists', () => {
523
+ // 旧归档库仍有历史绑定,但 lastUsed 已超出活跃窗口。
524
+ // 旧数据分不清是用户归档还是老扫描误归档,所以只复活「还热」的;冷的不动。
525
+ const lib = state.createLibrary({ name: 'legacy-cold', cwd: path.join(home, 'legacy-cold') })
526
+ const st = state.loadState()
527
+ st.libraries[lib.id].archived = true
528
+ st.libraries[lib.id].archivedAt = new Date(Date.now() - 40 * 86_400_000).toISOString()
529
+ st.libraries[lib.id].lastUsedAt = new Date(Date.now() - 30 * 86_400_000).toISOString()
530
+ delete st.libraries[lib.id].archivedBy
531
+ st.sessions['cycle-legacy'] = { libraryId: lib.id, scopeKey: path.join(home, 'legacy-cold') }
532
+ state.saveState(st)
533
+
534
+ const pass = cycle.runLibraryHousekeeping(registryCtx(['/work/unrelated']))
535
+ assert.ok(!pass.revived.includes(lib.id), 'a cold legacy archive stays archived')
536
+ assert.ok(state.listArchivedLibraries().some((row) => row.id === lib.id))
537
+ })
538
+
539
+ test('a warm legacy archive (no source recorded, used minutes ago) is revived', () => {
540
+ const lib = state.createLibrary({ name: 'legacy-warm', cwd: path.join(home, 'legacy-warm') })
541
+ const st = state.loadState()
542
+ st.libraries[lib.id].archived = true
543
+ st.libraries[lib.id].archivedAt = new Date(Date.now() - 60_000).toISOString()
544
+ st.libraries[lib.id].lastUsedAt = new Date(Date.now() - 60_000).toISOString()
545
+ delete st.libraries[lib.id].archivedBy
546
+ st.sessions['cycle-warm'] = { libraryId: lib.id, scopeKey: path.join(home, 'legacy-warm') }
547
+ state.saveState(st)
548
+
549
+ const pass = cycle.runLibraryHousekeeping(registryCtx(['/work/unrelated']))
550
+ assert.ok(pass.revived.includes(lib.id), 'a library still being written minutes ago must not stay hidden')
551
+ assert.ok(state.listLibraries().some((row) => row.id === lib.id))
552
+ })
553
+
554
+ test('a cold legacy archive with an old binding can still be deleted', () => {
555
+ // 归档已久的库仍有旧绑定,lastUsed 已超出活跃窗口。
556
+ // 它不是扫描误归档(那类会被自愈),也不该因为“有旧绑定”变成永远删不掉。
557
+ const lib = state.createLibrary({ name: 'legacy-deletable', cwd: path.join(home, 'legacy-deletable') })
558
+ const st = state.loadState()
559
+ st.libraries[lib.id].archived = true
560
+ st.libraries[lib.id].archivedAt = new Date(Date.now() - 40 * 86_400_000).toISOString()
561
+ st.libraries[lib.id].lastUsedAt = new Date(Date.now() - 30 * 86_400_000).toISOString()
562
+ delete st.libraries[lib.id].archivedBy
563
+ st.sessions['cycle-legacy-del'] = { libraryId: lib.id, scopeKey: path.join(home, 'legacy-deletable') }
564
+ state.saveState(st)
565
+ const result = state.deleteLibrary(lib.id)
566
+ assert.equal(result.ok, true, result.error || '')
567
+ })