dsh-memu-memory 1.4.2 → 1.4.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (389) hide show
  1. package/AGENTS.md +108 -110
  2. package/CHANGELOG.md +169 -868
  3. package/LICENSE +21 -21
  4. package/README.md +368 -374
  5. package/README.zh.md +354 -360
  6. package/assets/icon.svg +7 -7
  7. package/cordis.patch.yml +8 -8
  8. package/docs/active-memory-ab.md +279 -385
  9. package/docs/binding-lifecycle.md +99 -99
  10. package/docs/client-conventions.md +75 -75
  11. package/docs/contributing.md +217 -217
  12. package/docs/emotion-model-spec.md +247 -281
  13. package/docs/env-and-commands.md +149 -152
  14. package/docs/host-adaptation.md +339 -360
  15. package/docs/host-api.md +131 -137
  16. package/docs/host-versions.md +117 -120
  17. package/docs/mcp-porting.md +146 -146
  18. package/docs/memory-semantics.md +271 -259
  19. package/docs/pending-work.md +44 -51
  20. package/docs/troubleshooting.md +909 -854
  21. package/lib/active-memory.js +160 -165
  22. package/lib/activity-log.js +207 -207
  23. package/lib/auto-link/apply.js +248 -249
  24. package/lib/auto-link/candidates.js +163 -163
  25. package/lib/auto-link/decide.js +300 -300
  26. package/lib/auto-link/normalize.js +99 -99
  27. package/lib/auto-link/policy.js +42 -42
  28. package/lib/auto-link/suppression.js +101 -101
  29. package/lib/auto-link/terminology.js +311 -311
  30. package/lib/backup.js +1254 -1254
  31. package/lib/binding-diagnostics.js +634 -634
  32. package/lib/budget.js +118 -118
  33. package/lib/client.js +9820 -9751
  34. package/lib/commitment.js +178 -138
  35. package/lib/consolidation-ledger.js +434 -438
  36. package/lib/consolidation-receipt.js +386 -387
  37. package/lib/consolidation-snapshot.js +420 -405
  38. package/lib/consolidation-worker.js +240 -241
  39. package/lib/context.js +33 -33
  40. package/lib/curator-evidence.js +131 -131
  41. package/lib/curator-policy.js +198 -202
  42. package/lib/curator.js +1813 -1811
  43. package/lib/cycle.js +524 -513
  44. package/lib/diagnostics.js +524 -524
  45. package/lib/embedding-catalog.js +1051 -1055
  46. package/lib/embedding-download.js +637 -607
  47. package/lib/embedding-runtime.js +946 -946
  48. package/lib/engine.js +1103 -1103
  49. package/lib/entity-repair.js +285 -285
  50. package/lib/environment-check.js +394 -394
  51. package/lib/fork-model.js +312 -312
  52. package/lib/freshness.js +128 -121
  53. package/lib/global-graph.js +389 -389
  54. package/lib/graph.js +1193 -1193
  55. package/lib/host-surface.js +30 -30
  56. package/lib/inbound.js +284 -281
  57. package/lib/index.js +506 -511
  58. package/lib/inject.js +2639 -2619
  59. package/lib/lexicon-scope.js +143 -143
  60. package/lib/lexicon.js +1183 -1192
  61. package/lib/lifecycle-audit.js +37 -0
  62. package/lib/local-embedding-entry.js +145 -145
  63. package/lib/local-embedding-manager.js +306 -306
  64. package/lib/local-embedding-protocol.js +210 -210
  65. package/lib/local-embedding-worker.js +682 -682
  66. package/lib/local-vector-service.js +506 -453
  67. package/lib/maintenance-ledger.js +138 -0
  68. package/lib/maintenance-review.js +103 -0
  69. package/lib/maintenance-runner.js +267 -0
  70. package/lib/managed-runtime.js +118 -118
  71. package/lib/media.js +607 -513
  72. package/lib/memory.js +5035 -4941
  73. package/lib/memu-config.js +213 -213
  74. package/lib/memu.js +565 -565
  75. package/lib/migrate.js +200 -200
  76. package/lib/mood.js +300 -300
  77. package/lib/paths.js +453 -457
  78. package/lib/port-surface.js +82 -82
  79. package/lib/preset-mount.js +79 -0
  80. package/lib/preset-scope.js +126 -126
  81. package/lib/private-links.js +567 -567
  82. package/lib/private.js +2198 -2209
  83. package/lib/prompts/global-curator.md +135 -135
  84. package/lib/prompts/image-caption.md +1 -1
  85. package/lib/prompts/private-consolidation.coding.md +39 -39
  86. package/lib/prompts/private-consolidation.md +32 -32
  87. package/lib/prompts/private-consolidation.mixed.md +37 -37
  88. package/lib/prompts/private-consolidation.rp.md +47 -47
  89. package/lib/prompts/private-policy.coding.md +35 -35
  90. package/lib/prompts/private-policy.md +36 -36
  91. package/lib/prompts/private-policy.mixed.md +29 -29
  92. package/lib/prompts/private-policy.rp.md +43 -43
  93. package/lib/prompts/system-guide.coding.md +20 -20
  94. package/lib/prompts/system-guide.md +25 -25
  95. package/lib/prompts/system-guide.mixed.md +22 -22
  96. package/lib/prompts/system-guide.rp.md +23 -23
  97. package/lib/prompts.js +331 -331
  98. package/lib/recall-cache.js +212 -212
  99. package/lib/remote-summary.js +123 -123
  100. package/lib/rpc.js +2531 -2532
  101. package/lib/salient-wake.js +438 -438
  102. package/lib/snippet.js +125 -125
  103. package/lib/state.js +1948 -1928
  104. package/lib/stats.js +236 -236
  105. package/lib/temporal.js +345 -348
  106. package/lib/text-retrieval.js +992 -1001
  107. package/lib/text-similarity.js +305 -305
  108. package/lib/tokenizer-v2.js +271 -271
  109. package/lib/tools.js +1098 -1091
  110. package/lib/turn-log.js +545 -545
  111. package/lib/vector-migration.js +928 -930
  112. package/lib/vector-profile.js +1353 -1359
  113. package/lib/visibility.js +59 -59
  114. package/lib/webui/graph-LICENSE.txt +1 -1
  115. package/lib/webui/graph-view.bundle.js +2 -2
  116. package/lib/webui/graph-view.js +1171 -1175
  117. package/lib/webui/mark.svg +7 -7
  118. package/lib/webui/standalone.css +1178 -1178
  119. package/lib/webui/standalone.js +238 -238
  120. package/lib/webui.js +136 -136
  121. package/lib/worker-pool.js +1015 -979
  122. package/package.json +153 -153
  123. package/requirements.lock +34 -34
  124. package/scripts/acceptance-local.mjs +946 -946
  125. package/scripts/active-memory-ab-live.mjs +653 -655
  126. package/scripts/active-memory-ab.mjs +1302 -1302
  127. package/scripts/audit-memory-lifecycle.mjs +55 -0
  128. package/scripts/bench-recall.mjs +142 -142
  129. package/scripts/build-graph.mjs +44 -45
  130. package/scripts/chain-matrix.mjs +541 -541
  131. package/scripts/check-all.mjs +68 -74
  132. package/scripts/check-doc-drift.mjs +547 -547
  133. package/scripts/check-graph-browser.mjs +261 -261
  134. package/scripts/check-i18n.mjs +81 -83
  135. package/scripts/check-idle-compositing.mjs +61 -61
  136. package/scripts/check-seed-compat.mjs +115 -118
  137. package/scripts/check-text-format.mjs +55 -0
  138. package/scripts/curator-pair-calibrate.mjs +259 -259
  139. package/scripts/diagnose-bindings.mjs +176 -176
  140. package/scripts/drive-session.mjs +863 -864
  141. package/scripts/engine-smoke.mjs +69 -69
  142. package/scripts/entity-dedupe.mjs +110 -110
  143. package/scripts/lexicon-calibrate.mjs +230 -230
  144. package/scripts/lexicon-dedupe.mjs +318 -318
  145. package/scripts/local-runtime-install.mjs +142 -142
  146. package/scripts/local-runtime-verify.mjs +56 -56
  147. package/scripts/local-vector-verify.mjs +93 -93
  148. package/scripts/make-readme-shots.mjs +59 -59
  149. package/scripts/migrate-visibility.mjs +94 -94
  150. package/scripts/mock-llm.mjs +938 -903
  151. package/scripts/preview.mjs +58 -58
  152. package/scripts/prune-sessions.mjs +31 -34
  153. package/scripts/prune-turnlogs.mjs +29 -30
  154. package/scripts/prune-vectors.mjs +24 -24
  155. package/scripts/rebuild-auto-links.mjs +252 -252
  156. package/scripts/recall-bench.mjs +820 -820
  157. package/scripts/repetition-ab-scenarios.mjs +93 -93
  158. package/scripts/repetition-detector-snapshot.mjs +314 -314
  159. package/scripts/repetition-eval-live.mjs +360 -360
  160. package/scripts/repetition-eval.mjs +702 -702
  161. package/scripts/replay.mjs +705 -575
  162. package/scripts/setup.mjs +46 -46
  163. package/scripts/simulate-injection.mjs +299 -301
  164. package/tests/absorb-review.test.mjs +354 -354
  165. package/tests/activation.test.mjs +89 -89
  166. package/tests/active-memory-ab.test.mjs +745 -745
  167. package/tests/active-memory.test.mjs +129 -129
  168. package/tests/activity-log.test.mjs +126 -126
  169. package/tests/activity-wiring.test.mjs +155 -155
  170. package/tests/appendix-b.test.mjs +217 -217
  171. package/tests/appendix-b2.test.mjs +166 -166
  172. package/tests/audit-batch3.test.mjs +247 -247
  173. package/tests/audit-regression.test.mjs +275 -275
  174. package/tests/audit-safety.test.mjs +227 -227
  175. package/tests/auto-link-candidates.test.mjs +245 -245
  176. package/tests/auto-link-decide.test.mjs +512 -512
  177. package/tests/auto-link-migration.test.mjs +133 -133
  178. package/tests/backend-compensation.test.mjs +272 -272
  179. package/tests/backup.test.mjs +793 -793
  180. package/tests/binding-diagnostics.test.mjs +720 -720
  181. package/tests/browser.test.mjs +476 -476
  182. package/tests/client-export.test.mjs +521 -521
  183. package/tests/client-render.test.mjs +2008 -1728
  184. package/tests/coalesce.test.mjs +113 -113
  185. package/tests/commitment.test.mjs +243 -144
  186. package/tests/config.test.mjs +159 -159
  187. package/tests/consolidation-credential.test.mjs +330 -330
  188. package/tests/consolidation-feed.test.mjs +122 -122
  189. package/tests/consolidation-fork.test.mjs +1586 -1539
  190. package/tests/consolidation-ledger.test.mjs +389 -389
  191. package/tests/consolidation-snapshot.test.mjs +567 -505
  192. package/tests/consolidation-value.test.mjs +89 -89
  193. package/tests/context-scope.test.mjs +40 -40
  194. package/tests/cross-library-recall.test.mjs +269 -269
  195. package/tests/cue.test.mjs +58 -58
  196. package/tests/curator-absorb.test.mjs +444 -444
  197. package/tests/curator-calibrate.test.mjs +173 -173
  198. package/tests/curator-clusters.test.mjs +306 -306
  199. package/tests/curator-commit.test.mjs +325 -325
  200. package/tests/curator-contract.test.mjs +191 -191
  201. package/tests/curator-evidence.test.mjs +102 -102
  202. package/tests/curator-link.test.mjs +317 -317
  203. package/tests/curator-pairing.test.mjs +339 -339
  204. package/tests/curator-probe.test.mjs +490 -490
  205. package/tests/curator-review-mode.test.mjs +315 -315
  206. package/tests/curator.test.mjs +152 -152
  207. package/tests/cycle.test.mjs +567 -568
  208. package/tests/diagnostics.test.mjs +278 -278
  209. package/tests/disclosure.test.mjs +249 -249
  210. package/tests/doc-drift.test.mjs +342 -342
  211. package/tests/drive-session.test.mjs +152 -152
  212. package/tests/dynamic-rrf.test.mjs +182 -182
  213. package/tests/dynamic-threshold.test.mjs +52 -52
  214. package/tests/embedding-catalog.test.mjs +374 -374
  215. package/tests/embedding-download.test.mjs +529 -486
  216. package/tests/embedding-runtime.test.mjs +449 -449
  217. package/tests/emotion-chain.test.mjs +84 -84
  218. package/tests/emotion-contract.test.mjs +445 -445
  219. package/tests/engine.test.mjs +108 -108
  220. package/tests/entity-merge.test.mjs +278 -278
  221. package/tests/environment-check.test.mjs +187 -187
  222. package/tests/fact-version.test.mjs +146 -146
  223. package/tests/fixtures/active-memory-ab/README.md +56 -56
  224. package/tests/fixtures/active-memory-ab/cases/01-clean-dense-turn.json +351 -351
  225. package/tests/fixtures/active-memory-ab/cases/02-clean-thin-turn.json +122 -122
  226. package/tests/fixtures/active-memory-ab/cases/03-clean-starved-small.json +125 -125
  227. package/tests/fixtures/active-memory-ab/cases/04-clean-large-thin.json +137 -137
  228. package/tests/fixtures/active-memory-ab/cases/05-clean-half-step.json +166 -166
  229. package/tests/fixtures/active-memory-ab/cases/06-clean-duplicate-reread.json +197 -197
  230. package/tests/fixtures/active-memory-ab/cases/07-clean-recent-recall.json +125 -125
  231. package/tests/fixtures/active-memory-ab/cases/08-global-relevant.json +111 -111
  232. package/tests/fixtures/active-memory-ab/cases/09-global-irrelevant-conflict.json +158 -158
  233. package/tests/fixtures/active-memory-ab/cases/10-no-human-turn.json +97 -97
  234. package/tests/fixtures/active-memory-ab/cases/11-clean-scale-100.json +137 -137
  235. package/tests/fixtures/active-memory-ab/cases/12-clean-scale-1000.json +137 -137
  236. package/tests/fixtures/active-memory-ab/cases/13-clean-scale-5000.json +137 -137
  237. package/tests/fixtures/active-memory-ab/cases/14-clean-scale-20000.json +137 -137
  238. package/tests/fixtures/active-memory-ab/lead-ai-reviewed-reference.json +191 -191
  239. package/tests/fixtures/active-memory-ab/manifest.json +199 -199
  240. package/tests/fixtures/curator-pairs/labeled.v1.jsonl +90 -90
  241. package/tests/fixtures/lexicon-stub-hooks.mjs +15 -15
  242. package/tests/fixtures/lexicon-stub.mjs +284 -284
  243. package/tests/fixtures/mock-llm/reply.txt +1 -1
  244. package/tests/fixtures/recall-bench/01-paraphrase.json +183 -183
  245. package/tests/fixtures/recall-bench/02-exact.json +152 -152
  246. package/tests/fixtures/recall-bench/03-negation.json +172 -172
  247. package/tests/fixtures/recall-bench/04-no-answer.json +161 -161
  248. package/tests/fixtures/recall-bench/05-conflict.json +193 -193
  249. package/tests/fixtures/recall-bench/06-boundary.json +272 -272
  250. package/tests/fixtures/recall-bench/07-secret.json +190 -190
  251. package/tests/fixtures/recall-bench/08-coding.json +163 -163
  252. package/tests/fixtures/recall-bench-gold-candidates/01-paraphrase.json +193 -193
  253. package/tests/fixtures/recall-bench-gold-candidates/02-exact.json +197 -197
  254. package/tests/fixtures/recall-bench-gold-candidates/03-negation.json +244 -244
  255. package/tests/fixtures/recall-bench-gold-candidates/04-no-answer.json +189 -189
  256. package/tests/fixtures/recall-bench-gold-candidates/05-conflict.json +245 -245
  257. package/tests/fixtures/recall-bench-gold-candidates/06-boundary.json +279 -279
  258. package/tests/fixtures/recall-bench-gold-candidates/07-secret.json +224 -224
  259. package/tests/fixtures/recall-bench-gold-candidates/08-coding.json +218 -218
  260. package/tests/fixtures/repetition-eval/01-zh-rp.json +92 -92
  261. package/tests/fixtures/repetition-eval/02-en.json +96 -96
  262. package/tests/fixtures/repetition-eval/03-code.json +90 -90
  263. package/tests/fixtures/repetition-eval/04-names.json +115 -115
  264. package/tests/fixtures/repetition-eval/05-user-quote.json +95 -95
  265. package/tests/fixtures/repetition-eval/06-agreement.json +85 -85
  266. package/tests/fixtures/tokenizer-cases.mjs +27 -27
  267. package/tests/fork-model.test.mjs +345 -345
  268. package/tests/freshness.test.mjs +140 -140
  269. package/tests/global-graph.test.mjs +106 -106
  270. package/tests/global-lifecycle.test.mjs +149 -149
  271. package/tests/graph-cascade.test.mjs +363 -363
  272. package/tests/graph-view.test.mjs +414 -414
  273. package/tests/graph.test.mjs +371 -371
  274. package/tests/help-page.test.mjs +416 -416
  275. package/tests/hook-order.test.mjs +72 -72
  276. package/tests/humanlike.test.mjs +232 -232
  277. package/tests/hybrid-recall.test.mjs +610 -610
  278. package/tests/inbound.test.mjs +441 -441
  279. package/tests/inject-conflict.test.mjs +173 -173
  280. package/tests/inject-guide.test.mjs +513 -513
  281. package/tests/inject.test.mjs +384 -384
  282. package/tests/injection-budget-settings.test.mjs +35 -35
  283. package/tests/injection-budget.test.mjs +165 -165
  284. package/tests/injection-chain.test.mjs +442 -442
  285. package/tests/injection-intent-budget.test.mjs +92 -92
  286. package/tests/injection-rollback.test.mjs +428 -428
  287. package/tests/issue2-chain.test.mjs +169 -169
  288. package/tests/lexical-bm25.test.mjs +171 -171
  289. package/tests/lexicon-calibrate.test.mjs +48 -48
  290. package/tests/lexicon-dedupe.test.mjs +171 -171
  291. package/tests/lexicon-frequency.test.mjs +195 -195
  292. package/tests/lexicon-inject.test.mjs +459 -459
  293. package/tests/lexicon-perf.test.mjs +464 -464
  294. package/tests/lexicon-scope.test.mjs +256 -256
  295. package/tests/lexicon-ui.test.mjs +667 -667
  296. package/tests/lexicon.test.mjs +922 -922
  297. package/tests/lifecycle-audit.test.mjs +56 -0
  298. package/tests/loader-register.mjs +3 -3
  299. package/tests/loader.mjs +17 -17
  300. package/tests/local-embedding-entry.test.mjs +95 -95
  301. package/tests/local-embedding-env.test.mjs +51 -51
  302. package/tests/local-embedding-manager.test.mjs +494 -494
  303. package/tests/local-embedding-protocol.test.mjs +121 -121
  304. package/tests/local-embedding-worker.test.mjs +440 -440
  305. package/tests/local-vector-service.test.mjs +41 -0
  306. package/tests/maintenance-status.test.mjs +77 -0
  307. package/tests/maintenance.test.mjs +438 -0
  308. package/tests/managed-memory.test.mjs +1234 -1234
  309. package/tests/managed-runtime.test.mjs +72 -72
  310. package/tests/media-injection.test.mjs +225 -0
  311. package/tests/media.test.mjs +135 -135
  312. package/tests/memory-chain.test.mjs +169 -169
  313. package/tests/memory-fields.test.mjs +134 -134
  314. package/tests/memu-resident-route.test.mjs +130 -130
  315. package/tests/memu-resident.test.mjs +33 -33
  316. package/tests/migration-payload.test.mjs +40 -42
  317. package/tests/mock-llm.test.mjs +263 -225
  318. package/tests/mood.test.mjs +109 -109
  319. package/tests/multiprocess.test.mjs +29 -29
  320. package/tests/negation-polarity.test.mjs +135 -135
  321. package/tests/new-session-gate.test.mjs +617 -617
  322. package/tests/open-loop-date.test.mjs +416 -416
  323. package/tests/ops-hardening.test.mjs +209 -209
  324. package/tests/package-shipping.test.mjs +88 -88
  325. package/tests/pending-injection.test.mjs +107 -107
  326. package/tests/port-surface.test.mjs +138 -138
  327. package/tests/preset-mount.test.mjs +124 -0
  328. package/tests/preset-scope.test.mjs +212 -212
  329. package/tests/private-links.test.mjs +493 -493
  330. package/tests/prompt-semantics.test.mjs +51 -51
  331. package/tests/prompts.test.mjs +315 -315
  332. package/tests/query-decompose.test.mjs +62 -62
  333. package/tests/react-snapshot.test.mjs +24 -24
  334. package/tests/recall-bench.test.mjs +317 -317
  335. package/tests/recall-cache.test.mjs +292 -292
  336. package/tests/recall-corpus-eligibility.test.mjs +51 -51
  337. package/tests/recall-dedup.test.mjs +446 -446
  338. package/tests/recall-intent.test.mjs +172 -172
  339. package/tests/regression-sweep.test.mjs +311 -311
  340. package/tests/reminder-fairness.test.mjs +55 -0
  341. package/tests/remote.test.mjs +140 -140
  342. package/tests/rename.test.mjs +30 -30
  343. package/tests/repetition-detector-snapshot.test.mjs +231 -231
  344. package/tests/repetition-eval-live.test.mjs +177 -177
  345. package/tests/repetition-eval.test.mjs +373 -373
  346. package/tests/salience-domain.test.mjs +173 -173
  347. package/tests/salient-date.test.mjs +142 -142
  348. package/tests/salient-wake.test.mjs +389 -389
  349. package/tests/settings-beat.test.mjs +222 -222
  350. package/tests/settings-coverage.test.mjs +97 -97
  351. package/tests/settings-plumbing.test.mjs +79 -79
  352. package/tests/short-term.test.mjs +182 -166
  353. package/tests/sidebar-beat.test.mjs +213 -213
  354. package/tests/sidebar-refresh.test.mjs +123 -123
  355. package/tests/sidebar.test.mjs +102 -74
  356. package/tests/simulate-injection.test.mjs +76 -76
  357. package/tests/slot-similarity.test.mjs +153 -153
  358. package/tests/snippet.test.mjs +79 -79
  359. package/tests/source-kind.test.mjs +52 -52
  360. package/tests/speaker-provenance.test.mjs +120 -120
  361. package/tests/stale-maintenance.test.mjs +206 -131
  362. package/tests/state-gc.test.mjs +34 -34
  363. package/tests/state.test.mjs +155 -155
  364. package/tests/stats.test.mjs +112 -112
  365. package/tests/storage.test.mjs +125 -125
  366. package/tests/stubs/child-process-spy.mjs +14 -14
  367. package/tests/stubs/dsh-llm-pi-ai.js +13 -13
  368. package/tests/stubs/dsh-llm.js +5 -5
  369. package/tests/stubs/dsh-schedule.js +140 -140
  370. package/tests/stubs/dsh-session-query.js +26 -26
  371. package/tests/stubs/dsh-session.js +7 -7
  372. package/tests/stubs/dsh-tools.js +101 -101
  373. package/tests/temporal-repair.test.mjs +78 -0
  374. package/tests/temporal.test.mjs +124 -124
  375. package/tests/text-format.test.mjs +24 -0
  376. package/tests/tokenizer-v2.test.mjs +142 -142
  377. package/tests/tool-schema.test.mjs +126 -126
  378. package/tests/tools.test.mjs +810 -810
  379. package/tests/turn-log.test.mjs +487 -487
  380. package/tests/ui-defaults.test.mjs +57 -57
  381. package/tests/update-fields.test.mjs +138 -138
  382. package/tests/vector-gc.test.mjs +37 -37
  383. package/tests/vector-migration.test.mjs +810 -810
  384. package/tests/vector-profile.test.mjs +449 -449
  385. package/tests/visibility-migration.test.mjs +152 -152
  386. package/tests/webui-auth.test.mjs +963 -963
  387. package/tests/webui.test.mjs +421 -421
  388. package/tests/windows-env.test.mjs +89 -89
  389. package/tests/worker-lifecycle.test.mjs +1521 -1429
@@ -1,946 +1,946 @@
1
- #!/usr/bin/env node
2
- // Local stand-in for the manual half of the acceptance checklist.
3
- //
4
- // Most of that checklist describes behaviour a person would verify by clicking
5
- // around, but nearly all of it is observable through the same RPC surface the UI
6
- // uses. This script drives that surface against a throwaway DSH_MEMU_HOME and
7
- // reports one verdict per checklist item. What stays in the MANUAL column needs a
8
- // real GUI (visual layout, screenshots, dark mode), a real engine install, or a real
9
- // DSH conversation the host itself has to start.
10
- //
11
- // Usage: node scripts/acceptance-local.mjs [--verbose]
12
-
13
- import assert from 'node:assert/strict'
14
- import fs from 'node:fs'
15
- import os from 'node:os'
16
- import path from 'node:path'
17
- import { execFile, spawnSync } from 'node:child_process'
18
- import { promisify } from 'node:util'
19
- import { fileURLToPath } from 'node:url'
20
-
21
- const execFileAsync = promisify(execFile)
22
- const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..')
23
- const VERBOSE = process.argv.includes('--verbose')
24
- // The plugin imports two packages that only exist inside DSH. The test suite
25
- // resolves them through a small loader stub; re-exec under that loader so this
26
- // script runs against exactly the same module surface as `npm test`.
27
- if (!process.env.DSH_MEMU_ACCEPT_CHILD) {
28
- const child = spawnSync(process.execPath, [
29
- '--import', './tests/loader-register.mjs',
30
- fileURLToPath(import.meta.url),
31
- ...process.argv.slice(2),
32
- ], { cwd: ROOT, stdio: 'inherit', env: { ...process.env, DSH_MEMU_ACCEPT_CHILD: '1' } })
33
- process.exit(typeof child.status === 'number' ? child.status : 1)
34
- }
35
-
36
- const tmpBase = process.env.TEMP || process.env.TMP || os.tmpdir()
37
- const home = fs.mkdtempSync(path.join(tmpBase, 'dsh-memu-memory-accept-'))
38
- process.env.DSH_MEMU_HOME = home
39
-
40
- const state = await import('../lib/state.js')
41
- const memory = await import('../lib/memory.js')
42
- const inject = await import('../lib/inject.js')
43
- const prompts = await import('../lib/prompts.js')
44
- const engine = await import('../lib/engine.js')
45
- const budget = await import('../lib/budget.js')
46
- const snippet = await import('../lib/snippet.js')
47
- const paths = await import('../lib/paths.js')
48
- const { dispatch } = await import('../lib/rpc.js')
49
- const { registerTools } = await import('../lib/tools.js')
50
-
51
- const results = []
52
-
53
- async function auto(id, title, fn) {
54
- try {
55
- const detail = await fn()
56
- results.push({ id, title, verdict: 'PASS', detail: String(detail || '') })
57
- } catch (error) {
58
- results.push({ id, title, verdict: 'FAIL', detail: String(error?.message || error) })
59
- }
60
- }
61
-
62
- function manual(id, title, why) {
63
- results.push({ id, title, verdict: 'MANUAL', detail: why })
64
- }
65
-
66
- let seq = 0
67
- function makeLibrary(name) {
68
- seq += 1
69
- return state.createLibrary({ name: name + '-' + seq, cwd: path.join(home, 'ws', name + '-' + seq) })
70
- }
71
-
72
- function seed(libraryId, id, entry = {}) {
73
- const index = state.loadPrivateIndex(libraryId)
74
- index.entries[id] = {
75
- layer: 'long_term', title: 'title of ' + id, content: 'body of ' + id, status: 'active',
76
- createdAt: new Date().toISOString(), ...entry,
77
- }
78
- state.savePrivateIndex(libraryId, index)
79
- }
80
-
81
- function bindSession(sessionId, options = {}) {
82
- state.ensureSession(sessionId, {
83
- cwd: options.cwd,
84
- libraryId: options.libraryId || null,
85
- agentPreset: options.agentPreset || 'coding',
86
- createLibrary: options.createLibrary !== false,
87
- })
88
- if (options.patch) state.setSessionBinding(sessionId, options.patch)
89
- return state.getSessionBinding(sessionId)
90
- }
91
-
92
- function idsIn(text) {
93
- return [...String(text || '').matchAll(/mem-[A-Za-z0-9]+-[A-Za-z0-9]+/g)].map((m) => m[0])
94
- }
95
- async function runTestFile(file) {
96
- const env = { ...process.env, ELECTRON_RUN_AS_NODE: '1' }
97
- try {
98
- const out = await execFileAsync(
99
- process.execPath,
100
- // spec is required for the check-mark count below: the default TAP
101
- // reporter never prints ✔, so every count would read 0.
102
- ['--import', './tests/loader-register.mjs', '--test-reporter=spec', '--test', file],
103
- { cwd: ROOT, env, timeout: 240000 },
104
- )
105
- const text = String(out.stdout || '')
106
- const passed = (text.match(/\u2714/g) || []).length
107
- return passed + ' check marks in ' + file
108
- } catch (error) {
109
- const raw = String((error.stdout || '') + (error.stderr || ''))
110
- const bad = raw.split('\n').filter((line) => line.includes('not ok') || line.includes('\u2716'))
111
- throw new Error(file + ' is not green: ' + (bad.slice(0, 3).join(' | ') || raw.slice(-400)))
112
- }
113
- }
114
- // ------------------------------------------------------------ data safety (A)
115
-
116
- await auto('A-1', 'a corrupt index is quarantined with its bytes intact', async () => {
117
- const lib = makeLibrary('a1')
118
- seed(lib.id, 'mem-a1a', {})
119
- seed(lib.id, 'mem-a1b', {})
120
- const file = path.join(home, 'index', lib.id + '.json')
121
- const good = fs.readFileSync(file, 'utf8')
122
- const broken = '{"entries": {"mem-a1a": '
123
- fs.writeFileSync(file, broken)
124
- state.clearCaches()
125
- const index = state.loadPrivateIndex(lib.id)
126
- const names = fs.readdirSync(path.join(home, 'index'))
127
- const aside = names.filter((name) => name.includes('.corrupt-'))
128
- assert.equal(aside.length, 1, 'the broken file is moved aside exactly once')
129
- const kept = fs.readFileSync(path.join(home, 'index', aside[0]), 'utf8')
130
- assert.equal(kept, broken, 'the corrupt bytes are preserved, not truncated')
131
- assert.deepEqual(Object.keys(index.entries || {}), [], 'the conversation carries on with an empty view')
132
- assert.throws(() => seed(lib.id, 'mem-blocked', {}), /earlier read failed/)
133
- fs.writeFileSync(file, good)
134
- state.clearCaches()
135
- assert.ok(state.loadPrivateIndex(lib.id).entries['mem-a1a'])
136
- seed(lib.id, 'mem-a1c', {})
137
- assert.equal(fs.readFileSync(path.join(home, 'index', aside[0]), 'utf8'), broken, 'a later write leaves the quarantined bytes alone')
138
- return 'quarantined as ' + aside[0]
139
- })
140
-
141
- await auto('A-2', 'a corrupt state.json is quarantined and can be restored by hand', async () => {
142
- const lib = makeLibrary('a2')
143
- const file = path.join(home, 'state.json')
144
- const good = fs.readFileSync(file, 'utf8')
145
- const broken = '{ "libraries": '
146
- fs.writeFileSync(file, broken)
147
- state.clearCaches()
148
- const recovered = state.loadState()
149
- const aside = fs.readdirSync(home).filter((name) => name.includes('.corrupt-'))
150
- assert.equal(aside.length, 1, 'state.json is quarantined once')
151
- assert.equal(fs.readFileSync(path.join(home, aside[0]), 'utf8'), broken, 'the broken bytes stay in the copy')
152
- assert.equal(recovered.libraries?.[lib.id], undefined, 'the degraded state is empty instead of a crash')
153
- fs.writeFileSync(file, good)
154
- state.clearCaches()
155
- assert.ok(state.loadState().libraries[lib.id], 'copying the bytes back restores the library registry')
156
- return 'quarantined as ' + aside[0] + ', hand recovery verified'
157
- })
158
-
159
- // A transient EBUSY needs a second process to hold the handle, but the barrier it
160
- // trips does not care which error caused it. Replacing the index file with a
161
- // directory produces a real read failure (EISDIR) that is *not* a parse failure —
162
- // exactly the distinction this item is about: an unreadable file must be left in
163
- // place and write-protected, while a corrupt one is moved aside.
164
- await auto('A-3', 'an I/O failure hangs a write barrier instead of moving the file', async () => {
165
- const lib = makeLibrary('a3')
166
- seed(lib.id, 'mem-a3a', { content: 'kept across the barrier' })
167
- const file = path.join(home, 'index', lib.id + '.json')
168
- const good = fs.readFileSync(file, 'utf8')
169
- const warns = []
170
- paths.setWarnSink((message) => warns.push(String(message)))
171
- fs.rmSync(file)
172
- fs.mkdirSync(file)
173
- state.clearCaches()
174
- const index = state.loadPrivateIndex(lib.id)
175
- assert.deepEqual(Object.keys(index.entries || {}), [], 'an unreadable index reads as empty, not as a crash')
176
- // Only this library's own quarantine copies count: A-1 left one behind on purpose.
177
- const aside = fs.readdirSync(path.join(home, 'index')).filter((name) => name.startsWith(lib.id + '.json.corrupt-'))
178
- assert.equal(aside.length, 0, 'an I/O failure is not corruption: nothing may be moved aside')
179
- const failure = paths.readFailure(file)
180
- assert.ok(failure, 'the failed read did not register a write barrier')
181
- assert.notEqual(failure.kind, 'corrupt')
182
- let blocked = null
183
- try { state.savePrivateIndex(lib.id, { version: 1, entries: {} }) } catch (error) { blocked = error }
184
- assert.ok(blocked, 'a write went through on top of an unreadable index')
185
- assert.equal(blocked.code, 'dsh-memu-memory/read-failed')
186
- assert.match(blocked.message, /refusing to overwrite/)
187
- assert.ok(warns.some((line) => /writes are blocked/.test(line)), 'the barrier is silent: ' + JSON.stringify(warns))
188
- fs.rmSync(file, { recursive: true, force: true })
189
- fs.writeFileSync(file, good)
190
- state.clearCaches()
191
- const back = state.loadPrivateIndex(lib.id)
192
- assert.ok(back.entries['mem-a3a'], 'the memory did not come back once the file read cleanly')
193
- assert.equal(paths.readFailure(file), null, 'the barrier did not lift on the next clean read')
194
- seed(lib.id, 'mem-a3b', {})
195
- assert.deepEqual(paths.readFailuresUnder(path.join(home, 'index')), [], 'a stale barrier is left behind')
196
- paths.setWarnSink(null)
197
- return 'barrier hung and lifted; no file moved aside'
198
- })
199
-
200
- await auto('A-4', 'a write that lands during an await is not lost', async () => {
201
- const lib = makeLibrary('a4')
202
- seed(lib.id, 'mem-a4base', {})
203
- const writer = (async () => {
204
- await new Promise((resolve) => setTimeout(resolve, 15))
205
- state.updatePrivateIndex(lib.id, (index) => {
206
- index.entries['mem-a4x'] = {
207
- layer: 'long_term', title: 'X', content: 'written by the browser', status: 'active',
208
- createdAt: new Date().toISOString(),
209
- }
210
- })
211
- })()
212
- const remembered = (async () => {
213
- await new Promise((resolve) => setTimeout(resolve, 5))
214
- return memory.privateRemember({ libraryId: lib.id, content: 'written by a tool call', title: 'Y', layer: 'long_term' })
215
- })()
216
- const [, stored] = await Promise.all([writer, remembered])
217
- const ids = Object.keys(state.loadPrivateIndex(lib.id).entries)
218
- assert.ok(ids.includes('mem-a4base'), 'the seeded entry is still there')
219
- assert.ok(ids.includes('mem-a4x'), 'the browser write survives')
220
- assert.ok(ids.includes(stored.id), 'the tool write survives')
221
- return ids.length + ' entries kept from two interleaved writers'
222
- })
223
- // -------------------------------------------------------- recall and budget (B)
224
-
225
- await auto('B-2', 'a failing recall is reported and the turn still gets its text', async () => {
226
- const library = makeLibrary('b2')
227
- seed(library.id, 'mem-b2a', {})
228
- const cwd = path.join(home, 'ws', 'b2-session')
229
- const sessionId = 'sess-b2'
230
- const binding = bindSession(sessionId, { cwd, libraryId: library.id, patch: { domain: 'coding' } })
231
- const exec = { agent: { session: { header: { id: sessionId, cwd, agentPreset: binding.agentPreset } } } }
232
- // The realistic failure: the engine backend is selected but not installed. It is
233
- // set through the same RPC the settings page uses, so this is the user-facing path.
234
- await dispatch({}, 'setSettings', { patch: { memoryBackend: 'api', vectorSource: 'local' } })
235
- const failed = await inject.buildRecall(binding, 'title mem-b2a', 1, state.getSettings(), exec, sessionId)
236
- await dispatch({}, 'setSettings', { patch: { memoryBackend: 'agent', vectorSource: 'local' } })
237
- assert.ok(failed.errors.length > 0, 'the failure is carried out, not swallowed')
238
- assert.match(failed.errors.join(' '), /semantic recall failed/)
239
- assert.match(failed.text, /mem-b2a/, 'lexical fallback still returns the matching memory')
240
- assert.equal(typeof failed.text, 'string', 'the caller still receives a string to inject')
241
- const healthy = await inject.buildRecall(binding, 'something to look up', 2, state.getSettings(), exec, sessionId)
242
- assert.deepEqual(healthy.errors, [], 'a healthy turn reports nothing')
243
- return failed.errors[0].slice(0, 90)
244
- })
245
-
246
- await auto('B-3', 'anchor ids and the ids written into the text are the same set', async () => {
247
- const library = makeLibrary('b3')
248
- const body = '这一段是中文正文,用来把预算撑满。'.repeat(24)
249
- for (let i = 0; i < 16; i += 1) {
250
- seed(library.id, 'mem-b3-' + i, {
251
- layer: 'must_remember', pinReason: 'because it matters', pinSource: 'user_explicit',
252
- content: body + ' ' + i,
253
- })
254
- }
255
- const globalIndex = state.loadGlobalIndex()
256
- for (let i = 0; i < 10; i += 1) {
257
- globalIndex.entries['mem-g3-' + i] = {
258
- title: 'global ' + i, content: body + ' g' + i, status: 'active', domain: 'coding',
259
- confidence: 0.8, createdAt: new Date().toISOString(),
260
- }
261
- }
262
- state.saveGlobalIndex(globalIndex)
263
- const cwd = path.join(home, 'ws', 'b3-session')
264
- const binding = bindSession('sess-b3', { cwd, libraryId: library.id, patch: { domain: 'coding' } })
265
- const anchor = inject.buildAnchor(binding, state.getSettings(), null)
266
- const inText = [...new Set(idsIn(anchor.text))].sort()
267
- const recorded = [...new Set(anchor.ids)].sort()
268
- assert.ok(inText.length > 0, 'the anchor rendered something')
269
- assert.ok(inText.length < 26, 'the budget actually cut something, otherwise this proves nothing')
270
- assert.deepEqual(inText, recorded, 'nothing is recorded that was not said, and nothing said is left unrecorded')
271
- return inText.length + ' ids matched, ' + (26 - inText.length) + ' cut by the budget'
272
- })
273
-
274
- await auto('B-4', 'a Chinese anchor lands inside its token budget', async () => {
275
- const library = makeLibrary('b4')
276
- const body = '这条记忆写的是中文,一共几十个字,用来测预算。'.repeat(20)
277
- for (let i = 0; i < 20; i += 1) {
278
- seed(library.id, 'mem-b4-' + i, { layer: 'must_remember', pinReason: 'because', pinSource: 'user_explicit', content: body })
279
- }
280
- // Keep this case independent of whatever earlier cases left in the global
281
- // index, and fill the remaining anchor segments with RP-domain evidence.
282
- state.saveGlobalIndex({ entries: {} })
283
- const globalIndex = state.loadGlobalIndex()
284
- for (let i = 0; i < 10; i += 1) {
285
- globalIndex.entries['mem-b4-global-' + i] = {
286
- title: 'global ' + i, content: body, status: 'active', domain: 'rp',
287
- confidence: 0.8, createdAt: new Date().toISOString(),
288
- }
289
- }
290
- state.saveGlobalIndex(globalIndex)
291
- const cwd = path.join(home, 'ws', 'b4-session')
292
- const binding = bindSession('sess-b4', { cwd, libraryId: library.id, patch: { domain: 'coding' } })
293
- const settings = state.getSettings()
294
- const anchor = inject.buildAnchor(binding, settings, null)
295
- const tokens = budget.estTokens(anchor.text)
296
- const target = Number(settings.anchorTokens || 700)
297
- // Title cards spend less than the old full-text cards: the invariant is that the
298
- // anchor never exceeds its budget and still renders a useful block, not that it
299
- // fills the budget to 85%.
300
- const low = Math.min(120, target)
301
- const high = target
302
- assert.ok(tokens >= low && tokens <= high,
303
- 'estimated ' + tokens + ' tokens, wanted ' + low + '..' + high + ' for a ' + target + ' budget')
304
- return tokens + ' tokens for a ' + target + ' budget (' + low + '..' + high + ')'
305
- })
306
- await auto('B-5', 'the anchor keeps the pins that were said out loud, not just the newest', async () => {
307
- const library = makeLibrary('b5')
308
- // Short bodies on purpose: pins get a fraction of the anchor budget, so long text
309
- // would leave nothing rendered and the ordering claim would go untested.
310
- seed(library.id, 'mem-b5said-1', {
311
- layer: 'must_remember', pinSource: 'user_explicit', pinReason: 'said out loud',
312
- title: 'what they told me', content: '这条是对方亲口交代的,必须一直记得。',
313
- createdAt: '2019-01-01T00:00:00.000Z', updatedAt: '2019-01-01T00:00:00.000Z',
314
- })
315
- for (let i = 0; i < 30; i += 1) {
316
- seed(library.id, 'mem-b5new-' + i, {
317
- layer: 'must_remember', pinSource: 'self', pinReason: 'i noticed it',
318
- title: 'trivia ' + i, content: '最近自己发现的琐碎置顶 ' + i + '。',
319
- createdAt: new Date().toISOString(), updatedAt: new Date().toISOString(),
320
- })
321
- }
322
- const cwd = path.join(home, 'ws', 'b5-session')
323
- const binding = bindSession('sess-b5', { cwd, libraryId: library.id, patch: { domain: 'coding' } })
324
- const anchor = inject.buildAnchor(binding, state.getSettings(), null)
325
- const ids = idsIn(anchor.text)
326
- assert.ok(ids.includes('mem-b5said-1'), 'the explicit pin survives even though it is years old')
327
- assert.ok(ids.length < 31, 'something was cut, otherwise the ordering claim is untested')
328
- // Among pins of equal rank the newest wins, so the oldest self-noticed pins are
329
- // what the budget squeezes out — the explicit one keeps its place on rank alone.
330
- assert.equal(ids[0], 'mem-b5said-1', 'the explicit pin is rendered first, ahead of 30 newer ones')
331
- assert.ok(!ids.includes('mem-b5new-0'), 'the oldest self-noticed pin is the one that got cut')
332
- return ids.length + ' of 31 kept, oldest self pins cut'
333
- })
334
-
335
- await auto('B-6', 'memu_status reports real counts and a degraded recall', async () => {
336
- const library = makeLibrary('b6')
337
- seed(library.id, 'mem-b6a', { layer: 'must_remember', pinSource: 'user_explicit', pinReason: 'said' })
338
- seed(library.id, 'mem-b6b', { layer: 'must_remember', pinSource: 'self', pinReason: 'noticed' })
339
- seed(library.id, 'mem-b6c', { layer: 'short_term' })
340
- seed(library.id, 'mem-b6d', { status: 'archived' })
341
- const cwd = path.join(home, 'ws', 'b6-session')
342
- const sessionId = 'sess-b6'
343
- const binding = bindSession(sessionId, { cwd, libraryId: library.id, patch: { domain: 'coding' } })
344
- const registered = new Map()
345
- registerTools({ tools: { register(tool) { registered.set(tool.name, tool) } }, logger: { warn() {} } })
346
- const status = registered.get('memu_status')
347
- assert.ok(status, 'the status tool is registered')
348
- const exec = { agent: { session: { header: { id: sessionId, cwd, agentPreset: binding.agentPreset } } } }
349
- const out = await status.execute({}, exec)
350
- const text = typeof out === 'string' ? out : (out?.content?.[0]?.text || JSON.stringify(out))
351
- assert.match(text, /private: 3 active, 2\/\d+ pinned/, 'counts match what is really in the index')
352
- assert.match(text, /short_term: 1 active/)
353
- assert.doesNotMatch(text, /recall: degraded/, 'a healthy session says nothing about recall')
354
- state.setSessionBinding(sessionId, { lastRecallError: 'provider key missing', lastRecallErrorAt: new Date().toISOString() })
355
- const degraded = await status.execute({}, exec)
356
- const degradedText = typeof degraded === 'string' ? degraded : (degraded?.content?.[0]?.text || '')
357
- assert.match(degradedText, /recall: degraded .*provider key missing/, 'the failure surfaces where the user can see it')
358
- return 'counts correct, degraded recall surfaced'
359
- })
360
-
361
- await auto('B-7', 'id resolution: exact, unique prefix, ambiguous, unknown', async () => {
362
- const index = { entries: {
363
- 'mem-b7one': { layer: 'long_term' },
364
- 'mem-b7two': { layer: 'long_term' },
365
- 'mem-b7twox': { layer: 'long_term' },
366
- } }
367
- assert.equal(memory.resolveEntryId(index, 'mem-b7one'), 'mem-b7one', 'an exact id resolves to itself')
368
- assert.equal(memory.resolveEntryId(index, 'mem-b7two'), 'mem-b7two', 'an exact id wins even when it prefixes another')
369
- assert.equal(memory.resolveEntryId(index, 'mem-b7one.md'), 'mem-b7one', 'a trailing .md is tolerated')
370
- assert.equal(memory.resolveEntryId(index, 'mem-b7twox'), 'mem-b7twox')
371
- assert.throws(() => memory.resolveEntryId(index, 'mem-b7tw'), /ambiguous id .*candidates: mem-b7two, mem-b7twox/)
372
- assert.throws(() => memory.resolveEntryId(index, 'mem-b7nope'), /unknown memory: mem-b7nope/)
373
- assert.throws(() => memory.resolveEntryId(index, ' '), /id is required/)
374
- return 'exact, prefix, ambiguous, unknown all behave as documented'
375
- })
376
- // ------------------------------------------------------------- guards (C)
377
-
378
- await auto('C-1', 'a v4 message with a producer-less source kind still fails its test', async () => {
379
- return runTestFile('tests/source-kind.test.mjs')
380
- })
381
-
382
- await auto('C-2', 'unpin is fenced: a reason, a quota, a cooldown', async () => {
383
- const library = makeLibrary('c2')
384
- seed(library.id, 'mem-c2pin', { layer: 'must_remember', pinSource: 'self', pinReason: 'noticed it' })
385
- seed(library.id, 'mem-c2plain', { layer: 'long_term' })
386
- const cwd = path.join(home, 'ws', 'c2-session')
387
- const sessionId = 'sess-c2'
388
- bindSession(sessionId, { cwd, libraryId: library.id })
389
- const exec = { agent: { session: { header: { id: sessionId, cwd } } } }
390
- const fine = 'I thought that remark mattered, but it was my own reading of it and it can go now.'
391
- assert.throws(() => memory.privateUnpin({ exec, id: 'mem-c2pin', reason: 'too short' }), /at least \d+ characters/)
392
- const first = memory.privateUnpin({ exec, id: 'mem-c2pin', reason: fine })
393
- assert.equal(first.entry.layer, 'long_term', 'the pin is demoted, not deleted')
394
- assert.equal(first.entry.marginalized, true)
395
- assert.equal(first.entry.pinSource, null, 'the pin source is cleared so it cannot rank as a pin again')
396
- assert.ok(first.entry.strength <= 0.2, 'strength is cut, not zeroed')
397
- assert.throws(() => memory.privateUnpin({ exec, id: 'mem-c2plain', reason: fine }), /cooldown/)
398
- const second = { agent: { session: { header: { id: 'sess-c2b', cwd } } } }
399
- bindSession('sess-c2b', { cwd, libraryId: library.id })
400
- assert.throws(() => memory.privateUnpin({ exec: second, id: 'mem-c2plain', reason: fine }), /not in must_remember/)
401
- state.setSessionBinding('sess-c2b', { unpinCount: 2 })
402
- assert.throws(() => memory.privateUnpin({ exec: second, id: 'mem-c2plain', reason: fine }), /quota for this conversation is used up/)
403
- return 'reason, cooldown, layer and quota all hold'
404
- })
405
-
406
- await auto('C-3', 'no trauma leftovers in code or scripts', async () => {
407
- const dirs = [path.join(ROOT, 'lib'), path.join(ROOT, 'scripts')]
408
- const hits = []
409
- const walk = (dir) => {
410
- for (const name of fs.readdirSync(dir, { withFileTypes: true })) {
411
- const full = path.join(dir, name.name)
412
- if (name.isDirectory()) walk(full)
413
- // This file names the word it is looking for; do not report itself.
414
- else if (full === fileURLToPath(import.meta.url)) continue
415
- else if (/\.(js|mjs|json|md)$/.test(name.name)) {
416
- const text = fs.readFileSync(full, 'utf8')
417
- if (/trauma/i.test(text)) hits.push(path.relative(ROOT, full))
418
- }
419
- }
420
- }
421
- for (const dir of dirs) walk(dir)
422
- assert.deepEqual(hits, [], 'the old trauma flag is gone: ' + hits.join(', '))
423
- return 'lib/ and scripts/ are clean'
424
- })
425
- // ------------------------------------------------------------- prompts (D)
426
-
427
- await auto('D-1', 'prompts resolve to the conversation domain and fall back to base', async () => {
428
- const coding = prompts.resolveDef('system-guide', 'coding')
429
- assert.equal(coding.key, 'system-guide.coding', 'a coding session gets the coding variant')
430
- assert.equal(prompts.resolveDef('system-guide', 'rp').key, 'system-guide.rp', 'and an rp session does not')
431
- assert.equal(prompts.resolveDef('system-guide', 'general').key, 'system-guide', 'general is not a layered domain')
432
- assert.equal(prompts.resolveDef('system-guide', 'no-such-domain').key, 'system-guide', 'an unknown domain falls back instead of throwing')
433
- const layered = prompts.loadPromptForDomain('system-guide', {}, 'coding')
434
- assert.equal(layered.fellBackToBase, false)
435
- const plain = prompts.loadPromptForDomain('system-guide', {}, 'general')
436
- assert.equal(plain.fellBackToBase, true, 'the caller can tell it got the generic text')
437
- assert.ok(layered.text.length > 0 && plain.text.length > 0)
438
- assert.notEqual(layered.text, plain.text, 'the two domains do not render the same text')
439
- return 'coding/rp variants resolve, general and unknown fall back'
440
- })
441
-
442
- await auto('D-2', 'the prompts page renders every page and saving takes effect next turn', async () => {
443
- const rendered = await runTestFile('tests/client-render.test.mjs')
444
- const units = await runTestFile('tests/prompts.test.mjs')
445
- return rendered + '; ' + units
446
- })
447
-
448
- await auto('D-3', 'a corrupted prompts manifest only degrades the wording', async () => {
449
- const dir = prompts.promptsDir()
450
- assert.ok(dir.startsWith(home), 'this check must run inside the throwaway home: ' + dir)
451
- fs.mkdirSync(dir, { recursive: true })
452
- const manifest = path.join(dir, 'manifest.json')
453
- const before = fs.existsSync(manifest) ? fs.readFileSync(manifest, 'utf8') : null
454
- fs.writeFileSync(manifest, '{ this is not json', 'utf8')
455
- const states = prompts.getPromptStates()
456
- assert.ok(Array.isArray(states) && states.length > 0, 'the prompt list still loads')
457
- const guide = prompts.loadPrompt('system-guide', {})
458
- assert.ok(guide.text && guide.text.length > 0, 'the system prompt still assembles')
459
- if (before === null) fs.rmSync(manifest, { force: true })
460
- else fs.writeFileSync(manifest, before, 'utf8')
461
- return states.length + ' prompts survived a broken manifest'
462
- })
463
- // ---------------------------------------------- folders, sidebar, settings (E)
464
-
465
- await auto('E-1', 'both folder switches off: no library, no injection, no prompt', async () => {
466
- const cwd = path.join(home, 'ws', 'e1-folder')
467
- const before = (await dispatch({}, 'listLibraries', {})).length
468
- await dispatch({}, 'setFolderPolicy', { scopeKey: cwd, useLibrary: false, useGlobal: false })
469
- const init = await dispatch({}, 'initSession', { sessionId: 'sess-e1', cwd, createLibrary: false })
470
- assert.equal(init.binding.libraryId, null, 'the conversation starts unbound instead of inventing a library')
471
- const after = (await dispatch({}, 'listLibraries', {})).length
472
- assert.equal(after, before, 'no library appeared on disk')
473
- const anchor = inject.buildAnchor(init.binding, state.getSettings(), 'sess-e1')
474
- assert.deepEqual(anchor.ids, [], 'nothing is injected')
475
- const sidebar = await dispatch({}, 'getSidebarState', { sessionId: 'sess-e1' })
476
- assert.deepEqual(sidebar.private?.items || [], [], 'the sidebar has no private list to show')
477
- assert.equal(sidebar.effective?.libraryBlocked, true, 'and it knows why: the folder turned it off')
478
- return 'unbound, no library, no injection'
479
- })
480
-
481
- await auto('E-2', 'the sidebar never hands out an absolute path', async () => {
482
- const lib = makeLibrary('e2')
483
- const cwd = path.join(home, 'ws', 'e2-folder')
484
- seed(lib.id, 'mem-e2a', {})
485
- bindSession('sess-e2', { cwd, libraryId: lib.id })
486
- const sidebar = await dispatch({}, 'getSidebarState', { sessionId: 'sess-e2' })
487
- const text = JSON.stringify(sidebar)
488
- assert.ok(!text.includes(home.split(path.sep).join('/')), 'the temp home path does not leak')
489
- assert.ok(!/[A-Za-z]:\\|\.\/lib\//.test(text), 'no drive letters or repo-relative paths either')
490
- return 'two levels, no paths in ' + text.length + ' bytes of sidebar state'
491
- })
492
-
493
- await auto('E-3', 'a switch the folder forbids snaps back instead of silently winning', async () => {
494
- const lib = makeLibrary('e3')
495
- const cwd = path.join(home, 'ws', 'e3-folder')
496
- bindSession('sess-e3', { cwd, libraryId: lib.id })
497
- await dispatch({}, 'setFolderPolicy', { scopeKey: cwd, useLibrary: false, useGlobal: false })
498
- const res = await dispatch({}, 'setSessionScope', { sessionId: 'sess-e3', useLibrary: true, useGlobal: true })
499
- assert.equal(res.clamped.length, 2, 'both fields come back clamped')
500
- assert.deepEqual(res.clamped.map((c) => c.field).sort(), ['useGlobal', 'useLibrary'])
501
- assert.equal(res.clamped[0].reason, 'folder')
502
- // The clamp drops the field from the patch instead of applying and undoing it,
503
- // so the binding keeps what it had while the effective answer stays narrow.
504
- assert.equal(res.effective.useLibrary, false, 'the conversation cannot widen itself past the folder')
505
- assert.equal(res.effective.libraryBlocked, true)
506
- return 'both switches clamped with reason=folder'
507
- })
508
- await auto('E-4', 'a 500-memory library still paints its first screen in one call', async () => {
509
- const lib = makeLibrary('e4')
510
- const index = state.loadPrivateIndex(lib.id)
511
- for (let i = 0; i < 500; i += 1) {
512
- index.entries['mem-e4-' + i] = {
513
- layer: 'long_term', title: 'entry ' + i, content: '正文 ' + i + ' ' + 'x'.repeat(400),
514
- status: 'active', createdAt: new Date().toISOString(),
515
- }
516
- }
517
- state.savePrivateIndex(lib.id, index)
518
- const cwd = path.join(home, 'ws', 'e4-folder')
519
- bindSession('sess-e4', { cwd, libraryId: lib.id })
520
- const t0 = Date.now()
521
- const sidebar = await dispatch({}, 'getSidebarState', { sessionId: 'sess-e4' })
522
- const full = Date.now() - t0
523
- const t1 = Date.now()
524
- const beat = await dispatch({}, 'getSidebarState', { sessionId: 'sess-e4', revisionOnly: true })
525
- const heartbeat = Date.now() - t1
526
- assert.ok(sidebar.private.items.length <= 120, 'previews are capped at the page size, got ' + sidebar.private.items.length)
527
- assert.ok(typeof beat.revision === 'number')
528
- assert.ok(heartbeat < 150, 'the heartbeat must stay cheap, took ' + heartbeat + 'ms')
529
- return 'first screen ' + full + 'ms for ' + sidebar.private.items.length + ' rows, heartbeat ' + heartbeat + 'ms'
530
- })
531
-
532
- await auto('E-5', 'a folder lists the conversations that live in it', async () => {
533
- const lib = makeLibrary('e5')
534
- const cwd = path.join(home, 'ws', 'e5-folder')
535
- bindSession('sess-e5', { cwd, libraryId: lib.id })
536
- const res = await dispatch({}, 'listFolderSessions', { scopeKey: cwd })
537
- const rows = res.sessions || res.items || []
538
- assert.ok(Array.isArray(rows), 'the folder view answers with a list')
539
- assert.ok(rows.some((row) => row.sessionId === 'sess-e5' || row.id === 'sess-e5'),
540
- 'the conversation in this folder is listed: ' + JSON.stringify(rows).slice(0, 200))
541
- const other = await dispatch({}, 'listFolderSessions', { scopeKey: path.join(home, 'ws', 'e5-other') })
542
- const otherRows = other.sessions || other.items || []
543
- assert.equal(otherRows.length, 0, 'a folder nobody used stays empty')
544
- return rows.length + ' rows in the folder that was used'
545
- })
546
-
547
- await auto('E-8', 'the folder policy is a ceiling, not a suggestion', async () => {
548
- const cwd = path.join(home, 'ws', 'e8-folder')
549
- await dispatch({}, 'setFolderPolicy', { scopeKey: cwd, useLibrary: false, useGlobal: false })
550
- const policy = state.getWorkspacePolicy(cwd)
551
- assert.equal(policy.useLibrary, false)
552
- const scope = state.effectiveScope({ useLibrary: true, useGlobal: true }, policy)
553
- assert.equal(scope.useLibrary, false, 'a conversation asking for more than the folder allows gets the folder')
554
- assert.equal(scope.libraryBlocked, true)
555
- await dispatch({}, 'setFolderPolicy', { scopeKey: cwd, useLibrary: true })
556
- const reopened = state.effectiveScope({ useLibrary: true }, state.getWorkspacePolicy(cwd))
557
- assert.equal(reopened.useLibrary, true, 'and turning the folder back on reopens it')
558
- return 'clamped down and reopened'
559
- })
560
-
561
- await auto('E-9', 'the sidebar hears about a write no other reload announced', async () => {
562
- const lib = makeLibrary('e9')
563
- const cwd = path.join(home, 'ws', 'e9-folder')
564
- bindSession('sess-e9', { cwd, libraryId: lib.id })
565
- const first = await dispatch({}, 'getSidebarState', { sessionId: 'sess-e9', revisionOnly: true })
566
- state.savePrivateIndex(lib.id, state.loadPrivateIndex(lib.id))
567
- const second = await dispatch({}, 'getSidebarState', { sessionId: 'sess-e9', revisionOnly: true })
568
- assert.ok(second.revision > first.revision, 'the revision moved: ' + first.revision + ' -> ' + second.revision)
569
- assert.deepEqual(Object.keys(second).sort(), ['revision', 'stamp'], 'the heartbeat answers with a counter and a disk fingerprint')
570
- assert.equal(typeof second.stamp, 'string', 'the fingerprint is a string this process did not have to write')
571
- // The counter lives in module memory, so a write from another instance moves the
572
- // fingerprint and nothing else — that is the case the sidebar used to miss.
573
- fs.writeFileSync(path.join(home, 'index', lib.id + '.json'), JSON.stringify(state.loadPrivateIndex(lib.id), null, 2))
574
- const third = await dispatch({}, 'getSidebarState', { sessionId: 'sess-e9', revisionOnly: true })
575
- assert.notEqual(third.stamp, second.stamp, 'a write from outside this module still changes the fingerprint')
576
- return 'revision ' + first.revision + ' -> ' + second.revision + ', stamp moved across instances'
577
- })
578
-
579
- // The gate is mounted through ReactDOM.createRoot, which is stubbed away from the
580
- // settings harness — its own test builds the dialog and counts the cards.
581
- await auto('E-6', 'the new-session prompt is four cards, and a folder can veto them', async () => {
582
- const rendered = await runTestFile('tests/new-session-gate.test.mjs')
583
- const cases = Number(String(rendered).split(' ')[0])
584
- assert.ok(cases >= 3, 'the gate test file only ran ' + cases + ' cases')
585
- return cases + ' renders: four cards, a folder veto, a silent bind'
586
- })
587
- await auto('E-10', 'the settings pane hears a settings write made in another window', async () => {
588
- const rendered = await runTestFile('tests/settings-beat.test.mjs')
589
- const cases = Number(String(rendered).split(' ')[0])
590
- assert.ok(cases >= 5, 'the settings heartbeat test file only ran ' + cases + ' cases')
591
- return cases + ' cases: seeded beat, stamp-only write, channel wake, hidden silence, no-channel fallback'
592
- })
593
- await auto('E-7', 'reviewed desktop/mobile/theme screenshots exist and the shared UI keeps its layout guards', async () => {
594
- const { default: sharp } = await import('sharp')
595
- const folder = path.join(ROOT, 'assets', 'screenshots')
596
- const desktop = await sharp(path.join(folder, 'webui-memory.jpg')).metadata()
597
- const mobile = await sharp(path.join(folder, 'mobile.jpg')).metadata()
598
- const dark = await sharp(path.join(folder, 'webui-dark.jpg')).stats()
599
- assert.ok(desktop.width >= 1000)
600
- assert.ok(mobile.width <= 480 && mobile.height >= 700)
601
- assert.ok(dark.channels.some(channel => channel.stdev > 10), 'dark screenshot must not be blank')
602
- const client = fs.readFileSync(path.join(ROOT, 'lib', 'client.js'), 'utf8')
603
- assert.match(client, /prefers-reduced-motion/)
604
- assert.match(client, /dshm-card-actions>div\{flex-wrap:wrap/)
605
- return 'visual review recorded 2026-10-28; desktop/mobile/dark evidence checked, not a substitute for future visual review'
606
- })
607
- // ------------------------------------------------ statistics
608
-
609
- await auto('H-8', 'the statistics follow real activity and survive a damaged sidecar', async () => {
610
- const rendered = await runTestFile('tests/stats.test.mjs')
611
- const cases = Number(String(rendered).split(' ')[0])
612
- assert.ok(cases >= 5, 'the statistics test file only ran ' + cases + ' cases')
613
- return cases + ' cases: counts, zero-filled empty library, 90-day roll, damaged sidecar, edit-archive'
614
- })
615
- // ------------------------------------------------ engine, backups, docs (F, G)
616
-
617
- await auto('F-1', 'the engine can be listed, switched and pruned', async () => {
618
- const units = await runTestFile('tests/engine.test.mjs')
619
- const listing = await dispatch({}, 'listVersions', {})
620
- assert.ok(Array.isArray(listing.versions || listing.items || []), 'the version list is an array even with no engine installed')
621
- const pruned = engine.pruneEngineVersions({ keep: 3 })
622
- assert.ok(pruned && typeof pruned === 'object', 'prune answers instead of throwing on an empty install')
623
- return units + '; prune keep=3 survived an empty install'
624
- })
625
-
626
- await auto('F-2', 'a backup restore brings a deleted memory back', async () => {
627
- const lib = makeLibrary('f2')
628
- seed(lib.id, 'mem-f2keep', { title: 'written before the backup' })
629
- const made = await state.backupDatabases()
630
- assert.ok(made, 'a backup was taken')
631
- const backups = (await dispatch({}, 'listBackups', {})).backups
632
- assert.ok(backups.length >= 1, 'it shows up in the list')
633
- const index = state.loadPrivateIndex(lib.id)
634
- delete index.entries['mem-f2keep']
635
- state.savePrivateIndex(lib.id, index)
636
- assert.equal(state.loadPrivateIndex(lib.id).entries['mem-f2keep'], undefined, 'the memory is really gone')
637
- const name = backups[0].name || backups[0].file || backups[0]
638
- await dispatch({}, 'restoreBackup', { name: String(name) })
639
- state.clearCaches()
640
- const back = state.loadPrivateIndex(lib.id).entries['mem-f2keep']
641
- assert.ok(back, 'the restore put it back')
642
- assert.match(String(back.title), /written before the backup/)
643
- return 'restored ' + String(name).slice(0, 40)
644
- })
645
-
646
- await auto('F-3', 'only three engine versions are kept', async () => {
647
- const src = fs.readFileSync(path.join(ROOT, 'lib', 'engine.js'), 'utf8')
648
- assert.match(src, /export function pruneEngineVersions\(\{ keep = 3 \}/, 'the default really is three')
649
- assert.ok(!/engineKeepVersions/.test(fs.readFileSync(path.join(ROOT, 'lib', 'state.js'), 'utf8')),
650
- 'and it is not a setting that pretends to exist')
651
- return 'default keep=3, no phantom setting'
652
- })
653
-
654
- await auto('F-4', 'the activation log prints the settings the engine actually ran with', async () => {
655
- // Reading ~/.dsh logs is not possible: the host keeps no log on disk (checked — the
656
- // only files under ~/.dsh/logs are startup diagnostics, and none of them contain a
657
- // dsh-memu-memory line). What the line says is asserted instead, by running the real apply()
658
- // against a fake context that records logger.info.
659
- const plugin = await import('../lib/index.js')
660
- const info = []
661
- const warn = []
662
- const handlers = []
663
- const disposers = []
664
- const scope = {
665
- effect(fn) { const dispose = fn(); if (typeof dispose === 'function') disposers.push(dispose) },
666
- tools: { register() { return () => {} } },
667
- webServer: { register() { return () => {} } },
668
- connection: { requestRejection: () => undefined },
669
- interval() { return 1 },
670
- on(event, handler) { handlers.push({ event, handler }); return () => {} },
671
- }
672
- plugin.apply({
673
- ...scope,
674
- logger: { info: (message) => info.push(message), warn: (message) => warn.push(message) },
675
- inject: (_deps, callback) => callback(scope),
676
- })
677
- const line = info.find((message) => message.startsWith('dsh-memu-memory: loaded'))
678
- assert.ok(line, 'apply() logged no activation line at all')
679
- const match = /^dsh-memu-memory: loaded \(engine (\S+)\) backend=(\S+) autoInject=(\S+) anchorTokens=(\d+) turnTokens=(\d+) mustRememberCap=(\d+) unpinBudget=(\d+)$/.exec(line)
680
- assert.ok(match, 'the activation line lost its shape: ' + line)
681
- const settings = state.getSettings()
682
- assert.equal(match[1], engine.ENGINE_VERSION)
683
- assert.equal(match[2], state.getMemoryBackend())
684
- assert.equal(match[3], settings.autoInject)
685
- assert.equal(Number(match[4]), settings.anchorTokens)
686
- assert.equal(Number(match[5]), settings.turnTokens)
687
- assert.equal(Number(match[6]), settings.mustRememberCap)
688
- assert.equal(Number(match[7]), settings.unpinBudgetPerSession)
689
- assert.deepEqual(
690
- handlers.filter((entry) => ['agent/pre-step', 'session/event'].includes(entry.event)).map((entry) => entry.event).sort(),
691
- // 两个 session/event:注入管线一个 + 增量回合日志记录器一个(设计文档 §3.2,T0 起挂载)。
692
- ['agent/pre-step', 'session/event', 'session/event'],
693
- 'the same activation must wire the injection hooks and the turn-log recorder',
694
- )
695
- for (const dispose of disposers) { try { dispose() } catch {} }
696
- return 'line matches live settings, injection + turn-log hooks wired'
697
- })
698
-
699
- await auto('G-1', 'the kept docs exist and nothing points at a retired one', async () => {
700
- for (const rel of ['README.md', 'README.zh.md', 'AGENTS.md', 'LICENSE']) {
701
- assert.ok(fs.existsSync(path.join(ROOT, rel)), rel + ' exists')
702
- }
703
- for (const rel of ['assets/icon.png', 'assets/icon-256.png', 'assets/icon.svg']) {
704
- assert.ok(fs.existsSync(path.join(ROOT, rel)), rel + ' exists')
705
- }
706
- // Since 1.1.3 the changelog is the source for release notes (release.yml), so it is kept.
707
- assert.ok(fs.existsSync(path.join(ROOT, 'CHANGELOG' + '.md')), 'CHANGELOG.md carries release notes')
708
- // 细节从 AGENTS.md 搬进了 docs/:索引必须短,指针必须都能落地
709
- const agents = fs.readFileSync(path.join(ROOT, 'AGENTS.md'), 'utf8')
710
- assert.ok(agents.includes('plugin:dsh-memu-memory'), 'the notes carry the real source kind, not the old one')
711
- const docs = ['troubleshooting', 'contributing', 'host-api', 'client-conventions', 'memory-semantics', 'env-and-commands']
712
- for (const name of docs) {
713
- assert.ok(fs.existsSync(path.join(ROOT, 'docs', name + '.md')), 'docs/' + name + '.md exists')
714
- assert.ok(agents.includes('docs/' + name + '.md'), 'the index points at docs/' + name + '.md')
715
- }
716
- // 硬规则在 AGENTS.md §1 与附录 E 各有一份:改一处忘另一处,这里会红
717
- const appendix = fs.readFileSync(path.join(ROOT, 'docs', 'troubleshooting.md'), 'utf8')
718
- const ruleLead = (text) => text.split(String.fromCharCode(10)).filter((l) => /^[0-9]+[.] [*][*]/.test(l)).map((l) => { const end = l.indexOf('**', 5); return end < 0 ? l.slice(0, 40) : l.slice(0, end + 2) })
719
- const inIndex = ruleLead(agents)
720
- const inAppendix = ruleLead(appendix)
721
- assert.ok(inIndex.length >= 10, 'the index carries at least ten hard rules, got ' + inIndex.length)
722
- assert.equal(inAppendix.length, inIndex.length, 'the appendix carries the same hard rules')
723
- for (const lead of inIndex) assert.ok(inAppendix.includes(lead), 'rule drifted between AGENTS.md and appendix E: ' + lead)
724
- const pointers = agents.match(new RegExp('docs/[A-Za-z0-9._-]+[.]md', 'g')) || []
725
- for (const rel of new Set(pointers)) {
726
- assert.ok(fs.existsSync(path.join(ROOT, rel)), 'AGENTS.md points at a missing file: ' + rel)
727
- }
728
- const retired = ['DESIGN', 'CONSTRUCTION', 'ACCEPTANCE', 'TASKS'].map((name) => name + '.md')
729
- const offenders = []
730
- for (const dir of ['', 'lib', 'scripts', 'tests', 'docs']) {
731
- for (const name of fs.readdirSync(path.join(ROOT, dir))) {
732
- if (!/\.(md|js|mjs)$/.test(name)) continue
733
- const text = fs.readFileSync(path.join(ROOT, dir, name), 'utf8')
734
- for (const gone of retired) if (text.includes(gone)) offenders.push((dir || '.') + '/' + name + ' -> ' + gone)
735
- }
736
- }
737
- assert.deepEqual(offenders, [], 'file still pointing at a retired document: ' + offenders.join(', '))
738
- return 'four documents exist, icons live in assets/, no planning files, no dangling reference'
739
- })
740
-
741
- await auto('G-2', 'the client only calls RPC methods the server implements', async () => {
742
- const rpc = fs.readFileSync(path.join(ROOT, 'lib', 'rpc.js'), 'utf8')
743
- const methods = new Set([...rpc.matchAll(/case \x27([a-zA-Z]+)\x27:/g)].map((match) => match[1]))
744
- assert.ok(methods.size >= 60, 'the RPC surface is ' + methods.size + ' methods, expected at least 60')
745
- const dangling = []
746
- for (const match of fs.readFileSync(path.join(ROOT, 'lib', 'client.js'), 'utf8').matchAll(/\bcall\(\s*[\x22\x27]([a-zA-Z]+)[\x22\x27]/g)) {
747
- if (!methods.has(match[1])) dangling.push(match[1])
748
- }
749
- assert.deepEqual([...new Set(dangling)], [], 'client calls no case answers: ' + dangling.join(', '))
750
- return methods.size + ' methods, every client call resolves'
751
- })
752
-
753
- await auto('G-3', 'the README states install, privacy, limits and license', async () => {
754
- const readme = fs.readFileSync(path.join(ROOT, 'README.md'), 'utf8')
755
- for (const phrase of ['## Installation', 'dsh plugin --profile web add dsh-memu-memory', 'Privacy, permissions & data', 'Compatibility & limits', '## License']) {
756
- assert.ok(readme.includes(phrase), 'the README lost ' + phrase)
757
- }
758
- return 'README carries install, privacy, limits and license'
759
- })
760
-
761
- await auto('G-4', 'the README includes the reviewed UI screenshots', async () => {
762
- const readme = fs.readFileSync(path.join(ROOT, 'README.md'), 'utf8')
763
- const chinese = fs.readFileSync(path.join(ROOT, 'README.zh.md'), 'utf8')
764
- for (const name of ['webui-memory', 'settings', 'drawer', 'relations', 'stats', 'webui-dark', 'mobile']) {
765
- const relative = `assets/screenshots/${name}.jpg`
766
- assert.ok(readme.includes(relative), `${relative} is not linked from README.md`)
767
- assert.ok(chinese.includes(relative), `${relative} is not linked from README.zh.md`)
768
- assert.ok(fs.statSync(path.join(ROOT, relative)).size > 1000, `${relative} is empty`)
769
- }
770
- return 'the wall, drawer, relations, settings, stats, dark and narrow screenshots are linked in both READMEs'
771
- })
772
- for (const [id, file, title] of [
773
- ['J-1', 'tests/audit-safety.test.mjs', 'storage, isolation, review and bounded recall regressions'],
774
- ['J-2', 'tests/graph.test.mjs', 'bounded relationships, entity rename and evidence-backed snapshots'],
775
- ['J-3', 'tests/media.test.mjs', 'images, authenticated thumbnails, quota, GC and streaming archives'],
776
- ['J-4', 'tests/context-scope.test.mjs', 'group speakers, story branches and character knowledge boundaries'],
777
- ['J-5', 'tests/multiprocess.test.mjs', 'independent process writes preserve every disjoint entry'],
778
- ['J-6', 'tests/managed-runtime.test.mjs', 'pinned runtime checksums and contained Python fallback'],
779
- ['J-7', 'tests/rename.test.mjs', 'package rename keeps existing data and explicit roots'],
780
- ['J-8', 'tests/inbound.test.mjs', 'long tool turns admit real human batches, images and logical recall without treating logs as speech'],
781
- ]) {
782
- await auto(id, title, () => runTestFile(file))
783
- }
784
- // ---------------------------------------------------- the v4 additions (H)
785
-
786
- await auto('H-1', 'every browser row carries its source, and it can be corrected', async () => {
787
- const lib = makeLibrary('h1')
788
- seed(lib.id, 'mem-h1a', { source: 'inferred', title: 'a guess' })
789
- const before = (await dispatch({}, 'browseLibrary', { libraryId: lib.id })).files[0]
790
- assert.equal(before.source, 'inferred', 'the default is the honest one: this is what i worked out, not what i was told')
791
- await dispatch({}, 'updateMemory', { libraryId: lib.id, id: 'mem-h1a', patch: { source: 'user_said' } })
792
- const after = (await dispatch({}, 'browseLibrary', { libraryId: lib.id })).files[0]
793
- assert.equal(after.source, 'user_said', 'it can be corrected by hand')
794
- let rejected = ""
795
- try {
796
- await dispatch({}, 'updateMemory', { libraryId: lib.id, id: 'mem-h1a', patch: { source: 'guessed' } })
797
- } catch (error) { rejected = error.message }
798
- assert.match(rejected, /source must be/, 'and a typo is refused rather than stored')
799
- const client = fs.readFileSync(path.join(ROOT, 'lib', 'client.js'), 'utf8')
800
- for (const key of ['sourceUserSaid', 'sourceInferred', 'sourceImagined', 'sourceTold', 'sourceLabel']) {
801
- assert.ok(client.includes(key), 'the browser knows how to label ' + key)
802
- }
803
- return 'inferred by default, editable, typo refused'
804
- })
805
-
806
- await auto('H-2', 'a vivid memory that may be inaccurate is labelled as such', async () => {
807
- const lib = makeLibrary('h2')
808
- const stored = await memory.privateRemember({
809
- libraryId: lib.id, title: 'the night of the outage', layer: 'long_term',
810
- content: '警报响了三次,我只记得自己站在走廊里看表。', peak: true, arousal: 0.95, confidence: 0.9,
811
- })
812
- const view = await dispatch({}, 'browseLibrary', { libraryId: lib.id })
813
- const row = view.files.find((item) => item.id === stored.id)
814
- assert.ok(row, 'the row is in the browser after the write')
815
- assert.ok(row.accuracy < row.confidence, 'accuracy is its own number: ' + row.accuracy + ' vs ' + row.confidence)
816
- const client = fs.readFileSync(path.join(ROOT, 'lib', 'client.js'), 'utf8')
817
- assert.ok(client.includes('accuracyTag'), 'the browser can say so in words')
818
- return 'accuracy ' + row.accuracy + ' under confidence ' + row.confidence
819
- })
820
-
821
- await auto('H-3', 'a recall shows the passage around the hit, not the start of the memory', async () => {
822
- const lib = makeLibrary('h3')
823
- const filler = 'A'.repeat(400)
824
- const content = filler + '那天他说不想再改需求了。' + 'B'.repeat(400)
825
- seed(lib.id, 'mem-h3a', { title: 'a long one', content })
826
- const excerpt = snippet.centeredSnippet(content, '不想再改需求')
827
- assert.ok(excerpt.includes('不想再改需求'), 'the hit is inside the excerpt')
828
- assert.ok(excerpt.startsWith('…'), 'and the excerpt starts mid-memory')
829
- assert.ok(excerpt.length < 200, 'while staying short: ' + excerpt.length)
830
- const registered = new Map()
831
- registerTools({ tools: { register(tool) { registered.set(tool.name, tool) } }, logger: { warn() {} } })
832
- const cwd = path.join(home, 'ws', 'h3-folder')
833
- const binding = bindSession('sess-h3', { cwd, libraryId: lib.id })
834
- const exec = { agent: { session: { header: { id: 'sess-h3', cwd, agentPreset: binding.agentPreset } } } }
835
- const out = await registered.get('memu_private_recall').execute({ query: '不想再改需求' }, exec)
836
- const text = typeof out === 'string' ? out : JSON.stringify(out)
837
- assert.ok(text.includes('不想再改需求'), 'the tool result carries the hit, not the head of the memory')
838
- return excerpt.length + ' chars around the hit'
839
- })
840
- await auto('H-4', 'a contradiction is held back until someone settles it', async () => {
841
- const lib = makeLibrary('h4')
842
- const first = await memory.privateRemember({ libraryId: lib.id, title: 'deploy rule', layer: 'long_term', content: '部署前必须先跑一遍全量测试,确认没有回归。' })
843
- const second = await memory.privateRemember({ libraryId: lib.id, title: 'deploy rule', layer: 'long_term', content: '部署前不用跑测试,直接上就行,省时间。' })
844
- assert.equal(second.entry.status, 'pending_review', 'the second claim is held, not merged')
845
- assert.equal(second.conflict, first.id, 'and it says what it collides with')
846
- const queue = await dispatch({}, 'listReviews', { libraryId: lib.id })
847
- assert.equal(queue.scope, 'private')
848
- assert.ok(queue.items.some((item) => item.id === second.id), 'it shows up in the private queue')
849
- assert.equal(queue.items.find((item) => item.id === second.id).libraryId, lib.id, 'each row knows its library')
850
- const before = inject.buildAnchor({ libraryId: lib.id }, state.getSettings(), null)
851
- assert.ok(!before.text.includes('直接上就行'), 'both halves of a contradiction never sit in one prompt')
852
- await dispatch({}, 'resolveReview', { id: second.id, action: 'accept', libraryId: lib.id })
853
- const settled = (await dispatch({}, 'browseLibrary', { libraryId: lib.id })).files.find((item) => item.id === second.id)
854
- assert.equal(settled.status, 'active', 'accepting settles it')
855
- assert.ok(!(await dispatch({}, 'listReviews', { libraryId: lib.id })).items.some((item) => item.id === second.id), 'and takes it off the queue')
856
- const third = await memory.privateRemember({ libraryId: lib.id, title: 'staging rule', layer: 'long_term', content: '预发环境必须手动点一次发布按钮。' })
857
- const fourth = await memory.privateRemember({ libraryId: lib.id, title: 'staging rule', layer: 'long_term', content: '预发环境不需要手动点,自动发布就好。' })
858
- assert.equal(fourth.entry.status, 'pending_review')
859
- await dispatch({}, 'resolveReview', { id: fourth.id, action: 'reject', libraryId: lib.id })
860
- const rejected = (await dispatch({}, 'browseLibrary', { libraryId: lib.id })).files.find((item) => item.id === fourth.id)
861
- assert.equal(rejected.status, 'archived', 'rejecting archives instead of deleting: the claim is still history')
862
- return 'same-title conflict held, accepted, and rejected'
863
- })
864
-
865
- await auto('H-5', 'a memory on the tip of the tongue arrives as a title without its body', async () => {
866
- const lib = makeLibrary('h5')
867
- const long = '那年夏天我们在旧办公室最后一晚把所有抽屉清空,有人把钥匙挂在门框上,谁也没说要走,但所有人都知道第二周不会再来。'
868
- // Not must_remember: a pinned memory is never on the tip of the tongue by design.
869
- seed(lib.id, 'mem-h5a', { layer: 'long_term', title: 'the last night', content: long, confidence: 0.4 })
870
- const anchor = inject.buildAnchor({ libraryId: lib.id }, state.getSettings(), null)
871
- assert.ok(anchor.text.includes('the last night'), 'the title is the directory entry')
872
- assert.ok(anchor.text.includes('mem-h5a'), 'and points at the id so a recall can finish the job')
873
- assert.ok(!anchor.text.includes('第二周不会再来'), 'while withholding the body')
874
- return 'title only, id included'
875
- })
876
- await auto('H-6', 'a held claim is visible in the browser, with its library named', async () => {
877
- const lib = makeLibrary('h6')
878
- await memory.privateRemember({ libraryId: lib.id, title: 'deploy rule', layer: 'long_term', content: '部署前必须先跑一遍全量测试,确认没有回归。' })
879
- const second = await memory.privateRemember({ libraryId: lib.id, title: 'deploy rule', layer: 'long_term', content: '部署前不用跑测试,直接上就行,省时间。' })
880
- const rows = (await dispatch({}, 'browseLibrary', { libraryId: lib.id })).files
881
- const held = rows.find((item) => item.id === second.id)
882
- assert.ok(held, 'the browser still shows it: a queue nobody can see is not a queue')
883
- assert.equal(held.status, 'pending_review')
884
- const client = fs.readFileSync(path.join(ROOT, 'lib', 'client.js'), 'utf8')
885
- assert.ok(client.includes('reviewScopePrivate'), 'and the review row can say which library it came from')
886
- return 'visible as pending_review, queue row labelled'
887
- })
888
-
889
- await auto('H-7', 'an archived memory can be deleted, and only an archived one', async () => {
890
- const lib = makeLibrary('h7')
891
- const live = await memory.privateRemember({ libraryId: lib.id, title: 'still in use', content: '这条还在用,不该能被删掉。' })
892
- let refused = ""
893
- try { await dispatch({}, 'deleteMemory', { id: live.id, libraryId: lib.id }) } catch (error) { refused = error.message }
894
- assert.match(refused, /archive it first/, 'a live memory cannot be deleted in one step')
895
- await memory.privateArchive({ libraryId: lib.id, id: live.id })
896
- const archivedRow = (await dispatch({}, 'browseLibrary', { libraryId: lib.id })).files.find((item) => item.id === live.id)
897
- assert.equal(archivedRow.status, 'archived', 'archiving keeps it, so the archived tab has something to show')
898
- const gone = await dispatch({}, 'deleteMemory', { id: live.id, libraryId: lib.id, confirmed: true })
899
- assert.equal(gone.deleted, true)
900
- assert.ok(!(await dispatch({}, 'browseLibrary', { libraryId: lib.id })).files.some((item) => item.id === live.id), 'and then it is really gone')
901
- let needsLib = ""
902
- try { await dispatch({}, 'deleteMemory', { id: live.id }) } catch (error) { needsLib = error.message }
903
- assert.match(needsLib, /libraryId is required/, 'deleting without a library is refused: one hallucinated id must not erase a memory')
904
- let unknownLib = ""
905
- try { await dispatch({}, 'deleteMemory', { id: live.id, libraryId: 'lib-does-not-exist' }) } catch (error) { unknownLib = error.message }
906
- assert.match(unknownLib, /library not found/)
907
- const client = fs.readFileSync(path.join(ROOT, 'lib', 'client.js'), 'utf8')
908
- for (const key of ['browseArchivedTab', 'browseActiveTab', 'confirmDelete', 'deleteForever']) {
909
- assert.ok(client.includes(key), 'the browser has ' + key)
910
- }
911
- return 'guarded, then deleted for good'
912
- })
913
- // ------------------------------------------------------------ the tally
914
-
915
- const counts = { PASS: 0, FAIL: 0, MANUAL: 0 }
916
- for (const entry of results) counts[entry.verdict] += 1
917
-
918
- console.log('')
919
- console.log('===== local acceptance run =====')
920
- console.log('data root: ' + home)
921
- const groups = new Map()
922
- for (const entry of results) {
923
- const group = entry.id.charAt(0)
924
- if (!groups.has(group)) groups.set(group, [])
925
- groups.get(group).push(entry)
926
- }
927
- for (const [group, list] of groups) {
928
- const passed = list.filter((entry) => entry.verdict === "PASS").length
929
- const total = list.filter((entry) => entry.verdict !== "MANUAL").length
930
- console.log("")
931
- console.log(group + ": " + passed + "/" + total + " automated")
932
- for (const entry of list) {
933
- console.log(" [" + entry.verdict + "] " + entry.id + " " + entry.title)
934
- if (entry.detail) console.log(" " + entry.detail)
935
- }
936
- }
937
- console.log('')
938
- const automated = counts.PASS + counts.FAIL
939
- console.log('automated: ' + counts.PASS + '/' + automated + ' passed, ' + counts.FAIL + ' failed, ' + counts.MANUAL + ' left for a human')
940
- if (counts.FAIL > 0) {
941
- console.log('')
942
- console.log('FAILURES >>> rerun with --verbose to see the assertions')
943
- process.exitCode = 1
944
- } else {
945
- console.log('visual evidence reflects the recorded review; UI changes require a fresh browser review, see docs/client-conventions.md for the client conventions')
946
- }
1
+ #!/usr/bin/env node
2
+ // Local stand-in for the manual half of the acceptance checklist.
3
+ //
4
+ // Most of that checklist describes behaviour a person would verify by clicking
5
+ // around, but nearly all of it is observable through the same RPC surface the UI
6
+ // uses. This script drives that surface against a throwaway DSH_MEMU_HOME and
7
+ // reports one verdict per checklist item. What stays in the MANUAL column needs a
8
+ // real GUI (visual layout, screenshots, dark mode), a real engine install, or a real
9
+ // DSH conversation the host itself has to start.
10
+ //
11
+ // Usage: node scripts/acceptance-local.mjs [--verbose]
12
+
13
+ import assert from 'node:assert/strict'
14
+ import fs from 'node:fs'
15
+ import os from 'node:os'
16
+ import path from 'node:path'
17
+ import { execFile, spawnSync } from 'node:child_process'
18
+ import { promisify } from 'node:util'
19
+ import { fileURLToPath } from 'node:url'
20
+
21
+ const execFileAsync = promisify(execFile)
22
+ const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..')
23
+ const VERBOSE = process.argv.includes('--verbose')
24
+ // The plugin imports two packages that only exist inside DSH. The test suite
25
+ // resolves them through a small loader stub; re-exec under that loader so this
26
+ // script runs against exactly the same module surface as `npm test`.
27
+ if (!process.env.DSH_MEMU_ACCEPT_CHILD) {
28
+ const child = spawnSync(process.execPath, [
29
+ '--import', './tests/loader-register.mjs',
30
+ fileURLToPath(import.meta.url),
31
+ ...process.argv.slice(2),
32
+ ], { cwd: ROOT, stdio: 'inherit', env: { ...process.env, DSH_MEMU_ACCEPT_CHILD: '1' } })
33
+ process.exit(typeof child.status === 'number' ? child.status : 1)
34
+ }
35
+
36
+ const tmpBase = process.env.TEMP || process.env.TMP || os.tmpdir()
37
+ const home = fs.mkdtempSync(path.join(tmpBase, 'dsh-memu-memory-accept-'))
38
+ process.env.DSH_MEMU_HOME = home
39
+
40
+ const state = await import('../lib/state.js')
41
+ const memory = await import('../lib/memory.js')
42
+ const inject = await import('../lib/inject.js')
43
+ const prompts = await import('../lib/prompts.js')
44
+ const engine = await import('../lib/engine.js')
45
+ const budget = await import('../lib/budget.js')
46
+ const snippet = await import('../lib/snippet.js')
47
+ const paths = await import('../lib/paths.js')
48
+ const { dispatch } = await import('../lib/rpc.js')
49
+ const { registerTools } = await import('../lib/tools.js')
50
+
51
+ const results = []
52
+
53
+ async function auto(id, title, fn) {
54
+ try {
55
+ const detail = await fn()
56
+ results.push({ id, title, verdict: 'PASS', detail: String(detail || '') })
57
+ } catch (error) {
58
+ results.push({ id, title, verdict: 'FAIL', detail: String(error?.message || error) })
59
+ }
60
+ }
61
+
62
+ function manual(id, title, why) {
63
+ results.push({ id, title, verdict: 'MANUAL', detail: why })
64
+ }
65
+
66
+ let seq = 0
67
+ function makeLibrary(name) {
68
+ seq += 1
69
+ return state.createLibrary({ name: name + '-' + seq, cwd: path.join(home, 'ws', name + '-' + seq) })
70
+ }
71
+
72
+ function seed(libraryId, id, entry = {}) {
73
+ const index = state.loadPrivateIndex(libraryId)
74
+ index.entries[id] = {
75
+ layer: 'long_term', title: 'title of ' + id, content: 'body of ' + id, status: 'active',
76
+ createdAt: new Date().toISOString(), ...entry,
77
+ }
78
+ state.savePrivateIndex(libraryId, index)
79
+ }
80
+
81
+ function bindSession(sessionId, options = {}) {
82
+ state.ensureSession(sessionId, {
83
+ cwd: options.cwd,
84
+ libraryId: options.libraryId || null,
85
+ agentPreset: options.agentPreset || 'coding',
86
+ createLibrary: options.createLibrary !== false,
87
+ })
88
+ if (options.patch) state.setSessionBinding(sessionId, options.patch)
89
+ return state.getSessionBinding(sessionId)
90
+ }
91
+
92
+ function idsIn(text) {
93
+ return [...String(text || '').matchAll(/mem-[A-Za-z0-9]+-[A-Za-z0-9]+/g)].map((m) => m[0])
94
+ }
95
+ async function runTestFile(file) {
96
+ const env = { ...process.env, ELECTRON_RUN_AS_NODE: '1' }
97
+ try {
98
+ const out = await execFileAsync(
99
+ process.execPath,
100
+ // spec is required for the check-mark count below: the default TAP
101
+ // reporter never prints ✔, so every count would read 0.
102
+ ['--import', './tests/loader-register.mjs', '--test-reporter=spec', '--test', file],
103
+ { cwd: ROOT, env, timeout: 240000 },
104
+ )
105
+ const text = String(out.stdout || '')
106
+ const passed = (text.match(/\u2714/g) || []).length
107
+ return passed + ' check marks in ' + file
108
+ } catch (error) {
109
+ const raw = String((error.stdout || '') + (error.stderr || ''))
110
+ const bad = raw.split('\n').filter((line) => line.includes('not ok') || line.includes('\u2716'))
111
+ throw new Error(file + ' is not green: ' + (bad.slice(0, 3).join(' | ') || raw.slice(-400)))
112
+ }
113
+ }
114
+ // ------------------------------------------------------------ data safety (A)
115
+
116
+ await auto('A-1', 'a corrupt index is quarantined with its bytes intact', async () => {
117
+ const lib = makeLibrary('a1')
118
+ seed(lib.id, 'mem-a1a', {})
119
+ seed(lib.id, 'mem-a1b', {})
120
+ const file = path.join(home, 'index', lib.id + '.json')
121
+ const good = fs.readFileSync(file, 'utf8')
122
+ const broken = '{"entries": {"mem-a1a": '
123
+ fs.writeFileSync(file, broken)
124
+ state.clearCaches()
125
+ const index = state.loadPrivateIndex(lib.id)
126
+ const names = fs.readdirSync(path.join(home, 'index'))
127
+ const aside = names.filter((name) => name.includes('.corrupt-'))
128
+ assert.equal(aside.length, 1, 'the broken file is moved aside exactly once')
129
+ const kept = fs.readFileSync(path.join(home, 'index', aside[0]), 'utf8')
130
+ assert.equal(kept, broken, 'the corrupt bytes are preserved, not truncated')
131
+ assert.deepEqual(Object.keys(index.entries || {}), [], 'the conversation carries on with an empty view')
132
+ assert.throws(() => seed(lib.id, 'mem-blocked', {}), /earlier read failed/)
133
+ fs.writeFileSync(file, good)
134
+ state.clearCaches()
135
+ assert.ok(state.loadPrivateIndex(lib.id).entries['mem-a1a'])
136
+ seed(lib.id, 'mem-a1c', {})
137
+ assert.equal(fs.readFileSync(path.join(home, 'index', aside[0]), 'utf8'), broken, 'a later write leaves the quarantined bytes alone')
138
+ return 'quarantined as ' + aside[0]
139
+ })
140
+
141
+ await auto('A-2', 'a corrupt state.json is quarantined and can be restored by hand', async () => {
142
+ const lib = makeLibrary('a2')
143
+ const file = path.join(home, 'state.json')
144
+ const good = fs.readFileSync(file, 'utf8')
145
+ const broken = '{ "libraries": '
146
+ fs.writeFileSync(file, broken)
147
+ state.clearCaches()
148
+ const recovered = state.loadState()
149
+ const aside = fs.readdirSync(home).filter((name) => name.includes('.corrupt-'))
150
+ assert.equal(aside.length, 1, 'state.json is quarantined once')
151
+ assert.equal(fs.readFileSync(path.join(home, aside[0]), 'utf8'), broken, 'the broken bytes stay in the copy')
152
+ assert.equal(recovered.libraries?.[lib.id], undefined, 'the degraded state is empty instead of a crash')
153
+ fs.writeFileSync(file, good)
154
+ state.clearCaches()
155
+ assert.ok(state.loadState().libraries[lib.id], 'copying the bytes back restores the library registry')
156
+ return 'quarantined as ' + aside[0] + ', hand recovery verified'
157
+ })
158
+
159
+ // A transient EBUSY needs a second process to hold the handle, but the barrier it
160
+ // trips does not care which error caused it. Replacing the index file with a
161
+ // directory produces a real read failure (EISDIR) that is *not* a parse failure —
162
+ // exactly the distinction this item is about: an unreadable file must be left in
163
+ // place and write-protected, while a corrupt one is moved aside.
164
+ await auto('A-3', 'an I/O failure hangs a write barrier instead of moving the file', async () => {
165
+ const lib = makeLibrary('a3')
166
+ seed(lib.id, 'mem-a3a', { content: 'kept across the barrier' })
167
+ const file = path.join(home, 'index', lib.id + '.json')
168
+ const good = fs.readFileSync(file, 'utf8')
169
+ const warns = []
170
+ paths.setWarnSink((message) => warns.push(String(message)))
171
+ fs.rmSync(file)
172
+ fs.mkdirSync(file)
173
+ state.clearCaches()
174
+ const index = state.loadPrivateIndex(lib.id)
175
+ assert.deepEqual(Object.keys(index.entries || {}), [], 'an unreadable index reads as empty, not as a crash')
176
+ // Only this library's own quarantine copies count: A-1 left one behind on purpose.
177
+ const aside = fs.readdirSync(path.join(home, 'index')).filter((name) => name.startsWith(lib.id + '.json.corrupt-'))
178
+ assert.equal(aside.length, 0, 'an I/O failure is not corruption: nothing may be moved aside')
179
+ const failure = paths.readFailure(file)
180
+ assert.ok(failure, 'the failed read did not register a write barrier')
181
+ assert.notEqual(failure.kind, 'corrupt')
182
+ let blocked = null
183
+ try { state.savePrivateIndex(lib.id, { version: 1, entries: {} }) } catch (error) { blocked = error }
184
+ assert.ok(blocked, 'a write went through on top of an unreadable index')
185
+ assert.equal(blocked.code, 'dsh-memu-memory/read-failed')
186
+ assert.match(blocked.message, /refusing to overwrite/)
187
+ assert.ok(warns.some((line) => /writes are blocked/.test(line)), 'the barrier is silent: ' + JSON.stringify(warns))
188
+ fs.rmSync(file, { recursive: true, force: true })
189
+ fs.writeFileSync(file, good)
190
+ state.clearCaches()
191
+ const back = state.loadPrivateIndex(lib.id)
192
+ assert.ok(back.entries['mem-a3a'], 'the memory did not come back once the file read cleanly')
193
+ assert.equal(paths.readFailure(file), null, 'the barrier did not lift on the next clean read')
194
+ seed(lib.id, 'mem-a3b', {})
195
+ assert.deepEqual(paths.readFailuresUnder(path.join(home, 'index')), [], 'a stale barrier is left behind')
196
+ paths.setWarnSink(null)
197
+ return 'barrier hung and lifted; no file moved aside'
198
+ })
199
+
200
+ await auto('A-4', 'a write that lands during an await is not lost', async () => {
201
+ const lib = makeLibrary('a4')
202
+ seed(lib.id, 'mem-a4base', {})
203
+ const writer = (async () => {
204
+ await new Promise((resolve) => setTimeout(resolve, 15))
205
+ state.updatePrivateIndex(lib.id, (index) => {
206
+ index.entries['mem-a4x'] = {
207
+ layer: 'long_term', title: 'X', content: 'written by the browser', status: 'active',
208
+ createdAt: new Date().toISOString(),
209
+ }
210
+ })
211
+ })()
212
+ const remembered = (async () => {
213
+ await new Promise((resolve) => setTimeout(resolve, 5))
214
+ return memory.privateRemember({ libraryId: lib.id, content: 'written by a tool call', title: 'Y', layer: 'long_term' })
215
+ })()
216
+ const [, stored] = await Promise.all([writer, remembered])
217
+ const ids = Object.keys(state.loadPrivateIndex(lib.id).entries)
218
+ assert.ok(ids.includes('mem-a4base'), 'the seeded entry is still there')
219
+ assert.ok(ids.includes('mem-a4x'), 'the browser write survives')
220
+ assert.ok(ids.includes(stored.id), 'the tool write survives')
221
+ return ids.length + ' entries kept from two interleaved writers'
222
+ })
223
+ // -------------------------------------------------------- recall and budget (B)
224
+
225
+ await auto('B-2', 'a failing recall is reported and the turn still gets its text', async () => {
226
+ const library = makeLibrary('b2')
227
+ seed(library.id, 'mem-b2a', {})
228
+ const cwd = path.join(home, 'ws', 'b2-session')
229
+ const sessionId = 'sess-b2'
230
+ const binding = bindSession(sessionId, { cwd, libraryId: library.id, patch: { domain: 'coding' } })
231
+ const exec = { agent: { session: { header: { id: sessionId, cwd, agentPreset: binding.agentPreset } } } }
232
+ // The realistic failure: the engine backend is selected but not installed. It is
233
+ // set through the same RPC the settings page uses, so this is the user-facing path.
234
+ await dispatch({}, 'setSettings', { patch: { memoryBackend: 'api', vectorSource: 'local' } })
235
+ const failed = await inject.buildRecall(binding, 'title mem-b2a', 1, state.getSettings(), exec, sessionId)
236
+ await dispatch({}, 'setSettings', { patch: { memoryBackend: 'agent', vectorSource: 'local' } })
237
+ assert.ok(failed.errors.length > 0, 'the failure is carried out, not swallowed')
238
+ assert.match(failed.errors.join(' '), /semantic recall failed/)
239
+ assert.match(failed.text, /mem-b2a/, 'lexical fallback still returns the matching memory')
240
+ assert.equal(typeof failed.text, 'string', 'the caller still receives a string to inject')
241
+ const healthy = await inject.buildRecall(binding, 'something to look up', 2, state.getSettings(), exec, sessionId)
242
+ assert.deepEqual(healthy.errors, [], 'a healthy turn reports nothing')
243
+ return failed.errors[0].slice(0, 90)
244
+ })
245
+
246
+ await auto('B-3', 'anchor ids and the ids written into the text are the same set', async () => {
247
+ const library = makeLibrary('b3')
248
+ const body = '这一段是中文正文,用来把预算撑满。'.repeat(24)
249
+ for (let i = 0; i < 16; i += 1) {
250
+ seed(library.id, 'mem-b3-' + i, {
251
+ layer: 'must_remember', pinReason: 'because it matters', pinSource: 'user_explicit',
252
+ content: body + ' ' + i,
253
+ })
254
+ }
255
+ const globalIndex = state.loadGlobalIndex()
256
+ for (let i = 0; i < 10; i += 1) {
257
+ globalIndex.entries['mem-g3-' + i] = {
258
+ title: 'global ' + i, content: body + ' g' + i, status: 'active', domain: 'coding',
259
+ confidence: 0.8, createdAt: new Date().toISOString(),
260
+ }
261
+ }
262
+ state.saveGlobalIndex(globalIndex)
263
+ const cwd = path.join(home, 'ws', 'b3-session')
264
+ const binding = bindSession('sess-b3', { cwd, libraryId: library.id, patch: { domain: 'coding' } })
265
+ const anchor = inject.buildAnchor(binding, state.getSettings(), null)
266
+ const inText = [...new Set(idsIn(anchor.text))].sort()
267
+ const recorded = [...new Set(anchor.ids)].sort()
268
+ assert.ok(inText.length > 0, 'the anchor rendered something')
269
+ assert.ok(inText.length < 26, 'the budget actually cut something, otherwise this proves nothing')
270
+ assert.deepEqual(inText, recorded, 'nothing is recorded that was not said, and nothing said is left unrecorded')
271
+ return inText.length + ' ids matched, ' + (26 - inText.length) + ' cut by the budget'
272
+ })
273
+
274
+ await auto('B-4', 'a Chinese anchor lands inside its token budget', async () => {
275
+ const library = makeLibrary('b4')
276
+ const body = '这条记忆写的是中文,一共几十个字,用来测预算。'.repeat(20)
277
+ for (let i = 0; i < 20; i += 1) {
278
+ seed(library.id, 'mem-b4-' + i, { layer: 'must_remember', pinReason: 'because', pinSource: 'user_explicit', content: body })
279
+ }
280
+ // Keep this case independent of whatever earlier cases left in the global
281
+ // index, and fill the remaining anchor segments with RP-domain evidence.
282
+ state.saveGlobalIndex({ entries: {} })
283
+ const globalIndex = state.loadGlobalIndex()
284
+ for (let i = 0; i < 10; i += 1) {
285
+ globalIndex.entries['mem-b4-global-' + i] = {
286
+ title: 'global ' + i, content: body, status: 'active', domain: 'rp',
287
+ confidence: 0.8, createdAt: new Date().toISOString(),
288
+ }
289
+ }
290
+ state.saveGlobalIndex(globalIndex)
291
+ const cwd = path.join(home, 'ws', 'b4-session')
292
+ const binding = bindSession('sess-b4', { cwd, libraryId: library.id, patch: { domain: 'coding' } })
293
+ const settings = state.getSettings()
294
+ const anchor = inject.buildAnchor(binding, settings, null)
295
+ const tokens = budget.estTokens(anchor.text)
296
+ const target = Number(settings.anchorTokens || 700)
297
+ // Title cards spend less than the old full-text cards: the invariant is that the
298
+ // anchor never exceeds its budget and still renders a useful block, not that it
299
+ // fills the budget to 85%.
300
+ const low = Math.min(120, target)
301
+ const high = target
302
+ assert.ok(tokens >= low && tokens <= high,
303
+ 'estimated ' + tokens + ' tokens, wanted ' + low + '..' + high + ' for a ' + target + ' budget')
304
+ return tokens + ' tokens for a ' + target + ' budget (' + low + '..' + high + ')'
305
+ })
306
+ await auto('B-5', 'the anchor keeps the pins that were said out loud, not just the newest', async () => {
307
+ const library = makeLibrary('b5')
308
+ // Short bodies on purpose: pins get a fraction of the anchor budget, so long text
309
+ // would leave nothing rendered and the ordering claim would go untested.
310
+ seed(library.id, 'mem-b5said-1', {
311
+ layer: 'must_remember', pinSource: 'user_explicit', pinReason: 'said out loud',
312
+ title: 'what they told me', content: '这条是对方亲口交代的,必须一直记得。',
313
+ createdAt: '2019-01-01T00:00:00.000Z', updatedAt: '2019-01-01T00:00:00.000Z',
314
+ })
315
+ for (let i = 0; i < 30; i += 1) {
316
+ seed(library.id, 'mem-b5new-' + i, {
317
+ layer: 'must_remember', pinSource: 'self', pinReason: 'i noticed it',
318
+ title: 'trivia ' + i, content: '最近自己发现的琐碎置顶 ' + i + '。',
319
+ createdAt: new Date().toISOString(), updatedAt: new Date().toISOString(),
320
+ })
321
+ }
322
+ const cwd = path.join(home, 'ws', 'b5-session')
323
+ const binding = bindSession('sess-b5', { cwd, libraryId: library.id, patch: { domain: 'coding' } })
324
+ const anchor = inject.buildAnchor(binding, state.getSettings(), null)
325
+ const ids = idsIn(anchor.text)
326
+ assert.ok(ids.includes('mem-b5said-1'), 'the explicit pin survives even though it is years old')
327
+ assert.ok(ids.length < 31, 'something was cut, otherwise the ordering claim is untested')
328
+ // Among pins of equal rank the newest wins, so the oldest self-noticed pins are
329
+ // what the budget squeezes out — the explicit one keeps its place on rank alone.
330
+ assert.equal(ids[0], 'mem-b5said-1', 'the explicit pin is rendered first, ahead of 30 newer ones')
331
+ assert.ok(!ids.includes('mem-b5new-0'), 'the oldest self-noticed pin is the one that got cut')
332
+ return ids.length + ' of 31 kept, oldest self pins cut'
333
+ })
334
+
335
+ await auto('B-6', 'memu_status reports real counts and a degraded recall', async () => {
336
+ const library = makeLibrary('b6')
337
+ seed(library.id, 'mem-b6a', { layer: 'must_remember', pinSource: 'user_explicit', pinReason: 'said' })
338
+ seed(library.id, 'mem-b6b', { layer: 'must_remember', pinSource: 'self', pinReason: 'noticed' })
339
+ seed(library.id, 'mem-b6c', { layer: 'short_term' })
340
+ seed(library.id, 'mem-b6d', { status: 'archived' })
341
+ const cwd = path.join(home, 'ws', 'b6-session')
342
+ const sessionId = 'sess-b6'
343
+ const binding = bindSession(sessionId, { cwd, libraryId: library.id, patch: { domain: 'coding' } })
344
+ const registered = new Map()
345
+ registerTools({ tools: { register(tool) { registered.set(tool.name, tool) } }, logger: { warn() {} } })
346
+ const status = registered.get('memu_status')
347
+ assert.ok(status, 'the status tool is registered')
348
+ const exec = { agent: { session: { header: { id: sessionId, cwd, agentPreset: binding.agentPreset } } } }
349
+ const out = await status.execute({}, exec)
350
+ const text = typeof out === 'string' ? out : (out?.content?.[0]?.text || JSON.stringify(out))
351
+ assert.match(text, /private: 3 active, 2\/\d+ pinned/, 'counts match what is really in the index')
352
+ assert.match(text, /short_term: 1 active/)
353
+ assert.doesNotMatch(text, /recall: degraded/, 'a healthy session says nothing about recall')
354
+ state.setSessionBinding(sessionId, { lastRecallError: 'provider key missing', lastRecallErrorAt: new Date().toISOString() })
355
+ const degraded = await status.execute({}, exec)
356
+ const degradedText = typeof degraded === 'string' ? degraded : (degraded?.content?.[0]?.text || '')
357
+ assert.match(degradedText, /recall: degraded .*provider key missing/, 'the failure surfaces where the user can see it')
358
+ return 'counts correct, degraded recall surfaced'
359
+ })
360
+
361
+ await auto('B-7', 'id resolution: exact, unique prefix, ambiguous, unknown', async () => {
362
+ const index = { entries: {
363
+ 'mem-b7one': { layer: 'long_term' },
364
+ 'mem-b7two': { layer: 'long_term' },
365
+ 'mem-b7twox': { layer: 'long_term' },
366
+ } }
367
+ assert.equal(memory.resolveEntryId(index, 'mem-b7one'), 'mem-b7one', 'an exact id resolves to itself')
368
+ assert.equal(memory.resolveEntryId(index, 'mem-b7two'), 'mem-b7two', 'an exact id wins even when it prefixes another')
369
+ assert.equal(memory.resolveEntryId(index, 'mem-b7one.md'), 'mem-b7one', 'a trailing .md is tolerated')
370
+ assert.equal(memory.resolveEntryId(index, 'mem-b7twox'), 'mem-b7twox')
371
+ assert.throws(() => memory.resolveEntryId(index, 'mem-b7tw'), /ambiguous id .*candidates: mem-b7two, mem-b7twox/)
372
+ assert.throws(() => memory.resolveEntryId(index, 'mem-b7nope'), /unknown memory: mem-b7nope/)
373
+ assert.throws(() => memory.resolveEntryId(index, ' '), /id is required/)
374
+ return 'exact, prefix, ambiguous, unknown all behave as documented'
375
+ })
376
+ // ------------------------------------------------------------- guards (C)
377
+
378
+ await auto('C-1', 'a v4 message with a producer-less source kind still fails its test', async () => {
379
+ return runTestFile('tests/source-kind.test.mjs')
380
+ })
381
+
382
+ await auto('C-2', 'unpin is fenced: a reason, a quota, a cooldown', async () => {
383
+ const library = makeLibrary('c2')
384
+ seed(library.id, 'mem-c2pin', { layer: 'must_remember', pinSource: 'self', pinReason: 'noticed it' })
385
+ seed(library.id, 'mem-c2plain', { layer: 'long_term' })
386
+ const cwd = path.join(home, 'ws', 'c2-session')
387
+ const sessionId = 'sess-c2'
388
+ bindSession(sessionId, { cwd, libraryId: library.id })
389
+ const exec = { agent: { session: { header: { id: sessionId, cwd } } } }
390
+ const fine = 'I thought that remark mattered, but it was my own reading of it and it can go now.'
391
+ assert.throws(() => memory.privateUnpin({ exec, id: 'mem-c2pin', reason: 'too short' }), /at least \d+ characters/)
392
+ const first = memory.privateUnpin({ exec, id: 'mem-c2pin', reason: fine })
393
+ assert.equal(first.entry.layer, 'long_term', 'the pin is demoted, not deleted')
394
+ assert.equal(first.entry.marginalized, true)
395
+ assert.equal(first.entry.pinSource, null, 'the pin source is cleared so it cannot rank as a pin again')
396
+ assert.ok(first.entry.strength <= 0.2, 'strength is cut, not zeroed')
397
+ assert.throws(() => memory.privateUnpin({ exec, id: 'mem-c2plain', reason: fine }), /cooldown/)
398
+ const second = { agent: { session: { header: { id: 'sess-c2b', cwd } } } }
399
+ bindSession('sess-c2b', { cwd, libraryId: library.id })
400
+ assert.throws(() => memory.privateUnpin({ exec: second, id: 'mem-c2plain', reason: fine }), /not in must_remember/)
401
+ state.setSessionBinding('sess-c2b', { unpinCount: 2 })
402
+ assert.throws(() => memory.privateUnpin({ exec: second, id: 'mem-c2plain', reason: fine }), /quota for this conversation is used up/)
403
+ return 'reason, cooldown, layer and quota all hold'
404
+ })
405
+
406
+ await auto('C-3', 'no trauma leftovers in code or scripts', async () => {
407
+ const dirs = [path.join(ROOT, 'lib'), path.join(ROOT, 'scripts')]
408
+ const hits = []
409
+ const walk = (dir) => {
410
+ for (const name of fs.readdirSync(dir, { withFileTypes: true })) {
411
+ const full = path.join(dir, name.name)
412
+ if (name.isDirectory()) walk(full)
413
+ // This file names the word it is looking for; do not report itself.
414
+ else if (full === fileURLToPath(import.meta.url)) continue
415
+ else if (/\.(js|mjs|json|md)$/.test(name.name)) {
416
+ const text = fs.readFileSync(full, 'utf8')
417
+ if (/trauma/i.test(text)) hits.push(path.relative(ROOT, full))
418
+ }
419
+ }
420
+ }
421
+ for (const dir of dirs) walk(dir)
422
+ assert.deepEqual(hits, [], 'the old trauma flag is gone: ' + hits.join(', '))
423
+ return 'lib/ and scripts/ are clean'
424
+ })
425
+ // ------------------------------------------------------------- prompts (D)
426
+
427
+ await auto('D-1', 'prompts resolve to the conversation domain and fall back to base', async () => {
428
+ const coding = prompts.resolveDef('system-guide', 'coding')
429
+ assert.equal(coding.key, 'system-guide.coding', 'a coding session gets the coding variant')
430
+ assert.equal(prompts.resolveDef('system-guide', 'rp').key, 'system-guide.rp', 'and an rp session does not')
431
+ assert.equal(prompts.resolveDef('system-guide', 'general').key, 'system-guide', 'general is not a layered domain')
432
+ assert.equal(prompts.resolveDef('system-guide', 'no-such-domain').key, 'system-guide', 'an unknown domain falls back instead of throwing')
433
+ const layered = prompts.loadPromptForDomain('system-guide', {}, 'coding')
434
+ assert.equal(layered.fellBackToBase, false)
435
+ const plain = prompts.loadPromptForDomain('system-guide', {}, 'general')
436
+ assert.equal(plain.fellBackToBase, true, 'the caller can tell it got the generic text')
437
+ assert.ok(layered.text.length > 0 && plain.text.length > 0)
438
+ assert.notEqual(layered.text, plain.text, 'the two domains do not render the same text')
439
+ return 'coding/rp variants resolve, general and unknown fall back'
440
+ })
441
+
442
+ await auto('D-2', 'the prompts page renders every page and saving takes effect next turn', async () => {
443
+ const rendered = await runTestFile('tests/client-render.test.mjs')
444
+ const units = await runTestFile('tests/prompts.test.mjs')
445
+ return rendered + '; ' + units
446
+ })
447
+
448
+ await auto('D-3', 'a corrupted prompts manifest only degrades the wording', async () => {
449
+ const dir = prompts.promptsDir()
450
+ assert.ok(dir.startsWith(home), 'this check must run inside the throwaway home: ' + dir)
451
+ fs.mkdirSync(dir, { recursive: true })
452
+ const manifest = path.join(dir, 'manifest.json')
453
+ const before = fs.existsSync(manifest) ? fs.readFileSync(manifest, 'utf8') : null
454
+ fs.writeFileSync(manifest, '{ this is not json', 'utf8')
455
+ const states = prompts.getPromptStates()
456
+ assert.ok(Array.isArray(states) && states.length > 0, 'the prompt list still loads')
457
+ const guide = prompts.loadPrompt('system-guide', {})
458
+ assert.ok(guide.text && guide.text.length > 0, 'the system prompt still assembles')
459
+ if (before === null) fs.rmSync(manifest, { force: true })
460
+ else fs.writeFileSync(manifest, before, 'utf8')
461
+ return states.length + ' prompts survived a broken manifest'
462
+ })
463
+ // ---------------------------------------------- folders, sidebar, settings (E)
464
+
465
+ await auto('E-1', 'both folder switches off: no library, no injection, no prompt', async () => {
466
+ const cwd = path.join(home, 'ws', 'e1-folder')
467
+ const before = (await dispatch({}, 'listLibraries', {})).length
468
+ await dispatch({}, 'setFolderPolicy', { scopeKey: cwd, useLibrary: false, useGlobal: false })
469
+ const init = await dispatch({}, 'initSession', { sessionId: 'sess-e1', cwd, createLibrary: false })
470
+ assert.equal(init.binding.libraryId, null, 'the conversation starts unbound instead of inventing a library')
471
+ const after = (await dispatch({}, 'listLibraries', {})).length
472
+ assert.equal(after, before, 'no library appeared on disk')
473
+ const anchor = inject.buildAnchor(init.binding, state.getSettings(), 'sess-e1')
474
+ assert.deepEqual(anchor.ids, [], 'nothing is injected')
475
+ const sidebar = await dispatch({}, 'getSidebarState', { sessionId: 'sess-e1' })
476
+ assert.deepEqual(sidebar.private?.items || [], [], 'the sidebar has no private list to show')
477
+ assert.equal(sidebar.effective?.libraryBlocked, true, 'and it knows why: the folder turned it off')
478
+ return 'unbound, no library, no injection'
479
+ })
480
+
481
+ await auto('E-2', 'the sidebar never hands out an absolute path', async () => {
482
+ const lib = makeLibrary('e2')
483
+ const cwd = path.join(home, 'ws', 'e2-folder')
484
+ seed(lib.id, 'mem-e2a', {})
485
+ bindSession('sess-e2', { cwd, libraryId: lib.id })
486
+ const sidebar = await dispatch({}, 'getSidebarState', { sessionId: 'sess-e2' })
487
+ const text = JSON.stringify(sidebar)
488
+ assert.ok(!text.includes(home.split(path.sep).join('/')), 'the temp home path does not leak')
489
+ assert.ok(!/[A-Za-z]:\\|\.\/lib\//.test(text), 'no drive letters or repo-relative paths either')
490
+ return 'two levels, no paths in ' + text.length + ' bytes of sidebar state'
491
+ })
492
+
493
+ await auto('E-3', 'a switch the folder forbids snaps back instead of silently winning', async () => {
494
+ const lib = makeLibrary('e3')
495
+ const cwd = path.join(home, 'ws', 'e3-folder')
496
+ bindSession('sess-e3', { cwd, libraryId: lib.id })
497
+ await dispatch({}, 'setFolderPolicy', { scopeKey: cwd, useLibrary: false, useGlobal: false })
498
+ const res = await dispatch({}, 'setSessionScope', { sessionId: 'sess-e3', useLibrary: true, useGlobal: true })
499
+ assert.equal(res.clamped.length, 2, 'both fields come back clamped')
500
+ assert.deepEqual(res.clamped.map((c) => c.field).sort(), ['useGlobal', 'useLibrary'])
501
+ assert.equal(res.clamped[0].reason, 'folder')
502
+ // The clamp drops the field from the patch instead of applying and undoing it,
503
+ // so the binding keeps what it had while the effective answer stays narrow.
504
+ assert.equal(res.effective.useLibrary, false, 'the conversation cannot widen itself past the folder')
505
+ assert.equal(res.effective.libraryBlocked, true)
506
+ return 'both switches clamped with reason=folder'
507
+ })
508
+ await auto('E-4', 'a 500-memory library still paints its first screen in one call', async () => {
509
+ const lib = makeLibrary('e4')
510
+ const index = state.loadPrivateIndex(lib.id)
511
+ for (let i = 0; i < 500; i += 1) {
512
+ index.entries['mem-e4-' + i] = {
513
+ layer: 'long_term', title: 'entry ' + i, content: '正文 ' + i + ' ' + 'x'.repeat(400),
514
+ status: 'active', createdAt: new Date().toISOString(),
515
+ }
516
+ }
517
+ state.savePrivateIndex(lib.id, index)
518
+ const cwd = path.join(home, 'ws', 'e4-folder')
519
+ bindSession('sess-e4', { cwd, libraryId: lib.id })
520
+ const t0 = Date.now()
521
+ const sidebar = await dispatch({}, 'getSidebarState', { sessionId: 'sess-e4' })
522
+ const full = Date.now() - t0
523
+ const t1 = Date.now()
524
+ const beat = await dispatch({}, 'getSidebarState', { sessionId: 'sess-e4', revisionOnly: true })
525
+ const heartbeat = Date.now() - t1
526
+ assert.ok(sidebar.private.items.length <= 120, 'previews are capped at the page size, got ' + sidebar.private.items.length)
527
+ assert.ok(typeof beat.revision === 'number')
528
+ assert.ok(heartbeat < 150, 'the heartbeat must stay cheap, took ' + heartbeat + 'ms')
529
+ return 'first screen ' + full + 'ms for ' + sidebar.private.items.length + ' rows, heartbeat ' + heartbeat + 'ms'
530
+ })
531
+
532
+ await auto('E-5', 'a folder lists the conversations that live in it', async () => {
533
+ const lib = makeLibrary('e5')
534
+ const cwd = path.join(home, 'ws', 'e5-folder')
535
+ bindSession('sess-e5', { cwd, libraryId: lib.id })
536
+ const res = await dispatch({}, 'listFolderSessions', { scopeKey: cwd })
537
+ const rows = res.sessions || res.items || []
538
+ assert.ok(Array.isArray(rows), 'the folder view answers with a list')
539
+ assert.ok(rows.some((row) => row.sessionId === 'sess-e5' || row.id === 'sess-e5'),
540
+ 'the conversation in this folder is listed: ' + JSON.stringify(rows).slice(0, 200))
541
+ const other = await dispatch({}, 'listFolderSessions', { scopeKey: path.join(home, 'ws', 'e5-other') })
542
+ const otherRows = other.sessions || other.items || []
543
+ assert.equal(otherRows.length, 0, 'a folder nobody used stays empty')
544
+ return rows.length + ' rows in the folder that was used'
545
+ })
546
+
547
+ await auto('E-8', 'the folder policy is a ceiling, not a suggestion', async () => {
548
+ const cwd = path.join(home, 'ws', 'e8-folder')
549
+ await dispatch({}, 'setFolderPolicy', { scopeKey: cwd, useLibrary: false, useGlobal: false })
550
+ const policy = state.getWorkspacePolicy(cwd)
551
+ assert.equal(policy.useLibrary, false)
552
+ const scope = state.effectiveScope({ useLibrary: true, useGlobal: true }, policy)
553
+ assert.equal(scope.useLibrary, false, 'a conversation asking for more than the folder allows gets the folder')
554
+ assert.equal(scope.libraryBlocked, true)
555
+ await dispatch({}, 'setFolderPolicy', { scopeKey: cwd, useLibrary: true })
556
+ const reopened = state.effectiveScope({ useLibrary: true }, state.getWorkspacePolicy(cwd))
557
+ assert.equal(reopened.useLibrary, true, 'and turning the folder back on reopens it')
558
+ return 'clamped down and reopened'
559
+ })
560
+
561
+ await auto('E-9', 'the sidebar hears about a write no other reload announced', async () => {
562
+ const lib = makeLibrary('e9')
563
+ const cwd = path.join(home, 'ws', 'e9-folder')
564
+ bindSession('sess-e9', { cwd, libraryId: lib.id })
565
+ const first = await dispatch({}, 'getSidebarState', { sessionId: 'sess-e9', revisionOnly: true })
566
+ state.savePrivateIndex(lib.id, state.loadPrivateIndex(lib.id))
567
+ const second = await dispatch({}, 'getSidebarState', { sessionId: 'sess-e9', revisionOnly: true })
568
+ assert.ok(second.revision > first.revision, 'the revision moved: ' + first.revision + ' -> ' + second.revision)
569
+ assert.deepEqual(Object.keys(second).sort(), ['revision', 'stamp'], 'the heartbeat answers with a counter and a disk fingerprint')
570
+ assert.equal(typeof second.stamp, 'string', 'the fingerprint is a string this process did not have to write')
571
+ // The counter lives in module memory, so a write from another instance moves the
572
+ // fingerprint and nothing else — that is the case the sidebar used to miss.
573
+ fs.writeFileSync(path.join(home, 'index', lib.id + '.json'), JSON.stringify(state.loadPrivateIndex(lib.id), null, 2))
574
+ const third = await dispatch({}, 'getSidebarState', { sessionId: 'sess-e9', revisionOnly: true })
575
+ assert.notEqual(third.stamp, second.stamp, 'a write from outside this module still changes the fingerprint')
576
+ return 'revision ' + first.revision + ' -> ' + second.revision + ', stamp moved across instances'
577
+ })
578
+
579
+ // The gate is mounted through ReactDOM.createRoot, which is stubbed away from the
580
+ // settings harness — its own test builds the dialog and counts the cards.
581
+ await auto('E-6', 'the new-session prompt is four cards, and a folder can veto them', async () => {
582
+ const rendered = await runTestFile('tests/new-session-gate.test.mjs')
583
+ const cases = Number(String(rendered).split(' ')[0])
584
+ assert.ok(cases >= 3, 'the gate test file only ran ' + cases + ' cases')
585
+ return cases + ' renders: four cards, a folder veto, a silent bind'
586
+ })
587
+ await auto('E-10', 'the settings pane hears a settings write made in another window', async () => {
588
+ const rendered = await runTestFile('tests/settings-beat.test.mjs')
589
+ const cases = Number(String(rendered).split(' ')[0])
590
+ assert.ok(cases >= 5, 'the settings heartbeat test file only ran ' + cases + ' cases')
591
+ return cases + ' cases: seeded beat, stamp-only write, channel wake, hidden silence, no-channel fallback'
592
+ })
593
+ await auto('E-7', 'reviewed desktop/mobile/theme screenshots exist and the shared UI keeps its layout guards', async () => {
594
+ const { default: sharp } = await import('sharp')
595
+ const folder = path.join(ROOT, 'assets', 'screenshots')
596
+ const desktop = await sharp(path.join(folder, 'webui-memory.jpg')).metadata()
597
+ const mobile = await sharp(path.join(folder, 'mobile.jpg')).metadata()
598
+ const dark = await sharp(path.join(folder, 'webui-dark.jpg')).stats()
599
+ assert.ok(desktop.width >= 1000)
600
+ assert.ok(mobile.width <= 480 && mobile.height >= 700)
601
+ assert.ok(dark.channels.some(channel => channel.stdev > 10), 'dark screenshot must not be blank')
602
+ const client = fs.readFileSync(path.join(ROOT, 'lib', 'client.js'), 'utf8')
603
+ assert.match(client, /prefers-reduced-motion/)
604
+ assert.match(client, /dshm-card-actions>div\{flex-wrap:wrap/)
605
+ return 'visual review recorded 2026-10-28; desktop/mobile/dark evidence checked, not a substitute for future visual review'
606
+ })
607
+ // ------------------------------------------------ statistics
608
+
609
+ await auto('H-8', 'the statistics follow real activity and survive a damaged sidecar', async () => {
610
+ const rendered = await runTestFile('tests/stats.test.mjs')
611
+ const cases = Number(String(rendered).split(' ')[0])
612
+ assert.ok(cases >= 5, 'the statistics test file only ran ' + cases + ' cases')
613
+ return cases + ' cases: counts, zero-filled empty library, 90-day roll, damaged sidecar, edit-archive'
614
+ })
615
+ // ------------------------------------------------ engine, backups, docs (F, G)
616
+
617
+ await auto('F-1', 'the engine can be listed, switched and pruned', async () => {
618
+ const units = await runTestFile('tests/engine.test.mjs')
619
+ const listing = await dispatch({}, 'listVersions', {})
620
+ assert.ok(Array.isArray(listing.versions || listing.items || []), 'the version list is an array even with no engine installed')
621
+ const pruned = engine.pruneEngineVersions({ keep: 3 })
622
+ assert.ok(pruned && typeof pruned === 'object', 'prune answers instead of throwing on an empty install')
623
+ return units + '; prune keep=3 survived an empty install'
624
+ })
625
+
626
+ await auto('F-2', 'a backup restore brings a deleted memory back', async () => {
627
+ const lib = makeLibrary('f2')
628
+ seed(lib.id, 'mem-f2keep', { title: 'written before the backup' })
629
+ const made = await state.backupDatabases()
630
+ assert.ok(made, 'a backup was taken')
631
+ const backups = (await dispatch({}, 'listBackups', {})).backups
632
+ assert.ok(backups.length >= 1, 'it shows up in the list')
633
+ const index = state.loadPrivateIndex(lib.id)
634
+ delete index.entries['mem-f2keep']
635
+ state.savePrivateIndex(lib.id, index)
636
+ assert.equal(state.loadPrivateIndex(lib.id).entries['mem-f2keep'], undefined, 'the memory is really gone')
637
+ const name = backups[0].name || backups[0].file || backups[0]
638
+ await dispatch({}, 'restoreBackup', { name: String(name) })
639
+ state.clearCaches()
640
+ const back = state.loadPrivateIndex(lib.id).entries['mem-f2keep']
641
+ assert.ok(back, 'the restore put it back')
642
+ assert.match(String(back.title), /written before the backup/)
643
+ return 'restored ' + String(name).slice(0, 40)
644
+ })
645
+
646
+ await auto('F-3', 'only three engine versions are kept', async () => {
647
+ const src = fs.readFileSync(path.join(ROOT, 'lib', 'engine.js'), 'utf8')
648
+ assert.match(src, /export function pruneEngineVersions\(\{ keep = 3 \}/, 'the default really is three')
649
+ assert.ok(!/engineKeepVersions/.test(fs.readFileSync(path.join(ROOT, 'lib', 'state.js'), 'utf8')),
650
+ 'and it is not a setting that pretends to exist')
651
+ return 'default keep=3, no phantom setting'
652
+ })
653
+
654
+ await auto('F-4', 'the activation log prints the settings the engine actually ran with', async () => {
655
+ // Reading ~/.dsh logs is not possible: the host keeps no log on disk (checked — the
656
+ // only files under ~/.dsh/logs are startup diagnostics, and none of them contain a
657
+ // dsh-memu-memory line). What the line says is asserted instead, by running the real apply()
658
+ // against a fake context that records logger.info.
659
+ const plugin = await import('../lib/index.js')
660
+ const info = []
661
+ const warn = []
662
+ const handlers = []
663
+ const disposers = []
664
+ const scope = {
665
+ effect(fn) { const dispose = fn(); if (typeof dispose === 'function') disposers.push(dispose) },
666
+ tools: { register() { return () => {} } },
667
+ webServer: { register() { return () => {} } },
668
+ connection: { requestRejection: () => undefined },
669
+ interval() { return 1 },
670
+ on(event, handler) { handlers.push({ event, handler }); return () => {} },
671
+ }
672
+ plugin.apply({
673
+ ...scope,
674
+ logger: { info: (message) => info.push(message), warn: (message) => warn.push(message) },
675
+ inject: (_deps, callback) => callback(scope),
676
+ })
677
+ const line = info.find((message) => message.startsWith('dsh-memu-memory: loaded'))
678
+ assert.ok(line, 'apply() logged no activation line at all')
679
+ const match = /^dsh-memu-memory: loaded \(engine (\S+)\) backend=(\S+) autoInject=(\S+) anchorTokens=(\d+) turnTokens=(\d+) mustRememberCap=(\d+) unpinBudget=(\d+)$/.exec(line)
680
+ assert.ok(match, 'the activation line lost its shape: ' + line)
681
+ const settings = state.getSettings()
682
+ assert.equal(match[1], engine.ENGINE_VERSION)
683
+ assert.equal(match[2], state.getMemoryBackend())
684
+ assert.equal(match[3], settings.autoInject)
685
+ assert.equal(Number(match[4]), settings.anchorTokens)
686
+ assert.equal(Number(match[5]), settings.turnTokens)
687
+ assert.equal(Number(match[6]), settings.mustRememberCap)
688
+ assert.equal(Number(match[7]), settings.unpinBudgetPerSession)
689
+ assert.deepEqual(
690
+ handlers.filter((entry) => ['agent/pre-step', 'session/event'].includes(entry.event)).map((entry) => entry.event).sort(),
691
+ // 两个 session/event:注入管线一个 + 增量回合日志记录器一个(设计文档 §3.2,T0 起挂载)。
692
+ ['agent/pre-step', 'session/event', 'session/event'],
693
+ 'the same activation must wire the injection hooks and the turn-log recorder',
694
+ )
695
+ for (const dispose of disposers) { try { dispose() } catch {} }
696
+ return 'line matches live settings, injection + turn-log hooks wired'
697
+ })
698
+
699
+ await auto('G-1', 'the kept docs exist and nothing points at a retired one', async () => {
700
+ for (const rel of ['README.md', 'README.zh.md', 'AGENTS.md', 'LICENSE']) {
701
+ assert.ok(fs.existsSync(path.join(ROOT, rel)), rel + ' exists')
702
+ }
703
+ for (const rel of ['assets/icon.png', 'assets/icon-256.png', 'assets/icon.svg']) {
704
+ assert.ok(fs.existsSync(path.join(ROOT, rel)), rel + ' exists')
705
+ }
706
+ // Since 1.1.3 the changelog is the source for release notes (release.yml), so it is kept.
707
+ assert.ok(fs.existsSync(path.join(ROOT, 'CHANGELOG' + '.md')), 'CHANGELOG.md carries release notes')
708
+ // 细节从 AGENTS.md 搬进了 docs/:索引必须短,指针必须都能落地
709
+ const agents = fs.readFileSync(path.join(ROOT, 'AGENTS.md'), 'utf8')
710
+ assert.ok(agents.includes('plugin:dsh-memu-memory'), 'the notes carry the real source kind, not the old one')
711
+ const docs = ['troubleshooting', 'contributing', 'host-api', 'client-conventions', 'memory-semantics', 'env-and-commands']
712
+ for (const name of docs) {
713
+ assert.ok(fs.existsSync(path.join(ROOT, 'docs', name + '.md')), 'docs/' + name + '.md exists')
714
+ assert.ok(agents.includes('docs/' + name + '.md'), 'the index points at docs/' + name + '.md')
715
+ }
716
+ // 硬规则在 AGENTS.md §1 与附录 E 各有一份:改一处忘另一处,这里会红
717
+ const appendix = fs.readFileSync(path.join(ROOT, 'docs', 'troubleshooting.md'), 'utf8')
718
+ const ruleLead = (text) => text.split(String.fromCharCode(10)).filter((l) => /^[0-9]+[.] [*][*]/.test(l)).map((l) => { const end = l.indexOf('**', 5); return end < 0 ? l.slice(0, 40) : l.slice(0, end + 2) })
719
+ const inIndex = ruleLead(agents)
720
+ const inAppendix = ruleLead(appendix)
721
+ assert.ok(inIndex.length >= 10, 'the index carries at least ten hard rules, got ' + inIndex.length)
722
+ assert.equal(inAppendix.length, inIndex.length, 'the appendix carries the same hard rules')
723
+ for (const lead of inIndex) assert.ok(inAppendix.includes(lead), 'rule drifted between AGENTS.md and appendix E: ' + lead)
724
+ const pointers = agents.match(new RegExp('docs/[A-Za-z0-9._-]+[.]md', 'g')) || []
725
+ for (const rel of new Set(pointers)) {
726
+ assert.ok(fs.existsSync(path.join(ROOT, rel)), 'AGENTS.md points at a missing file: ' + rel)
727
+ }
728
+ const retired = ['DESIGN', 'CONSTRUCTION', 'ACCEPTANCE', 'TASKS'].map((name) => name + '.md')
729
+ const offenders = []
730
+ for (const dir of ['', 'lib', 'scripts', 'tests', 'docs']) {
731
+ for (const name of fs.readdirSync(path.join(ROOT, dir))) {
732
+ if (!/\.(md|js|mjs)$/.test(name)) continue
733
+ const text = fs.readFileSync(path.join(ROOT, dir, name), 'utf8')
734
+ for (const gone of retired) if (text.includes(gone)) offenders.push((dir || '.') + '/' + name + ' -> ' + gone)
735
+ }
736
+ }
737
+ assert.deepEqual(offenders, [], 'file still pointing at a retired document: ' + offenders.join(', '))
738
+ return 'four documents exist, icons live in assets/, no planning files, no dangling reference'
739
+ })
740
+
741
+ await auto('G-2', 'the client only calls RPC methods the server implements', async () => {
742
+ const rpc = fs.readFileSync(path.join(ROOT, 'lib', 'rpc.js'), 'utf8')
743
+ const methods = new Set([...rpc.matchAll(/case \x27([a-zA-Z]+)\x27:/g)].map((match) => match[1]))
744
+ assert.ok(methods.size >= 60, 'the RPC surface is ' + methods.size + ' methods, expected at least 60')
745
+ const dangling = []
746
+ for (const match of fs.readFileSync(path.join(ROOT, 'lib', 'client.js'), 'utf8').matchAll(/\bcall\(\s*[\x22\x27]([a-zA-Z]+)[\x22\x27]/g)) {
747
+ if (!methods.has(match[1])) dangling.push(match[1])
748
+ }
749
+ assert.deepEqual([...new Set(dangling)], [], 'client calls no case answers: ' + dangling.join(', '))
750
+ return methods.size + ' methods, every client call resolves'
751
+ })
752
+
753
+ await auto('G-3', 'the README states install, privacy, limits and license', async () => {
754
+ const readme = fs.readFileSync(path.join(ROOT, 'README.md'), 'utf8')
755
+ for (const phrase of ['## Installation', 'dsh plugin --profile web add dsh-memu-memory', 'Privacy, permissions & data', 'Compatibility & limits', '## License']) {
756
+ assert.ok(readme.includes(phrase), 'the README lost ' + phrase)
757
+ }
758
+ return 'README carries install, privacy, limits and license'
759
+ })
760
+
761
+ await auto('G-4', 'the README includes the reviewed UI screenshots', async () => {
762
+ const readme = fs.readFileSync(path.join(ROOT, 'README.md'), 'utf8')
763
+ const chinese = fs.readFileSync(path.join(ROOT, 'README.zh.md'), 'utf8')
764
+ for (const name of ['webui-memory', 'settings', 'drawer', 'relations', 'stats', 'webui-dark', 'mobile']) {
765
+ const relative = `assets/screenshots/${name}.jpg`
766
+ assert.ok(readme.includes(relative), `${relative} is not linked from README.md`)
767
+ assert.ok(chinese.includes(relative), `${relative} is not linked from README.zh.md`)
768
+ assert.ok(fs.statSync(path.join(ROOT, relative)).size > 1000, `${relative} is empty`)
769
+ }
770
+ return 'the wall, drawer, relations, settings, stats, dark and narrow screenshots are linked in both READMEs'
771
+ })
772
+ for (const [id, file, title] of [
773
+ ['J-1', 'tests/audit-safety.test.mjs', 'storage, isolation, review and bounded recall regressions'],
774
+ ['J-2', 'tests/graph.test.mjs', 'bounded relationships, entity rename and evidence-backed snapshots'],
775
+ ['J-3', 'tests/media.test.mjs', 'images, authenticated thumbnails, quota, GC and streaming archives'],
776
+ ['J-4', 'tests/context-scope.test.mjs', 'group speakers, story branches and character knowledge boundaries'],
777
+ ['J-5', 'tests/multiprocess.test.mjs', 'independent process writes preserve every disjoint entry'],
778
+ ['J-6', 'tests/managed-runtime.test.mjs', 'pinned runtime checksums and contained Python fallback'],
779
+ ['J-7', 'tests/rename.test.mjs', 'package rename keeps existing data and explicit roots'],
780
+ ['J-8', 'tests/inbound.test.mjs', 'long tool turns admit real human batches, images and logical recall without treating logs as speech'],
781
+ ]) {
782
+ await auto(id, title, () => runTestFile(file))
783
+ }
784
+ // ---------------------------------------------------- the v4 additions (H)
785
+
786
+ await auto('H-1', 'every browser row carries its source, and it can be corrected', async () => {
787
+ const lib = makeLibrary('h1')
788
+ seed(lib.id, 'mem-h1a', { source: 'inferred', title: 'a guess' })
789
+ const before = (await dispatch({}, 'browseLibrary', { libraryId: lib.id })).files[0]
790
+ assert.equal(before.source, 'inferred', 'the default is the honest one: this is what i worked out, not what i was told')
791
+ await dispatch({}, 'updateMemory', { libraryId: lib.id, id: 'mem-h1a', patch: { source: 'user_said' } })
792
+ const after = (await dispatch({}, 'browseLibrary', { libraryId: lib.id })).files[0]
793
+ assert.equal(after.source, 'user_said', 'it can be corrected by hand')
794
+ let rejected = ""
795
+ try {
796
+ await dispatch({}, 'updateMemory', { libraryId: lib.id, id: 'mem-h1a', patch: { source: 'guessed' } })
797
+ } catch (error) { rejected = error.message }
798
+ assert.match(rejected, /source must be/, 'and a typo is refused rather than stored')
799
+ const client = fs.readFileSync(path.join(ROOT, 'lib', 'client.js'), 'utf8')
800
+ for (const key of ['sourceUserSaid', 'sourceInferred', 'sourceImagined', 'sourceTold', 'sourceLabel']) {
801
+ assert.ok(client.includes(key), 'the browser knows how to label ' + key)
802
+ }
803
+ return 'inferred by default, editable, typo refused'
804
+ })
805
+
806
+ await auto('H-2', 'a vivid memory that may be inaccurate is labelled as such', async () => {
807
+ const lib = makeLibrary('h2')
808
+ const stored = await memory.privateRemember({
809
+ libraryId: lib.id, title: 'the night of the outage', layer: 'long_term',
810
+ content: '警报响了三次,我只记得自己站在走廊里看表。', peak: true, arousal: 0.95, confidence: 0.9,
811
+ })
812
+ const view = await dispatch({}, 'browseLibrary', { libraryId: lib.id })
813
+ const row = view.files.find((item) => item.id === stored.id)
814
+ assert.ok(row, 'the row is in the browser after the write')
815
+ assert.ok(row.accuracy < row.confidence, 'accuracy is its own number: ' + row.accuracy + ' vs ' + row.confidence)
816
+ const client = fs.readFileSync(path.join(ROOT, 'lib', 'client.js'), 'utf8')
817
+ assert.ok(client.includes('accuracyTag'), 'the browser can say so in words')
818
+ return 'accuracy ' + row.accuracy + ' under confidence ' + row.confidence
819
+ })
820
+
821
+ await auto('H-3', 'a recall shows the passage around the hit, not the start of the memory', async () => {
822
+ const lib = makeLibrary('h3')
823
+ const filler = 'A'.repeat(400)
824
+ const content = filler + '那天他说不想再改需求了。' + 'B'.repeat(400)
825
+ seed(lib.id, 'mem-h3a', { title: 'a long one', content })
826
+ const excerpt = snippet.centeredSnippet(content, '不想再改需求')
827
+ assert.ok(excerpt.includes('不想再改需求'), 'the hit is inside the excerpt')
828
+ assert.ok(excerpt.startsWith('…'), 'and the excerpt starts mid-memory')
829
+ assert.ok(excerpt.length < 200, 'while staying short: ' + excerpt.length)
830
+ const registered = new Map()
831
+ registerTools({ tools: { register(tool) { registered.set(tool.name, tool) } }, logger: { warn() {} } })
832
+ const cwd = path.join(home, 'ws', 'h3-folder')
833
+ const binding = bindSession('sess-h3', { cwd, libraryId: lib.id })
834
+ const exec = { agent: { session: { header: { id: 'sess-h3', cwd, agentPreset: binding.agentPreset } } } }
835
+ const out = await registered.get('memu_private_recall').execute({ query: '不想再改需求' }, exec)
836
+ const text = typeof out === 'string' ? out : JSON.stringify(out)
837
+ assert.ok(text.includes('不想再改需求'), 'the tool result carries the hit, not the head of the memory')
838
+ return excerpt.length + ' chars around the hit'
839
+ })
840
+ await auto('H-4', 'a contradiction is held back until someone settles it', async () => {
841
+ const lib = makeLibrary('h4')
842
+ const first = await memory.privateRemember({ libraryId: lib.id, title: 'deploy rule', layer: 'long_term', content: '部署前必须先跑一遍全量测试,确认没有回归。' })
843
+ const second = await memory.privateRemember({ libraryId: lib.id, title: 'deploy rule', layer: 'long_term', content: '部署前不用跑测试,直接上就行,省时间。' })
844
+ assert.equal(second.entry.status, 'pending_review', 'the second claim is held, not merged')
845
+ assert.equal(second.conflict, first.id, 'and it says what it collides with')
846
+ const queue = await dispatch({}, 'listReviews', { libraryId: lib.id })
847
+ assert.equal(queue.scope, 'private')
848
+ assert.ok(queue.items.some((item) => item.id === second.id), 'it shows up in the private queue')
849
+ assert.equal(queue.items.find((item) => item.id === second.id).libraryId, lib.id, 'each row knows its library')
850
+ const before = inject.buildAnchor({ libraryId: lib.id }, state.getSettings(), null)
851
+ assert.ok(!before.text.includes('直接上就行'), 'both halves of a contradiction never sit in one prompt')
852
+ await dispatch({}, 'resolveReview', { id: second.id, action: 'accept', libraryId: lib.id })
853
+ const settled = (await dispatch({}, 'browseLibrary', { libraryId: lib.id })).files.find((item) => item.id === second.id)
854
+ assert.equal(settled.status, 'active', 'accepting settles it')
855
+ assert.ok(!(await dispatch({}, 'listReviews', { libraryId: lib.id })).items.some((item) => item.id === second.id), 'and takes it off the queue')
856
+ const third = await memory.privateRemember({ libraryId: lib.id, title: 'staging rule', layer: 'long_term', content: '预发环境必须手动点一次发布按钮。' })
857
+ const fourth = await memory.privateRemember({ libraryId: lib.id, title: 'staging rule', layer: 'long_term', content: '预发环境不需要手动点,自动发布就好。' })
858
+ assert.equal(fourth.entry.status, 'pending_review')
859
+ await dispatch({}, 'resolveReview', { id: fourth.id, action: 'reject', libraryId: lib.id })
860
+ const rejected = (await dispatch({}, 'browseLibrary', { libraryId: lib.id })).files.find((item) => item.id === fourth.id)
861
+ assert.equal(rejected.status, 'archived', 'rejecting archives instead of deleting: the claim is still history')
862
+ return 'same-title conflict held, accepted, and rejected'
863
+ })
864
+
865
+ await auto('H-5', 'a memory on the tip of the tongue arrives as a title without its body', async () => {
866
+ const lib = makeLibrary('h5')
867
+ const long = '那年夏天我们在旧办公室最后一晚把所有抽屉清空,有人把钥匙挂在门框上,谁也没说要走,但所有人都知道第二周不会再来。'
868
+ // Not must_remember: a pinned memory is never on the tip of the tongue by design.
869
+ seed(lib.id, 'mem-h5a', { layer: 'long_term', title: 'the last night', content: long, confidence: 0.4 })
870
+ const anchor = inject.buildAnchor({ libraryId: lib.id }, state.getSettings(), null)
871
+ assert.ok(anchor.text.includes('the last night'), 'the title is the directory entry')
872
+ assert.ok(anchor.text.includes('mem-h5a'), 'and points at the id so a recall can finish the job')
873
+ assert.ok(!anchor.text.includes('第二周不会再来'), 'while withholding the body')
874
+ return 'title only, id included'
875
+ })
876
+ await auto('H-6', 'a held claim is visible in the browser, with its library named', async () => {
877
+ const lib = makeLibrary('h6')
878
+ await memory.privateRemember({ libraryId: lib.id, title: 'deploy rule', layer: 'long_term', content: '部署前必须先跑一遍全量测试,确认没有回归。' })
879
+ const second = await memory.privateRemember({ libraryId: lib.id, title: 'deploy rule', layer: 'long_term', content: '部署前不用跑测试,直接上就行,省时间。' })
880
+ const rows = (await dispatch({}, 'browseLibrary', { libraryId: lib.id })).files
881
+ const held = rows.find((item) => item.id === second.id)
882
+ assert.ok(held, 'the browser still shows it: a queue nobody can see is not a queue')
883
+ assert.equal(held.status, 'pending_review')
884
+ const client = fs.readFileSync(path.join(ROOT, 'lib', 'client.js'), 'utf8')
885
+ assert.ok(client.includes('reviewScopePrivate'), 'and the review row can say which library it came from')
886
+ return 'visible as pending_review, queue row labelled'
887
+ })
888
+
889
+ await auto('H-7', 'an archived memory can be deleted, and only an archived one', async () => {
890
+ const lib = makeLibrary('h7')
891
+ const live = await memory.privateRemember({ libraryId: lib.id, title: 'still in use', content: '这条还在用,不该能被删掉。' })
892
+ let refused = ""
893
+ try { await dispatch({}, 'deleteMemory', { id: live.id, libraryId: lib.id }) } catch (error) { refused = error.message }
894
+ assert.match(refused, /archive it first/, 'a live memory cannot be deleted in one step')
895
+ await memory.privateArchive({ libraryId: lib.id, id: live.id })
896
+ const archivedRow = (await dispatch({}, 'browseLibrary', { libraryId: lib.id })).files.find((item) => item.id === live.id)
897
+ assert.equal(archivedRow.status, 'archived', 'archiving keeps it, so the archived tab has something to show')
898
+ const gone = await dispatch({}, 'deleteMemory', { id: live.id, libraryId: lib.id, confirmed: true })
899
+ assert.equal(gone.deleted, true)
900
+ assert.ok(!(await dispatch({}, 'browseLibrary', { libraryId: lib.id })).files.some((item) => item.id === live.id), 'and then it is really gone')
901
+ let needsLib = ""
902
+ try { await dispatch({}, 'deleteMemory', { id: live.id }) } catch (error) { needsLib = error.message }
903
+ assert.match(needsLib, /libraryId is required/, 'deleting without a library is refused: one hallucinated id must not erase a memory')
904
+ let unknownLib = ""
905
+ try { await dispatch({}, 'deleteMemory', { id: live.id, libraryId: 'lib-does-not-exist' }) } catch (error) { unknownLib = error.message }
906
+ assert.match(unknownLib, /library not found/)
907
+ const client = fs.readFileSync(path.join(ROOT, 'lib', 'client.js'), 'utf8')
908
+ for (const key of ['browseArchivedTab', 'browseActiveTab', 'confirmDelete', 'deleteForever']) {
909
+ assert.ok(client.includes(key), 'the browser has ' + key)
910
+ }
911
+ return 'guarded, then deleted for good'
912
+ })
913
+ // ------------------------------------------------------------ the tally
914
+
915
+ const counts = { PASS: 0, FAIL: 0, MANUAL: 0 }
916
+ for (const entry of results) counts[entry.verdict] += 1
917
+
918
+ console.log('')
919
+ console.log('===== local acceptance run =====')
920
+ console.log('data root: ' + home)
921
+ const groups = new Map()
922
+ for (const entry of results) {
923
+ const group = entry.id.charAt(0)
924
+ if (!groups.has(group)) groups.set(group, [])
925
+ groups.get(group).push(entry)
926
+ }
927
+ for (const [group, list] of groups) {
928
+ const passed = list.filter((entry) => entry.verdict === "PASS").length
929
+ const total = list.filter((entry) => entry.verdict !== "MANUAL").length
930
+ console.log("")
931
+ console.log(group + ": " + passed + "/" + total + " automated")
932
+ for (const entry of list) {
933
+ console.log(" [" + entry.verdict + "] " + entry.id + " " + entry.title)
934
+ if (entry.detail) console.log(" " + entry.detail)
935
+ }
936
+ }
937
+ console.log('')
938
+ const automated = counts.PASS + counts.FAIL
939
+ console.log('automated: ' + counts.PASS + '/' + automated + ' passed, ' + counts.FAIL + ' failed, ' + counts.MANUAL + ' left for a human')
940
+ if (counts.FAIL > 0) {
941
+ console.log('')
942
+ console.log('FAILURES >>> rerun with --verbose to see the assertions')
943
+ process.exitCode = 1
944
+ } else {
945
+ console.log('visual evidence reflects the recorded review; UI changes require a fresh browser review, see docs/client-conventions.md for the client conventions')
946
+ }