dsh-memu-memory 1.4.2 → 1.4.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (389) hide show
  1. package/AGENTS.md +108 -110
  2. package/CHANGELOG.md +173 -868
  3. package/LICENSE +21 -21
  4. package/README.md +368 -374
  5. package/README.zh.md +354 -360
  6. package/assets/icon.svg +7 -7
  7. package/cordis.patch.yml +8 -8
  8. package/docs/active-memory-ab.md +279 -385
  9. package/docs/binding-lifecycle.md +99 -99
  10. package/docs/client-conventions.md +75 -75
  11. package/docs/contributing.md +217 -217
  12. package/docs/emotion-model-spec.md +247 -281
  13. package/docs/env-and-commands.md +149 -152
  14. package/docs/host-adaptation.md +339 -360
  15. package/docs/host-api.md +131 -137
  16. package/docs/host-versions.md +117 -120
  17. package/docs/mcp-porting.md +146 -146
  18. package/docs/memory-semantics.md +271 -259
  19. package/docs/pending-work.md +44 -51
  20. package/docs/troubleshooting.md +909 -854
  21. package/lib/active-memory.js +160 -165
  22. package/lib/activity-log.js +207 -207
  23. package/lib/auto-link/apply.js +248 -249
  24. package/lib/auto-link/candidates.js +163 -163
  25. package/lib/auto-link/decide.js +300 -300
  26. package/lib/auto-link/normalize.js +99 -99
  27. package/lib/auto-link/policy.js +42 -42
  28. package/lib/auto-link/suppression.js +101 -101
  29. package/lib/auto-link/terminology.js +311 -311
  30. package/lib/backup.js +1254 -1254
  31. package/lib/binding-diagnostics.js +634 -634
  32. package/lib/budget.js +118 -118
  33. package/lib/client.js +9820 -9751
  34. package/lib/commitment.js +178 -138
  35. package/lib/consolidation-ledger.js +434 -438
  36. package/lib/consolidation-receipt.js +386 -387
  37. package/lib/consolidation-snapshot.js +420 -405
  38. package/lib/consolidation-worker.js +240 -241
  39. package/lib/context.js +33 -33
  40. package/lib/curator-evidence.js +131 -131
  41. package/lib/curator-policy.js +198 -202
  42. package/lib/curator.js +1813 -1811
  43. package/lib/cycle.js +524 -513
  44. package/lib/diagnostics.js +524 -524
  45. package/lib/embedding-catalog.js +1051 -1055
  46. package/lib/embedding-download.js +637 -607
  47. package/lib/embedding-runtime.js +946 -946
  48. package/lib/engine.js +1103 -1103
  49. package/lib/entity-repair.js +285 -285
  50. package/lib/environment-check.js +394 -394
  51. package/lib/fork-model.js +312 -312
  52. package/lib/freshness.js +128 -121
  53. package/lib/global-graph.js +389 -389
  54. package/lib/graph.js +1193 -1193
  55. package/lib/host-surface.js +30 -30
  56. package/lib/inbound.js +284 -281
  57. package/lib/index.js +506 -511
  58. package/lib/inject.js +2639 -2619
  59. package/lib/lexicon-scope.js +143 -143
  60. package/lib/lexicon.js +1183 -1192
  61. package/lib/lifecycle-audit.js +37 -0
  62. package/lib/local-embedding-entry.js +145 -145
  63. package/lib/local-embedding-manager.js +306 -306
  64. package/lib/local-embedding-protocol.js +210 -210
  65. package/lib/local-embedding-worker.js +682 -682
  66. package/lib/local-vector-service.js +506 -453
  67. package/lib/maintenance-ledger.js +138 -0
  68. package/lib/maintenance-review.js +103 -0
  69. package/lib/maintenance-runner.js +267 -0
  70. package/lib/managed-runtime.js +118 -118
  71. package/lib/media.js +607 -513
  72. package/lib/memory.js +5035 -4941
  73. package/lib/memu-config.js +213 -213
  74. package/lib/memu.js +565 -565
  75. package/lib/migrate.js +200 -200
  76. package/lib/mood.js +300 -300
  77. package/lib/paths.js +453 -457
  78. package/lib/port-surface.js +82 -82
  79. package/lib/preset-mount.js +85 -0
  80. package/lib/preset-scope.js +126 -126
  81. package/lib/private-links.js +567 -567
  82. package/lib/private.js +2198 -2209
  83. package/lib/prompts/global-curator.md +135 -135
  84. package/lib/prompts/image-caption.md +1 -1
  85. package/lib/prompts/private-consolidation.coding.md +39 -39
  86. package/lib/prompts/private-consolidation.md +32 -32
  87. package/lib/prompts/private-consolidation.mixed.md +37 -37
  88. package/lib/prompts/private-consolidation.rp.md +47 -47
  89. package/lib/prompts/private-policy.coding.md +35 -35
  90. package/lib/prompts/private-policy.md +36 -36
  91. package/lib/prompts/private-policy.mixed.md +29 -29
  92. package/lib/prompts/private-policy.rp.md +43 -43
  93. package/lib/prompts/system-guide.coding.md +20 -20
  94. package/lib/prompts/system-guide.md +25 -25
  95. package/lib/prompts/system-guide.mixed.md +22 -22
  96. package/lib/prompts/system-guide.rp.md +23 -23
  97. package/lib/prompts.js +331 -331
  98. package/lib/recall-cache.js +212 -212
  99. package/lib/remote-summary.js +123 -123
  100. package/lib/rpc.js +2531 -2532
  101. package/lib/salient-wake.js +438 -438
  102. package/lib/snippet.js +125 -125
  103. package/lib/state.js +1948 -1928
  104. package/lib/stats.js +236 -236
  105. package/lib/temporal.js +345 -348
  106. package/lib/text-retrieval.js +992 -1001
  107. package/lib/text-similarity.js +305 -305
  108. package/lib/tokenizer-v2.js +271 -271
  109. package/lib/tools.js +1098 -1091
  110. package/lib/turn-log.js +545 -545
  111. package/lib/vector-migration.js +928 -930
  112. package/lib/vector-profile.js +1353 -1359
  113. package/lib/visibility.js +59 -59
  114. package/lib/webui/graph-LICENSE.txt +1 -1
  115. package/lib/webui/graph-view.bundle.js +2 -2
  116. package/lib/webui/graph-view.js +1171 -1175
  117. package/lib/webui/mark.svg +7 -7
  118. package/lib/webui/standalone.css +1178 -1178
  119. package/lib/webui/standalone.js +238 -238
  120. package/lib/webui.js +136 -136
  121. package/lib/worker-pool.js +1020 -979
  122. package/package.json +153 -153
  123. package/requirements.lock +34 -34
  124. package/scripts/acceptance-local.mjs +946 -946
  125. package/scripts/active-memory-ab-live.mjs +653 -655
  126. package/scripts/active-memory-ab.mjs +1302 -1302
  127. package/scripts/audit-memory-lifecycle.mjs +55 -0
  128. package/scripts/bench-recall.mjs +142 -142
  129. package/scripts/build-graph.mjs +44 -45
  130. package/scripts/chain-matrix.mjs +541 -541
  131. package/scripts/check-all.mjs +68 -74
  132. package/scripts/check-doc-drift.mjs +547 -547
  133. package/scripts/check-graph-browser.mjs +261 -261
  134. package/scripts/check-i18n.mjs +81 -83
  135. package/scripts/check-idle-compositing.mjs +61 -61
  136. package/scripts/check-seed-compat.mjs +115 -118
  137. package/scripts/check-text-format.mjs +55 -0
  138. package/scripts/curator-pair-calibrate.mjs +259 -259
  139. package/scripts/diagnose-bindings.mjs +176 -176
  140. package/scripts/drive-session.mjs +863 -864
  141. package/scripts/engine-smoke.mjs +69 -69
  142. package/scripts/entity-dedupe.mjs +110 -110
  143. package/scripts/lexicon-calibrate.mjs +230 -230
  144. package/scripts/lexicon-dedupe.mjs +318 -318
  145. package/scripts/local-runtime-install.mjs +142 -142
  146. package/scripts/local-runtime-verify.mjs +56 -56
  147. package/scripts/local-vector-verify.mjs +93 -93
  148. package/scripts/make-readme-shots.mjs +59 -59
  149. package/scripts/migrate-visibility.mjs +94 -94
  150. package/scripts/mock-llm.mjs +938 -903
  151. package/scripts/preview.mjs +58 -58
  152. package/scripts/prune-sessions.mjs +31 -34
  153. package/scripts/prune-turnlogs.mjs +29 -30
  154. package/scripts/prune-vectors.mjs +24 -24
  155. package/scripts/rebuild-auto-links.mjs +252 -252
  156. package/scripts/recall-bench.mjs +820 -820
  157. package/scripts/repetition-ab-scenarios.mjs +93 -93
  158. package/scripts/repetition-detector-snapshot.mjs +314 -314
  159. package/scripts/repetition-eval-live.mjs +360 -360
  160. package/scripts/repetition-eval.mjs +702 -702
  161. package/scripts/replay.mjs +705 -575
  162. package/scripts/setup.mjs +46 -46
  163. package/scripts/simulate-injection.mjs +299 -301
  164. package/tests/absorb-review.test.mjs +354 -354
  165. package/tests/activation.test.mjs +89 -89
  166. package/tests/active-memory-ab.test.mjs +745 -745
  167. package/tests/active-memory.test.mjs +129 -129
  168. package/tests/activity-log.test.mjs +126 -126
  169. package/tests/activity-wiring.test.mjs +155 -155
  170. package/tests/appendix-b.test.mjs +217 -217
  171. package/tests/appendix-b2.test.mjs +166 -166
  172. package/tests/audit-batch3.test.mjs +247 -247
  173. package/tests/audit-regression.test.mjs +275 -275
  174. package/tests/audit-safety.test.mjs +227 -227
  175. package/tests/auto-link-candidates.test.mjs +245 -245
  176. package/tests/auto-link-decide.test.mjs +512 -512
  177. package/tests/auto-link-migration.test.mjs +133 -133
  178. package/tests/backend-compensation.test.mjs +272 -272
  179. package/tests/backup.test.mjs +793 -793
  180. package/tests/binding-diagnostics.test.mjs +720 -720
  181. package/tests/browser.test.mjs +476 -476
  182. package/tests/client-export.test.mjs +521 -521
  183. package/tests/client-render.test.mjs +2008 -1728
  184. package/tests/coalesce.test.mjs +113 -113
  185. package/tests/commitment.test.mjs +243 -144
  186. package/tests/config.test.mjs +159 -159
  187. package/tests/consolidation-credential.test.mjs +330 -330
  188. package/tests/consolidation-feed.test.mjs +122 -122
  189. package/tests/consolidation-fork.test.mjs +1587 -1539
  190. package/tests/consolidation-ledger.test.mjs +389 -389
  191. package/tests/consolidation-snapshot.test.mjs +567 -505
  192. package/tests/consolidation-value.test.mjs +89 -89
  193. package/tests/context-scope.test.mjs +40 -40
  194. package/tests/cross-library-recall.test.mjs +269 -269
  195. package/tests/cue.test.mjs +58 -58
  196. package/tests/curator-absorb.test.mjs +444 -444
  197. package/tests/curator-calibrate.test.mjs +173 -173
  198. package/tests/curator-clusters.test.mjs +306 -306
  199. package/tests/curator-commit.test.mjs +325 -325
  200. package/tests/curator-contract.test.mjs +191 -191
  201. package/tests/curator-evidence.test.mjs +102 -102
  202. package/tests/curator-link.test.mjs +317 -317
  203. package/tests/curator-pairing.test.mjs +339 -339
  204. package/tests/curator-probe.test.mjs +490 -490
  205. package/tests/curator-review-mode.test.mjs +315 -315
  206. package/tests/curator.test.mjs +152 -152
  207. package/tests/cycle.test.mjs +567 -568
  208. package/tests/diagnostics.test.mjs +278 -278
  209. package/tests/disclosure.test.mjs +249 -249
  210. package/tests/doc-drift.test.mjs +342 -342
  211. package/tests/drive-session.test.mjs +152 -152
  212. package/tests/dynamic-rrf.test.mjs +182 -182
  213. package/tests/dynamic-threshold.test.mjs +52 -52
  214. package/tests/embedding-catalog.test.mjs +374 -374
  215. package/tests/embedding-download.test.mjs +529 -486
  216. package/tests/embedding-runtime.test.mjs +449 -449
  217. package/tests/emotion-chain.test.mjs +84 -84
  218. package/tests/emotion-contract.test.mjs +445 -445
  219. package/tests/engine.test.mjs +108 -108
  220. package/tests/entity-merge.test.mjs +278 -278
  221. package/tests/environment-check.test.mjs +187 -187
  222. package/tests/fact-version.test.mjs +146 -146
  223. package/tests/fixtures/active-memory-ab/README.md +56 -56
  224. package/tests/fixtures/active-memory-ab/cases/01-clean-dense-turn.json +351 -351
  225. package/tests/fixtures/active-memory-ab/cases/02-clean-thin-turn.json +122 -122
  226. package/tests/fixtures/active-memory-ab/cases/03-clean-starved-small.json +125 -125
  227. package/tests/fixtures/active-memory-ab/cases/04-clean-large-thin.json +137 -137
  228. package/tests/fixtures/active-memory-ab/cases/05-clean-half-step.json +166 -166
  229. package/tests/fixtures/active-memory-ab/cases/06-clean-duplicate-reread.json +197 -197
  230. package/tests/fixtures/active-memory-ab/cases/07-clean-recent-recall.json +125 -125
  231. package/tests/fixtures/active-memory-ab/cases/08-global-relevant.json +111 -111
  232. package/tests/fixtures/active-memory-ab/cases/09-global-irrelevant-conflict.json +158 -158
  233. package/tests/fixtures/active-memory-ab/cases/10-no-human-turn.json +97 -97
  234. package/tests/fixtures/active-memory-ab/cases/11-clean-scale-100.json +137 -137
  235. package/tests/fixtures/active-memory-ab/cases/12-clean-scale-1000.json +137 -137
  236. package/tests/fixtures/active-memory-ab/cases/13-clean-scale-5000.json +137 -137
  237. package/tests/fixtures/active-memory-ab/cases/14-clean-scale-20000.json +137 -137
  238. package/tests/fixtures/active-memory-ab/lead-ai-reviewed-reference.json +191 -191
  239. package/tests/fixtures/active-memory-ab/manifest.json +199 -199
  240. package/tests/fixtures/curator-pairs/labeled.v1.jsonl +90 -90
  241. package/tests/fixtures/lexicon-stub-hooks.mjs +15 -15
  242. package/tests/fixtures/lexicon-stub.mjs +284 -284
  243. package/tests/fixtures/mock-llm/reply.txt +1 -1
  244. package/tests/fixtures/recall-bench/01-paraphrase.json +183 -183
  245. package/tests/fixtures/recall-bench/02-exact.json +152 -152
  246. package/tests/fixtures/recall-bench/03-negation.json +172 -172
  247. package/tests/fixtures/recall-bench/04-no-answer.json +161 -161
  248. package/tests/fixtures/recall-bench/05-conflict.json +193 -193
  249. package/tests/fixtures/recall-bench/06-boundary.json +272 -272
  250. package/tests/fixtures/recall-bench/07-secret.json +190 -190
  251. package/tests/fixtures/recall-bench/08-coding.json +163 -163
  252. package/tests/fixtures/recall-bench-gold-candidates/01-paraphrase.json +193 -193
  253. package/tests/fixtures/recall-bench-gold-candidates/02-exact.json +197 -197
  254. package/tests/fixtures/recall-bench-gold-candidates/03-negation.json +244 -244
  255. package/tests/fixtures/recall-bench-gold-candidates/04-no-answer.json +189 -189
  256. package/tests/fixtures/recall-bench-gold-candidates/05-conflict.json +245 -245
  257. package/tests/fixtures/recall-bench-gold-candidates/06-boundary.json +279 -279
  258. package/tests/fixtures/recall-bench-gold-candidates/07-secret.json +224 -224
  259. package/tests/fixtures/recall-bench-gold-candidates/08-coding.json +218 -218
  260. package/tests/fixtures/repetition-eval/01-zh-rp.json +92 -92
  261. package/tests/fixtures/repetition-eval/02-en.json +96 -96
  262. package/tests/fixtures/repetition-eval/03-code.json +90 -90
  263. package/tests/fixtures/repetition-eval/04-names.json +115 -115
  264. package/tests/fixtures/repetition-eval/05-user-quote.json +95 -95
  265. package/tests/fixtures/repetition-eval/06-agreement.json +85 -85
  266. package/tests/fixtures/tokenizer-cases.mjs +27 -27
  267. package/tests/fork-model.test.mjs +345 -345
  268. package/tests/freshness.test.mjs +140 -140
  269. package/tests/global-graph.test.mjs +106 -106
  270. package/tests/global-lifecycle.test.mjs +149 -149
  271. package/tests/graph-cascade.test.mjs +363 -363
  272. package/tests/graph-view.test.mjs +414 -414
  273. package/tests/graph.test.mjs +371 -371
  274. package/tests/help-page.test.mjs +416 -416
  275. package/tests/hook-order.test.mjs +72 -72
  276. package/tests/humanlike.test.mjs +232 -232
  277. package/tests/hybrid-recall.test.mjs +610 -610
  278. package/tests/inbound.test.mjs +441 -441
  279. package/tests/inject-conflict.test.mjs +173 -173
  280. package/tests/inject-guide.test.mjs +513 -513
  281. package/tests/inject.test.mjs +384 -384
  282. package/tests/injection-budget-settings.test.mjs +35 -35
  283. package/tests/injection-budget.test.mjs +165 -165
  284. package/tests/injection-chain.test.mjs +442 -442
  285. package/tests/injection-intent-budget.test.mjs +92 -92
  286. package/tests/injection-rollback.test.mjs +428 -428
  287. package/tests/issue2-chain.test.mjs +169 -169
  288. package/tests/lexical-bm25.test.mjs +171 -171
  289. package/tests/lexicon-calibrate.test.mjs +48 -48
  290. package/tests/lexicon-dedupe.test.mjs +171 -171
  291. package/tests/lexicon-frequency.test.mjs +195 -195
  292. package/tests/lexicon-inject.test.mjs +459 -459
  293. package/tests/lexicon-perf.test.mjs +464 -464
  294. package/tests/lexicon-scope.test.mjs +256 -256
  295. package/tests/lexicon-ui.test.mjs +667 -667
  296. package/tests/lexicon.test.mjs +922 -922
  297. package/tests/lifecycle-audit.test.mjs +56 -0
  298. package/tests/loader-register.mjs +3 -3
  299. package/tests/loader.mjs +17 -17
  300. package/tests/local-embedding-entry.test.mjs +95 -95
  301. package/tests/local-embedding-env.test.mjs +51 -51
  302. package/tests/local-embedding-manager.test.mjs +494 -494
  303. package/tests/local-embedding-protocol.test.mjs +121 -121
  304. package/tests/local-embedding-worker.test.mjs +440 -440
  305. package/tests/local-vector-service.test.mjs +41 -0
  306. package/tests/maintenance-status.test.mjs +77 -0
  307. package/tests/maintenance.test.mjs +438 -0
  308. package/tests/managed-memory.test.mjs +1234 -1234
  309. package/tests/managed-runtime.test.mjs +72 -72
  310. package/tests/media-injection.test.mjs +225 -0
  311. package/tests/media.test.mjs +135 -135
  312. package/tests/memory-chain.test.mjs +169 -169
  313. package/tests/memory-fields.test.mjs +134 -134
  314. package/tests/memu-resident-route.test.mjs +130 -130
  315. package/tests/memu-resident.test.mjs +33 -33
  316. package/tests/migration-payload.test.mjs +40 -42
  317. package/tests/mock-llm.test.mjs +263 -225
  318. package/tests/mood.test.mjs +109 -109
  319. package/tests/multiprocess.test.mjs +29 -29
  320. package/tests/negation-polarity.test.mjs +135 -135
  321. package/tests/new-session-gate.test.mjs +617 -617
  322. package/tests/open-loop-date.test.mjs +416 -416
  323. package/tests/ops-hardening.test.mjs +209 -209
  324. package/tests/package-shipping.test.mjs +88 -88
  325. package/tests/pending-injection.test.mjs +107 -107
  326. package/tests/port-surface.test.mjs +138 -138
  327. package/tests/preset-mount.test.mjs +132 -0
  328. package/tests/preset-scope.test.mjs +212 -212
  329. package/tests/private-links.test.mjs +493 -493
  330. package/tests/prompt-semantics.test.mjs +51 -51
  331. package/tests/prompts.test.mjs +315 -315
  332. package/tests/query-decompose.test.mjs +62 -62
  333. package/tests/react-snapshot.test.mjs +24 -24
  334. package/tests/recall-bench.test.mjs +317 -317
  335. package/tests/recall-cache.test.mjs +292 -292
  336. package/tests/recall-corpus-eligibility.test.mjs +51 -51
  337. package/tests/recall-dedup.test.mjs +446 -446
  338. package/tests/recall-intent.test.mjs +172 -172
  339. package/tests/regression-sweep.test.mjs +311 -311
  340. package/tests/reminder-fairness.test.mjs +55 -0
  341. package/tests/remote.test.mjs +140 -140
  342. package/tests/rename.test.mjs +30 -30
  343. package/tests/repetition-detector-snapshot.test.mjs +231 -231
  344. package/tests/repetition-eval-live.test.mjs +177 -177
  345. package/tests/repetition-eval.test.mjs +373 -373
  346. package/tests/salience-domain.test.mjs +173 -173
  347. package/tests/salient-date.test.mjs +142 -142
  348. package/tests/salient-wake.test.mjs +389 -389
  349. package/tests/settings-beat.test.mjs +222 -222
  350. package/tests/settings-coverage.test.mjs +97 -97
  351. package/tests/settings-plumbing.test.mjs +79 -79
  352. package/tests/short-term.test.mjs +182 -166
  353. package/tests/sidebar-beat.test.mjs +213 -213
  354. package/tests/sidebar-refresh.test.mjs +123 -123
  355. package/tests/sidebar.test.mjs +102 -74
  356. package/tests/simulate-injection.test.mjs +76 -76
  357. package/tests/slot-similarity.test.mjs +153 -153
  358. package/tests/snippet.test.mjs +79 -79
  359. package/tests/source-kind.test.mjs +52 -52
  360. package/tests/speaker-provenance.test.mjs +120 -120
  361. package/tests/stale-maintenance.test.mjs +206 -131
  362. package/tests/state-gc.test.mjs +34 -34
  363. package/tests/state.test.mjs +155 -155
  364. package/tests/stats.test.mjs +112 -112
  365. package/tests/storage.test.mjs +125 -125
  366. package/tests/stubs/child-process-spy.mjs +14 -14
  367. package/tests/stubs/dsh-llm-pi-ai.js +13 -13
  368. package/tests/stubs/dsh-llm.js +5 -5
  369. package/tests/stubs/dsh-schedule.js +140 -140
  370. package/tests/stubs/dsh-session-query.js +26 -26
  371. package/tests/stubs/dsh-session.js +7 -7
  372. package/tests/stubs/dsh-tools.js +101 -101
  373. package/tests/temporal-repair.test.mjs +78 -0
  374. package/tests/temporal.test.mjs +124 -124
  375. package/tests/text-format.test.mjs +24 -0
  376. package/tests/tokenizer-v2.test.mjs +142 -142
  377. package/tests/tool-schema.test.mjs +126 -126
  378. package/tests/tools.test.mjs +810 -810
  379. package/tests/turn-log.test.mjs +487 -487
  380. package/tests/ui-defaults.test.mjs +57 -57
  381. package/tests/update-fields.test.mjs +138 -138
  382. package/tests/vector-gc.test.mjs +37 -37
  383. package/tests/vector-migration.test.mjs +810 -810
  384. package/tests/vector-profile.test.mjs +449 -449
  385. package/tests/visibility-migration.test.mjs +152 -152
  386. package/tests/webui-auth.test.mjs +963 -963
  387. package/tests/webui.test.mjs +421 -421
  388. package/tests/windows-env.test.mjs +89 -89
  389. package/tests/worker-lifecycle.test.mjs +1522 -1429
@@ -1,487 +1,487 @@
1
- import test from 'node:test'
2
- import assert from 'node:assert/strict'
3
- import fs from 'node:fs'
4
- import os from 'node:os'
5
- import path from 'node:path'
6
-
7
- const home = fs.mkdtempSync(path.join(os.tmpdir(), 'dsh-memu-turn-log-'))
8
- process.env.DSH_MEMU_HOME = home
9
- process.env.DSH_MEMU_MEMORY_HOME = home
10
-
11
- const state = await import('../lib/state.js')
12
- const turnLog = await import('../lib/turn-log.js')
13
- const rpc = await import('../lib/rpc.js')
14
- const { registerTurnLogRecorder } = await import('../lib/index.js')
15
-
16
- test.after(() => {
17
- state.flushState()
18
- try { fs.rmSync(home, { recursive: true, force: true }) } catch {}
19
- })
20
-
21
- // —— 宿主事件 fixture(形状与 consolidation-snapshot/private 的口径一致) ——————
22
-
23
- let clock = 0
24
- function userMessage(seq, text, { sceneTime, kind = 'user' } = {}) {
25
- clock += 1000
26
- return { type: 'user/message', seq, time: clock, data: { id: `u${seq}`, source: { kind }, content: [{ type: 'text', text }], ...(sceneTime ? { sceneTime } : {}) } }
27
- }
28
- function assistantMessage(seq, text, blocks = []) {
29
- clock += 1000
30
- return { type: 'assistant/message', seq, time: clock, data: { message: { content: [{ type: 'text', text }, ...blocks] } } }
31
- }
32
- function toolCallEvent(seq, callId, name, args) {
33
- return { type: 'tool/call', seq, time: clock, data: { callId, name, arguments: args } }
34
- }
35
- function toolResultEvent(seq, callId, text, { isError = false } = {}) {
36
- return { type: 'tool/result', seq, time: clock, data: { message: { callId, content: [{ type: 'text', text }], isError } } }
37
- }
38
- function turnStart(seq, turn = 1) {
39
- return { type: 'turn/start', seq, time: clock, data: { turn } }
40
- }
41
- function turnEnd(seq, { kind = 'completed', turn = 1, time } = {}) {
42
- return { type: 'turn/end', seq, ...(time !== undefined ? { time } : { time: (clock += 1000) }), data: { turn, reason: { kind } } }
43
- }
44
-
45
- function oneTurn({ user, assistant, scene, kind = 'completed', startSeq = 10, tools = [] } = {}) {
46
- const events = [turnStart(startSeq)]
47
- let seq = startSeq + 1
48
- if (user !== undefined) events.push(userMessage(seq++, user, { sceneTime: scene }))
49
- for (const [callId, name, args, result, isError] of tools) {
50
- events.push(assistantMessage(seq++, '', [{ type: 'tool-call', id: callId, name, arguments: args }]))
51
- events.push(toolCallEvent(seq++, callId, name, args))
52
- if (result !== undefined) events.push(toolResultEvent(seq++, callId, result, { isError }))
53
- }
54
- if (assistant !== undefined) events.push(assistantMessage(seq++, assistant))
55
- events.push(turnEnd(seq, { kind }))
56
- return events
57
- }
58
-
59
- // —— 记录规则(§3.1) ———————————————————————————————————————
60
-
61
- test('one closed turn is one record: seq interval, scene, and the filtering rules', () => {
62
- const events = [
63
- turnStart(10),
64
- userMessage(11, '帮我看看明天要不要带伞', { sceneTime: '第三日夜' }),
65
- userMessage(12, '(插件注入的提示)', { kind: 'plugin:dsh-memu-memory' }),
66
- toolCallEvent(13, 'c1', 'weather', '{"city":"杭州"}'),
67
- assistantMessage(14, '明天有雨,建议带伞。'),
68
- toolResultEvent(15, 'c1', 'rain'),
69
- userMessage(16, '谢谢', { sceneTime: '第四日晨' }),
70
- turnEnd(17),
71
- ]
72
- const records = turnLog.buildTurnRecords(events)
73
- assert.equal(records.length, 1)
74
- assert.deepEqual(records[0].seq, [10, 17])
75
- // scene 取回合内最后一个带 sceneTime 的 user 事件值;插件注入不进 user 文本。
76
- assert.equal(records[0].scene, '第四日晨')
77
- assert.equal(records[0].user, '帮我看看明天要不要带伞\n谢谢')
78
- assert.equal(records[0].model, '明天有雨,建议带伞。')
79
- assert.equal(records[0].interrupted, undefined)
80
- assert.ok(records[0].at, 'the turn/end timestamp lands on the record')
81
- })
82
-
83
- test('an open tail turn and a heartbeat-only turn produce no record', () => {
84
- const openTail = oneTurn({ user: '未闭合的回合' })
85
- openTail.pop() // 拿掉 turn/end:半回合不产出记录
86
- assert.deepEqual(turnLog.buildTurnRecords(openTail), [])
87
-
88
- // 心跳/调度回合:没有真人消息也没有工具 → 不落行。
89
- const heartbeat = [turnStart(50), userMessage(51, 'heartbeat', { kind: 'plugin:heartbeat' }), turnEnd(52)]
90
- assert.deepEqual(turnLog.buildTurnRecords(heartbeat), [])
91
- })
92
-
93
- test('an aborted turn is marked interrupted', () => {
94
- const records = turnLog.buildTurnRecords(oneTurn({ user: '说到一半被打断', kind: 'aborted' }))
95
- assert.equal(records.length, 1)
96
- assert.equal(records[0].interrupted, true)
97
- assert.equal(records[0].seq[0], 10)
98
- })
99
-
100
- test('redactSecrets is applied to user, model and tool text at record time', () => {
101
- const secret = 'sk-abcdefghijklmnopqrstuvwxyz123456'
102
- const events = [
103
- turnStart(10),
104
- userMessage(11, `我的 key 是 ${secret} 别外传`),
105
- toolCallEvent(12, 'c1', 'deploy', '{}'),
106
- toolResultEvent(13, 'c1', `failed with ${secret}`, { isError: true }),
107
- assistantMessage(14, `收到,key ${secret} 已记下`),
108
- turnEnd(15),
109
- ]
110
- const records = turnLog.buildTurnRecords(events, { tools: 'errors' })
111
- assert.equal(records.length, 1)
112
- const flat = JSON.stringify(records[0])
113
- assert.ok(!flat.includes(secret), 'the raw secret must never reach the log')
114
- assert.ok(flat.includes('[REDACTED_KEY]'))
115
- })
116
-
117
- // —— 工具行三档(§3.1) ——————————————————————————————————————
118
-
119
- const TOOL_FIXTURE = [
120
- ['c1', 'edit_memory', '{"id":"m1"}', '修改成功', false],
121
- ['c2', 'readSession', '{"path":"a.ts"}', 'not found', true],
122
- ]
123
-
124
- test('tools mode none (the default) records pure dialogue without a tools field', () => {
125
- const events = oneTurn({ user: '改一下记忆', tools: TOOL_FIXTURE })
126
- const record = turnLog.buildTurnRecords(events)[0]
127
- assert.equal(record.tools, undefined)
128
- // 默认值走设置而不是参数:默认档就是 none。
129
- assert.equal(turnLog.buildTurnRecords(events)[0].tools, undefined)
130
- })
131
-
132
- test('tools mode errors keeps only the isError result line', () => {
133
- const record = turnLog.buildTurnRecords(oneTurn({ user: '查一下', tools: TOOL_FIXTURE }), { tools: 'errors' })[0]
134
- assert.equal(record.tools.length, 1)
135
- assert.match(record.tools[0], /readSession → 失败: not found/)
136
- assert.ok(!record.tools.some((line) => line.includes('edit_memory')), 'the successful call is not in errors mode')
137
- })
138
-
139
- test('tools mode summary pairs calls with results and flags calls without one', () => {
140
- const tools = [...TOOL_FIXTURE, ['c3', 'interruptedTool', '{"x":1}']] // 没有结果:被打断的调用
141
- const record = turnLog.buildTurnRecords(oneTurn({ user: '干活', tools }), { tools: 'summary' })[0]
142
- assert.equal(record.tools.length, 3)
143
- assert.match(record.tools[0], /edit_memory\(\{"id":"m1"\}\) → 成功/)
144
- assert.match(record.tools[1], /readSession\(\{"path":"a.ts"\}\) → 失败: not found/)
145
- assert.match(record.tools[2], /interruptedTool\(\{"x":1\}\) → 无结果/)
146
- })
147
-
148
- test('the assistant tool-call block is not double-counted next to its tool/call event', () => {
149
- const events = [
150
- turnStart(10),
151
- userMessage(11, '只算一次'),
152
- assistantMessage(12, '', [{ type: 'tool-call', id: 'c9', name: 'dupTool', arguments: '{}' }]),
153
- toolCallEvent(13, 'c9', 'dupTool', '{}'),
154
- toolResultEvent(14, 'c9', 'ok'),
155
- turnEnd(15),
156
- ]
157
- const record = turnLog.buildTurnRecords(events, { tools: 'summary' })[0]
158
- assert.equal(record.tools.length, 1)
159
- assert.match(record.tools[0], /dupTool\(\{\}\) → 成功/)
160
- })
161
-
162
- // —— 三层 caps(§3.1) ———————————————————————————————————————
163
-
164
- test('user and model text are each capped at 2000 chars and always kept in full within that', () => {
165
- const longUser = 'u'.repeat(3000)
166
- const longModel = 'm'.repeat(3000)
167
- const record = turnLog.buildTurnRecords(oneTurn({ user: longUser, assistant: longModel }))[0]
168
- assert.ok(record.user.length <= turnLog.TURNLOG_USER_MODEL_CHARS + 1)
169
- assert.ok(record.user.startsWith('u'.repeat(50)))
170
- assert.ok(record.model.length <= turnLog.TURNLOG_USER_MODEL_CHARS + 1)
171
- })
172
-
173
- test('each tool line is capped at 160 chars', () => {
174
- const tools = [['c1', 'tool', '{}', 'e'.repeat(500), true]]
175
- const record = turnLog.buildTurnRecords(oneTurn({ user: 'hi', tools }), { tools: 'errors' })[0]
176
- assert.ok(record.tools[0].length <= turnLog.TURNLOG_TOOL_LINE_CHARS + 1)
177
- })
178
-
179
- test('the 4000-char record cap cuts tool lines from the tail, never user/model', () => {
180
- const pad = 'p'.repeat(130)
181
- const tools = Array.from({ length: 30 }, (_, i) => [`c${i}`, `tool${i}`, `{"n":${i},"pad":"${pad}"}`, `r${String(i).repeat(140)}`, false])
182
- const record = turnLog.buildTurnRecords(oneTurn({ user: '短问题', assistant: '短回答', tools }), { tools: 'summary' })[0]
183
- assert.ok(JSON.stringify(record).length <= turnLog.TURNLOG_RECORD_CHARS, 'the serialized record fits the total cap')
184
- assert.equal(record.user, '短问题')
185
- assert.equal(record.model, '短回答')
186
- const marker = record.tools[record.tools.length - 1]
187
- assert.match(marker, /…\[另有 \d+ 条工具调用已省略\]/)
188
- // 保留行按原始顺序装,来自头部;行格式与未超预算时一致(args 同样 120 字截断)。
189
- const kept = record.tools.slice(0, -1)
190
- const expectedLine = ([, name, args]) => `${name}(${args.length > 120 ? `${args.slice(0, 120)}…` : args}) → 成功`
191
- assert.deepEqual(kept, tools.slice(0, kept.length).map(expectedLine))
192
- })
193
-
194
- // —— 设置面(§10.1 / 构件 4) ———————————————————————————————————
195
-
196
- test('the two new settings survive the setSettings allowlist and reset to their defaults', async () => {
197
- await rpc.dispatch({}, 'setSettings', { patch: { consolidationTurnLog: 'off', consolidationTurnLogTools: 'summary' } })
198
- assert.equal(state.getSettings().consolidationTurnLog, 'off')
199
- assert.equal(state.getSettings().consolidationTurnLogTools, 'summary')
200
- // 设置档驱动默认 tools 档(无参数调用读设置)。
201
- const record = turnLog.buildTurnRecords(oneTurn({ user: '看档位', tools: TOOL_FIXTURE }))[0]
202
- assert.equal(record.tools.length, 2, 'the settings-chosen summary mode is now the default')
203
- await assert.rejects(
204
- rpc.dispatch({}, 'setSettings', { patch: { consolidationTurnLogTools: 'all' } }),
205
- /invalid setting consolidationTurnLogTools/,
206
- )
207
- const reset = await rpc.dispatch({}, 'resetSettings', {})
208
- assert.equal(reset.consolidationTurnLog, 'on')
209
- assert.equal(reset.consolidationTurnLogTools, 'none')
210
- })
211
-
212
- // —— 落盘、增量读取与对账(§3.3) ————————————————————————————————
213
-
214
- test('recordTurn appends one JSON line per turn and readIncrement returns whole turns only', () => {
215
- const sessionId = 'incr-turns'
216
- turnLog.recordTurn(sessionId, { seq: [0, 10], at: '2026-11-13T21:00:00.000Z', scene: null, user: '一', model: '甲' })
217
- turnLog.recordTurn(sessionId, { seq: [11, 20], at: '2026-11-13T21:01:00.000Z', scene: null, user: '二', model: '乙' })
218
- turnLog.recordTurn(sessionId, { seq: [21, 30], at: '2026-11-13T21:02:00.000Z', scene: null, user: '三', model: '丙' })
219
-
220
- // afterSeq 落在回合中间(15):按 seqStart > afterSeq 过滤,[11,20] 整回合让位——
221
- // 返回的永远只有完整回合,绝无半回合。
222
- assert.deepEqual(turnLog.readIncrement(sessionId, 15).records.map((r) => r.seq), [[21, 30]])
223
- assert.deepEqual(turnLog.readIncrement(sessionId, 10).records.map((r) => r.seq), [[11, 20], [21, 30]])
224
- assert.deepEqual(turnLog.readIncrement(sessionId, 30).records, [])
225
- assert.equal(turnLog.readIncrement(sessionId, -1).records.length, 3)
226
- assert.equal(turnLog.readIncrement(sessionId, undefined).records.length, 3, 'a missing cursor reads the whole log')
227
- })
228
-
229
- test('recordTurn fills a missing timestamp and refuses records without a seq range', () => {
230
- const sessionId = 'at-fill'
231
- turnLog.recordTurn(sessionId, { seq: [0, 5], scene: null, user: 'a', model: 'b' })
232
- const line = fs.readFileSync(turnLog.turnLogPath(sessionId), 'utf8').trim().split('\n')[0]
233
- assert.ok(JSON.parse(line).at, 'recordTurn stamps the record when the turn/end had no time')
234
- assert.equal(turnLog.recordTurn(sessionId, { user: 'no seq' }), null, 'unanchorable records are rejected with a warn')
235
- })
236
-
237
- test('verifyGap finds holes between and around records', () => {
238
- const sessionId = 'gap-check'
239
- turnLog.recordTurn(sessionId, { seq: [0, 10], at: 't', scene: null, user: 'a', model: 'b' })
240
- turnLog.recordTurn(sessionId, { seq: [21, 30], at: 't', scene: null, user: 'c', model: 'd' })
241
- const hole = turnLog.verifyGap(sessionId, 0, 30)
242
- assert.equal(hole.ok, false)
243
- assert.deepEqual(hole.missingRanges, [[11, 20]])
244
- assert.equal(turnLog.verifyGap(sessionId, 0, 10).ok, true)
245
- const empty = turnLog.verifyGap('gap-never-written', 5, 50)
246
- assert.deepEqual(empty.missingRanges, [[5, 50]])
247
- })
248
-
249
- test('rebuildRange fills exactly the missing range from host events and is idempotent', () => {
250
- const sessionId = 'rebuild'
251
- const events = [
252
- ...oneTurn({ user: '第一回合', startSeq: 0 }),
253
- ...oneTurn({ user: '第二回合', startSeq: 40 }),
254
- ...oneTurn({ user: '第三回合', startSeq: 80 }),
255
- ]
256
- // 只记了第一回合,中间与尾部都是洞。
257
- turnLog.recordTurn(sessionId, { seq: [0, 17], at: 't', scene: null, user: '第一回合', model: '' })
258
-
259
- const first = turnLog.rebuildRange(sessionId, 18, 120, events)
260
- assert.equal(first.ok, true)
261
- assert.equal(first.rebuilt, 2)
262
- const { records } = turnLog.readIncrement(sessionId, 17)
263
- assert.deepEqual(records.map((r) => r.seq[0]), [40, 80])
264
-
265
- // 再跑一遍不产生重复行:重建幂等。
266
- const second = turnLog.rebuildRange(sessionId, 0, 120, events)
267
- assert.equal(second.rebuilt, 0)
268
- assert.equal(turnLog.readIncrement(sessionId, -1).records.length, 3)
269
- // 请求区间之外的事件不进日志。
270
- const outside = turnLog.rebuildRange(sessionId, 1000, 2000, events)
271
- assert.equal(outside.rebuilt, 0)
272
- })
273
-
274
- test('readers tolerate bad lines: skipped, counted, never thrown', () => {
275
- const sessionId = 'bad-lines'
276
- turnLog.recordTurn(sessionId, { seq: [0, 10], at: 't', scene: null, user: 'a', model: 'b' })
277
- fs.appendFileSync(turnLog.turnLogPath(sessionId), '{this is not json\n', 'utf8')
278
- turnLog.recordTurn(sessionId, { seq: [11, 20], at: 't', scene: null, user: 'c', model: 'd' })
279
-
280
- const inc = turnLog.readIncrement(sessionId, -1)
281
- assert.equal(inc.records.length, 2)
282
- assert.equal(inc.badLines, 1)
283
- assert.equal(turnLog.verifyGap(sessionId, 0, 20).badLines, 1)
284
- assert.equal(turnLog.tailSlice(sessionId, 10_000).records.length, 2)
285
- })
286
-
287
- // —— 头部裁剪(§3.4:绝不裁进未结算区间) ————————————————————————————
288
-
289
- function writeBulkyTurns(sessionId, count) {
290
- for (let i = 0; i < count; i++) {
291
- turnLog.recordTurn(sessionId, { seq: [i * 10, i * 10 + 9], at: 't', scene: null, user: `回合${i}`.padEnd(40, '字'), model: '' })
292
- }
293
- }
294
-
295
- test('pruneHead drops settled head records down to the budget, never past lastSleepSeq', () => {
296
- const sessionId = 'prune-head'
297
- writeBulkyTurns(sessionId, 6)
298
- // lastSleepSeq = 49:前 5 条已结算,最后一条(seqEnd 59)未结算。
299
- const report = turnLog.pruneHead(sessionId, 300, 49)
300
- assert.ok(report.pruned > 0, 'settled head records were cut')
301
- assert.ok(report.charsAfter <= 300)
302
- const after = turnLog.readIncrement(sessionId, -1).records
303
- assert.deepEqual(after.map((r) => r.seq[0]), [30, 40, 50], 'the cut stops inside settled range only; the unsettled turn survives')
304
- })
305
-
306
- test('pruneHead lets the file stay over budget rather than cut into the unsettled range', () => {
307
- const sessionId = 'prune-head-over'
308
- writeBulkyTurns(sessionId, 6)
309
- // lastSleepSeq = 19:只有前两条可裁,预算再小也不越过 seqEnd 19。
310
- const report = turnLog.pruneHead(sessionId, 100, 19)
311
- assert.ok(report.pruned > 0)
312
- assert.ok(report.charsAfter > 100, 'the file may stay over budget instead of pruning unsettled turns')
313
- const after = turnLog.readIncrement(sessionId, -1).records
314
- assert.ok(after.every((r) => r.seq[0] >= 20), 'every settled head record was taken; the unsettled tail is intact')
315
-
316
- // 没有结算游标:整份日志都是未结算段,一条不裁。
317
- const sessionId2 = 'prune-head-unsettled'
318
- writeBulkyTurns(sessionId2, 3)
319
- const untouched = turnLog.pruneHead(sessionId2, 50, null)
320
- assert.equal(untouched.pruned, 0)
321
- assert.equal(turnLog.readIncrement(sessionId2, -1).records.length, 3)
322
- })
323
-
324
- test('pruneHead preserves bad lines instead of dropping what it could not read', () => {
325
- const sessionId = 'prune-bad'
326
- turnLog.recordTurn(sessionId, { seq: [0, 9], at: 't', scene: null, user: 'a'.repeat(60), model: '' })
327
- fs.appendFileSync(turnLog.turnLogPath(sessionId), 'garbage line\n', 'utf8')
328
- turnLog.recordTurn(sessionId, { seq: [10, 19], at: 't', scene: null, user: 'b'.repeat(60), model: '' })
329
- turnLog.pruneHead(sessionId, 80, 100)
330
- const raw = fs.readFileSync(turnLog.turnLogPath(sessionId), 'utf8')
331
- assert.ok(raw.includes('garbage line'), 'a bad line cannot be proven settled, so it is kept')
332
- })
333
-
334
- // —— tailSlice(§5.1 交接尾部的来源) ——————————————————————————————
335
-
336
- test('tailSlice takes whole turns from the tail within the char budget', () => {
337
- const sessionId = 'tail'
338
- turnLog.recordTurn(sessionId, { seq: [0, 9], at: 't', scene: null, user: 'a'.repeat(100), model: '' })
339
- turnLog.recordTurn(sessionId, { seq: [10, 19], at: 't', scene: null, user: 'b'.repeat(100), model: '' })
340
- turnLog.recordTurn(sessionId, { seq: [20, 29], at: 't', scene: null, user: 'c'.repeat(100), model: '' })
341
- const slice = turnLog.tailSlice(sessionId, 400)
342
- assert.deepEqual(slice.records.map((r) => r.seq[0]), [10, 20], 'whole turns from the tail, chronological')
343
- assert.ok(slice.chars <= 400)
344
- assert.ok(!slice.text.includes('aaaa'), 'the oldest turn did not fit the budget and was left out')
345
- assert.equal(slice.text.split('\n').length, 2, 'the text is whole-turn JSONL from the tail')
346
- })
347
-
348
- // —— 删除与休眠 GC(§3.4) ——————————————————————————————————————
349
-
350
- test('deleteTurnLog removes the file and tolerates a missing one', () => {
351
- const sessionId = 'delete-me'
352
- turnLog.recordTurn(sessionId, { seq: [0, 1], at: 't', scene: null, user: 'a', model: 'b' })
353
- assert.ok(fs.existsSync(turnLog.turnLogPath(sessionId)))
354
- assert.equal(turnLog.deleteTurnLog(sessionId).ok, true)
355
- assert.equal(fs.existsSync(turnLog.turnLogPath(sessionId)), false)
356
- assert.equal(turnLog.deleteTurnLog(sessionId).ok, true, 'deleting a missing log is a no-op')
357
- })
358
-
359
- test('gcTurnLogs deletes only when idle past the threshold AND fully settled', () => {
360
- const now = Date.now()
361
- const old = new Date(now - 40 * 86_400_000).toISOString()
362
- const fresh = new Date(now - 1 * 86_400_000).toISOString()
363
- const writeLog = (sessionId, lastSeqEnd) => {
364
- turnLog.recordTurn(sessionId, { seq: [0, lastSeqEnd], at: 't', scene: null, user: 'a', model: 'b' })
365
- }
366
- writeLog('gc-settled', 30)
367
- writeLog('gc-unsettled', 30)
368
- writeLog('gc-recent', 30)
369
- writeLog('gc-never-settled', 30)
370
-
371
- const bindings = [
372
- { sessionId: 'gc-settled', lastTurnAt: old, lastSleepSeq: 30 },
373
- { sessionId: 'gc-unsettled', lastTurnAt: old, lastSleepSeq: 10 },
374
- { sessionId: 'gc-recent', lastTurnAt: fresh, lastSleepSeq: 30 },
375
- { sessionId: 'gc-never-settled', lastTurnAt: old },
376
- { sessionId: 'gc-no-log', lastTurnAt: old, lastSleepSeq: 30 },
377
- ]
378
- const dry = turnLog.gcTurnLogs(bindings, { now, dryRun: true })
379
- assert.deepEqual(dry.deleted, ['gc-settled'])
380
- assert.ok(fs.existsSync(turnLog.turnLogPath('gc-settled')), 'dry-run must not delete')
381
- assert.ok(dry.kept.some((k) => k.sessionId === 'gc-unsettled' && k.reason === 'unsettled-increment'))
382
- assert.ok(dry.kept.some((k) => k.sessionId === 'gc-recent' && k.reason === 'recent-activity'))
383
- assert.ok(dry.kept.some((k) => k.sessionId === 'gc-never-settled' && k.reason === 'never-settled'))
384
- assert.ok(!dry.deleted.includes('gc-no-log') && !dry.kept.some((k) => k.sessionId === 'gc-no-log'), 'a session without a log is not reported')
385
-
386
- const applied = turnLog.gcTurnLogs(bindings, { now })
387
- assert.deepEqual(applied.deleted, ['gc-settled'])
388
- assert.equal(fs.existsSync(turnLog.turnLogPath('gc-settled')), false)
389
- assert.ok(fs.existsSync(turnLog.turnLogPath('gc-unsettled')), 'the unsettled log is the increment source and stays')
390
- })
391
-
392
- // —— 订阅接线(§3.2:session/event 全局订阅,worker 会话绝不记) ————————————
393
-
394
- function fakeCtx() {
395
- const handlers = new Map()
396
- return {
397
- ctx: { on: (name, handler) => { if (!handlers.has(name)) handlers.set(name, []); handlers.get(name).push(handler); return () => { handlers.set(name, handlers.get(name).filter((h) => h !== handler)) } } },
398
- emit(name, ...args) { for (const handler of handlers.get(name) || []) handler(...args) },
399
- off(name) { handlers.delete(name) },
400
- }
401
- }
402
-
403
- function bindSession(sessionId, { origin, useLibrary, sessionGone } = {}) {
404
- state.ensureSession(sessionId, { cwd: path.join(home, 'ws', sessionId) })
405
- const patch = {}
406
- if (useLibrary !== undefined) patch.useLibrary = useLibrary
407
- if (sessionGone !== undefined) patch.sessionGone = sessionGone
408
- if (Object.keys(patch).length > 0) state.setSessionBinding(sessionId, patch)
409
- return { header: { id: sessionId, origin, cwd: path.join(home, 'ws', sessionId) } }
410
- }
411
-
412
- test('the session/event recorder writes one line per turn for admitted sessions', () => {
413
- const { ctx, emit } = fakeCtx()
414
- const dispose = registerTurnLogRecorder(ctx)
415
- const session = bindSession('rec-on')
416
- emit('session/event', session, turnStart(0, 1))
417
- emit('session/event', session, userMessage(1, '记下这一句'))
418
- emit('session/event', session, assistantMessage(2, '好的。'))
419
- emit('session/event', session, turnEnd(3, { turn: 1 }))
420
-
421
- const { records } = turnLog.readIncrement('rec-on', -1)
422
- assert.equal(records.length, 1)
423
- assert.equal(records[0].user, '记下这一句')
424
- assert.equal(records[0].model, '好的。')
425
- dispose()
426
- })
427
-
428
- test('worker (subagent) sessions, unbound sessions and the off switch never record', () => {
429
- const { ctx, emit } = fakeCtx()
430
- const dispose = registerTurnLogRecorder(ctx)
431
- const subagent = bindSession('rec-subagent', { origin: 'subagent' })
432
- state.ensureSession('rec-subagent', { cwd: path.join(home, 'ws', 'rec-subagent') })
433
- emit('session/event', subagent, turnStart(0))
434
- emit('session/event', subagent, userMessage(1, 'worker 的回合'))
435
- emit('session/event', subagent, turnEnd(2))
436
- assert.equal(fs.existsSync(turnLog.turnLogPath('rec-subagent')), false, 'worker sessions are never recorded')
437
-
438
- const unbound = { header: { id: 'rec-unbound', origin: undefined } }
439
- emit('session/event', unbound, turnStart(0))
440
- emit('session/event', unbound, userMessage(1, '没有绑定'))
441
- emit('session/event', unbound, turnEnd(2))
442
- assert.equal(fs.existsSync(turnLog.turnLogPath('rec-unbound')), false)
443
-
444
- const offSession = bindSession('rec-off', { useLibrary: false })
445
- emit('session/event', offSession, turnStart(0))
446
- emit('session/event', offSession, userMessage(1, '库关了'))
447
- emit('session/event', offSession, turnEnd(2))
448
- assert.equal(fs.existsSync(turnLog.turnLogPath('rec-off')), false, 'useLibrary === false sessions are skipped')
449
-
450
- state.updateSettings({ consolidationTurnLog: 'off' })
451
- const switchOff = bindSession('rec-switch-off')
452
- emit('session/event', switchOff, turnStart(0))
453
- emit('session/event', switchOff, userMessage(1, '开关关了'))
454
- emit('session/event', switchOff, turnEnd(2))
455
- assert.equal(fs.existsSync(turnLog.turnLogPath('rec-switch-off')), false, 'the off switch stops the recorder')
456
- state.updateSettings({ consolidationTurnLog: 'on' })
457
- dispose()
458
- })
459
-
460
- test('a deleted session (sessionGone) loses its log on session/disposed', () => {
461
- const { ctx, emit } = fakeCtx()
462
- const dispose = registerTurnLogRecorder(ctx)
463
- const session = bindSession('rec-gone', { sessionGone: true })
464
- turnLog.recordTurn('rec-gone', { seq: [0, 5], at: 't', scene: null, user: 'a', model: 'b' })
465
- assert.ok(fs.existsSync(turnLog.turnLogPath('rec-gone')))
466
- emit('session/disposed', session)
467
- assert.equal(fs.existsSync(turnLog.turnLogPath('rec-gone')), false, 'sessionGone bindings get their log deleted')
468
- // 未标 sessionGone 的销毁(进程内卸载)不删:日志比会话活得长。
469
- const alive = bindSession('rec-alive')
470
- turnLog.recordTurn('rec-alive', { seq: [0, 5], at: 't', scene: null, user: 'a', model: 'b' })
471
- emit('session/disposed', alive)
472
- assert.ok(fs.existsSync(turnLog.turnLogPath('rec-alive')))
473
- dispose()
474
- })
475
-
476
- test('coding tool lines keep 600 chars of arguments and error text instead of 160', () => {
477
- const args = '{"cmd":"npm test -- --grep memory","pad":"' + 'a'.repeat(400) + '"}'
478
- const tools = [['c1', 'bash', args, 'E'.repeat(800), true]]
479
- const plain = turnLog.buildTurnRecords(oneTurn({ user: '跑测试', tools }), { tools: 'summary' })[0].tools[0]
480
- const coding = turnLog.buildTurnRecords(oneTurn({ user: '跑测试', tools }), { tools: 'summary', ...turnLog.turnLogLimits('coding') })[0].tools[0]
481
- assert.ok(plain.length <= turnLog.TURNLOG_TOOL_LINE_CHARS + 1)
482
- assert.ok(coding.length > turnLog.TURNLOG_TOOL_LINE_CHARS, 'the coding cap is wider than the default')
483
- assert.ok(coding.length <= turnLog.TURNLOG_TOOL_LINE_CHARS_CODING + 1)
484
- assert.ok(coding.includes('npm test'), 'the command survives in coding mode')
485
- assert.ok(coding.includes('E'.repeat(20)), 'the error output tail survives in coding mode')
486
- assert.equal(turnLog.turnLogLimits('rp').toolLineChars, turnLog.TURNLOG_TOOL_LINE_CHARS)
487
- })
1
+ import test from 'node:test'
2
+ import assert from 'node:assert/strict'
3
+ import fs from 'node:fs'
4
+ import os from 'node:os'
5
+ import path from 'node:path'
6
+
7
+ const home = fs.mkdtempSync(path.join(os.tmpdir(), 'dsh-memu-turn-log-'))
8
+ process.env.DSH_MEMU_HOME = home
9
+ process.env.DSH_MEMU_MEMORY_HOME = home
10
+
11
+ const state = await import('../lib/state.js')
12
+ const turnLog = await import('../lib/turn-log.js')
13
+ const rpc = await import('../lib/rpc.js')
14
+ const { registerTurnLogRecorder } = await import('../lib/index.js')
15
+
16
+ test.after(() => {
17
+ state.flushState()
18
+ try { fs.rmSync(home, { recursive: true, force: true }) } catch {}
19
+ })
20
+
21
+ // —— 宿主事件 fixture(形状与 consolidation-snapshot/private 的口径一致) ——————
22
+
23
+ let clock = 0
24
+ function userMessage(seq, text, { sceneTime, kind = 'user' } = {}) {
25
+ clock += 1000
26
+ return { type: 'user/message', seq, time: clock, data: { id: `u${seq}`, source: { kind }, content: [{ type: 'text', text }], ...(sceneTime ? { sceneTime } : {}) } }
27
+ }
28
+ function assistantMessage(seq, text, blocks = []) {
29
+ clock += 1000
30
+ return { type: 'assistant/message', seq, time: clock, data: { message: { content: [{ type: 'text', text }, ...blocks] } } }
31
+ }
32
+ function toolCallEvent(seq, callId, name, args) {
33
+ return { type: 'tool/call', seq, time: clock, data: { callId, name, arguments: args } }
34
+ }
35
+ function toolResultEvent(seq, callId, text, { isError = false } = {}) {
36
+ return { type: 'tool/result', seq, time: clock, data: { message: { callId, content: [{ type: 'text', text }], isError } } }
37
+ }
38
+ function turnStart(seq, turn = 1) {
39
+ return { type: 'turn/start', seq, time: clock, data: { turn } }
40
+ }
41
+ function turnEnd(seq, { kind = 'completed', turn = 1, time } = {}) {
42
+ return { type: 'turn/end', seq, ...(time !== undefined ? { time } : { time: (clock += 1000) }), data: { turn, reason: { kind } } }
43
+ }
44
+
45
+ function oneTurn({ user, assistant, scene, kind = 'completed', startSeq = 10, tools = [] } = {}) {
46
+ const events = [turnStart(startSeq)]
47
+ let seq = startSeq + 1
48
+ if (user !== undefined) events.push(userMessage(seq++, user, { sceneTime: scene }))
49
+ for (const [callId, name, args, result, isError] of tools) {
50
+ events.push(assistantMessage(seq++, '', [{ type: 'tool-call', id: callId, name, arguments: args }]))
51
+ events.push(toolCallEvent(seq++, callId, name, args))
52
+ if (result !== undefined) events.push(toolResultEvent(seq++, callId, result, { isError }))
53
+ }
54
+ if (assistant !== undefined) events.push(assistantMessage(seq++, assistant))
55
+ events.push(turnEnd(seq, { kind }))
56
+ return events
57
+ }
58
+
59
+ // —— 记录规则(§3.1) ———————————————————————————————————————
60
+
61
+ test('one closed turn is one record: seq interval, scene, and the filtering rules', () => {
62
+ const events = [
63
+ turnStart(10),
64
+ userMessage(11, '帮我看看明天要不要带伞', { sceneTime: '第三日夜' }),
65
+ userMessage(12, '(插件注入的提示)', { kind: 'plugin:dsh-memu-memory' }),
66
+ toolCallEvent(13, 'c1', 'weather', '{"city":"杭州"}'),
67
+ assistantMessage(14, '明天有雨,建议带伞。'),
68
+ toolResultEvent(15, 'c1', 'rain'),
69
+ userMessage(16, '谢谢', { sceneTime: '第四日晨' }),
70
+ turnEnd(17),
71
+ ]
72
+ const records = turnLog.buildTurnRecords(events)
73
+ assert.equal(records.length, 1)
74
+ assert.deepEqual(records[0].seq, [10, 17])
75
+ // scene 取回合内最后一个带 sceneTime 的 user 事件值;插件注入不进 user 文本。
76
+ assert.equal(records[0].scene, '第四日晨')
77
+ assert.equal(records[0].user, '帮我看看明天要不要带伞\n谢谢')
78
+ assert.equal(records[0].model, '明天有雨,建议带伞。')
79
+ assert.equal(records[0].interrupted, undefined)
80
+ assert.ok(records[0].at, 'the turn/end timestamp lands on the record')
81
+ })
82
+
83
+ test('an open tail turn and a heartbeat-only turn produce no record', () => {
84
+ const openTail = oneTurn({ user: '未闭合的回合' })
85
+ openTail.pop() // 拿掉 turn/end:半回合不产出记录
86
+ assert.deepEqual(turnLog.buildTurnRecords(openTail), [])
87
+
88
+ // 心跳/调度回合:没有真人消息也没有工具 → 不落行。
89
+ const heartbeat = [turnStart(50), userMessage(51, 'heartbeat', { kind: 'plugin:heartbeat' }), turnEnd(52)]
90
+ assert.deepEqual(turnLog.buildTurnRecords(heartbeat), [])
91
+ })
92
+
93
+ test('an aborted turn is marked interrupted', () => {
94
+ const records = turnLog.buildTurnRecords(oneTurn({ user: '说到一半被打断', kind: 'aborted' }))
95
+ assert.equal(records.length, 1)
96
+ assert.equal(records[0].interrupted, true)
97
+ assert.equal(records[0].seq[0], 10)
98
+ })
99
+
100
+ test('redactSecrets is applied to user, model and tool text at record time', () => {
101
+ const secret = 'sk-abcdefghijklmnopqrstuvwxyz123456'
102
+ const events = [
103
+ turnStart(10),
104
+ userMessage(11, `我的 key 是 ${secret} 别外传`),
105
+ toolCallEvent(12, 'c1', 'deploy', '{}'),
106
+ toolResultEvent(13, 'c1', `failed with ${secret}`, { isError: true }),
107
+ assistantMessage(14, `收到,key ${secret} 已记下`),
108
+ turnEnd(15),
109
+ ]
110
+ const records = turnLog.buildTurnRecords(events, { tools: 'errors' })
111
+ assert.equal(records.length, 1)
112
+ const flat = JSON.stringify(records[0])
113
+ assert.ok(!flat.includes(secret), 'the raw secret must never reach the log')
114
+ assert.ok(flat.includes('[REDACTED_KEY]'))
115
+ })
116
+
117
+ // —— 工具行三档(§3.1) ——————————————————————————————————————
118
+
119
+ const TOOL_FIXTURE = [
120
+ ['c1', 'edit_memory', '{"id":"m1"}', '修改成功', false],
121
+ ['c2', 'readSession', '{"path":"a.ts"}', 'not found', true],
122
+ ]
123
+
124
+ test('tools mode none (the default) records pure dialogue without a tools field', () => {
125
+ const events = oneTurn({ user: '改一下记忆', tools: TOOL_FIXTURE })
126
+ const record = turnLog.buildTurnRecords(events)[0]
127
+ assert.equal(record.tools, undefined)
128
+ // 默认值走设置而不是参数:默认档就是 none。
129
+ assert.equal(turnLog.buildTurnRecords(events)[0].tools, undefined)
130
+ })
131
+
132
+ test('tools mode errors keeps only the isError result line', () => {
133
+ const record = turnLog.buildTurnRecords(oneTurn({ user: '查一下', tools: TOOL_FIXTURE }), { tools: 'errors' })[0]
134
+ assert.equal(record.tools.length, 1)
135
+ assert.match(record.tools[0], /readSession → 失败: not found/)
136
+ assert.ok(!record.tools.some((line) => line.includes('edit_memory')), 'the successful call is not in errors mode')
137
+ })
138
+
139
+ test('tools mode summary pairs calls with results and flags calls without one', () => {
140
+ const tools = [...TOOL_FIXTURE, ['c3', 'interruptedTool', '{"x":1}']] // 没有结果:被打断的调用
141
+ const record = turnLog.buildTurnRecords(oneTurn({ user: '干活', tools }), { tools: 'summary' })[0]
142
+ assert.equal(record.tools.length, 3)
143
+ assert.match(record.tools[0], /edit_memory\(\{"id":"m1"\}\) → 成功/)
144
+ assert.match(record.tools[1], /readSession\(\{"path":"a.ts"\}\) → 失败: not found/)
145
+ assert.match(record.tools[2], /interruptedTool\(\{"x":1\}\) → 无结果/)
146
+ })
147
+
148
+ test('the assistant tool-call block is not double-counted next to its tool/call event', () => {
149
+ const events = [
150
+ turnStart(10),
151
+ userMessage(11, '只算一次'),
152
+ assistantMessage(12, '', [{ type: 'tool-call', id: 'c9', name: 'dupTool', arguments: '{}' }]),
153
+ toolCallEvent(13, 'c9', 'dupTool', '{}'),
154
+ toolResultEvent(14, 'c9', 'ok'),
155
+ turnEnd(15),
156
+ ]
157
+ const record = turnLog.buildTurnRecords(events, { tools: 'summary' })[0]
158
+ assert.equal(record.tools.length, 1)
159
+ assert.match(record.tools[0], /dupTool\(\{\}\) → 成功/)
160
+ })
161
+
162
+ // —— 三层 caps(§3.1) ———————————————————————————————————————
163
+
164
+ test('user and model text are each capped at 2000 chars and always kept in full within that', () => {
165
+ const longUser = 'u'.repeat(3000)
166
+ const longModel = 'm'.repeat(3000)
167
+ const record = turnLog.buildTurnRecords(oneTurn({ user: longUser, assistant: longModel }))[0]
168
+ assert.ok(record.user.length <= turnLog.TURNLOG_USER_MODEL_CHARS + 1)
169
+ assert.ok(record.user.startsWith('u'.repeat(50)))
170
+ assert.ok(record.model.length <= turnLog.TURNLOG_USER_MODEL_CHARS + 1)
171
+ })
172
+
173
+ test('each tool line is capped at 160 chars', () => {
174
+ const tools = [['c1', 'tool', '{}', 'e'.repeat(500), true]]
175
+ const record = turnLog.buildTurnRecords(oneTurn({ user: 'hi', tools }), { tools: 'errors' })[0]
176
+ assert.ok(record.tools[0].length <= turnLog.TURNLOG_TOOL_LINE_CHARS + 1)
177
+ })
178
+
179
+ test('the 4000-char record cap cuts tool lines from the tail, never user/model', () => {
180
+ const pad = 'p'.repeat(130)
181
+ const tools = Array.from({ length: 30 }, (_, i) => [`c${i}`, `tool${i}`, `{"n":${i},"pad":"${pad}"}`, `r${String(i).repeat(140)}`, false])
182
+ const record = turnLog.buildTurnRecords(oneTurn({ user: '短问题', assistant: '短回答', tools }), { tools: 'summary' })[0]
183
+ assert.ok(JSON.stringify(record).length <= turnLog.TURNLOG_RECORD_CHARS, 'the serialized record fits the total cap')
184
+ assert.equal(record.user, '短问题')
185
+ assert.equal(record.model, '短回答')
186
+ const marker = record.tools[record.tools.length - 1]
187
+ assert.match(marker, /…\[另有 \d+ 条工具调用已省略\]/)
188
+ // 保留行按原始顺序装,来自头部;行格式与未超预算时一致(args 同样 120 字截断)。
189
+ const kept = record.tools.slice(0, -1)
190
+ const expectedLine = ([, name, args]) => `${name}(${args.length > 120 ? `${args.slice(0, 120)}…` : args}) → 成功`
191
+ assert.deepEqual(kept, tools.slice(0, kept.length).map(expectedLine))
192
+ })
193
+
194
+ // —— 设置面(§10.1 / 构件 4) ———————————————————————————————————
195
+
196
+ test('the two new settings survive the setSettings allowlist and reset to their defaults', async () => {
197
+ await rpc.dispatch({}, 'setSettings', { patch: { consolidationTurnLog: 'off', consolidationTurnLogTools: 'summary' } })
198
+ assert.equal(state.getSettings().consolidationTurnLog, 'off')
199
+ assert.equal(state.getSettings().consolidationTurnLogTools, 'summary')
200
+ // 设置档驱动默认 tools 档(无参数调用读设置)。
201
+ const record = turnLog.buildTurnRecords(oneTurn({ user: '看档位', tools: TOOL_FIXTURE }))[0]
202
+ assert.equal(record.tools.length, 2, 'the settings-chosen summary mode is now the default')
203
+ await assert.rejects(
204
+ rpc.dispatch({}, 'setSettings', { patch: { consolidationTurnLogTools: 'all' } }),
205
+ /invalid setting consolidationTurnLogTools/,
206
+ )
207
+ const reset = await rpc.dispatch({}, 'resetSettings', {})
208
+ assert.equal(reset.consolidationTurnLog, 'on')
209
+ assert.equal(reset.consolidationTurnLogTools, 'none')
210
+ })
211
+
212
+ // —— 落盘、增量读取与对账(§3.3) ————————————————————————————————
213
+
214
+ test('recordTurn appends one JSON line per turn and readIncrement returns whole turns only', () => {
215
+ const sessionId = 'incr-turns'
216
+ turnLog.recordTurn(sessionId, { seq: [0, 10], at: '2026-11-13T21:00:00.000Z', scene: null, user: '一', model: '甲' })
217
+ turnLog.recordTurn(sessionId, { seq: [11, 20], at: '2026-11-13T21:01:00.000Z', scene: null, user: '二', model: '乙' })
218
+ turnLog.recordTurn(sessionId, { seq: [21, 30], at: '2026-11-13T21:02:00.000Z', scene: null, user: '三', model: '丙' })
219
+
220
+ // afterSeq 落在回合中间(15):按 seqStart > afterSeq 过滤,[11,20] 整回合让位——
221
+ // 返回的永远只有完整回合,绝无半回合。
222
+ assert.deepEqual(turnLog.readIncrement(sessionId, 15).records.map((r) => r.seq), [[21, 30]])
223
+ assert.deepEqual(turnLog.readIncrement(sessionId, 10).records.map((r) => r.seq), [[11, 20], [21, 30]])
224
+ assert.deepEqual(turnLog.readIncrement(sessionId, 30).records, [])
225
+ assert.equal(turnLog.readIncrement(sessionId, -1).records.length, 3)
226
+ assert.equal(turnLog.readIncrement(sessionId, undefined).records.length, 3, 'a missing cursor reads the whole log')
227
+ })
228
+
229
+ test('recordTurn fills a missing timestamp and refuses records without a seq range', () => {
230
+ const sessionId = 'at-fill'
231
+ turnLog.recordTurn(sessionId, { seq: [0, 5], scene: null, user: 'a', model: 'b' })
232
+ const line = fs.readFileSync(turnLog.turnLogPath(sessionId), 'utf8').trim().split('\n')[0]
233
+ assert.ok(JSON.parse(line).at, 'recordTurn stamps the record when the turn/end had no time')
234
+ assert.equal(turnLog.recordTurn(sessionId, { user: 'no seq' }), null, 'unanchorable records are rejected with a warn')
235
+ })
236
+
237
+ test('verifyGap finds holes between and around records', () => {
238
+ const sessionId = 'gap-check'
239
+ turnLog.recordTurn(sessionId, { seq: [0, 10], at: 't', scene: null, user: 'a', model: 'b' })
240
+ turnLog.recordTurn(sessionId, { seq: [21, 30], at: 't', scene: null, user: 'c', model: 'd' })
241
+ const hole = turnLog.verifyGap(sessionId, 0, 30)
242
+ assert.equal(hole.ok, false)
243
+ assert.deepEqual(hole.missingRanges, [[11, 20]])
244
+ assert.equal(turnLog.verifyGap(sessionId, 0, 10).ok, true)
245
+ const empty = turnLog.verifyGap('gap-never-written', 5, 50)
246
+ assert.deepEqual(empty.missingRanges, [[5, 50]])
247
+ })
248
+
249
+ test('rebuildRange fills exactly the missing range from host events and is idempotent', () => {
250
+ const sessionId = 'rebuild'
251
+ const events = [
252
+ ...oneTurn({ user: '第一回合', startSeq: 0 }),
253
+ ...oneTurn({ user: '第二回合', startSeq: 40 }),
254
+ ...oneTurn({ user: '第三回合', startSeq: 80 }),
255
+ ]
256
+ // 只记了第一回合,中间与尾部都是洞。
257
+ turnLog.recordTurn(sessionId, { seq: [0, 17], at: 't', scene: null, user: '第一回合', model: '' })
258
+
259
+ const first = turnLog.rebuildRange(sessionId, 18, 120, events)
260
+ assert.equal(first.ok, true)
261
+ assert.equal(first.rebuilt, 2)
262
+ const { records } = turnLog.readIncrement(sessionId, 17)
263
+ assert.deepEqual(records.map((r) => r.seq[0]), [40, 80])
264
+
265
+ // 再跑一遍不产生重复行:重建幂等。
266
+ const second = turnLog.rebuildRange(sessionId, 0, 120, events)
267
+ assert.equal(second.rebuilt, 0)
268
+ assert.equal(turnLog.readIncrement(sessionId, -1).records.length, 3)
269
+ // 请求区间之外的事件不进日志。
270
+ const outside = turnLog.rebuildRange(sessionId, 1000, 2000, events)
271
+ assert.equal(outside.rebuilt, 0)
272
+ })
273
+
274
+ test('readers tolerate bad lines: skipped, counted, never thrown', () => {
275
+ const sessionId = 'bad-lines'
276
+ turnLog.recordTurn(sessionId, { seq: [0, 10], at: 't', scene: null, user: 'a', model: 'b' })
277
+ fs.appendFileSync(turnLog.turnLogPath(sessionId), '{this is not json\n', 'utf8')
278
+ turnLog.recordTurn(sessionId, { seq: [11, 20], at: 't', scene: null, user: 'c', model: 'd' })
279
+
280
+ const inc = turnLog.readIncrement(sessionId, -1)
281
+ assert.equal(inc.records.length, 2)
282
+ assert.equal(inc.badLines, 1)
283
+ assert.equal(turnLog.verifyGap(sessionId, 0, 20).badLines, 1)
284
+ assert.equal(turnLog.tailSlice(sessionId, 10_000).records.length, 2)
285
+ })
286
+
287
+ // —— 头部裁剪(§3.4:绝不裁进未结算区间) ————————————————————————————
288
+
289
+ function writeBulkyTurns(sessionId, count) {
290
+ for (let i = 0; i < count; i++) {
291
+ turnLog.recordTurn(sessionId, { seq: [i * 10, i * 10 + 9], at: 't', scene: null, user: `回合${i}`.padEnd(40, '字'), model: '' })
292
+ }
293
+ }
294
+
295
+ test('pruneHead drops settled head records down to the budget, never past lastSleepSeq', () => {
296
+ const sessionId = 'prune-head'
297
+ writeBulkyTurns(sessionId, 6)
298
+ // lastSleepSeq = 49:前 5 条已结算,最后一条(seqEnd 59)未结算。
299
+ const report = turnLog.pruneHead(sessionId, 300, 49)
300
+ assert.ok(report.pruned > 0, 'settled head records were cut')
301
+ assert.ok(report.charsAfter <= 300)
302
+ const after = turnLog.readIncrement(sessionId, -1).records
303
+ assert.deepEqual(after.map((r) => r.seq[0]), [30, 40, 50], 'the cut stops inside settled range only; the unsettled turn survives')
304
+ })
305
+
306
+ test('pruneHead lets the file stay over budget rather than cut into the unsettled range', () => {
307
+ const sessionId = 'prune-head-over'
308
+ writeBulkyTurns(sessionId, 6)
309
+ // lastSleepSeq = 19:只有前两条可裁,预算再小也不越过 seqEnd 19。
310
+ const report = turnLog.pruneHead(sessionId, 100, 19)
311
+ assert.ok(report.pruned > 0)
312
+ assert.ok(report.charsAfter > 100, 'the file may stay over budget instead of pruning unsettled turns')
313
+ const after = turnLog.readIncrement(sessionId, -1).records
314
+ assert.ok(after.every((r) => r.seq[0] >= 20), 'every settled head record was taken; the unsettled tail is intact')
315
+
316
+ // 没有结算游标:整份日志都是未结算段,一条不裁。
317
+ const sessionId2 = 'prune-head-unsettled'
318
+ writeBulkyTurns(sessionId2, 3)
319
+ const untouched = turnLog.pruneHead(sessionId2, 50, null)
320
+ assert.equal(untouched.pruned, 0)
321
+ assert.equal(turnLog.readIncrement(sessionId2, -1).records.length, 3)
322
+ })
323
+
324
+ test('pruneHead preserves bad lines instead of dropping what it could not read', () => {
325
+ const sessionId = 'prune-bad'
326
+ turnLog.recordTurn(sessionId, { seq: [0, 9], at: 't', scene: null, user: 'a'.repeat(60), model: '' })
327
+ fs.appendFileSync(turnLog.turnLogPath(sessionId), 'garbage line\n', 'utf8')
328
+ turnLog.recordTurn(sessionId, { seq: [10, 19], at: 't', scene: null, user: 'b'.repeat(60), model: '' })
329
+ turnLog.pruneHead(sessionId, 80, 100)
330
+ const raw = fs.readFileSync(turnLog.turnLogPath(sessionId), 'utf8')
331
+ assert.ok(raw.includes('garbage line'), 'a bad line cannot be proven settled, so it is kept')
332
+ })
333
+
334
+ // —— tailSlice(§5.1 交接尾部的来源) ——————————————————————————————
335
+
336
+ test('tailSlice takes whole turns from the tail within the char budget', () => {
337
+ const sessionId = 'tail'
338
+ turnLog.recordTurn(sessionId, { seq: [0, 9], at: 't', scene: null, user: 'a'.repeat(100), model: '' })
339
+ turnLog.recordTurn(sessionId, { seq: [10, 19], at: 't', scene: null, user: 'b'.repeat(100), model: '' })
340
+ turnLog.recordTurn(sessionId, { seq: [20, 29], at: 't', scene: null, user: 'c'.repeat(100), model: '' })
341
+ const slice = turnLog.tailSlice(sessionId, 400)
342
+ assert.deepEqual(slice.records.map((r) => r.seq[0]), [10, 20], 'whole turns from the tail, chronological')
343
+ assert.ok(slice.chars <= 400)
344
+ assert.ok(!slice.text.includes('aaaa'), 'the oldest turn did not fit the budget and was left out')
345
+ assert.equal(slice.text.split('\n').length, 2, 'the text is whole-turn JSONL from the tail')
346
+ })
347
+
348
+ // —— 删除与休眠 GC(§3.4) ——————————————————————————————————————
349
+
350
+ test('deleteTurnLog removes the file and tolerates a missing one', () => {
351
+ const sessionId = 'delete-me'
352
+ turnLog.recordTurn(sessionId, { seq: [0, 1], at: 't', scene: null, user: 'a', model: 'b' })
353
+ assert.ok(fs.existsSync(turnLog.turnLogPath(sessionId)))
354
+ assert.equal(turnLog.deleteTurnLog(sessionId).ok, true)
355
+ assert.equal(fs.existsSync(turnLog.turnLogPath(sessionId)), false)
356
+ assert.equal(turnLog.deleteTurnLog(sessionId).ok, true, 'deleting a missing log is a no-op')
357
+ })
358
+
359
+ test('gcTurnLogs deletes only when idle past the threshold AND fully settled', () => {
360
+ const now = Date.now()
361
+ const old = new Date(now - 40 * 86_400_000).toISOString()
362
+ const fresh = new Date(now - 1 * 86_400_000).toISOString()
363
+ const writeLog = (sessionId, lastSeqEnd) => {
364
+ turnLog.recordTurn(sessionId, { seq: [0, lastSeqEnd], at: 't', scene: null, user: 'a', model: 'b' })
365
+ }
366
+ writeLog('gc-settled', 30)
367
+ writeLog('gc-unsettled', 30)
368
+ writeLog('gc-recent', 30)
369
+ writeLog('gc-never-settled', 30)
370
+
371
+ const bindings = [
372
+ { sessionId: 'gc-settled', lastTurnAt: old, lastSleepSeq: 30 },
373
+ { sessionId: 'gc-unsettled', lastTurnAt: old, lastSleepSeq: 10 },
374
+ { sessionId: 'gc-recent', lastTurnAt: fresh, lastSleepSeq: 30 },
375
+ { sessionId: 'gc-never-settled', lastTurnAt: old },
376
+ { sessionId: 'gc-no-log', lastTurnAt: old, lastSleepSeq: 30 },
377
+ ]
378
+ const dry = turnLog.gcTurnLogs(bindings, { now, dryRun: true })
379
+ assert.deepEqual(dry.deleted, ['gc-settled'])
380
+ assert.ok(fs.existsSync(turnLog.turnLogPath('gc-settled')), 'dry-run must not delete')
381
+ assert.ok(dry.kept.some((k) => k.sessionId === 'gc-unsettled' && k.reason === 'unsettled-increment'))
382
+ assert.ok(dry.kept.some((k) => k.sessionId === 'gc-recent' && k.reason === 'recent-activity'))
383
+ assert.ok(dry.kept.some((k) => k.sessionId === 'gc-never-settled' && k.reason === 'never-settled'))
384
+ assert.ok(!dry.deleted.includes('gc-no-log') && !dry.kept.some((k) => k.sessionId === 'gc-no-log'), 'a session without a log is not reported')
385
+
386
+ const applied = turnLog.gcTurnLogs(bindings, { now })
387
+ assert.deepEqual(applied.deleted, ['gc-settled'])
388
+ assert.equal(fs.existsSync(turnLog.turnLogPath('gc-settled')), false)
389
+ assert.ok(fs.existsSync(turnLog.turnLogPath('gc-unsettled')), 'the unsettled log is the increment source and stays')
390
+ })
391
+
392
+ // —— 订阅接线(§3.2:session/event 全局订阅,worker 会话绝不记) ————————————
393
+
394
+ function fakeCtx() {
395
+ const handlers = new Map()
396
+ return {
397
+ ctx: { on: (name, handler) => { if (!handlers.has(name)) handlers.set(name, []); handlers.get(name).push(handler); return () => { handlers.set(name, handlers.get(name).filter((h) => h !== handler)) } } },
398
+ emit(name, ...args) { for (const handler of handlers.get(name) || []) handler(...args) },
399
+ off(name) { handlers.delete(name) },
400
+ }
401
+ }
402
+
403
+ function bindSession(sessionId, { origin, useLibrary, sessionGone } = {}) {
404
+ state.ensureSession(sessionId, { cwd: path.join(home, 'ws', sessionId) })
405
+ const patch = {}
406
+ if (useLibrary !== undefined) patch.useLibrary = useLibrary
407
+ if (sessionGone !== undefined) patch.sessionGone = sessionGone
408
+ if (Object.keys(patch).length > 0) state.setSessionBinding(sessionId, patch)
409
+ return { header: { id: sessionId, origin, cwd: path.join(home, 'ws', sessionId) } }
410
+ }
411
+
412
+ test('the session/event recorder writes one line per turn for admitted sessions', () => {
413
+ const { ctx, emit } = fakeCtx()
414
+ const dispose = registerTurnLogRecorder(ctx)
415
+ const session = bindSession('rec-on')
416
+ emit('session/event', session, turnStart(0, 1))
417
+ emit('session/event', session, userMessage(1, '记下这一句'))
418
+ emit('session/event', session, assistantMessage(2, '好的。'))
419
+ emit('session/event', session, turnEnd(3, { turn: 1 }))
420
+
421
+ const { records } = turnLog.readIncrement('rec-on', -1)
422
+ assert.equal(records.length, 1)
423
+ assert.equal(records[0].user, '记下这一句')
424
+ assert.equal(records[0].model, '好的。')
425
+ dispose()
426
+ })
427
+
428
+ test('worker (subagent) sessions, unbound sessions and the off switch never record', () => {
429
+ const { ctx, emit } = fakeCtx()
430
+ const dispose = registerTurnLogRecorder(ctx)
431
+ const subagent = bindSession('rec-subagent', { origin: 'subagent' })
432
+ state.ensureSession('rec-subagent', { cwd: path.join(home, 'ws', 'rec-subagent') })
433
+ emit('session/event', subagent, turnStart(0))
434
+ emit('session/event', subagent, userMessage(1, 'worker 的回合'))
435
+ emit('session/event', subagent, turnEnd(2))
436
+ assert.equal(fs.existsSync(turnLog.turnLogPath('rec-subagent')), false, 'worker sessions are never recorded')
437
+
438
+ const unbound = { header: { id: 'rec-unbound', origin: undefined } }
439
+ emit('session/event', unbound, turnStart(0))
440
+ emit('session/event', unbound, userMessage(1, '没有绑定'))
441
+ emit('session/event', unbound, turnEnd(2))
442
+ assert.equal(fs.existsSync(turnLog.turnLogPath('rec-unbound')), false)
443
+
444
+ const offSession = bindSession('rec-off', { useLibrary: false })
445
+ emit('session/event', offSession, turnStart(0))
446
+ emit('session/event', offSession, userMessage(1, '库关了'))
447
+ emit('session/event', offSession, turnEnd(2))
448
+ assert.equal(fs.existsSync(turnLog.turnLogPath('rec-off')), false, 'useLibrary === false sessions are skipped')
449
+
450
+ state.updateSettings({ consolidationTurnLog: 'off' })
451
+ const switchOff = bindSession('rec-switch-off')
452
+ emit('session/event', switchOff, turnStart(0))
453
+ emit('session/event', switchOff, userMessage(1, '开关关了'))
454
+ emit('session/event', switchOff, turnEnd(2))
455
+ assert.equal(fs.existsSync(turnLog.turnLogPath('rec-switch-off')), false, 'the off switch stops the recorder')
456
+ state.updateSettings({ consolidationTurnLog: 'on' })
457
+ dispose()
458
+ })
459
+
460
+ test('a deleted session (sessionGone) loses its log on session/disposed', () => {
461
+ const { ctx, emit } = fakeCtx()
462
+ const dispose = registerTurnLogRecorder(ctx)
463
+ const session = bindSession('rec-gone', { sessionGone: true })
464
+ turnLog.recordTurn('rec-gone', { seq: [0, 5], at: 't', scene: null, user: 'a', model: 'b' })
465
+ assert.ok(fs.existsSync(turnLog.turnLogPath('rec-gone')))
466
+ emit('session/disposed', session)
467
+ assert.equal(fs.existsSync(turnLog.turnLogPath('rec-gone')), false, 'sessionGone bindings get their log deleted')
468
+ // 未标 sessionGone 的销毁(进程内卸载)不删:日志比会话活得长。
469
+ const alive = bindSession('rec-alive')
470
+ turnLog.recordTurn('rec-alive', { seq: [0, 5], at: 't', scene: null, user: 'a', model: 'b' })
471
+ emit('session/disposed', alive)
472
+ assert.ok(fs.existsSync(turnLog.turnLogPath('rec-alive')))
473
+ dispose()
474
+ })
475
+
476
+ test('coding tool lines keep 600 chars of arguments and error text instead of 160', () => {
477
+ const args = '{"cmd":"npm test -- --grep memory","pad":"' + 'a'.repeat(400) + '"}'
478
+ const tools = [['c1', 'bash', args, 'E'.repeat(800), true]]
479
+ const plain = turnLog.buildTurnRecords(oneTurn({ user: '跑测试', tools }), { tools: 'summary' })[0].tools[0]
480
+ const coding = turnLog.buildTurnRecords(oneTurn({ user: '跑测试', tools }), { tools: 'summary', ...turnLog.turnLogLimits('coding') })[0].tools[0]
481
+ assert.ok(plain.length <= turnLog.TURNLOG_TOOL_LINE_CHARS + 1)
482
+ assert.ok(coding.length > turnLog.TURNLOG_TOOL_LINE_CHARS, 'the coding cap is wider than the default')
483
+ assert.ok(coding.length <= turnLog.TURNLOG_TOOL_LINE_CHARS_CODING + 1)
484
+ assert.ok(coding.includes('npm test'), 'the command survives in coding mode')
485
+ assert.ok(coding.includes('E'.repeat(20)), 'the error output tail survives in coding mode')
486
+ assert.equal(turnLog.turnLogLimits('rp').toolLineChars, turnLog.TURNLOG_TOOL_LINE_CHARS)
487
+ })