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,1539 +1,1586 @@
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
- import { spawn } from 'node:child_process'
7
-
8
- const home = fs.mkdtempSync(path.join(os.tmpdir(), 'dsh-memu-memory-fork-'))
9
- process.env.DSH_HOME = home
10
- process.env.DSH_MEMU_HOME = home
11
- process.env.DSH_MEMU_MEMORY_HOME = home
12
-
13
- const state = await import('../lib/state.js')
14
- const activity = await import('../lib/activity-log.js')
15
- const ledger = await import('../lib/consolidation-ledger.js')
16
- const forkModel = await import('../lib/fork-model.js')
17
- const { dataDir, setWarnSink } = await import('../lib/paths.js')
18
- const { retireWorker } = await import('../lib/worker-pool.js')
19
- const { CORE_WRITE_TOOLS, WORKER_TOOL_ALLOW } = await import('../lib/consolidation-worker.js')
20
- const { requestPrivateConsolidation, isConsolidating, consolidationWaitBudget, CONSOLIDATION_WAIT_POLICY, CONSOLIDATION_WINDOW_EVENTS, isEffortRefused, markEffortRefused, effortRefusalOf, compactSeedEvents, selectConsolidationWindow, selectTailTurnWindow, mustCoverCandidates, mergeMustCover, candidateCovered, seedLimitsFor } = await import('../lib/private.js')
21
- // 这些用例验证“路由继承”,不是推理强度;默认 medium 由 config 测试单独覆盖。
22
- state.updateSettings({ consolidationReasoningEffort: 'inherit' })
23
-
24
- test.after(() => {
25
- forkModel.disposeConsolidationRoute()
26
- try { fs.rmSync(home, { recursive: true, force: true }) } catch {}
27
- })
28
-
29
- // The manual path (the sidebar button, RPC generatePrivate) shares one entry point
30
- // with the idle sweep. Both now fork; neither may queue anything on the live agent,
31
- // because a queued followup is what the host renders as a pending draft above the
32
- // user's composer and what ends up as a permanent housekeeping turn in their chat.
33
- // The host contract this plugin must satisfy, mirrored from the runtime:
34
- // packages/core/session SessionStore.prepare() rebuilds a session header from a
35
- // fixed meta whitelist and `Session` then throws "seeded session requires an
36
- // inherited event count" when the count was not passed as a TOP-LEVEL option.
37
- // The host drops an unknown meta key silently; this fake refuses it loudly, so a
38
- // plugin that misplaces the field fails the test instead of dying in production.
39
- const META_KEYS = ['cwd', 'parentSession', 'isSeeded', 'origin', 'delegationDepth', 'agentPreset']
40
-
41
- function assertHostCreateAccepts(spec = {}) {
42
- const meta = spec.meta ?? {}
43
- const count = spec.inheritedEventCount
44
- for (const key of Object.keys(meta)) {
45
- if (!META_KEYS.includes(key)) {
46
- throw new Error(`session meta "${key}" is not a header field: SessionStore.prepare() drops it`)
47
- }
48
- }
49
- if (meta.isSeeded === true) {
50
- if (spec.seed === undefined) throw new Error('seeded session requires an explicit constructor seed')
51
- if (count === undefined) throw new Error('seeded session requires an inherited event count')
52
- } else if (count !== undefined && count !== 0) {
53
- throw new Error('unseeded session inherited event count must be 0')
54
- }
55
- // buildForkSeed() returns a seed object, not a bare array, so the length guard
56
- // only applies to an array seed.
57
- if (Array.isArray(spec.seed) && count !== undefined && count > spec.seed.length) {
58
- throw new Error('session inherited event count exceeds its event log')
59
- }
60
- if (spec.agentOptions !== undefined) {
61
- if (!spec.agentOptions || typeof spec.agentOptions.provider !== 'string' || typeof spec.agentOptions.model !== 'string') {
62
- throw new Error('agentOptions must carry the parent provider and model')
63
- }
64
- }
65
- }
66
-
67
- function host({ live = false, whenIdle = null, parentOptions = { provider: 'test-provider', model: 'test-model' }, requestConfig = null, extraEvents = [], transcriptSize = 0, turnReason = { kind: 'completed' }, emitTurnEnd = true, headerTools = null, childCtxFactory = null, llm = null, cwd = path.join(home, 'proj') } = {}) {
68
- const rec = { liveFollowups: [], created: [], forkFollowups: [], disposed: [], sessionHandlers: [], workerToolRegistrations: [], workerToolDisposals: [] }
69
- // agents.get 返回裸 agent;dispose 注销活句柄,但会话 id 仍在磁盘上占用。
70
- const childAgents = new Map()
71
- const tick = String.fromCharCode(96)
72
- const receiptFence = (range, identity) => [tick + tick + tick + 'memu-consolidation-receipt', JSON.stringify({ version: 1, ...identity, status: 'completed', outcome: 'no_value', checkedRange: range, createdIds: [], updatedIds: [], heldIds: [], reasonCode: null, retryable: false }), tick + tick + tick].join('\n')
73
- // 真实长会话的规模:补齐不产生证据的事件,只影响 fork 成本判定。
74
- const padding = Math.max(0, transcriptSize - 3 - extraEvents.length)
75
- const filler = Array.from({ length: padding }, (_, i) => ({ seq: 3 + extraEvents.length + i, type: 'todo/write', data: {} }))
76
- const ctx = {
77
- rec,
78
- on: (name, handler) => {
79
- if (name !== 'session/event') return () => {}
80
- rec.sessionHandlers.push(handler)
81
- return () => {
82
- const index = rec.sessionHandlers.indexOf(handler)
83
- if (index >= 0) rec.sessionHandlers.splice(index, 1)
84
- }
85
- },
86
- get: (name) => {
87
- if (name === 'agents') {
88
- return {
89
- get: (id) => {
90
- if (childAgents.has(id)) return childAgents.get(id)
91
- return (live
92
- ? {
93
- followup: (message) => rec.liveFollowups.push({ id, message }),
94
- ...(parentOptions ? { options: parentOptions } : {}),
95
- ...(requestConfig || headerTools ? { session: { requestHeader: () => ({
96
- ...(requestConfig ? { config: requestConfig } : {}),
97
- ...(headerTools ? { tools: headerTools.map((toolName) => ({ name: toolName })) } : {}),
98
- }) } } : {}),
99
- }
100
- : undefined)
101
- },
102
- create: async (spec) => {
103
- assertHostCreateAccepts(spec)
104
- if (childAgents.has(spec.sessionId)) throw new Error('session already exists: ' + spec.sessionId)
105
- rec.created.push(spec)
106
- const childSession = { id: spec.sessionId }
107
- const dispose = async () => {
108
- rec.disposed.push(spec.sessionId)
109
- childAgents.set(spec.sessionId, null)
110
- }
111
- const handle = {
112
- agent: {
113
- session: childSession,
114
- ctx: childCtxFactory?.(),
115
- dispose,
116
- followup: (message) => {
117
- rec.forkFollowups.push({ child: spec.sessionId, message })
118
- if (emitTurnEnd) {
119
- const reason = typeof turnReason === 'function' ? turnReason(spec) : turnReason
120
- if (reason?.kind === 'completed') {
121
- // The worker receipt must match the window the fork was seeded
122
- // with, not the whole parent transcript.
123
- const child = state.getSessionBinding(spec.sessionId)
124
- const fromSeq = Number.isSafeInteger(child?.snapshotFromSeq) ? child.snapshotFromSeq : 0
125
- const throughSeq = Number.isSafeInteger(child?.snapshotThroughSeq)
126
- ? child.snapshotThroughSeq
127
- : 2 + extraEvents.length + padding
128
- for (const handler of rec.sessionHandlers) {
129
- handler(childSession, { type: 'assistant/message', seq: 99, data: { message: { content: [{ type: 'text', text: receiptFence({ fromSeq, throughSeq }, child) }] } } })
130
- }
131
- }
132
- for (const handler of rec.sessionHandlers) {
133
- handler(childSession, { type: 'turn/end', seq: 100, data: { turn: 1, reason } })
134
- }
135
- }
136
- },
137
- whenIdle: whenIdle || (async () => {}),
138
- },
139
- dispose,
140
- }
141
- childAgents.set(spec.sessionId, handle.agent)
142
- return handle
143
- },
144
- }
145
- }
146
- // 整理 fork 的模型选择(lib/fork-model.js)按需探测的宿主 llm service;
147
- // 缺省没有 = custom 模式必须降级回 inherit 的宿主形态。
148
- if (name === 'llm') return llm
149
- if (name === 'sessionQuery') {
150
- return {
151
- readSession: async () => ({
152
- events: [
153
- { seq: 0, type: 'user/message', data: { source: { kind: 'user' }, content: [{ type: 'text', text: '这个 fork 为什么一直建不起来,帮我看下' }] } },
154
- { seq: 1, type: 'assistant/message', data: { message: { content: [{ type: 'tool-call', name: 'read', arguments: '{}' }] } } },
155
- { seq: 2, type: 'assistant/message', data: { message: { content: [{ type: 'text', text: '看到了' }] } } },
156
- ...extraEvents,
157
- ...filler,
158
- ],
159
- session: { cwd, agentPreset: 'coding' },
160
- }),
161
- }
162
- }
163
- return undefined
164
- },
165
- }
166
- return ctx
167
- }
168
-
169
- test('enabling local or remote vectors does not opt into remote summary', async () => {
170
- const originalFetch = globalThis.fetch
171
- let fetches = 0
172
- globalThis.fetch = async () => { fetches += 1; throw new Error('summary API must not be called') }
173
- try {
174
- for (const vectorSource of ['local', 'api']) {
175
- state.updateSettings({ memoryBackend: 'api', vectorSource })
176
- const id = 'fork-vector-' + vectorSource
177
- state.ensureSession(id, { cwd: path.join(home, id), agentPreset: 'coding' })
178
- const ctx = host({ live: true })
179
- const result = await requestPrivateConsolidation(ctx, id)
180
- assert.equal(result.ok, true)
181
- assert.equal(ctx.rec.created.length, 1, 'vector enable still delegates extraction to the conversation Agent')
182
- assert.equal(ctx.rec.forkFollowups.length, 1)
183
- }
184
- assert.equal(fetches, 0)
185
- } finally {
186
- globalThis.fetch = originalFetch
187
- state.updateSettings({ memoryBackend: 'agent', vectorSource: 'local' })
188
- }
189
- })
190
-
191
- test('a live session is consolidated in a fork, not by queueing on itself', async () => {
192
- const binding = state.ensureSession('fork-live', { cwd: path.join(home, 'proj'), agentPreset: 'coding' })
193
- const parentOptions = { provider: 'test-provider', model: 'test-model', reasoningEffort: 'max', maxTokens: 262144 }
194
- const ctx = host({ live: true, parentOptions })
195
- const result = await requestPrivateConsolidation(ctx, 'fork-live')
196
- assert.equal(result.ok, true)
197
- assert.equal(result.settled, true)
198
- assert.equal(ctx.rec.liveFollowups.length, 0, 'no queued draft on the live agent')
199
- assert.equal(ctx.rec.created.length, 1, 'exactly one scratch fork')
200
- assert.equal(ctx.rec.forkFollowups.length, 1, 'the fork does the work')
201
- assert.equal(ctx.rec.disposed.length, 1, 'the fork is disposed')
202
- const spec = ctx.rec.created[0]
203
- assert.equal(spec.meta.parentSession, 'fork-live')
204
- assert.equal(spec.meta.origin, 'subagent')
205
- assert.equal(spec.meta.isSeeded, true)
206
- assert.equal(spec.inheritedEventCount, 3, 'inherits the whole transcript as a top-level option')
207
- assert.equal(Object.hasOwn(spec.meta, 'inheritedEventCount'), false, 'must not hide in the session meta: prepare() drops it')
208
- assert.deepEqual(spec.agentOptions, parentOptions, 'the fork starts on the parent model route')
209
- const child = state.getSessionBinding(spec.sessionId)
210
- assert.equal(child, null, 'disposed worker binding is removed')
211
- assert.equal(state.getSessionBinding('fork-live').lastSleepSeq, 2, 'only a completed turn advances the sleep cursor')
212
- assert.equal(result.scanned, 3, 'report how much of the transcript was scanned')
213
- assert.equal(result.fresh, 3, 'report how many events were new since the last consolidation')
214
- assert.equal(result.wrote, 0, 'the fake fork writes nothing, but the metric must still be measured')
215
- const text = ctx.rec.forkFollowups[0].message.content[0].text
216
- const { estTokens } = await import('../lib/budget.js')
217
- assert.equal(result.measurement.runner, 'fork')
218
- assert.equal(result.measurement.packet.inputChars, text.length)
219
- assert.equal(result.measurement.packet.estimatedTokens, estTokens(text))
220
- assert.equal(result.measurement.usage.inputTokens, null)
221
- })
222
-
223
- for (const restriction of ['succeeds', 'missing', 'throws twice']) {
224
- test(`a fork keeps host permissions and dispatches when tools.restrict ${restriction}`, async (t) => {
225
- const id = 'fork-permissions-' + restriction.replaceAll(' ', '-')
226
- state.ensureSession(id, { cwd: home, agentPreset: 'coding' })
227
- const setPermission = t.mock.fn()
228
- const disposeRestriction = t.mock.fn()
229
- const followupsAtRestriction = []
230
- const restrict = t.mock.fn(() => {
231
- followupsAtRestriction.push(ctx.rec.forkFollowups.length)
232
- if (restriction === 'throws twice') throw new Error('host refused tool restriction')
233
- return disposeRestriction
234
- })
235
- const ctx = host({
236
- live: true,
237
- headerTools: [...CORE_WRITE_TOOLS, 'read', 'shell'],
238
- childCtxFactory: () => ({ tools: restriction === 'missing' ? {} : { restrict } }),
239
- })
240
- ctx.permissionPresets = { set: setPermission }
241
-
242
- const result = await requestPrivateConsolidation(ctx, id)
243
- assert.equal(setPermission.mock.callCount(), 0, 'the plugin must not change the host permission preset')
244
- assert.equal(result.ok, true, String(result.error || ''))
245
- assert.equal(result.settled, true, 'missing or failing restrict keeps the existing capability fallback')
246
- assert.equal(ctx.rec.created.length, 1)
247
- assert.equal(ctx.rec.forkFollowups.length, 1, 'the fork still receives the consolidation task')
248
- assert.equal(ctx.rec.liveFollowups.length, 0, 'the parent never receives the task')
249
- assert.equal(ctx.rec.disposed.length, 1, 'the scratch fork is still disposed')
250
- const expectedAllows = restriction === 'missing' ? []
251
- : restriction === 'throws twice' ? [WORKER_TOOL_ALLOW, CORE_WRITE_TOOLS] : [WORKER_TOOL_ALLOW]
252
- assert.deepEqual(restrict.mock.calls.map((call) => call.arguments), expectedAllows.map((allow) => [{ allow }]),
253
- 'restriction still tries the full allowlist and falls back to the write core on failure')
254
- assert.deepEqual(followupsAtRestriction, expectedAllows.map(() => 0), 'all restriction attempts precede dispatch')
255
- assert.equal(disposeRestriction.mock.callCount(), restriction === 'succeeds' ? 1 : 0)
256
- })
257
- }
258
-
259
- test('a fork preserves an existing parent cwd', async () => {
260
- const cwd = fs.mkdtempSync(path.join(home, 'existing-cwd-'))
261
- state.ensureSession('fork-cwd-existing', { cwd, agentPreset: 'coding' })
262
- const ctx = host({ live: true, cwd })
263
- const result = await requestPrivateConsolidation(ctx, 'fork-cwd-existing')
264
- assert.equal(result.ok, true, String(result.error || ''))
265
- assert.equal(ctx.rec.created.length, 1)
266
- assert.notEqual(cwd, dataDir(), 'the existing cwd differs from the fallback')
267
- assert.equal(ctx.rec.created[0].meta.cwd, cwd)
268
- assert.equal(ctx.rec.forkFollowups.length, 1)
269
- })
270
-
271
- test('a fork falls back to the real dataDir when the parent cwd no longer exists', async () => {
272
- const cwd = path.join(home, 'missing-cwd')
273
- assert.equal(fs.existsSync(cwd), false)
274
- state.ensureSession('fork-cwd-missing', { cwd, agentPreset: 'coding' })
275
- const ctx = host({ live: true, cwd })
276
- const result = await requestPrivateConsolidation(ctx, 'fork-cwd-missing')
277
- assert.equal(result.ok, true, String(result.error || ''))
278
- assert.equal(ctx.rec.created.length, 1)
279
- assert.equal(ctx.rec.created[0].meta.cwd, dataDir())
280
- assert.equal(fs.statSync(ctx.rec.created[0].meta.cwd).isDirectory(), true, 'the fallback is a real directory')
281
- assert.equal(ctx.rec.forkFollowups.length, 1)
282
- })
283
-
284
- test('a live session inherits the route of its latest turn, not stale creation options', async () => {
285
- state.ensureSession('fork-route', { cwd: path.join(home, 'proj-route'), agentPreset: 'coding' })
286
- const ctx = host({
287
- live: true,
288
- parentOptions: { provider: 'creation', model: 'old-model' },
289
- requestConfig: { provider: 'request', model: 'new-model', reasoningEffort: 'high', maxTokens: 32768 },
290
- })
291
- const result = await requestPrivateConsolidation(ctx, 'fork-route')
292
- assert.equal(result.ok, true)
293
- assert.deepEqual(ctx.rec.created[0].agentOptions, {
294
- provider: 'request',
295
- model: 'new-model',
296
- reasoningEffort: 'high',
297
- maxTokens: 32768,
298
- }, 'requestHeader() is the route that served the parent, options can be stale')
299
- })
300
-
301
- test('a closed session inherits the last request/header event', async () => {
302
- state.ensureSession('fork-closed', { cwd: path.join(home, 'proj-closed'), agentPreset: 'coding' })
303
- const ctx = host({
304
- live: false,
305
- extraEvents: [
306
- { seq: 3, type: 'request/header', data: { header: { config: { provider: 'old', model: 'old-model' } } } },
307
- { seq: 4, type: 'request/header', data: { header: { config: { provider: 'latest', model: 'latest-model', reasoningEffort: 'low', maxTokens: 4096 } } } },
308
- ],
309
- })
310
- const result = await requestPrivateConsolidation(ctx, 'fork-closed')
311
- assert.equal(result.ok, true)
312
- const spec = ctx.rec.created[0]
313
- assert.equal(spec.inheritedEventCount, 3, 'only conversation events are seeded; request/header is noise')
314
- assert.deepEqual(spec.agentOptions, { provider: 'latest', model: 'latest-model', reasoningEffort: 'low', maxTokens: 4096 })
315
- })
316
-
317
- test('a session with no model source is refused before a doomed fork', async () => {
318
- state.ensureSession('fork-no-model', { cwd: path.join(home, 'proj-no-model'), agentPreset: 'coding' })
319
- const ctx = host({ live: true, parentOptions: null })
320
- const result = await requestPrivateConsolidation(ctx, 'fork-no-model')
321
- assert.equal(result.ok, false)
322
- assert.match(result.error, /model\/provider/)
323
- assert.equal(ctx.rec.created.length, 0, 'never create a fork that cannot resolve {{model}}')
324
- })
325
-
326
- test('a failed fork turn is reported as failure and does not advance the sleep cursor', async () => {
327
- state.ensureSession('fork-turn-error', { cwd: path.join(home, 'proj-turn-error'), agentPreset: 'coding' })
328
- const ctx = host({
329
- live: true,
330
- turnReason: { kind: 'error', error: { message: 'prompt variable "{{model}}" has no value for this assembly', code: 'UNKNOWN' } },
331
- })
332
- const result = await requestPrivateConsolidation(ctx, 'fork-turn-error')
333
- assert.equal(result.ok, false)
334
- assert.equal(result.settled, false)
335
- assert.match(result.error, /fork turn ended error/)
336
- assert.match(result.error, /prompt variable/)
337
- assert.equal(state.getSessionBinding('fork-turn-error').lastSleepSeq, undefined, 'a failed turn must be retried, not marked asleep')
338
- assert.equal(ctx.rec.disposed.length, 1, 'the failed fork is still disposed')
339
- assert.equal(ctx.rec.sessionHandlers.length, 0, 'the failed fork listener is removed')
340
- const { sessionState } = await import('../lib/consolidation-ledger.js')
341
- const ledger = sessionState('fork-turn-error')
342
- assert.equal(ledger.checked, null)
343
- assert.equal(ledger.pending.fromSeq, 0)
344
- assert.equal(ledger.pending.throughSeq, 2)
345
- assert.ok(result.measurement.packet.inputChars > 0, 'failed dispatches still carry cost measurement')
346
- })
347
-
348
- test('a fork that never reports turn/end is a failure, not a success', async () => {
349
- state.ensureSession('fork-no-turn-end', { cwd: path.join(home, 'proj-no-turn-end'), agentPreset: 'coding' })
350
- const ctx = host({ live: true, emitTurnEnd: false })
351
- const result = await requestPrivateConsolidation(ctx, 'fork-no-turn-end')
352
- assert.equal(result.ok, false)
353
- assert.equal(result.settled, false)
354
- assert.match(result.error, /no turn\/end/)
355
- assert.equal(state.getSessionBinding('fork-no-turn-end').lastSleepSeq, undefined, 'without a turn/end event the cursor must not advance')
356
- assert.equal(ctx.rec.disposed.length, 1, 'the unmatched fork is still disposed')
357
- assert.equal(ctx.rec.sessionHandlers.length, 0, 'the listener is removed even when no turn/end arrives')
358
- })
359
-
360
- test('a fork still running at the deadline reports a timeout instead of silence', async () => {
361
- state.ensureSession('fork-timeout', { cwd: path.join(home, 'proj-timeout'), agentPreset: 'coding' })
362
- const ctx = host({ live: true, whenIdle: () => new Promise(() => {}) })
363
- const result = await requestPrivateConsolidation(ctx, 'fork-timeout', { maxWaitMs: 30 })
364
- assert.equal(result.ok, false)
365
- assert.equal(result.timedOut, true)
366
- assert.equal(result.settled, false)
367
- // The settings button renders result.error and nothing else; an empty string
368
- // there is why two clicks in a row looked like the button did nothing.
369
- assert.match(result.error, /timed out after \d+s/)
370
- assert.equal(state.getSessionBinding('fork-timeout').lastSleepSeq, undefined, 'a timeout must not advance the sleep cursor')
371
- assert.equal(ctx.rec.disposed.length, 1, 'the timed-out fork is stopped')
372
- assert.equal(ctx.rec.sessionHandlers.length, 0, 'the listener is removed on timeout')
373
- })
374
-
375
- test('a session already being consolidated is not forked twice', async () => {
376
- state.ensureSession('fork-busy', { cwd: path.join(home, 'proj2'), agentPreset: 'coding' })
377
- let release = null
378
- const gate = new Promise((resolve) => { release = resolve })
379
- const ctx = host({ live: true, whenIdle: () => gate })
380
- const first = requestPrivateConsolidation(ctx, 'fork-busy')
381
- await new Promise((resolve) => setTimeout(resolve, 20))
382
- assert.equal(isConsolidating('fork-busy'), true)
383
- const second = await requestPrivateConsolidation(ctx, 'fork-busy')
384
- assert.equal(second.ok, false)
385
- assert.equal(second.running, true)
386
- assert.equal(ctx.rec.created.length, 1, 'the second call must not fork again')
387
- release()
388
- const done = await first
389
- assert.equal(done.ok, true)
390
- assert.equal(isConsolidating('fork-busy'), false)
391
- })
392
-
393
- test('two calls in the same tick fork once, not twice', async () => {
394
- // The guard used to be checked before the first await and claimed only after
395
- // readSession() and agents.create() resolved, so this exact pair raced past it
396
- // and forked the same transcript twice on the real host.
397
- state.ensureSession('fork-race', { cwd: path.join(home, 'proj3'), agentPreset: 'coding' })
398
- let release = null
399
- const gate = new Promise((resolve) => { release = resolve })
400
- const ctx = host({ live: true, whenIdle: () => gate })
401
- const both = Promise.all([
402
- requestPrivateConsolidation(ctx, 'fork-race'),
403
- requestPrivateConsolidation(ctx, 'fork-race'),
404
- ])
405
- await new Promise((resolve) => setTimeout(resolve, 20))
406
- release()
407
- const [a, b] = await both
408
- assert.equal(ctx.rec.created.length, 1, 'exactly one scratch fork for the pair')
409
- const outcomes = [a, b].map((r) => r.running === true ? 'running' : r.ok === true ? 'ok' : 'error').sort()
410
- assert.deepEqual(outcomes, ['ok', 'running'], 'the loser is told the session is already being consolidated')
411
- })
412
-
413
- test('an unbound session is refused before any fork is attempted', async () => {
414
- const ctx = host({ live: true })
415
- const result = await requestPrivateConsolidation(ctx, 'fork-unbound')
416
- assert.equal(result.ok, false)
417
- assert.match(result.error, /not bound/)
418
- assert.equal(ctx.rec.created.length, 0)
419
- assert.equal(ctx.rec.liveFollowups.length, 0)
420
- })
421
- test('thin evidence holds the fork back until the starvation threshold', async () => {
422
- state.ensureSession('fork-thin', { cwd: path.join(home, 'proj-thin'), agentPreset: 'coding' })
423
- // 空闲 5 分钟:还在"短空闲"区间,证据又薄(一条短消息 + 一个工具调用),不唤醒。
424
- state.setSessionBinding('fork-thin', { lastTurnAt: new Date(Date.now() - 5 * 60_000).toISOString() })
425
- const ctx = host({ live: true })
426
- const result = await requestPrivateConsolidation(ctx, 'fork-thin')
427
- assert.equal(result.ok, true)
428
- assert.equal(result.skipped, 'low-score')
429
- assert.equal(ctx.rec.created.length, 0, 'a thin short-idle session must not pay for a fork')
430
- })
431
-
432
- test('starvation wakes a thin session so it can never be starved', async () => {
433
- state.ensureSession('fork-starved', { cwd: path.join(home, 'proj-starved'), agentPreset: 'coding' })
434
- state.setSessionBinding('fork-starved', { lastTurnAt: new Date(Date.now() - 40 * 60_000).toISOString() })
435
- const ctx = host({ live: true })
436
- const result = await requestPrivateConsolidation(ctx, 'fork-starved')
437
- assert.equal(result.ok, true)
438
- assert.equal(ctx.rec.created.length, 1, 'past the starvation threshold the check runs regardless of score')
439
- })
440
-
441
- test('a large transcript with nothing new since the cursor does not refork', async () => {
442
- // 真机会话 5913 条事件、26MB 转录。游标停在末尾附近时,待整理区间只剩几条纯轮询:
443
- // 没有新的真人回合,就没有可整理的证据,不该为此把整段转录重新种进 fork。
444
- // (桩把填充事件全放在末尾,所以「大会话 + 末尾一句轻话」这种形态表达不出来;
445
- // 另一侧「从未整理过就必须整理」由下一条用例覆盖。)
446
- state.ensureSession('fork-large-thin', { cwd: path.join(home, 'proj-large'), agentPreset: 'coding' })
447
- state.setSessionBinding('fork-large-thin', {
448
- lastTurnAt: new Date(Date.now() - 40 * 60_000).toISOString(),
449
- lastSleepSeq: 5905,
450
- })
451
- const ctx = host({ live: true, transcriptSize: 5913 })
452
- const result = await requestPrivateConsolidation(ctx, 'fork-large-thin')
453
- assert.equal(result.ok, true)
454
- assert.equal(result.skipped, 'no-human-turn', 'the increment carries no human turn to consolidate')
455
- assert.equal(result.settled, true, 'a policy skip is terminal: the idle sweep stops re-reading the same greetings')
456
- assert.equal(ctx.rec.created.length, 0, 'no fork when the pending increment has no evidence')
457
- assert.equal(state.getSessionBinding('fork-large-thin').lastSleepSeq, 5912, 'a terminal policy skip advances the coarse cursor so the same thin tail is not rescanned')
458
- })
459
-
460
- test('a large transcript that was never consolidated does fork, because the backlog is real', async () => {
461
- // 同一条会话,但没有整理过:整段 5913 条事件都躺在 pending 里。
462
- // 守卫要躲的是「为一句轻话重种整段转录」,不是「把从没整理过的大会话永远挡在门外」;
463
- // 没有这条上界,长会话早期的决定永远进不了记忆——那不是省 token,是丢失。
464
- state.ensureSession('fork-large-owed', { cwd: path.join(home, 'proj-large-owed'), agentPreset: 'coding' })
465
- state.setSessionBinding('fork-large-owed', { lastTurnAt: new Date(Date.now() - 40 * 60_000).toISOString() })
466
- const ctx = host({ live: true, transcriptSize: 5913 })
467
- const result = await requestPrivateConsolidation(ctx, 'fork-large-owed')
468
- assert.equal(result.ok, true, 'the backlog bound lets this one through')
469
- assert.equal(ctx.rec.created.length, 1, 'a large unconsolidated backlog is worth exactly one fork')
470
- })
471
- // ---------------------------------------------------------------- window & seed
472
- test('the seed keeps conversation only, renumbers from zero, and strips replay/stream noise', () => {
473
- const plugin = { seq: 0, type: 'user/message', data: { source: { kind: 'plugin:dsh-memu-memory', form: 'recall' }, content: [{ type: 'text', text: '旧召回' }] } }
474
- const runtime = { seq: 1, type: 'user/message', data: { source: { kind: 'runtime-context', form: 'snapshot' }, content: [{ type: 'text', text: '运行时快照' }] } }
475
- const header = { seq: 2, type: 'request/header', data: { header: {} } }
476
- const user = { seq: 3, type: 'user/message', data: { source: { kind: 'user' }, content: [{ type: 'text', text: '记住:我不吃香菜' }] } }
477
- const assistant = { seq: 4, type: 'assistant/message', data: {
478
- message: {
479
- source: { provider: 'p', model: 'm', replayState: { huge: 'x'.repeat(400) } },
480
- content: [{ type: 'reasoning', text: '思考过程' }, { type: 'text', text: '好的' }, { type: 'tool-call', name: 'read', arguments: 'x'.repeat(2000) }],
481
- },
482
- stream: { blob: 'y'.repeat(400) },
483
- } }
484
- const repeated = 'R'.repeat(4000)
485
- const tool1 = { seq: 5, type: 'tool/result', data: { message: { content: [{ type: 'text', text: repeated }] } } }
486
- const tool2 = { seq: 6, type: 'tool/result', data: { message: { content: [{ type: 'text', text: repeated }] } } }
487
- const catalog = {
488
- type: 'user/message', seq: 0, time: 1, surfaceOp: 'append',
489
- data: { role: 'user', source: { kind: 'plugin:dsh-memu-memory', form: 'notice' }, content: [{ type: 'text', text: '已有记忆目录' }] },
490
- }
491
- const seed = compactSeedEvents([plugin, runtime, header, user, assistant, tool1, tool2], catalog)
492
- assert.deepEqual(seed.map(event => event.seq), [0, 1, 2, 3, 4], 'contiguous from zero, catalog at 0')
493
- assert.match(seed[0].data.content[0].text, /已有记忆目录/)
494
- assert.equal(seed[1].data.source.kind, 'user', 'only real user messages survive')
495
- const msg = seed[2].data.message
496
- assert.equal(msg.content.some(block => block.type === 'reasoning'), false, 'reasoning is not evidence')
497
- assert.equal(msg.source.replayState, undefined, 'replay state duplicates the body')
498
- assert.deepEqual(seed[2].data.stream, [], 'the raw chunk log is emptied, not deleted — 0.2.2-rc.1 seed validation requires the array')
499
- assert.match(msg.content.find(block => block.type === 'tool-call').arguments, /已截断/)
500
- assert.match(seed[3].data.message.content[0].text, /已截断/)
501
- assert.match(seed[4].data.message.content[0].text, /与前面相同的工具输出/, 'identical tool output is deduped')
502
- })
503
-
504
- test('a long tail is cut to one closed-turn window with a remainder', () => {
505
- const events = Array.from({ length: CONSOLIDATION_WINDOW_EVENTS + 180 }, (_, seq) => ({ seq, type: 'todo/write', data: {} }))
506
- const window = selectConsolidationWindow(events)
507
- assert.equal(window.fromSeq, 0)
508
- assert.ok(window.events.length <= CONSOLIDATION_WINDOW_EVENTS, 'the window stays bounded')
509
- assert.ok(window.remaining > 0, 'the rest is left for the next sweep')
510
- assert.ok(window.throughSeq < events.length - 1)
511
- })
512
-
513
- test('a manual re-check starts at a complete turn instead of mid-step', () => {
514
- const events = [
515
- { seq: 0, type: 'assistant/message', data: { message: { content: [{ type: 'text', text: '旧回答' }] } } },
516
- { seq: 1, type: 'user/message', data: { source: { kind: 'user' }, content: [{ type: 'text', text: '最后一问' }] } },
517
- { seq: 2, type: 'turn/start', data: { turn: 2 } },
518
- { seq: 3, type: 'assistant/message', data: { message: { content: [{ type: 'text', text: '最后回答' }] } } },
519
- { seq: 4, type: 'turn/end', data: { turn: 2, reason: { kind: 'completed' } } },
520
- ]
521
- const window = selectTailTurnWindow(events)
522
- assert.equal(window.fromSeq, 1, 'the user message that opened the turn is included')
523
- assert.equal(window.throughSeq, 4, 'the window ends on a closed turn')
524
- })
525
-
526
- test('must-cover candidates keep the high-signal turn and its seq range', () => {
527
- const events = [
528
- { seq: 0, type: 'turn/start', data: {} },
529
- { seq: 1, type: 'user/message', data: { source: { kind: 'user' }, content: [{ type: 'text', text: '说好周末拿给阿兰换伞骨,记得带过去。' }] } },
530
- { seq: 2, type: 'turn/end', data: {} },
531
- { seq: 3, type: 'turn/start', data: {} },
532
- { seq: 4, type: 'user/message', data: { source: { kind: 'user' }, content: [{ type: 'text', text: '今天天气不错。' }] } },
533
- { seq: 5, type: 'turn/end', data: {} },
534
- ]
535
- const rows = mustCoverCandidates(events, { max: 4 })
536
- assert.equal(rows.length, 1, 'a low-signal turn is not a must-cover candidate')
537
- assert.equal(rows[0].fromSeq, 0)
538
- assert.equal(rows[0].throughSeq, 2)
539
- assert.equal(rows[0].tag, '人物/关系')
540
- assert.match(rows[0].text, /阿兰/)
541
- })
542
-
543
- test('mergeMustCover puts carried candidates first and reserves room for fresh ones', () => {
544
- const carry = Array.from({ length: 6 }, (_, i) => ({ text: 'carry' + i, fromSeq: i, throughSeq: i, tag: '事实' }))
545
- const fresh = Array.from({ length: 6 }, (_, i) => ({ text: 'fresh' + i, fromSeq: i, throughSeq: i, tag: '事实' }))
546
- const merged = mergeMustCover(carry, fresh)
547
- assert.equal(merged.length, 8)
548
- assert.deepEqual(merged.slice(0, 4).map((row) => row.text), ['carry0', 'carry1', 'carry2', 'carry3'])
549
- assert.deepEqual(merged.slice(4).map((row) => row.text), ['fresh0', 'fresh1', 'fresh2', 'fresh3'])
550
- assert.ok(merged.slice(0, 4).every((row) => row.carried === true))
551
- assert.equal(mergeMustCover([{ text: 'same' }], [{ text: 'same' }]).length, 1, 'duplicates are dropped')
552
- })
553
-
554
- test('a candidate is covered only when a written entry carries the fact', () => {
555
- const index = {
556
- entries: {
557
- 'mem-1': { title: '楼下修伞的阿兰', content: '说好周末拿折伞给她换伞骨,布不用动。' },
558
- 'mem-2': { title: '同事叶楠生日是八月十八号', content: '叶楠生日八月十八号。' },
559
- },
560
- }
561
- assert.equal(candidateCovered({ text: '说好周末拿给阿兰换伞骨' }, ['mem-1'], index), true)
562
- assert.equal(candidateCovered({ text: '叶楠生日八月十八号' }, ['mem-2'], index), true)
563
- assert.equal(candidateCovered({ text: '父亲不吃芹菜' }, ['mem-1'], index), false)
564
- assert.equal(candidateCovered({ text: '父亲不吃芹菜' }, [], index), false, 'no writes means no coverage')
565
- })
566
-
567
- test('coverage does not discard facts for matching dates, polarity, values, or generic overlap', () => {
568
- const covered = (text, content, title = '') => candidateCovered({ text }, ['mem-written'], { entries: { 'mem-written': { title, content } } })
569
- assert.equal(covered('11月20日阿兰取伞', '11月20日小林去医院'), false, 'same date is not the same event')
570
- assert.equal(covered('父亲不吃芹菜', '父亲爱吃芹菜'), false, 'opposite polarity is not coverage')
571
- assert.equal(covered('父亲周末去图书馆还书', '父亲周末去图书馆借书'), false, 'shared topic must retain the action')
572
- assert.equal(covered('父亲生日是11月20日', '父亲生日是11月21日'), false, 'different date is not coverage')
573
- assert.equal(covered('项目预算是1200元', '项目预算是1500元'), false, 'different value is not coverage')
574
- assert.equal(covered('11月20日', '11月20日小林去医院'), false, 'date alone is insufficient evidence')
575
- assert.equal(covered('父亲不吃芹菜', '父亲不吃芹菜,母亲喜欢白菜'), true)
576
- assert.equal(covered('父亲喜欢芹菜', '父亲喜欢芹菜,母亲不吃白菜'), true, 'unrelated negation does not alter the fact')
577
- assert.equal(covered('11月20日阿兰取伞', '11月20日阿兰取伞,记得提前联系'), true)
578
- assert.equal(covered('项目预算是1200元', '项目预算是1200元'), true)
579
- })
580
-
581
- test('the same failed snapshot stops automatic re-forking after the failure cap', async () => {
582
- state.ensureSession('fork-failcap', { cwd: path.join(home, 'proj-failcap'), agentPreset: 'coding' })
583
- const ctx = host({ live: true, turnReason: { kind: 'error', error: { message: 'provider refused max-tokens argument' } } })
584
- const first = await requestPrivateConsolidation(ctx, 'fork-failcap', { force: true })
585
- const second = await requestPrivateConsolidation(ctx, 'fork-failcap', { force: true })
586
- assert.equal(first.ok, false)
587
- assert.equal(second.ok, false)
588
- assert.equal(ctx.rec.created.length, 2, 'two real attempts happen')
589
- // 自动路径仍然受上限约束:同一快照连续失败 2 次后不再付第三次 fork 成本。
590
- const third = await requestPrivateConsolidation(ctx, 'fork-failcap')
591
- assert.equal(third.ok, true)
592
- assert.equal(third.skipped, 'snapshot-failed')
593
- assert.equal(ctx.rec.created.length, 2, 'the automatic call does not pay for the same snapshot again')
594
- // 手动整理是明确的一次再决定:force 不受上限约束(否则冻结回放/用户重试会被永久卡住)。
595
- const forcedAgain = await requestPrivateConsolidation(ctx, 'fork-failcap', { force: true })
596
- assert.equal(forcedAgain.ok, false)
597
- assert.equal(ctx.rec.created.length, 3, 'a manual retry is allowed past the cap')
598
- })
599
-
600
- for (const runner of ['fork', 'worker']) {
601
- test(`${runner} preserves max-tokens pending and retries the same snapshot only after output configuration changes`, async () => {
602
- state.updateSettings({ consolidationRunner: runner, consolidationModelMode: 'inherit', consolidationReasoningEffort: 'inherit' })
603
- const id = 'output-limit-' + runner
604
- state.ensureSession(id, { cwd: path.join(home, id), agentPreset: 'coding' })
605
- const parentOptions = { provider: id, model: 'test-model', maxTokens: 4096, reasoningEffort: 'medium' }
606
- markEffortRefused([id, 'test-model', 'medium'].join('|'))
607
- const ctx = host({ live: true, parentOptions, turnReason: spec => spec.agentOptions.maxTokens <= 4096 ? { kind: 'max-tokens' } : { kind: 'completed' } })
608
- try {
609
- for (let i = 0; i < 2; i++) {
610
- const failed = await requestPrivateConsolidation(ctx, id, { force: true })
611
- assert.equal(failed.ok, false)
612
- assert.equal(failed.settled, false)
613
- assert.equal(failed.reasonCode, 'model-output-limit')
614
- assert.equal(failed.retryable, true)
615
- assert.equal(failed.configuredMaxTokens, 4096)
616
- assert.match(failed.error, /输出预算不足/)
617
- assert.equal(state.getSessionBinding(id).lastSleepSeq, undefined)
618
- assert.ok(ledger.sessionState(id).pending)
619
- assert.equal(parentOptions.maxTokens, 4096, 'the plugin never raises the parent limit')
620
- assert.equal(parentOptions.reasoningEffort, 'medium')
621
- assert.equal(ctx.rec.created.at(-1).agentOptions.reasoningEffort, undefined)
622
- }
623
- const suppressed = await requestPrivateConsolidation(ctx, id)
624
- assert.equal(suppressed.skipped, 'snapshot-failed')
625
- assert.equal(suppressed.settled, false)
626
- assert.equal(ctx.rec.created.length, 2)
627
- parentOptions.maxTokens = 32768
628
- const recovered = await requestPrivateConsolidation(ctx, id)
629
- assert.equal(recovered.ok, true, recovered.error || '')
630
- assert.equal(recovered.settled, true)
631
- assert.equal(ctx.rec.created.length, 3)
632
- assert.equal(ctx.rec.created.at(-1).agentOptions.maxTokens, 32768)
633
- assert.equal(state.getSessionBinding(id).lastSleepSeq, 2)
634
- assert.equal(ledger.sessionState(id).pending, null)
635
- } finally {
636
- const worker = state.getSessionBinding(id)?.workerEpoch?.forkSessionId
637
- if (worker) await retireWorker(ctx, worker, 'test-cleanup', { handoff: false })
638
- state.updateSettings({ consolidationRunner: 'fork', consolidationModelMode: 'inherit' })
639
- }
640
- })
641
- }
642
-
643
- test('host-route output default changes unlock a truncated snapshot without inheriting a parent route or overriding its cap', async () => {
644
- const id = 'output-default-host'
645
- state.ensureSession(id, { cwd: path.join(home, id), agentPreset: 'coding' })
646
- state.updateSettings({ consolidationRunner: 'fork', consolidationModelMode: 'host', consolidationModel: 'test-provider/test-model', consolidationReasoningEffort: 'inherit' })
647
- let defaultMaxTokens = 4096
648
- const ctx = host({ live: false, llm: { resolveModelInfo: async () => ({ defaultMaxTokens }) }, turnReason: () => defaultMaxTokens <= 4096 ? { kind: 'max-tokens' } : { kind: 'completed' } })
649
- try {
650
- for (let i = 0; i < 2; i++) {
651
- const result = await requestPrivateConsolidation(ctx, id, { force: true })
652
- assert.equal(result.reasonCode, 'model-output-limit')
653
- assert.equal(result.configuredMaxTokens, 4096)
654
- }
655
- const frozen = await requestPrivateConsolidation(ctx, id)
656
- assert.equal(frozen.skipped, 'snapshot-failed')
657
- defaultMaxTokens = 32768
658
- const resumed = await requestPrivateConsolidation(ctx, id)
659
- assert.equal(resumed.ok, true, resumed.error || '')
660
- assert.equal(resumed.settled, true)
661
- assert.equal(ctx.rec.created.length, 3)
662
- assert.ok(ctx.rec.created.every(spec => !Object.hasOwn(spec.agentOptions, 'maxTokens')))
663
- } finally {
664
- state.updateSettings({ consolidationModelMode: 'inherit', consolidationModel: '' })
665
- }
666
- })
667
-
668
- test('a budget change during a truncated turn is not charged as a failed attempt of the new configuration', async () => {
669
- const id = 'output-limit-mid-turn-change'
670
- state.ensureSession(id, { cwd: path.join(home, id), agentPreset: 'coding' })
671
- state.updateSettings({ consolidationRunner: 'fork', consolidationModelMode: 'inherit', consolidationReasoningEffort: 'inherit' })
672
- const parentOptions = { provider: id, model: 'test-model', maxTokens: 4096 }
673
- let oldAttempts = 0
674
- let newAttempts = 0
675
- const ctx = host({ live: true, parentOptions, turnReason: spec => {
676
- if (spec.agentOptions.maxTokens === 4096) {
677
- if (++oldAttempts === 2) parentOptions.maxTokens = 8192
678
- return { kind: 'max-tokens' }
679
- }
680
- return ++newAttempts === 1 ? { kind: 'max-tokens' } : { kind: 'completed' }
681
- } })
682
- for (let i = 0; i < 2; i++) assert.equal((await requestPrivateConsolidation(ctx, id, { force: true })).reasonCode, 'model-output-limit')
683
- assert.equal((await requestPrivateConsolidation(ctx, id)).reasonCode, 'model-output-limit')
684
- const recovered = await requestPrivateConsolidation(ctx, id)
685
- assert.equal(recovered.ok, true, recovered.error || '')
686
- assert.equal(recovered.settled, true)
687
- assert.equal(newAttempts, 2)
688
- assert.equal(ctx.rec.created.length, 4)
689
- assert.equal(state.getSessionBinding(id).lastSleepSeq, 2)
690
- })
691
-
692
- test('a provider default reasoning change reopens an output-limited host route without an explicit effort override', async () => {
693
- const id = 'output-limit-default-reasoning'
694
- state.ensureSession(id, { cwd: path.join(home, id), agentPreset: 'coding' })
695
- state.updateSettings({ consolidationRunner: 'fork', consolidationModelMode: 'host', consolidationModel: id + '/test-model', consolidationReasoningEffort: 'inherit' })
696
- let defaultEffort = 'high'
697
- const ctx = host({ live: false, llm: { resolveModelInfo: async () => ({ defaultMaxTokens: 4096, reasoning: { defaultEffort } }) }, turnReason: () => defaultEffort === 'high' ? { kind: 'max-tokens' } : { kind: 'completed' } })
698
- try {
699
- for (let i = 0; i < 2; i++) assert.equal((await requestPrivateConsolidation(ctx, id, { force: true })).reasonCode, 'model-output-limit')
700
- assert.equal((await requestPrivateConsolidation(ctx, id)).skipped, 'snapshot-failed')
701
- defaultEffort = 'low'
702
- const result = await requestPrivateConsolidation(ctx, id)
703
- assert.equal(result.ok, true, result.error || '')
704
- assert.equal(result.settled, true)
705
- assert.equal(ctx.rec.created.length, 3)
706
- assert.ok(ctx.rec.created.every(spec => !Object.hasOwn(spec.agentOptions, 'reasoningEffort')))
707
- } finally {
708
- state.updateSettings({ consolidationModelMode: 'inherit', consolidationModel: '' })
709
- }
710
- })
711
-
712
- test('unavailable model metadata does not masquerade as an output configuration change', async () => {
713
- const id = 'output-limit-unavailable-defaults'
714
- state.ensureSession(id, { cwd: path.join(home, id), agentPreset: 'coding' })
715
- state.updateSettings({ consolidationRunner: 'fork', consolidationModelMode: 'host', consolidationModel: id + '/test-model', consolidationReasoningEffort: 'inherit' })
716
- let unavailable = false
717
- let defaultMaxTokens = 4096
718
- const ctx = host({ live: false, llm: { resolveModelInfo: async () => {
719
- if (unavailable) throw new Error('model metadata unavailable')
720
- return { defaultMaxTokens }
721
- } }, turnReason: () => defaultMaxTokens <= 4096 ? { kind: 'max-tokens' } : { kind: 'completed' } })
722
- try {
723
- for (let i = 0; i < 2; i++) assert.equal((await requestPrivateConsolidation(ctx, id, { force: true })).reasonCode, 'model-output-limit')
724
- unavailable = true
725
- assert.equal((await requestPrivateConsolidation(ctx, id)).skipped, 'snapshot-failed')
726
- unavailable = false
727
- assert.equal((await requestPrivateConsolidation(ctx, id)).skipped, 'snapshot-failed')
728
- assert.equal(ctx.rec.created.length, 2)
729
- defaultMaxTokens = 32768
730
- assert.equal((await requestPrivateConsolidation(ctx, id)).settled, true)
731
- assert.equal(ctx.rec.created.length, 3)
732
- } finally {
733
- state.updateSettings({ consolidationModelMode: 'inherit', consolidationModel: '' })
734
- }
735
- })
736
-
737
- test('an explicit live output limit supersedes a cached header budget only on the same route', async () => {
738
- const id = 'output-limit-cached-header'
739
- state.ensureSession(id, { cwd: path.join(home, id), agentPreset: 'coding' })
740
- state.updateSettings({ consolidationRunner: 'fork', consolidationModelMode: 'inherit', consolidationReasoningEffort: 'inherit' })
741
- const parentOptions = { provider: id, model: 'test-model', maxTokens: 4096 }
742
- const requestConfig = Object.freeze({ provider: id, model: 'test-model', maxTokens: 4096 })
743
- const ctx = host({ live: true, parentOptions, requestConfig, turnReason: spec => spec.agentOptions.maxTokens <= 4096 ? { kind: 'max-tokens' } : { kind: 'completed' } })
744
- for (let i = 0; i < 2; i++) assert.equal((await requestPrivateConsolidation(ctx, id, { force: true })).reasonCode, 'model-output-limit')
745
- assert.equal((await requestPrivateConsolidation(ctx, id)).skipped, 'snapshot-failed')
746
- parentOptions.maxTokens = 32768
747
- const result = await requestPrivateConsolidation(ctx, id)
748
- assert.equal(result.ok, true, result.error || '')
749
- assert.equal(result.settled, true)
750
- assert.equal(ctx.rec.created.at(-1).agentOptions.maxTokens, 32768)
751
- assert.equal(requestConfig.maxTokens, 4096)
752
- assert.equal(ctx.rec.created.length, 3)
753
- })
754
-
755
- // ---------------------------------------------------------------- PTC 兼容
756
- // 现场(2026-10-31,yuike-ptc 会话):PTC 模式下 request/header 的工具表只有 run_code,
757
- // probe 曾据此判 unavailable(worker-tools-ptc-only),PTC 会话永远不被整理。宿主的
758
- // PTC executor 明确 "only run_code is directly callable",其余工具走 run_code 程序里的
759
- // SDK 绑定(tools.schemas(agent, toolSet) 枚举可见面)—— header 名单在 PTC 会话里
760
- // 不承载"能不能写记忆"。修复后:PTC 不构成否证 + fork 时把 worker 的读写面
761
- // (WORKER_WRITE_TOOLS + WORKER_READ_TOOLS)挂进 worker 自己的
762
- // scope(注册表按 scope 链取可见面,不扩散到其它会话)。
763
-
764
- test('a PTC session (run_code only header) is consolidated and the worker gets write tools on its own scope', async () => {
765
- const registered = []
766
- const disposals = []
767
- state.ensureSession('fork-ptc', { cwd: path.join(home, 'proj-ptc'), agentPreset: 'yuike-ptc' })
768
- const ctx = host({
769
- live: true,
770
- headerTools: ['run_code'],
771
- extraEvents: [
772
- { seq: 3, type: 'tool/ptc-dispatch-start', data: { rootCallId: 'r1', parentCallId: 'r1', subCallId: 'r1:ptc:1', name: 'read', arguments: {} } },
773
- { seq: 4, type: 'tool/ptc-dispatch', data: { rootCallId: 'r1', parentCallId: 'r1', subCallId: 'r1:ptc:1', name: 'read', arguments: {}, isError: false, content: [] } },
774
- ],
775
- childCtxFactory: () => ({
776
- tools: {
777
- register: (tool) => {
778
- registered.push(tool?.name)
779
- return () => { disposals.push(tool?.name) }
780
- },
781
- },
782
- }),
783
- })
784
- const result = await requestPrivateConsolidation(ctx, 'fork-ptc')
785
- assert.equal(result.ok, true, 'a run_code header must not block consolidation: ' + String(result.error || ''))
786
- assert.equal(result.settled, true)
787
- assert.equal(ctx.rec.created.length, 1, 'the fork is created for the PTC conversation')
788
- // 只挂 worker 真正用到的写面(remember/batch/update + link/link_suggest 裁决两件);
789
- // lexicon、archive/delete/unpin 这些用不到或破坏性的工具不进 worker 面。
790
- assert.deepEqual([...registered].sort(), ['memu_private_link', 'memu_private_link_suggest', 'memu_private_remember', 'memu_private_remember_batch', 'memu_private_update'])
791
- // 整理结束(finally)必须卸载挂载,不能给这条一次性 worker 留常驻注册。
792
- assert.deepEqual([...disposals].sort(), ['memu_private_link', 'memu_private_link_suggest', 'memu_private_remember', 'memu_private_remember_batch', 'memu_private_update'])
793
- // 全量挂载的活动元数据:attached=实际子集(此处=完整 wanted)、requested=完整 wanted、
794
- // partial=false。三件一起钉住"成功路径不再含糊"。
795
- const started = startedEntryFor(ctx, 'fork-ptc')
796
- assert.deepEqual([...started.detail.workerToolsAttached].sort(), ['memu_private_link', 'memu_private_link_suggest', 'memu_private_remember', 'memu_private_remember_batch', 'memu_private_update'])
797
- assert.deepEqual([...started.detail.workerToolsRequested].sort(), ['memu_private_link', 'memu_private_link_suggest', 'memu_private_remember', 'memu_private_remember_batch', 'memu_private_update'])
798
- assert.equal(started.detail.workerToolsPartial, false, 'a full mount is not partial')
799
- const followup = ctx.rec.forkFollowups[0]?.message
800
- const brief = Array.isArray(followup?.content)
801
- ? followup.content.map((block) => block?.text || '').join('\n')
802
- : String(followup || '')
803
- assert.match(brief, /run_code/, 'the brief names the PTC transport')
804
- assert.match(brief, /tools\.memu_private_remember/, 'the brief shows the SDK invocation shape')
805
- })
806
-
807
- // "整理已开始"那条活动日志:按 sessionId + phase=started 取,childId 对上这次的 fork。
808
- function startedEntryFor(ctx, sessionId) {
809
- const childId = ctx.rec.created[0]?.sessionId
810
- const entry = activity.listEvents({ kind: 'consolidate', sessionId })
811
- .find((row) => row.detail?.phase === 'started' && row.detail?.childId === childId)
812
- assert.ok(entry, 'the consolidation-started activity entry exists')
813
- return entry
814
- }
815
-
816
- test('a host registry refusing one write tool leaves a structured partial mount in the activity log', async () => {
817
- // 宿主注册表对单件工具说"不"(重名、scope 锁定)是真实的部分挂载路径:registerTools
818
- // 逐件 fail-open,其余工具照常挂上。活动日志必须记实际子集 + requested + partial,
819
- // 而不是把 wanted 全量误报成已挂载(旧口径的缺陷)。
820
- const registered = []
821
- const disposals = []
822
- state.ensureSession('fork-ptc-partial', { cwd: path.join(home, 'proj-ptc-partial'), agentPreset: 'yuike-ptc' })
823
- const ctx = host({
824
- live: true,
825
- headerTools: ['run_code'],
826
- childCtxFactory: () => ({
827
- tools: {
828
- register: (tool) => {
829
- if (tool?.name === 'memu_private_remember') throw new Error('registry refused: name already bound')
830
- registered.push(tool?.name)
831
- return () => { disposals.push(tool?.name) }
832
- },
833
- },
834
- }),
835
- })
836
- const result = await requestPrivateConsolidation(ctx, 'fork-ptc-partial')
837
- assert.equal(result.ok, true, String(result.error || ''))
838
- assert.equal(result.settled, true)
839
- assert.deepEqual([...registered].sort(), ['memu_private_link', 'memu_private_link_suggest', 'memu_private_remember_batch', 'memu_private_update'],
840
- 'exactly the tools that actually registered are mounted')
841
- assert.deepEqual([...disposals].sort(), ['memu_private_link', 'memu_private_link_suggest', 'memu_private_remember_batch', 'memu_private_update'],
842
- 'dispose unmounts exactly what was mounted')
843
- const started = startedEntryFor(ctx, 'fork-ptc-partial')
844
- assert.deepEqual([...started.detail.workerToolsAttached].sort(), ['memu_private_link', 'memu_private_link_suggest', 'memu_private_remember_batch', 'memu_private_update'],
845
- 'the log records the actual subset, not the full wanted list')
846
- assert.deepEqual([...started.detail.workerToolsRequested].sort(), ['memu_private_link', 'memu_private_link_suggest', 'memu_private_remember', 'memu_private_remember_batch', 'memu_private_update'])
847
- assert.equal(started.detail.workerToolsPartial, true)
848
- // 挂载为部分子集时任务书仍带 PTC 调用形态:worker 知道写记忆走 run_code 的 SDK 绑定。
849
- const followup = ctx.rec.forkFollowups[0]?.message
850
- const brief = Array.isArray(followup?.content)
851
- ? followup.content.map((block) => block?.text || '').join('\n')
852
- : String(followup || '')
853
- assert.match(brief, /await tools\.memu_private_remember/, 'the brief keeps the PTC invocation shape on a partial mount')
854
- })
855
-
856
- test('a fork context without a tools service records a null mount, the request and the partial flag', async () => {
857
- // 宿主不暴露 agent ctx(或 ctx 上没有 tools 服务)→ attachWorkerTools 的现有 warn 路径。
858
- // 语义:workerToolsAttached=null = 挂载没有完成(与"挂全了"严格区分);requested 仍记
859
- // 完整 wanted;workerToolsPartial=true —— "未证明拿到完整 wanted 集",一件都没有
860
- // 是它最极端的形态。若这里标 false,false 会被一眼读成"全量挂载",元数据又不准了。
861
- state.ensureSession('fork-ptc-notools', { cwd: path.join(home, 'proj-ptc-notools'), agentPreset: 'yuike-ptc' })
862
- const ctx = host({ live: true, headerTools: ['run_code'] })
863
- const result = await requestPrivateConsolidation(ctx, 'fork-ptc-notools')
864
- assert.equal(result.ok, true, String(result.error || ''))
865
- const started = startedEntryFor(ctx, 'fork-ptc-notools')
866
- assert.equal(started.detail.workerToolsAttached, null, 'no mount completed, so the log must not claim one')
867
- assert.deepEqual([...started.detail.workerToolsRequested].sort(), ['memu_private_link', 'memu_private_link_suggest', 'memu_private_remember', 'memu_private_remember_batch', 'memu_private_update'])
868
- assert.equal(started.detail.workerToolsPartial, true)
869
- })
870
-
871
- test('a non-PTC header without write tools still refuses to fork', async () => {
872
- state.ensureSession('fork-notools', { cwd: path.join(home, 'proj-notools'), agentPreset: 'coding' })
873
- const ctx = host({ live: true, headerTools: ['read', 'shell', 'edit'] })
874
- const result = await requestPrivateConsolidation(ctx, 'fork-notools')
875
- assert.equal(result.ok, false)
876
- assert.equal(result.reasonCode, 'worker-tools-missing')
877
- assert.equal(ctx.rec.created.length, 0, 'no fork when the model surface provably lacks the write tools')
878
- })
879
-
880
- // 超时预算(2026-11-15):下限与封顶齐平为 600 s——预算恒为 600 s(10 分钟),不再随
881
- // 事件数缩放。慢推理模型(GLM-5.3-Flash)+ 500 事件窗需要完整的 10 分钟余量;卡死的
882
- // fork 仍会在 10 分钟到点后被收掉。显式 maxWaitMs 调用原样生效(另见 requestHistoricalConsolidation)。
883
- test('the consolidation wait budget is a flat 600 s for the slow-reasoning window', () => {
884
- assert.equal(CONSOLIDATION_WAIT_POLICY.minMs, 600_000)
885
- assert.equal(CONSOLIDATION_WAIT_POLICY.maxMs, 600_000)
886
- assert.equal(consolidationWaitBudget(0), 600_000, 'an empty range still gets the full budget')
887
- assert.equal(consolidationWaitBudget(100), 600_000, 'small sessions get the full ten minutes')
888
- assert.equal(consolidationWaitBudget(935), 600_000, 'the session that timed out gets the full ten minutes')
889
- assert.equal(consolidationWaitBudget(5_000), 600_000, 'a wedged fork still dies inside ten minutes')
890
- assert.equal(consolidationWaitBudget(undefined), 600_000)
891
- assert.equal(consolidationWaitBudget('not-a-number'), 600_000)
892
- assert.ok(CONSOLIDATION_WAIT_POLICY.minMs <= CONSOLIDATION_WAIT_POLICY.maxMs)
893
- })
894
-
895
- // ---------------------------------------------------------------- 整理 fork 的模型选择(三模式接线)
896
- // lib/fork-model.js 的解析与 route 生命周期在 fork-model.test.mjs 单测;这里钉住接线行为:
897
- // fork 真正拿到的 agentOptions、被拒时的 reasonCode、以及 inherit 模式与旧路径逐字节一致。
898
-
899
- function servingLlm() {
900
- const llm = {
901
- registerAdapter: (routes) => {
902
- const handle = () => {}
903
- handle.replace = () => {}
904
- return handle
905
- },
906
- listModels: async (provider) => [{ provider, id: 'any', name: 'route serves models', inputModalities: ['text'] }],
907
- }
908
- return llm
909
- }
910
-
911
- const CUSTOM = {
912
- consolidationModelMode: 'custom',
913
- consolidationCustomBaseURL: 'http://127.0.0.1:9100/v1',
914
- consolidationCustomModel: 'gateway-model',
915
- consolidationCustomApiKey: '',
916
- }
917
-
918
- function restoreSettings() {
919
- state.updateSettings({
920
- consolidationModelMode: 'inherit',
921
- consolidationModel: null,
922
- consolidationCustomBaseURL: '',
923
- consolidationCustomApiKey: '',
924
- consolidationCustomModel: '',
925
- consolidationCustomApi: 'openai-completions',
926
- })
927
- }
928
-
929
- test('custom mode puts the fork on the registered dsh-memu-custom route', async () => {
930
- state.updateSettings(CUSTOM)
931
- try {
932
- state.ensureSession('fork-mode-custom', { cwd: path.join(home, 'proj-mode-custom'), agentPreset: 'coding' })
933
- const ctx = host({ live: true, llm: servingLlm() })
934
- const result = await requestPrivateConsolidation(ctx, 'fork-mode-custom')
935
- assert.equal(result.ok, true, String(result.error || ''))
936
- assert.equal(result.settled, true)
937
- assert.equal(ctx.rec.created.length, 1)
938
- assert.deepEqual(ctx.rec.created[0].agentOptions, { provider: 'dsh-memu-custom', model: 'gateway-model' }, 'the fork names the plugin-owned custom route')
939
- const started = startedEntryFor(ctx, 'fork-mode-custom')
940
- assert.equal(started.detail.modelMode, 'custom')
941
- } finally {
942
- forkModel.disposeConsolidationRoute()
943
- restoreSettings()
944
- }
945
- })
946
-
947
- test('custom mode falls back to the inherited route when the host cannot serve the custom route', async () => {
948
- state.updateSettings(CUSTOM)
949
- try {
950
- state.ensureSession('fork-mode-fallback', { cwd: path.join(home, 'proj-mode-fallback'), agentPreset: 'coding' })
951
- // 没有 llm service 的宿主:custom 不可用,降级回父会话 route,整理照常完成。
952
- const ctx = host({ live: true, parentOptions: { provider: 'fallback-prov', model: 'fallback-model' } })
953
- const result = await requestPrivateConsolidation(ctx, 'fork-mode-fallback')
954
- assert.equal(result.ok, true, String(result.error || ''))
955
- assert.deepEqual(ctx.rec.created[0].agentOptions, { provider: 'fallback-prov', model: 'fallback-model' }, 'the fork falls back to the parent route instead of dying')
956
- const started = startedEntryFor(ctx, 'fork-mode-fallback')
957
- assert.equal(started.detail.modelMode, 'inherit-fallback')
958
- } finally {
959
- restoreSettings()
960
- }
961
- })
962
-
963
- test('custom mode without a usable custom route and without a parent route is refused', async () => {
964
- state.updateSettings(CUSTOM)
965
- try {
966
- state.ensureSession('fork-mode-custom-dead', { cwd: path.join(home, 'proj-mode-dead'), agentPreset: 'coding' })
967
- const ctx = host({ live: true, parentOptions: null })
968
- const result = await requestPrivateConsolidation(ctx, 'fork-mode-custom-dead')
969
- assert.equal(result.ok, false)
970
- assert.equal(result.reasonCode, 'custom-route-unavailable')
971
- assert.match(result.error, /custom consolidation route is unavailable/)
972
- assert.equal(ctx.rec.created.length, 0)
973
- } finally {
974
- restoreSettings()
975
- }
976
- })
977
-
978
- test('host mode resolves consolidationModel the same way the curator does', async () => {
979
- state.updateSettings({ consolidationModelMode: 'host', consolidationModel: 'host-prov/host-model/nested' })
980
- try {
981
- state.ensureSession('fork-mode-host', { cwd: path.join(home, 'proj-mode-host'), agentPreset: 'coding' })
982
- const ctx = host({ live: true, parentOptions: { provider: 'other', model: 'other-model' } })
983
- const result = await requestPrivateConsolidation(ctx, 'fork-mode-host')
984
- assert.equal(result.ok, true, String(result.error || ''))
985
- assert.deepEqual(ctx.rec.created[0].agentOptions, { provider: 'host-prov', model: 'host-model/nested' }, 'everything after the first slash is the model id')
986
- assert.equal(startedEntryFor(ctx, 'fork-mode-host').detail.modelMode, 'host')
987
- } finally {
988
- restoreSettings()
989
- }
990
- })
991
-
992
- test('a bad host consolidationModel is refused with its own reason, not the parent one', async () => {
993
- state.updateSettings({ consolidationModelMode: 'host', consolidationModel: 'no-slash' })
994
- try {
995
- state.ensureSession('fork-mode-host-bad', { cwd: path.join(home, 'proj-mode-host-bad'), agentPreset: 'coding' })
996
- const ctx = host({ live: true })
997
- const result = await requestPrivateConsolidation(ctx, 'fork-mode-host-bad')
998
- assert.equal(result.ok, false)
999
- assert.equal(result.reasonCode, 'invalid-consolidation-model')
1000
- assert.match(result.error, /consolidation model \(/, 'the new reasons name the bad configuration face, not the parent route')
1001
- assert.equal(ctx.rec.created.length, 0)
1002
- } finally {
1003
- restoreSettings()
1004
- }
1005
- })
1006
-
1007
- test('compactSeedEvents accepts the catalog and local recall as two read-only preludes', () => {
1008
- const user = {
1009
- seq: 10,
1010
- type: 'user/message',
1011
- time: 1,
1012
- sceneTime: '2026-11-06T04:00:00+08:00',
1013
- data: { source: { kind: 'user' }, content: [{ type: 'text', text: '明天码头见' }] },
1014
- }
1015
- const catalog = {
1016
- seq: 0,
1017
- type: 'user/message',
1018
- time: 1,
1019
- data: { source: { kind: 'plugin:dsh-memu-memory', form: 'notice', summary: 'memory-catalog' }, content: [{ type: 'text', text: '[memory-catalog]' }] },
1020
- }
1021
- const recall = {
1022
- seq: 0,
1023
- type: 'user/message',
1024
- time: 1,
1025
- data: { source: { kind: 'plugin:dsh-memu-memory', form: 'notice', summary: 'memory-recall' }, content: [{ type: 'text', text: '[memory-recall] [mem-1] 码头' }] },
1026
- }
1027
- const seed = compactSeedEvents([user], [catalog, recall])
1028
- assert.equal(seed.length, 3)
1029
- assert.deepEqual(seed.map((event) => event.seq), [0, 1, 2])
1030
- assert.equal(seed[0].data.source.summary, 'memory-catalog')
1031
- assert.equal(seed[1].data.source.summary, 'memory-recall')
1032
- assert.equal(seed[2].type, 'user/message')
1033
- assert.match(seed[2].data.content[0].text, /事件时间/)
1034
- })
1035
-
1036
- // ------------------------------------------------------- surface replacements
1037
- // Mirrors @deepseek-ai/dsh-session 0.2.2-rc.1 Session.create for the fields a
1038
- // consolidation seed touches: seq contiguity plus the surface fold. The host
1039
- // rejects "seed event at index N has seq M" and every dangling replace citation,
1040
- // so the assertion has to replay the fold, not just look at one event.
1041
- const HOST_SURFACE_EVENT_TYPES = new Set(['system/message', 'developer/message', 'user/message', 'assistant/message', 'tool/result'])
1042
- function assertSeedAcceptedByHost(seed, label = 'seed') {
1043
- const nodes = []
1044
- seed.forEach((event, index) => {
1045
- assert.equal(event.seq, index, `${label}: event at index ${index} has seq ${event.seq}`)
1046
- if (!HOST_SURFACE_EVENT_TYPES.has(event.type)) {
1047
- assert.equal(event.surfaceOp, undefined, `${label}: ${event.type} cannot carry surfaceOp`)
1048
- assert.equal(event.sourceEventSeqs, undefined, `${label}: ${event.type} cannot carry sourceEventSeqs`)
1049
- return
1050
- }
1051
- const op = event.surfaceOp
1052
- assert.ok(op !== undefined, `${label}: ${event.type} at ${index} requires a surfaceOp marker`)
1053
- const sources = event.sourceEventSeqs
1054
- if (sources !== undefined) {
1055
- assert.ok(Array.isArray(sources) && sources.length > 0, `${label}: sourceEventSeqs must be a non-empty array`)
1056
- assert.equal(new Set(sources).size, sources.length, `${label}: sourceEventSeqs must not repeat`)
1057
- assert.ok(sources.every(seq => Number.isSafeInteger(seq) && seq < event.seq), `${label}: sourceEventSeqs must reference earlier events`)
1058
- }
1059
- if (op === 'append') {
1060
- nodes.push(event.seq)
1061
- return
1062
- }
1063
- assert.deepEqual(Object.keys(op).sort(), ['endSeq', 'op', 'startSeq'], `${label}: replace markers carry exactly op/startSeq/endSeq`)
1064
- assert.ok(op.startSeq < event.seq && op.endSeq < event.seq, `${label}: surface replace at ${index} must reference earlier events`)
1065
- const startIdx = nodes.indexOf(op.startSeq)
1066
- const endIdx = nodes.indexOf(op.endSeq)
1067
- assert.ok(startIdx >= 0, `${label}: replace start seq ${op.startSeq} is not on the surface`)
1068
- assert.ok(endIdx >= startIdx, `${label}: replace range must be ordered`)
1069
- const shadowed = nodes.slice(startIdx, endIdx + 1)
1070
- if (event.type === 'tool/result') assert.equal(shadowed.length, 1, `${label}: tool/result replacement rewrites exactly one node`)
1071
- assert.ok(Array.isArray(sources), `${label}: replace at ${index} needs sourceEventSeqs`)
1072
- assert.deepEqual(shadowed.filter(seq => !sources.includes(seq)), [], `${label}: replace at ${index} must cite every shadowed node`)
1073
- nodes.splice(startIdx, endIdx - startIdx + 1)
1074
- nodes.push(event.seq)
1075
- })
1076
- }
1077
-
1078
- const userEvent = (seq, text, extra = {}) => ({
1079
- seq, type: 'user/message', surfaceOp: 'append',
1080
- data: { source: { kind: 'user' }, content: [{ type: 'text', text }] }, ...extra,
1081
- })
1082
- const assistantEvent = (seq, text) => ({
1083
- seq, type: 'assistant/message', surfaceOp: 'append',
1084
- data: { message: { content: [{ type: 'text', text }] } },
1085
- })
1086
- const toolResultEvent = (seq, text, extra = {}) => ({
1087
- seq, type: 'tool/result', surfaceOp: 'append',
1088
- data: { message: { content: [{ type: 'text', text }] } }, ...extra,
1089
- })
1090
-
1091
- test('a surface replace is renumbered into the seed instead of citing original seqs', () => {
1092
- const seed = compactSeedEvents([
1093
- userEvent(0, '记住:周五交房租'),
1094
- assistantEvent(1, '好'),
1095
- toolResultEvent(2, '原始工具输出'),
1096
- toolResultEvent(3, '[已裁剪]', {
1097
- surfaceOp: { op: 'replace', startSeq: 2, endSeq: 2 },
1098
- sourceEventSeqs: [2],
1099
- }),
1100
- userEvent(4, '继续'),
1101
- ])
1102
- assert.deepEqual(seed.map(event => event.seq), [0, 1, 2, 3, 4])
1103
- assert.deepEqual(seed[3].surfaceOp, { op: 'replace', startSeq: 2, endSeq: 2 }, 'the citation follows the surviving node, not its original seq')
1104
- assert.deepEqual(seed[3].sourceEventSeqs, [2])
1105
- assertSeedAcceptedByHost(seed)
1106
- })
1107
-
1108
- test('a replace pointing outside the window is dropped and the seed stays contiguous', () => {
1109
- // 窗口从父会话中间切出:seq 4 不在这一窗里;后面的 replace 又引用前面被丢的
1110
- // replace。旧实现先编号后丢弃,留下 seq 空洞,宿主报 index 1 has seq 5。
1111
- const seed = compactSeedEvents([
1112
- userEvent(10, '这一窗的第一句'),
1113
- toolResultEvent(11, '输出'),
1114
- toolResultEvent(12, '[已裁剪]', {
1115
- surfaceOp: { op: 'replace', startSeq: 4, endSeq: 4 },
1116
- sourceEventSeqs: [4],
1117
- }),
1118
- assistantEvent(13, '回答'),
1119
- toolResultEvent(14, '[已裁剪]', {
1120
- surfaceOp: { op: 'replace', startSeq: 12, endSeq: 12 },
1121
- sourceEventSeqs: [12],
1122
- }),
1123
- ])
1124
- assert.deepEqual(seed.map(event => event.seq), [0, 1, 2], 'dropping a patch must renumber the survivors')
1125
- assert.equal(seed.some(event => event.surfaceOp && typeof event.surfaceOp === 'object'), false)
1126
- assertSeedAcceptedByHost(seed)
1127
- })
1128
-
1129
- test('a replacement that cites another replacement keeps both when their targets survive', () => {
1130
- const seed = compactSeedEvents([
1131
- userEvent(0, '开头'),
1132
- toolResultEvent(1, '原始输出'),
1133
- toolResultEvent(2, '[第一次裁剪]', {
1134
- surfaceOp: { op: 'replace', startSeq: 1, endSeq: 1 },
1135
- sourceEventSeqs: [1],
1136
- }),
1137
- assistantEvent(3, '中间'),
1138
- toolResultEvent(4, '[第二次裁剪]', {
1139
- surfaceOp: { op: 'replace', startSeq: 2, endSeq: 2 },
1140
- sourceEventSeqs: [2],
1141
- }),
1142
- ])
1143
- assert.deepEqual(seed.map(event => event.seq), [0, 1, 2, 3, 4])
1144
- assert.deepEqual(seed[2].surfaceOp, { op: 'replace', startSeq: 1, endSeq: 1 })
1145
- assert.deepEqual(seed[4].surfaceOp, { op: 'replace', startSeq: 2, endSeq: 2 })
1146
- assertSeedAcceptedByHost(seed)
1147
- })
1148
-
1149
- test('a multi-node replace is remapped when every shadowed node survives', () => {
1150
- const seed = compactSeedEvents([
1151
- userEvent(0, 'A'),
1152
- userEvent(1, 'X'),
1153
- userEvent(2, 'B'),
1154
- userEvent(3, '外层摘要', {
1155
- surfaceOp: { op: 'replace', startSeq: 0, endSeq: 2 },
1156
- sourceEventSeqs: [0, 1, 2],
1157
- }),
1158
- ])
1159
- assert.deepEqual(seed.map(event => event.seq), [0, 1, 2, 3])
1160
- assert.deepEqual(seed[3].surfaceOp, { op: 'replace', startSeq: 0, endSeq: 2 })
1161
- assert.deepEqual(seed[3].sourceEventSeqs, [0, 1, 2])
1162
- assertSeedAcceptedByHost(seed)
1163
- })
1164
-
1165
- test('a replace is dropped when filtering an inner checkpoint reveals a shadowed node', () => {
1166
- // 内层压缩检查点(source.kind 不是 user)会被种子过滤器丢掉;它遮住的 X 因此
1167
- // 重新出现在种子的 surface 上。外层替换写于 X 被遮住期间,引用里没有 X。
1168
- // 宿主会要求外层补上 X 的引用——补不出来就只能丢外层,种子回到纯 append。
1169
- const seed = compactSeedEvents([
1170
- userEvent(0, 'A'),
1171
- userEvent(1, 'X'),
1172
- userEvent(2, 'B'),
1173
- userEvent(3, '内层摘要', { data: { source: { kind: 'compact-checkpoint' }, content: [{ type: 'text', text: '内层摘要' }] }, surfaceOp: { op: 'replace', startSeq: 1, endSeq: 1 }, sourceEventSeqs: [1] }),
1174
- userEvent(4, '外层摘要', {
1175
- surfaceOp: { op: 'replace', startSeq: 0, endSeq: 2 },
1176
- sourceEventSeqs: [0, 2],
1177
- }),
1178
- ])
1179
- assert.deepEqual(seed.map(event => event.seq), [0, 1, 2])
1180
- assert.deepEqual(seed.map(event => event.data.content[0].text), ['A', 'X', 'B'])
1181
- assertSeedAcceptedByHost(seed)
1182
- })
1183
-
1184
-
1185
- // 2026-11-15 扫雷守卫:整理思考强度被模型拒绝 → 学习组合 → 清失败连击 → 下次 fork 不带档。
1186
- // 现场:wb/glm-5.3-flash 不支持 medium,fork 回合起点即失败,同快照 2 次后被冻结数天。
1187
- function rejectMedium(spec) {
1188
- const { provider, model, reasoningEffort } = spec.agentOptions
1189
- return reasoningEffort === 'medium'
1190
- ? { kind: 'error', error: { message: `provider "${provider}" model "${model}" does not support reasoning effort "medium"` } }
1191
- : { kind: 'completed' }
1192
- }
1193
-
1194
- function cleanupEffortHost(t, ctx, sessionId) {
1195
- t.after(async () => {
1196
- const forkId = state.getSessionBinding(sessionId)?.workerEpoch?.forkSessionId
1197
- if (forkId) await retireWorker(ctx, forkId, 'test-finished', { handoff: false })
1198
- state.updateSettings({ consolidationRunner: 'fork', consolidationReasoningEffort: 'inherit' })
1199
- restoreSettings()
1200
- })
1201
- }
1202
-
1203
- for (const runner of ['fork', 'worker']) {
1204
- for (const mode of ['inherit', 'custom']) {
1205
- for (const effort of ['inherit', 'medium']) {
1206
- test(`${runner} learns inherited medium with ${mode} route / ${effort} setting and really succeeds on retry`, async (t) => {
1207
- const id = `effort-${runner}-${mode}-${effort}`
1208
- const parentOptions = Object.freeze({ provider: id, model: 'test-model', reasoningEffort: 'medium', maxTokens: 32768 })
1209
- const key = `${id}|test-model|medium`
1210
- const ctx = host({ live: true, parentOptions, turnReason: rejectMedium })
1211
- ctx.permissionPresets = { set: t.mock.fn() }
1212
- cleanupEffortHost(t, ctx, id)
1213
- state.updateSettings({ ...(mode === 'custom' ? CUSTOM : {}), consolidationRunner: runner, consolidationReasoningEffort: effort })
1214
- state.ensureSession(id, { cwd: home, agentPreset: 'coding' })
1215
- assert.equal(effortRefusalOf(rejectMedium({ agentOptions: parentOptions }).error.message).key, key)
1216
- assert.equal(isEffortRefused(key), false)
1217
-
1218
- const first = await requestPrivateConsolidation(ctx, id, { force: true })
1219
- assert.equal(first.ok, false)
1220
- assert.equal(first.reasonCode, 'fork-turn-failed')
1221
- assert.equal(state.getSessionBinding(id).lastSleepSeq, undefined)
1222
- assert.equal(isEffortRefused(key), true)
1223
- assert.deepEqual(ctx.rec.created[0].agentOptions, parentOptions)
1224
- assert.ok(ctx.rec.disposed.includes(first.childId), 'the failed child was retired')
1225
- assert.equal(state.getSessionBinding(first.childId), null, 'the failed child binding was removed')
1226
- if (runner === 'worker') assert.equal(state.getSessionBinding(id).workerEpoch ?? null, null)
1227
- if (mode === 'custom') assert.equal(startedEntryFor(ctx, id).detail.modelMode, 'inherit-fallback')
1228
-
1229
- const second = await requestPrivateConsolidation(ctx, id)
1230
- assert.equal(second.skipped, undefined, 'the automatic retry is not frozen')
1231
- assert.equal(second.ok, true, second.error || '')
1232
- assert.equal(second.settled, true, 'the parameter-dependent host completed and its receipt settled')
1233
- assert.equal(state.getSessionBinding(id).lastSleepSeq, 2)
1234
- assert.equal(ctx.rec.created.length, 2, 'retry really creates a fresh child')
1235
- assert.notEqual(second.childId, first.childId)
1236
- const secondOptions = ctx.rec.created[1].agentOptions
1237
- assert.equal(Object.hasOwn(secondOptions, 'reasoningEffort'), false)
1238
- assert.deepEqual(secondOptions, { provider: id, model: 'test-model', maxTokens: 32768 })
1239
- assert.equal(ctx.get('agents').get(id).options, parentOptions, 'the parent object is not replaced')
1240
- assert.equal(parentOptions.reasoningEffort, 'medium', 'the parent effort is untouched')
1241
- assert.equal(ctx.permissionPresets.set.mock.callCount(), 0, 'no automatic permission elevation')
1242
- })
1243
- }
1244
- }
1245
-
1246
- test(`${runner} applies an allowed explicit effort after custom fallback and checks only the effective route`, async (t) => {
1247
- const id = `effort-override-${runner}`
1248
- const parentOptions = Object.freeze({ provider: id, model: 'model', reasoningEffort: 'medium', maxTokens: 4096 })
1249
- const ctx = host({ live: true, parentOptions, turnReason: rejectMedium })
1250
- cleanupEffortHost(t, ctx, id)
1251
- state.updateSettings({ ...CUSTOM, consolidationRunner: runner, consolidationReasoningEffort: 'high' })
1252
- state.ensureSession(id, { cwd: home, agentPreset: 'coding' })
1253
- markEffortRefused(`${id}|model|medium`)
1254
- markEffortRefused('dsh-memu-custom|gateway-model|high')
1255
- const result = await requestPrivateConsolidation(ctx, id, { force: true })
1256
- assert.equal(result.ok, true, result.error || '')
1257
- assert.equal(result.settled, true)
1258
- assert.equal(startedEntryFor(ctx, id).detail.modelMode, 'inherit-fallback')
1259
- assert.deepEqual(ctx.rec.created[0].agentOptions, { ...parentOptions, reasoningEffort: 'high' })
1260
- assert.equal(parentOptions.reasoningEffort, 'medium')
1261
- })
1262
- }
1263
-
1264
- test('a fresh worker shares the refusal learned by a fork', async (t) => {
1265
- const parentOptions = Object.freeze({ provider: 'shared-effort', model: 'model', reasoningEffort: 'medium', maxTokens: 8192 })
1266
- const ctx = host({ live: true, parentOptions, turnReason: rejectMedium })
1267
- cleanupEffortHost(t, ctx, 'effort-shared-worker')
1268
- state.updateSettings({ consolidationRunner: 'fork', consolidationReasoningEffort: 'inherit' })
1269
- state.ensureSession('effort-shared-fork', { cwd: home, agentPreset: 'coding' })
1270
- const failed = await requestPrivateConsolidation(ctx, 'effort-shared-fork', { force: true })
1271
- assert.equal(failed.reasonCode, 'fork-turn-failed')
1272
- state.updateSettings({ consolidationRunner: 'worker' })
1273
- state.ensureSession('effort-shared-worker', { cwd: home, agentPreset: 'coding' })
1274
- const result = await requestPrivateConsolidation(ctx, 'effort-shared-worker', { force: true })
1275
- assert.equal(result.ok, true, result.error || '')
1276
- assert.equal(result.settled, true)
1277
- assert.match(result.childId, /^memu-worker-/)
1278
- assert.deepEqual(ctx.rec.created[1].agentOptions, { provider: 'shared-effort', model: 'model', maxTokens: 8192 })
1279
- assert.equal(parentOptions.reasoningEffort, 'medium')
1280
- })
1281
-
1282
- // 2026-11-18:学习表持久化。反代服务商签名各异(raccoon/sn-deepseek-v4-1-flash-1017
1283
- // 拒 medium 实测),表只在内存时每次重启后的第一次整理都要再吃一次 fork-turn-failed。
1284
- test('a learned effort refusal survives a restart — it is persisted to the data dir', async (t) => {
1285
- state.updateSettings({ consolidationReasoningEffort: 'medium' })
1286
- state.ensureSession('fork-effort-persist', { cwd: path.join(home, 'proj-effort-persist'), agentPreset: 'coding' })
1287
- const ctx = host({ live: true, parentOptions: { provider: 'persist-provider', model: 'persist-model' }, turnReason: rejectMedium })
1288
- cleanupEffortHost(t, ctx, 'fork-effort-persist')
1289
- const first = await requestPrivateConsolidation(ctx, 'fork-effort-persist', { force: true })
1290
- assert.equal(first.ok, false)
1291
- assert.equal(first.reasonCode, 'fork-turn-failed')
1292
-
1293
- const persisted = JSON.parse(fs.readFileSync(path.join(dataDir(), 'effort-refusals.json'), 'utf8'))
1294
- assert.ok(persisted.keys.includes('persist-provider|persist-model|medium'), 'the refusal was written to the data dir')
1295
- const child = effortChild(t, home, `assert.equal(api.isEffortRefused('persist-provider|persist-model|medium'), true)`)
1296
- await child.ready
1297
- child.release()
1298
- await child.done
1299
- })
1300
-
1301
- // 子进程只加载测试 loader + private.js,home/cwd 全部指向临时目录。
1302
- // IPC 屏障保证并发用例里的两个进程先各自读完旧表,再同时开始 mark。
1303
- function effortChild(t, dir, before, after = '') {
1304
- const code = `
1305
- import assert from 'node:assert/strict'
1306
- const api = await import(${JSON.stringify(new URL('../lib/private.js', import.meta.url).href)})
1307
- ${before}
1308
- const released = new Promise(resolve => process.once('message', resolve))
1309
- process.send('loaded')
1310
- await released
1311
- ${after}
1312
- process.disconnect()
1313
- `
1314
- const child = spawn(process.execPath, ['--import', new URL('./loader-register.mjs', import.meta.url).href, '--input-type=module', '-e', code], {
1315
- cwd: dir, windowsHide: true, timeout: 20_000,
1316
- env: { ...process.env, DSH_HOME: dir, DSH_MEMU_HOME: dir, DSH_MEMU_MEMORY_HOME: dir },
1317
- stdio: ['ignore', 'pipe', 'pipe', 'ipc'],
1318
- })
1319
- let errors = ''
1320
- child.stdout.on('data', data => { errors += data })
1321
- child.stderr.on('data', data => { errors += data })
1322
- const ready = new Promise((resolve, reject) => {
1323
- child.on('message', message => { if (message === 'loaded') resolve() })
1324
- child.on('error', reject)
1325
- child.on('close', () => reject(new Error('child exited before barrier: ' + errors)))
1326
- })
1327
- const done = new Promise((resolve, reject) => {
1328
- child.on('error', reject)
1329
- child.on('close', code => code === 0 ? resolve() : reject(new Error('effort child failed: ' + errors)))
1330
- })
1331
- // 在等待另一个进程抵达屏障时也接住早退;原 promise 仍供断言 await。
1332
- ready.catch(() => {})
1333
- done.catch(() => {})
1334
- t.after(() => { if (child.exitCode === null) child.kill() })
1335
- return { ready, done, release: () => child.send('mark') }
1336
- }
1337
-
1338
- function refusalStore(t) {
1339
- state.flushState()
1340
- const dir = fs.mkdtempSync(path.join(home, 'effort-store-'))
1341
- const previous = [process.env.DSH_MEMU_HOME, process.env.DSH_MEMU_MEMORY_HOME]
1342
- process.env.DSH_MEMU_HOME = process.env.DSH_MEMU_MEMORY_HOME = dir
1343
- const warnings = []
1344
- setWarnSink(message => warnings.push(message))
1345
- t.after(() => {
1346
- ;[process.env.DSH_MEMU_HOME, process.env.DSH_MEMU_MEMORY_HOME] = previous
1347
- setWarnSink(null)
1348
- })
1349
- return { dir, file: path.join(dir, 'effort-refusals.json'), warnings }
1350
- }
1351
-
1352
- function seedRefusals(file, keys) {
1353
- const raw = JSON.stringify({ version: 1, keys })
1354
- fs.writeFileSync(file, raw)
1355
- return raw
1356
- }
1357
-
1358
- function refusalKeys(file) {
1359
- return JSON.parse(fs.readFileSync(file, 'utf8')).keys.sort()
1360
- }
1361
-
1362
- test('refusals load lazily once and clean queries/duplicate marks perform no file IO', async (t) => {
1363
- const { file } = refusalStore(t)
1364
- seedRefusals(file, ['initial|model|medium'])
1365
- const read = t.mock.method(fs, 'readFileSync')
1366
- const write = t.mock.method(fs, 'writeFileSync')
1367
- const fresh = await import('../lib/private.js?effort-lazy')
1368
- const tableReads = () => read.mock.calls.filter(call => call.arguments[0] === file).length
1369
- assert.equal(tableReads(), 0, 'import does not capture or read a home')
1370
- assert.equal(fresh.isEffortRefused('initial|model|medium'), true)
1371
- assert.equal(tableReads(), 1)
1372
- for (let i = 0; i < 20; i++) {
1373
- assert.equal(fresh.isEffortRefused('initial|model|medium'), true)
1374
- assert.equal(fresh.isEffortRefused('unknown|model|medium'), false)
1375
- fresh.markEffortRefused('initial|model|medium')
1376
- }
1377
- assert.equal(tableReads(), 1, 'a clean cache never rescans the table')
1378
- assert.equal(write.mock.callCount(), 0, 'queries and duplicate clean marks never rewrite the table')
1379
- })
1380
-
1381
- test('a failed initial read never replaces old keys and retries after IO recovers', (t) => {
1382
- const { file, warnings } = refusalStore(t)
1383
- const original = seedRefusals(file, ['old|model|medium'])
1384
- const read = fs.readFileSync
1385
- let failing = true
1386
- t.mock.method(fs, 'readFileSync', function (target, ...args) {
1387
- if (target === file && failing) throw Object.assign(new Error('read failed api_key=secret123456789'), { code: 'EIO' })
1388
- return read.call(this, target, ...args)
1389
- })
1390
- assert.equal(isEffortRefused('old|model|medium'), false, 'an unreadable key is not yet known')
1391
- markEffortRefused('new|model|medium')
1392
- assert.equal(isEffortRefused('new|model|medium'), true, 'new knowledge survives the failed read')
1393
- assert.equal(read(file, 'utf8'), original, 'read failure cannot be saved back as an empty table')
1394
- assert.ok(warnings.length > 0)
1395
- assert.ok(warnings.every(message => !message.includes('secret123456789')), 'warnings use the existing redaction sink')
1396
- failing = false
1397
- assert.equal(isEffortRefused('old|model|medium'), true, 'the query retries the pending merge')
1398
- assert.deepEqual(refusalKeys(file), ['new|model|medium', 'old|model|medium'])
1399
- })
1400
-
1401
- for (const retry of ['same-key mark', 'query']) {
1402
- test(`an atomic write failure keeps pending keys and recovers on ${retry}`, (t) => {
1403
- const { dir, file, warnings } = refusalStore(t)
1404
- const original = seedRefusals(file, ['old|model|medium'])
1405
- assert.equal(isEffortRefused('old|model|medium'), true)
1406
- const rename = fs.renameSync
1407
- let failing = true
1408
- t.mock.method(fs, 'renameSync', function (from, to) {
1409
- if (to === file && failing) throw Object.assign(new Error('injected rename failure'), { code: 'EIO' })
1410
- return rename.call(this, from, to)
1411
- })
1412
- markEffortRefused('new|model|medium')
1413
- assert.equal(isEffortRefused('new|model|medium'), true)
1414
- assert.equal(fs.readFileSync(file, 'utf8'), original, 'failed atomic replace preserves the previous bytes')
1415
- assert.deepEqual(fs.readdirSync(dir), ['effort-refusals.json'], 'temporary files and locks are cleaned')
1416
- assert.ok(warnings.some(message => message.includes('injected rename failure')))
1417
- failing = false
1418
- if (retry === 'same-key mark') markEffortRefused('new|model|medium')
1419
- else assert.equal(isEffortRefused('old|model|medium'), true, 'even an unrelated lookup flushes pending knowledge')
1420
- assert.deepEqual(refusalKeys(file), ['new|model|medium', 'old|model|medium'])
1421
- const reads = t.mock.method(fs, 'readFileSync')
1422
- const writes = t.mock.method(fs, 'writeFileSync')
1423
- isEffortRefused('new|model|medium')
1424
- markEffortRefused('new|model|medium')
1425
- assert.equal(reads.mock.callCount(), 0, 'successful recovery clears the pending state')
1426
- assert.equal(writes.mock.callCount(), 0)
1427
- })
1428
- }
1429
-
1430
- for (const [label, raw] of [
1431
- ['broken JSON', '{"version":1,"keys":['],
1432
- ['invalid keys', JSON.stringify({ version: 1, keys: [123] })],
1433
- ['unknown schema', JSON.stringify({ version: 2, keys: [] })],
1434
- ]) {
1435
- test(`${label} is never overwritten, and pending knowledge merges after repair`, (t) => {
1436
- const { file, warnings } = refusalStore(t)
1437
- fs.writeFileSync(file, raw)
1438
- assert.equal(isEffortRefused('pending|model|medium'), false)
1439
- markEffortRefused('pending|model|medium')
1440
- assert.equal(isEffortRefused('pending|model|medium'), true)
1441
- assert.equal(fs.readFileSync(file, 'utf8'), raw)
1442
- assert.ok(warnings.length > 0)
1443
- seedRefusals(file, ['restored|model|high'])
1444
- assert.equal(isEffortRefused('restored|model|high'), true)
1445
- assert.deepEqual(refusalKeys(file), ['pending|model|medium', 'restored|model|high'])
1446
- })
1447
- }
1448
-
1449
- test('refusal caches and writes follow the current home without leaking keys', (t) => {
1450
- const { file: firstFile } = refusalStore(t)
1451
- assert.equal(isEffortRefused('first|model|medium'), false, 'ENOENT starts an empty table')
1452
- markEffortRefused('first|model|medium')
1453
- const secondDir = fs.mkdtempSync(path.join(home, 'effort-other-'))
1454
- const secondFile = path.join(secondDir, 'effort-refusals.json')
1455
- seedRefusals(secondFile, ['second|model|high'])
1456
- process.env.DSH_MEMU_HOME = process.env.DSH_MEMU_MEMORY_HOME = secondDir
1457
- assert.equal(isEffortRefused('first|model|medium'), false)
1458
- assert.equal(isEffortRefused('second|model|high'), true)
1459
- markEffortRefused('second|model|medium')
1460
- process.env.DSH_MEMU_HOME = process.env.DSH_MEMU_MEMORY_HOME = path.dirname(firstFile)
1461
- assert.equal(isEffortRefused('first|model|medium'), true)
1462
- assert.equal(isEffortRefused('second|model|medium'), false)
1463
- assert.deepEqual(refusalKeys(firstFile), ['first|model|medium'])
1464
- assert.deepEqual(refusalKeys(secondFile), ['second|model|high', 'second|model|medium'])
1465
- })
1466
-
1467
- test('two processes merge stale refusal snapshots under the file lock', async (t) => {
1468
- const { dir, file } = refusalStore(t)
1469
- seedRefusals(file, ['old|model|medium'])
1470
- const children = ['left', 'right'].map(name => effortChild(t, dir,
1471
- `assert.equal(api.isEffortRefused('old|model|medium'), true)`,
1472
- `api.markEffortRefused('${name}|model|medium'); assert.equal(api.isEffortRefused('${name}|model|medium'), true)`,
1473
- ))
1474
- await Promise.all(children.map(child => child.ready))
1475
- for (const child of children) child.release()
1476
- await Promise.all(children.map(child => child.done))
1477
- assert.deepEqual(refusalKeys(file), ['left|model|medium', 'old|model|medium', 'right|model|medium'])
1478
- })
1479
-
1480
- test('missing buildForkSeed only disables fork; worker really completes without loading the seed API', async (t) => {
1481
- const dir = fs.mkdtempSync(path.join(home, 'missing-seed-'))
1482
- const before = `
1483
- const { registerHooks } = await import('node:module')
1484
- let seedImports = 0
1485
- const hooks = registerHooks({ resolve(specifier, context, next) {
1486
- if (specifier === '@deepseek-ai/dsh-session') {
1487
- seedImports++
1488
- return { url: 'data:text/javascript,export const unavailable = true', shortCircuit: true }
1489
- }
1490
- return next(specifier, context)
1491
- } })
1492
- const state = await import(${JSON.stringify(new URL('../lib/state.js', import.meta.url).href)})
1493
- const home = ${JSON.stringify(dir)}
1494
- const META_KEYS = ${JSON.stringify(META_KEYS)}
1495
- const assertHostCreateAccepts = ${assertHostCreateAccepts.toString()}
1496
- const host = ${host.toString()}
1497
- const ctx = host({ live: true, cwd: home })
1498
- state.ensureSession('missing-seed-fork', { cwd: home, agentPreset: 'coding' })
1499
- state.updateSettings({ consolidationRunner: 'fork', consolidationReasoningEffort: 'inherit' })
1500
- const fork = await api.requestPrivateConsolidation(ctx, 'missing-seed-fork', { force: true })
1501
- assert.equal(fork.reasonCode, 'no-fork-seed')
1502
- assert.equal(fork.settled, false)
1503
- assert.equal(ctx.rec.created.length, 0)
1504
- const afterFork = seedImports
1505
- state.ensureSession('missing-seed-worker', { cwd: home, agentPreset: 'coding' })
1506
- state.updateSettings({ consolidationRunner: 'worker' })
1507
- const worker = await api.requestPrivateConsolidation(ctx, 'missing-seed-worker', { force: true })
1508
- assert.equal(worker.ok, true, worker.error || '')
1509
- assert.equal(worker.settled, true)
1510
- assert.equal(ctx.rec.created.length, 1)
1511
- assert.equal(ctx.rec.created[0].seed, undefined)
1512
- assert.equal(state.getSessionBinding('missing-seed-worker').lastSleepSeq, 2)
1513
- assert.equal(seedImports, afterFork, 'worker never imports the missing seed API')
1514
- hooks.deregister()
1515
- `
1516
- const child = effortChild(t, dir, before)
1517
- await child.ready
1518
- child.release()
1519
- await child.done
1520
- })
1521
-
1522
- test('coding seeds keep more tool output and arguments than the default caps', () => {
1523
- const events = [
1524
- { seq: 0, type: 'user/message', data: { source: { kind: 'user' }, content: [{ type: 'text', text: '改代码' }] } },
1525
- { seq: 1, type: 'tool/call', data: { callId: 'c1', name: 'edit', arguments: '{"patch":"' + 'A'.repeat(1500) + '"}' } },
1526
- { seq: 2, type: 'tool/result', data: { message: { callId: 'c1', content: [{ type: 'text', text: 'R'.repeat(3000) }] } } },
1527
- { seq: 3, type: 'assistant/message', data: { message: { content: [{ type: 'text', text: '完成' }] } } },
1528
- ]
1529
- const sizes = (seed) => ({
1530
- args: String(seed.find((event) => event.type === 'tool/call').data.arguments).length,
1531
- result: String(seed.find((event) => event.type === 'tool/result').data.message.content[0].text).length,
1532
- })
1533
- const plain = sizes(compactSeedEvents(events))
1534
- const coding = sizes(compactSeedEvents(events, null, seedLimitsFor('coding')))
1535
- assert.ok(plain.args <= 510, 'the default argument cap is unchanged')
1536
- assert.ok(coding.args > 1000, 'coding keeps a longer tool-call argument body')
1537
- assert.ok(plain.result <= 1110, 'the default result cap is unchanged')
1538
- assert.ok(coding.result > 2100 && coding.result < 2300, 'coding keeps 2200 chars of the tool result')
1539
- })
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
+ import { spawn } from 'node:child_process'
7
+
8
+ const home = fs.mkdtempSync(path.join(os.tmpdir(), 'dsh-memu-memory-fork-'))
9
+ process.env.DSH_HOME = home
10
+ process.env.DSH_MEMU_HOME = home
11
+ process.env.DSH_MEMU_MEMORY_HOME = home
12
+
13
+ const state = await import('../lib/state.js')
14
+ const activity = await import('../lib/activity-log.js')
15
+ const ledger = await import('../lib/consolidation-ledger.js')
16
+ const forkModel = await import('../lib/fork-model.js')
17
+ const { dataDir, setWarnSink } = await import('../lib/paths.js')
18
+ const { retireWorker } = await import('../lib/worker-pool.js')
19
+ const { CORE_WRITE_TOOLS, WORKER_TOOL_ALLOW } = await import('../lib/consolidation-worker.js')
20
+ const { requestPrivateConsolidation, isConsolidating, consolidationWaitBudget, CONSOLIDATION_WAIT_POLICY, CONSOLIDATION_WINDOW_EVENTS, isEffortRefused, markEffortRefused, effortRefusalOf, compactSeedEvents, selectConsolidationWindow, selectTailTurnWindow, mustCoverCandidates, mergeMustCover, candidateCovered, seedLimitsFor } = await import('../lib/private.js')
21
+ // 这些用例验证“路由继承”,不是推理强度;默认 medium 由 config 测试单独覆盖。
22
+ state.updateSettings({ consolidationReasoningEffort: 'inherit' })
23
+
24
+ test.after(() => {
25
+ forkModel.disposeConsolidationRoute()
26
+ try { fs.rmSync(home, { recursive: true, force: true }) } catch {}
27
+ })
28
+
29
+ // The manual path (the sidebar button, RPC generatePrivate) shares one entry point
30
+ // with the idle sweep. Both now fork; neither may queue anything on the live agent,
31
+ // because a queued followup is what the host renders as a pending draft above the
32
+ // user's composer and what ends up as a permanent housekeeping turn in their chat.
33
+ // The host contract this plugin must satisfy, mirrored from the runtime:
34
+ // packages/core/session SessionStore.prepare() rebuilds a session header from a
35
+ // fixed meta whitelist and `Session` then throws "seeded session requires an
36
+ // inherited event count" when the count was not passed as a TOP-LEVEL option.
37
+ // The host drops an unknown meta key silently; this fake refuses it loudly, so a
38
+ // plugin that misplaces the field fails the test instead of dying in production.
39
+ const META_KEYS = ['cwd', 'parentSession', 'isSeeded', 'origin', 'delegationDepth', 'agentPreset']
40
+
41
+ function assertHostCreateAccepts(spec = {}) {
42
+ const meta = spec.meta ?? {}
43
+ const count = spec.inheritedEventCount
44
+ for (const key of Object.keys(meta)) {
45
+ if (!META_KEYS.includes(key)) {
46
+ throw new Error(`session meta "${key}" is not a header field: SessionStore.prepare() drops it`)
47
+ }
48
+ }
49
+ if (meta.isSeeded === true) {
50
+ if (spec.seed === undefined) throw new Error('seeded session requires an explicit constructor seed')
51
+ if (count === undefined) throw new Error('seeded session requires an inherited event count')
52
+ } else if (count !== undefined && count !== 0) {
53
+ throw new Error('unseeded session inherited event count must be 0')
54
+ }
55
+ // buildForkSeed() returns a seed object, not a bare array, so the length guard
56
+ // only applies to an array seed.
57
+ if (Array.isArray(spec.seed) && count !== undefined && count > spec.seed.length) {
58
+ throw new Error('session inherited event count exceeds its event log')
59
+ }
60
+ if (spec.agentOptions !== undefined) {
61
+ if (!spec.agentOptions || typeof spec.agentOptions.provider !== 'string' || typeof spec.agentOptions.model !== 'string') {
62
+ throw new Error('agentOptions must carry the parent provider and model')
63
+ }
64
+ }
65
+ }
66
+
67
+ function host({ live = false, whenIdle = null, parentOptions = { provider: 'test-provider', model: 'test-model' }, requestConfig = null, extraEvents = [], transcriptSize = 0, turnReason = { kind: 'completed' }, emitTurnEnd = true, headerTools = null, childCtxFactory = null, llm = null, presets = null, cwd = path.join(home, 'proj') } = {}) {
68
+ const rec = { liveFollowups: [], created: [], forkFollowups: [], disposed: [], sessionHandlers: [], workerToolRegistrations: [], workerToolDisposals: [], mountedPresets: [], forkLogLines: [] }
69
+ // agents.get 返回裸 agent;dispose 注销活句柄,但会话 id 仍在磁盘上占用。
70
+ const childAgents = new Map()
71
+ const tick = String.fromCharCode(96)
72
+ const receiptFence = (range, identity) => [tick + tick + tick + 'memu-consolidation-receipt', JSON.stringify({ version: 1, ...identity, status: 'completed', outcome: 'no_value', checkedRange: range, createdIds: [], updatedIds: [], heldIds: [], reasonCode: null, retryable: false }), tick + tick + tick].join('\n')
73
+ // 真实长会话的规模:补齐不产生证据的事件,只影响 fork 成本判定。
74
+ const padding = Math.max(0, transcriptSize - 3 - extraEvents.length)
75
+ const filler = Array.from({ length: padding }, (_, i) => ({ seq: 3 + extraEvents.length + i, type: 'todo/write', data: {} }))
76
+ const ctx = {
77
+ rec,
78
+ on: (name, handler) => {
79
+ if (name !== 'session/event') return () => {}
80
+ rec.sessionHandlers.push(handler)
81
+ return () => {
82
+ const index = rec.sessionHandlers.indexOf(handler)
83
+ if (index >= 0) rec.sessionHandlers.splice(index, 1)
84
+ }
85
+ },
86
+ get: (name) => {
87
+ if (name === 'agents') {
88
+ return {
89
+ get: (id) => {
90
+ if (childAgents.has(id)) return childAgents.get(id)
91
+ return (live
92
+ ? {
93
+ followup: (message) => rec.liveFollowups.push({ id, message }),
94
+ ...(parentOptions ? { options: parentOptions } : {}),
95
+ ...(requestConfig || headerTools ? { session: { requestHeader: () => ({
96
+ ...(requestConfig ? { config: requestConfig } : {}),
97
+ ...(headerTools ? { tools: headerTools.map((toolName) => ({ name: toolName })) } : {}),
98
+ }) } } : {}),
99
+ }
100
+ : undefined)
101
+ },
102
+ create: async (spec) => {
103
+ assertHostCreateAccepts(spec)
104
+ if (childAgents.has(spec.sessionId)) throw new Error('session already exists: ' + spec.sessionId)
105
+ rec.created.push(spec)
106
+ const childSession = { id: spec.sessionId, append: (type, data) => rec.forkLogLines.push({ type, data }) }
107
+ // 宿主在 create 里跑 setup(预设就是在这里被 mount 上去的)。
108
+ if (presets && typeof spec.setup === 'function') {
109
+ await spec.setup({ get: (name) => (name === 'agentPresets' ? presets : undefined) }, { session: childSession })
110
+ }
111
+ const dispose = async () => {
112
+ rec.disposed.push(spec.sessionId)
113
+ childAgents.set(spec.sessionId, null)
114
+ }
115
+ const handle = {
116
+ agent: {
117
+ session: childSession,
118
+ ctx: childCtxFactory?.(),
119
+ dispose,
120
+ followup: (message) => {
121
+ rec.forkFollowups.push({ child: spec.sessionId, message })
122
+ if (emitTurnEnd) {
123
+ const reason = typeof turnReason === 'function' ? turnReason(spec) : turnReason
124
+ if (reason?.kind === 'completed') {
125
+ // The worker receipt must match the window the fork was seeded
126
+ // with, not the whole parent transcript.
127
+ const child = state.getSessionBinding(spec.sessionId)
128
+ const fromSeq = Number.isSafeInteger(child?.snapshotFromSeq) ? child.snapshotFromSeq : 0
129
+ const throughSeq = Number.isSafeInteger(child?.snapshotThroughSeq)
130
+ ? child.snapshotThroughSeq
131
+ : 2 + extraEvents.length + padding
132
+ for (const handler of rec.sessionHandlers) {
133
+ handler(childSession, { type: 'assistant/message', seq: 99, data: { message: { content: [{ type: 'text', text: receiptFence({ fromSeq, throughSeq }, child) }] } } })
134
+ }
135
+ }
136
+ for (const handler of rec.sessionHandlers) {
137
+ handler(childSession, { type: 'turn/end', seq: 100, data: { turn: 1, reason } })
138
+ }
139
+ }
140
+ },
141
+ whenIdle: whenIdle || (async () => {}),
142
+ },
143
+ dispose,
144
+ }
145
+ childAgents.set(spec.sessionId, handle.agent)
146
+ return handle
147
+ },
148
+ }
149
+ }
150
+ // 整理 fork 的模型选择(lib/fork-model.js)按需探测的宿主 llm service;
151
+ // 缺省没有 = custom 模式必须降级回 inherit 的宿主形态。
152
+ if (name === 'llm') return llm
153
+ if (name === 'agentPresets') return presets
154
+ if (name === 'sessionQuery') {
155
+ return {
156
+ readSession: async () => ({
157
+ events: [
158
+ { seq: 0, type: 'user/message', data: { source: { kind: 'user' }, content: [{ type: 'text', text: '这个 fork 为什么一直建不起来,帮我看下' }] } },
159
+ { seq: 1, type: 'assistant/message', data: { message: { content: [{ type: 'tool-call', name: 'read', arguments: '{}' }] } } },
160
+ { seq: 2, type: 'assistant/message', data: { message: { content: [{ type: 'text', text: '看到了' }] } } },
161
+ ...extraEvents,
162
+ ...filler,
163
+ ],
164
+ session: { cwd, agentPreset: 'coding' },
165
+ }),
166
+ }
167
+ }
168
+ return undefined
169
+ },
170
+ }
171
+ return ctx
172
+ }
173
+
174
+ test('enabling local or remote vectors does not opt into remote summary', async () => {
175
+ const originalFetch = globalThis.fetch
176
+ let fetches = 0
177
+ globalThis.fetch = async () => { fetches += 1; throw new Error('summary API must not be called') }
178
+ try {
179
+ for (const vectorSource of ['local', 'api']) {
180
+ state.updateSettings({ memoryBackend: 'api', vectorSource })
181
+ const id = 'fork-vector-' + vectorSource
182
+ state.ensureSession(id, { cwd: path.join(home, id), agentPreset: 'coding' })
183
+ const ctx = host({ live: true })
184
+ const result = await requestPrivateConsolidation(ctx, id)
185
+ assert.equal(result.ok, true)
186
+ assert.equal(ctx.rec.created.length, 1, 'vector enable still delegates extraction to the conversation Agent')
187
+ assert.equal(ctx.rec.forkFollowups.length, 1)
188
+ }
189
+ assert.equal(fetches, 0)
190
+ } finally {
191
+ globalThis.fetch = originalFetch
192
+ state.updateSettings({ memoryBackend: 'agent', vectorSource: 'local' })
193
+ }
194
+ })
195
+
196
+ test('a live session is consolidated in a fork, not by queueing on itself', async () => {
197
+ const binding = state.ensureSession('fork-live', { cwd: path.join(home, 'proj'), agentPreset: 'coding' })
198
+ const parentOptions = { provider: 'test-provider', model: 'test-model', reasoningEffort: 'max', maxTokens: 262144 }
199
+ const ctx = host({ live: true, parentOptions })
200
+ const result = await requestPrivateConsolidation(ctx, 'fork-live')
201
+ assert.equal(result.ok, true)
202
+ assert.equal(result.settled, true)
203
+ assert.equal(ctx.rec.liveFollowups.length, 0, 'no queued draft on the live agent')
204
+ assert.equal(ctx.rec.created.length, 1, 'exactly one scratch fork')
205
+ assert.equal(ctx.rec.forkFollowups.length, 1, 'the fork does the work')
206
+ assert.equal(ctx.rec.disposed.length, 1, 'the fork is disposed')
207
+ const spec = ctx.rec.created[0]
208
+ assert.equal(spec.meta.parentSession, 'fork-live')
209
+ assert.equal(spec.meta.origin, 'subagent')
210
+ assert.equal(spec.meta.isSeeded, true)
211
+ assert.equal(spec.inheritedEventCount, 3, 'inherits the whole transcript as a top-level option')
212
+ assert.equal(Object.hasOwn(spec.meta, 'inheritedEventCount'), false, 'must not hide in the session meta: prepare() drops it')
213
+ assert.deepEqual(spec.agentOptions, parentOptions, 'the fork starts on the parent model route')
214
+ const child = state.getSessionBinding(spec.sessionId)
215
+ assert.equal(child, null, 'disposed worker binding is removed')
216
+ assert.equal(state.getSessionBinding('fork-live').lastSleepSeq, 2, 'only a completed turn advances the sleep cursor')
217
+ assert.equal(result.scanned, 3, 'report how much of the transcript was scanned')
218
+ assert.equal(result.fresh, 3, 'report how many events were new since the last consolidation')
219
+ assert.equal(result.wrote, 0, 'the fake fork writes nothing, but the metric must still be measured')
220
+ const text = ctx.rec.forkFollowups[0].message.content[0].text
221
+ const { estTokens } = await import('../lib/budget.js')
222
+ assert.equal(result.measurement.runner, 'fork')
223
+ assert.equal(result.measurement.packet.inputChars, text.length)
224
+ assert.equal(result.measurement.packet.estimatedTokens, estTokens(text))
225
+ assert.equal(result.measurement.usage.inputTokens, null)
226
+ })
227
+
228
+ for (const restriction of ['succeeds', 'missing', 'throws twice']) {
229
+ test(`a fork keeps host permissions and dispatches when tools.restrict ${restriction}`, async (t) => {
230
+ const id = 'fork-permissions-' + restriction.replaceAll(' ', '-')
231
+ state.ensureSession(id, { cwd: home, agentPreset: 'coding' })
232
+ const setPermission = t.mock.fn()
233
+ const disposeRestriction = t.mock.fn()
234
+ const followupsAtRestriction = []
235
+ const restrict = t.mock.fn(() => {
236
+ followupsAtRestriction.push(ctx.rec.forkFollowups.length)
237
+ if (restriction === 'throws twice') throw new Error('host refused tool restriction')
238
+ return disposeRestriction
239
+ })
240
+ const ctx = host({
241
+ live: true,
242
+ headerTools: [...CORE_WRITE_TOOLS, 'read', 'shell'],
243
+ childCtxFactory: () => ({ tools: restriction === 'missing' ? {} : { restrict } }),
244
+ })
245
+ ctx.permissionPresets = { set: setPermission }
246
+
247
+ const result = await requestPrivateConsolidation(ctx, id)
248
+ assert.equal(setPermission.mock.callCount(), 0, 'the plugin must not change the host permission preset')
249
+ assert.equal(result.ok, true, String(result.error || ''))
250
+ assert.equal(result.settled, true, 'missing or failing restrict keeps the existing capability fallback')
251
+ assert.equal(ctx.rec.created.length, 1)
252
+ assert.equal(ctx.rec.forkFollowups.length, 1, 'the fork still receives the consolidation task')
253
+ assert.equal(ctx.rec.liveFollowups.length, 0, 'the parent never receives the task')
254
+ assert.equal(ctx.rec.disposed.length, 1, 'the scratch fork is still disposed')
255
+ const expectedAllows = restriction === 'missing' ? []
256
+ : restriction === 'throws twice' ? [WORKER_TOOL_ALLOW, CORE_WRITE_TOOLS] : [WORKER_TOOL_ALLOW]
257
+ assert.deepEqual(restrict.mock.calls.map((call) => call.arguments), expectedAllows.map((allow) => [{ allow }]),
258
+ 'restriction still tries the full allowlist and falls back to the write core on failure')
259
+ assert.deepEqual(followupsAtRestriction, expectedAllows.map(() => 0), 'all restriction attempts precede dispatch')
260
+ assert.equal(disposeRestriction.mock.callCount(), restriction === 'succeeds' ? 1 : 0)
261
+ })
262
+ }
263
+
264
+ test('a fork preserves an existing parent cwd', async () => {
265
+ const cwd = fs.mkdtempSync(path.join(home, 'existing-cwd-'))
266
+ state.ensureSession('fork-cwd-existing', { cwd, agentPreset: 'coding' })
267
+ const ctx = host({ live: true, cwd })
268
+ const result = await requestPrivateConsolidation(ctx, 'fork-cwd-existing')
269
+ assert.equal(result.ok, true, String(result.error || ''))
270
+ assert.equal(ctx.rec.created.length, 1)
271
+ assert.notEqual(cwd, dataDir(), 'the existing cwd differs from the fallback')
272
+ assert.equal(ctx.rec.created[0].meta.cwd, cwd)
273
+ assert.equal(ctx.rec.forkFollowups.length, 1)
274
+ })
275
+
276
+ test('a fork falls back to the real dataDir when the parent cwd no longer exists', async () => {
277
+ const cwd = path.join(home, 'missing-cwd')
278
+ assert.equal(fs.existsSync(cwd), false)
279
+ state.ensureSession('fork-cwd-missing', { cwd, agentPreset: 'coding' })
280
+ const ctx = host({ live: true, cwd })
281
+ const result = await requestPrivateConsolidation(ctx, 'fork-cwd-missing')
282
+ assert.equal(result.ok, true, String(result.error || ''))
283
+ assert.equal(ctx.rec.created.length, 1)
284
+ assert.equal(ctx.rec.created[0].meta.cwd, dataDir())
285
+ assert.equal(fs.statSync(ctx.rec.created[0].meta.cwd).isDirectory(), true, 'the fallback is a real directory')
286
+ assert.equal(ctx.rec.forkFollowups.length, 1)
287
+ })
288
+
289
+ test('a live session inherits the route of its latest turn, not stale creation options', async () => {
290
+ state.ensureSession('fork-route', { cwd: path.join(home, 'proj-route'), agentPreset: 'coding' })
291
+ const ctx = host({
292
+ live: true,
293
+ parentOptions: { provider: 'creation', model: 'old-model' },
294
+ requestConfig: { provider: 'request', model: 'new-model', reasoningEffort: 'high', maxTokens: 32768 },
295
+ })
296
+ const result = await requestPrivateConsolidation(ctx, 'fork-route')
297
+ assert.equal(result.ok, true)
298
+ assert.deepEqual(ctx.rec.created[0].agentOptions, {
299
+ provider: 'request',
300
+ model: 'new-model',
301
+ reasoningEffort: 'high',
302
+ maxTokens: 32768,
303
+ }, 'requestHeader() is the route that served the parent, options can be stale')
304
+ })
305
+
306
+ test('a closed session inherits the last request/header event', async () => {
307
+ state.ensureSession('fork-closed', { cwd: path.join(home, 'proj-closed'), agentPreset: 'coding' })
308
+ const ctx = host({
309
+ live: false,
310
+ extraEvents: [
311
+ { seq: 3, type: 'request/header', data: { header: { config: { provider: 'old', model: 'old-model' } } } },
312
+ { seq: 4, type: 'request/header', data: { header: { config: { provider: 'latest', model: 'latest-model', reasoningEffort: 'low', maxTokens: 4096 } } } },
313
+ ],
314
+ })
315
+ const result = await requestPrivateConsolidation(ctx, 'fork-closed')
316
+ assert.equal(result.ok, true)
317
+ const spec = ctx.rec.created[0]
318
+ assert.equal(spec.inheritedEventCount, 3, 'only conversation events are seeded; request/header is noise')
319
+ assert.deepEqual(spec.agentOptions, { provider: 'latest', model: 'latest-model', reasoningEffort: 'low', maxTokens: 4096 })
320
+ })
321
+
322
+ test('a session with no model source is refused before a doomed fork', async () => {
323
+ state.ensureSession('fork-no-model', { cwd: path.join(home, 'proj-no-model'), agentPreset: 'coding' })
324
+ const ctx = host({ live: true, parentOptions: null })
325
+ const result = await requestPrivateConsolidation(ctx, 'fork-no-model')
326
+ assert.equal(result.ok, false)
327
+ assert.match(result.error, /model\/provider/)
328
+ assert.equal(ctx.rec.created.length, 0, 'never create a fork that cannot resolve {{model}}')
329
+ })
330
+
331
+ test('a failed fork turn is reported as failure and does not advance the sleep cursor', async () => {
332
+ state.ensureSession('fork-turn-error', { cwd: path.join(home, 'proj-turn-error'), agentPreset: 'coding' })
333
+ const ctx = host({
334
+ live: true,
335
+ turnReason: { kind: 'error', error: { message: 'prompt variable "{{model}}" has no value for this assembly', code: 'UNKNOWN' } },
336
+ })
337
+ const result = await requestPrivateConsolidation(ctx, 'fork-turn-error')
338
+ assert.equal(result.ok, false)
339
+ assert.equal(result.settled, false)
340
+ assert.match(result.error, /fork turn ended error/)
341
+ assert.match(result.error, /prompt variable/)
342
+ assert.equal(state.getSessionBinding('fork-turn-error').lastSleepSeq, undefined, 'a failed turn must be retried, not marked asleep')
343
+ assert.equal(ctx.rec.disposed.length, 1, 'the failed fork is still disposed')
344
+ assert.equal(ctx.rec.sessionHandlers.length, 0, 'the failed fork listener is removed')
345
+ const { sessionState } = await import('../lib/consolidation-ledger.js')
346
+ const ledger = sessionState('fork-turn-error')
347
+ assert.equal(ledger.checked, null)
348
+ assert.equal(ledger.pending.fromSeq, 0)
349
+ assert.equal(ledger.pending.throughSeq, 2)
350
+ assert.ok(result.measurement.packet.inputChars > 0, 'failed dispatches still carry cost measurement')
351
+ })
352
+
353
+ test('a fork that never reports turn/end is a failure, not a success', async () => {
354
+ state.ensureSession('fork-no-turn-end', { cwd: path.join(home, 'proj-no-turn-end'), agentPreset: 'coding' })
355
+ const ctx = host({ live: true, emitTurnEnd: false })
356
+ const result = await requestPrivateConsolidation(ctx, 'fork-no-turn-end')
357
+ assert.equal(result.ok, false)
358
+ assert.equal(result.settled, false)
359
+ assert.match(result.error, /no turn\/end/)
360
+ assert.equal(state.getSessionBinding('fork-no-turn-end').lastSleepSeq, undefined, 'without a turn/end event the cursor must not advance')
361
+ assert.equal(ctx.rec.disposed.length, 1, 'the unmatched fork is still disposed')
362
+ assert.equal(ctx.rec.sessionHandlers.length, 0, 'the listener is removed even when no turn/end arrives')
363
+ })
364
+
365
+ test('a fork still running at the deadline reports a timeout instead of silence', async () => {
366
+ state.ensureSession('fork-timeout', { cwd: path.join(home, 'proj-timeout'), agentPreset: 'coding' })
367
+ const ctx = host({ live: true, whenIdle: () => new Promise(() => {}) })
368
+ const result = await requestPrivateConsolidation(ctx, 'fork-timeout', { maxWaitMs: 30 })
369
+ assert.equal(result.ok, false)
370
+ assert.equal(result.timedOut, true)
371
+ assert.equal(result.settled, false)
372
+ // The settings button renders result.error and nothing else; an empty string
373
+ // there is why two clicks in a row looked like the button did nothing.
374
+ assert.match(result.error, /timed out after \d+s/)
375
+ assert.equal(state.getSessionBinding('fork-timeout').lastSleepSeq, undefined, 'a timeout must not advance the sleep cursor')
376
+ assert.equal(ctx.rec.disposed.length, 1, 'the timed-out fork is stopped')
377
+ assert.equal(ctx.rec.sessionHandlers.length, 0, 'the listener is removed on timeout')
378
+ })
379
+
380
+ test('a session already being consolidated is not forked twice', async () => {
381
+ state.ensureSession('fork-busy', { cwd: path.join(home, 'proj2'), agentPreset: 'coding' })
382
+ let release = null
383
+ const gate = new Promise((resolve) => { release = resolve })
384
+ const ctx = host({ live: true, whenIdle: () => gate })
385
+ const first = requestPrivateConsolidation(ctx, 'fork-busy')
386
+ await new Promise((resolve) => setTimeout(resolve, 20))
387
+ assert.equal(isConsolidating('fork-busy'), true)
388
+ const second = await requestPrivateConsolidation(ctx, 'fork-busy')
389
+ assert.equal(second.ok, false)
390
+ assert.equal(second.running, true)
391
+ assert.equal(ctx.rec.created.length, 1, 'the second call must not fork again')
392
+ release()
393
+ const done = await first
394
+ assert.equal(done.ok, true)
395
+ assert.equal(isConsolidating('fork-busy'), false)
396
+ })
397
+
398
+ test('two calls in the same tick fork once, not twice', async () => {
399
+ // The guard used to be checked before the first await and claimed only after
400
+ // readSession() and agents.create() resolved, so this exact pair raced past it
401
+ // and forked the same transcript twice on the real host.
402
+ state.ensureSession('fork-race', { cwd: path.join(home, 'proj3'), agentPreset: 'coding' })
403
+ let release = null
404
+ const gate = new Promise((resolve) => { release = resolve })
405
+ const ctx = host({ live: true, whenIdle: () => gate })
406
+ const both = Promise.all([
407
+ requestPrivateConsolidation(ctx, 'fork-race'),
408
+ requestPrivateConsolidation(ctx, 'fork-race'),
409
+ ])
410
+ await new Promise((resolve) => setTimeout(resolve, 20))
411
+ release()
412
+ const [a, b] = await both
413
+ assert.equal(ctx.rec.created.length, 1, 'exactly one scratch fork for the pair')
414
+ const outcomes = [a, b].map((r) => r.running === true ? 'running' : r.ok === true ? 'ok' : 'error').sort()
415
+ assert.deepEqual(outcomes, ['ok', 'running'], 'the loser is told the session is already being consolidated')
416
+ })
417
+
418
+ test('an unbound session is refused before any fork is attempted', async () => {
419
+ const ctx = host({ live: true })
420
+ const result = await requestPrivateConsolidation(ctx, 'fork-unbound')
421
+ assert.equal(result.ok, false)
422
+ assert.match(result.error, /not bound/)
423
+ assert.equal(ctx.rec.created.length, 0)
424
+ assert.equal(ctx.rec.liveFollowups.length, 0)
425
+ })
426
+ test('thin evidence holds the fork back until the starvation threshold', async () => {
427
+ state.ensureSession('fork-thin', { cwd: path.join(home, 'proj-thin'), agentPreset: 'coding' })
428
+ // 空闲 5 分钟:还在"短空闲"区间,证据又薄(一条短消息 + 一个工具调用),不唤醒。
429
+ state.setSessionBinding('fork-thin', { lastTurnAt: new Date(Date.now() - 5 * 60_000).toISOString() })
430
+ const ctx = host({ live: true })
431
+ const result = await requestPrivateConsolidation(ctx, 'fork-thin')
432
+ assert.equal(result.ok, true)
433
+ assert.equal(result.skipped, 'low-score')
434
+ assert.equal(ctx.rec.created.length, 0, 'a thin short-idle session must not pay for a fork')
435
+ })
436
+
437
+ test('starvation wakes a thin session so it can never be starved', async () => {
438
+ state.ensureSession('fork-starved', { cwd: path.join(home, 'proj-starved'), agentPreset: 'coding' })
439
+ state.setSessionBinding('fork-starved', { lastTurnAt: new Date(Date.now() - 40 * 60_000).toISOString() })
440
+ const ctx = host({ live: true })
441
+ const result = await requestPrivateConsolidation(ctx, 'fork-starved')
442
+ assert.equal(result.ok, true)
443
+ assert.equal(ctx.rec.created.length, 1, 'past the starvation threshold the check runs regardless of score')
444
+ })
445
+
446
+ test('a large transcript with nothing new since the cursor does not refork', async () => {
447
+ // 大转录的游标停在末尾附近时,待整理区间可能只剩几条纯轮询:
448
+ // 没有新的真人回合,就没有可整理的证据,不该为此把整段转录重新种进 fork。
449
+ // (桩把填充事件全放在末尾,所以「大会话 + 末尾一句轻话」这种形态表达不出来;
450
+ // 另一侧「从未整理过就必须整理」由下一条用例覆盖。)
451
+ state.ensureSession('fork-large-thin', { cwd: path.join(home, 'proj-large'), agentPreset: 'coding' })
452
+ state.setSessionBinding('fork-large-thin', {
453
+ lastTurnAt: new Date(Date.now() - 40 * 60_000).toISOString(),
454
+ lastSleepSeq: 5905,
455
+ })
456
+ const ctx = host({ live: true, transcriptSize: 5913 })
457
+ const result = await requestPrivateConsolidation(ctx, 'fork-large-thin')
458
+ assert.equal(result.ok, true)
459
+ assert.equal(result.skipped, 'no-human-turn', 'the increment carries no human turn to consolidate')
460
+ assert.equal(result.settled, true, 'a policy skip is terminal: the idle sweep stops re-reading the same greetings')
461
+ assert.equal(ctx.rec.created.length, 0, 'no fork when the pending increment has no evidence')
462
+ assert.equal(state.getSessionBinding('fork-large-thin').lastSleepSeq, 5912, 'a terminal policy skip advances the coarse cursor so the same thin tail is not rescanned')
463
+ })
464
+
465
+ test('a large transcript that was never consolidated does fork, because the backlog is real', async () => {
466
+ // 同一条会话,但没有整理过:整段 5913 条事件都躺在 pending 里。
467
+ // 守卫要躲的是「为一句轻话重种整段转录」,不是「把从没整理过的大会话永远挡在门外」;
468
+ // 没有这条上界,长会话早期的决定永远进不了记忆——那不是省 token,是丢失。
469
+ state.ensureSession('fork-large-owed', { cwd: path.join(home, 'proj-large-owed'), agentPreset: 'coding' })
470
+ state.setSessionBinding('fork-large-owed', { lastTurnAt: new Date(Date.now() - 40 * 60_000).toISOString() })
471
+ const ctx = host({ live: true, transcriptSize: 5913 })
472
+ const result = await requestPrivateConsolidation(ctx, 'fork-large-owed')
473
+ assert.equal(result.ok, true, 'the backlog bound lets this one through')
474
+ assert.equal(ctx.rec.created.length, 1, 'a large unconsolidated backlog is worth exactly one fork')
475
+ })
476
+ // ---------------------------------------------------------------- window & seed
477
+ test('the seed keeps conversation only, renumbers from zero, and strips replay/stream noise', () => {
478
+ const plugin = { seq: 0, type: 'user/message', data: { source: { kind: 'plugin:dsh-memu-memory', form: 'recall' }, content: [{ type: 'text', text: '旧召回' }] } }
479
+ const runtime = { seq: 1, type: 'user/message', data: { source: { kind: 'runtime-context', form: 'snapshot' }, content: [{ type: 'text', text: '运行时快照' }] } }
480
+ const header = { seq: 2, type: 'request/header', data: { header: {} } }
481
+ const user = { seq: 3, type: 'user/message', data: { source: { kind: 'user' }, content: [{ type: 'text', text: '记住:我不吃香菜' }] } }
482
+ const assistant = { seq: 4, type: 'assistant/message', data: {
483
+ message: {
484
+ source: { provider: 'p', model: 'm', replayState: { huge: 'x'.repeat(400) } },
485
+ content: [{ type: 'reasoning', text: '思考过程' }, { type: 'text', text: '好的' }, { type: 'tool-call', name: 'read', arguments: 'x'.repeat(2000) }],
486
+ },
487
+ stream: { blob: 'y'.repeat(400) },
488
+ } }
489
+ const repeated = 'R'.repeat(4000)
490
+ const tool1 = { seq: 5, type: 'tool/result', data: { message: { content: [{ type: 'text', text: repeated }] } } }
491
+ const tool2 = { seq: 6, type: 'tool/result', data: { message: { content: [{ type: 'text', text: repeated }] } } }
492
+ const catalog = {
493
+ type: 'user/message', seq: 0, time: 1, surfaceOp: 'append',
494
+ data: { role: 'user', source: { kind: 'plugin:dsh-memu-memory', form: 'notice' }, content: [{ type: 'text', text: '已有记忆目录' }] },
495
+ }
496
+ const seed = compactSeedEvents([plugin, runtime, header, user, assistant, tool1, tool2], catalog)
497
+ assert.deepEqual(seed.map(event => event.seq), [0, 1, 2, 3, 4], 'contiguous from zero, catalog at 0')
498
+ assert.match(seed[0].data.content[0].text, /已有记忆目录/)
499
+ assert.equal(seed[1].data.source.kind, 'user', 'only real user messages survive')
500
+ const msg = seed[2].data.message
501
+ assert.equal(msg.content.some(block => block.type === 'reasoning'), false, 'reasoning is not evidence')
502
+ assert.equal(msg.source.replayState, undefined, 'replay state duplicates the body')
503
+ assert.deepEqual(seed[2].data.stream, [], 'the raw chunk log is emptied, not deleted — 0.2.2-rc.1 seed validation requires the array')
504
+ assert.match(msg.content.find(block => block.type === 'tool-call').arguments, /已截断/)
505
+ assert.match(seed[3].data.message.content[0].text, /已截断/)
506
+ assert.match(seed[4].data.message.content[0].text, /与前面相同的工具输出/, 'identical tool output is deduped')
507
+ })
508
+
509
+ test('a long tail is cut to one closed-turn window with a remainder', () => {
510
+ const events = Array.from({ length: CONSOLIDATION_WINDOW_EVENTS + 180 }, (_, seq) => ({ seq, type: 'todo/write', data: {} }))
511
+ const window = selectConsolidationWindow(events)
512
+ assert.equal(window.fromSeq, 0)
513
+ assert.ok(window.events.length <= CONSOLIDATION_WINDOW_EVENTS, 'the window stays bounded')
514
+ assert.ok(window.remaining > 0, 'the rest is left for the next sweep')
515
+ assert.ok(window.throughSeq < events.length - 1)
516
+ })
517
+
518
+ test('a manual re-check starts at a complete turn instead of mid-step', () => {
519
+ const events = [
520
+ { seq: 0, type: 'assistant/message', data: { message: { content: [{ type: 'text', text: '旧回答' }] } } },
521
+ { seq: 1, type: 'user/message', data: { source: { kind: 'user' }, content: [{ type: 'text', text: '最后一问' }] } },
522
+ { seq: 2, type: 'turn/start', data: { turn: 2 } },
523
+ { seq: 3, type: 'assistant/message', data: { message: { content: [{ type: 'text', text: '最后回答' }] } } },
524
+ { seq: 4, type: 'turn/end', data: { turn: 2, reason: { kind: 'completed' } } },
525
+ ]
526
+ const window = selectTailTurnWindow(events)
527
+ assert.equal(window.fromSeq, 1, 'the user message that opened the turn is included')
528
+ assert.equal(window.throughSeq, 4, 'the window ends on a closed turn')
529
+ })
530
+
531
+ test('must-cover candidates keep the high-signal turn and its seq range', () => {
532
+ const events = [
533
+ { seq: 0, type: 'turn/start', data: {} },
534
+ { seq: 1, type: 'user/message', data: { source: { kind: 'user' }, content: [{ type: 'text', text: '说好周末拿给阿兰换伞骨,记得带过去。' }] } },
535
+ { seq: 2, type: 'turn/end', data: {} },
536
+ { seq: 3, type: 'turn/start', data: {} },
537
+ { seq: 4, type: 'user/message', data: { source: { kind: 'user' }, content: [{ type: 'text', text: '今天天气不错。' }] } },
538
+ { seq: 5, type: 'turn/end', data: {} },
539
+ ]
540
+ const rows = mustCoverCandidates(events, { max: 4 })
541
+ assert.equal(rows.length, 1, 'a low-signal turn is not a must-cover candidate')
542
+ assert.equal(rows[0].fromSeq, 0)
543
+ assert.equal(rows[0].throughSeq, 2)
544
+ assert.equal(rows[0].tag, '人物/关系')
545
+ assert.match(rows[0].text, /阿兰/)
546
+ })
547
+
548
+ test('mergeMustCover puts carried candidates first and reserves room for fresh ones', () => {
549
+ const carry = Array.from({ length: 6 }, (_, i) => ({ text: 'carry' + i, fromSeq: i, throughSeq: i, tag: '事实' }))
550
+ const fresh = Array.from({ length: 6 }, (_, i) => ({ text: 'fresh' + i, fromSeq: i, throughSeq: i, tag: '事实' }))
551
+ const merged = mergeMustCover(carry, fresh)
552
+ assert.equal(merged.length, 8)
553
+ assert.deepEqual(merged.slice(0, 4).map((row) => row.text), ['carry0', 'carry1', 'carry2', 'carry3'])
554
+ assert.deepEqual(merged.slice(4).map((row) => row.text), ['fresh0', 'fresh1', 'fresh2', 'fresh3'])
555
+ assert.ok(merged.slice(0, 4).every((row) => row.carried === true))
556
+ assert.equal(mergeMustCover([{ text: 'same' }], [{ text: 'same' }]).length, 1, 'duplicates are dropped')
557
+ })
558
+
559
+ test('a candidate is covered only when a written entry carries the fact', () => {
560
+ const index = {
561
+ entries: {
562
+ 'mem-1': { title: '楼下修伞的阿兰', content: '说好周末拿折伞给她换伞骨,布不用动。' },
563
+ 'mem-2': { title: '同事叶楠生日是八月十八号', content: '叶楠生日八月十八号。' },
564
+ },
565
+ }
566
+ assert.equal(candidateCovered({ text: '说好周末拿给阿兰换伞骨' }, ['mem-1'], index), true)
567
+ assert.equal(candidateCovered({ text: '叶楠生日八月十八号' }, ['mem-2'], index), true)
568
+ assert.equal(candidateCovered({ text: '父亲不吃芹菜' }, ['mem-1'], index), false)
569
+ assert.equal(candidateCovered({ text: '父亲不吃芹菜' }, [], index), false, 'no writes means no coverage')
570
+ })
571
+
572
+ test('coverage does not discard facts for matching dates, polarity, values, or generic overlap', () => {
573
+ const covered = (text, content, title = '') => candidateCovered({ text }, ['mem-written'], { entries: { 'mem-written': { title, content } } })
574
+ assert.equal(covered('11月20日阿兰取伞', '11月20日小林去医院'), false, 'same date is not the same event')
575
+ assert.equal(covered('父亲不吃芹菜', '父亲爱吃芹菜'), false, 'opposite polarity is not coverage')
576
+ assert.equal(covered('父亲周末去图书馆还书', '父亲周末去图书馆借书'), false, 'shared topic must retain the action')
577
+ assert.equal(covered('父亲生日是11月20日', '父亲生日是11月21日'), false, 'different date is not coverage')
578
+ assert.equal(covered('项目预算是1200元', '项目预算是1500元'), false, 'different value is not coverage')
579
+ assert.equal(covered('11月20日', '11月20日小林去医院'), false, 'date alone is insufficient evidence')
580
+ assert.equal(covered('父亲不吃芹菜', '父亲不吃芹菜,母亲喜欢白菜'), true)
581
+ assert.equal(covered('父亲喜欢芹菜', '父亲喜欢芹菜,母亲不吃白菜'), true, 'unrelated negation does not alter the fact')
582
+ assert.equal(covered('11月20日阿兰取伞', '11月20日阿兰取伞,记得提前联系'), true)
583
+ assert.equal(covered('项目预算是1200元', '项目预算是1200元'), true)
584
+ })
585
+
586
+ test('the same failed snapshot stops automatic re-forking after the failure cap', async () => {
587
+ state.ensureSession('fork-failcap', { cwd: path.join(home, 'proj-failcap'), agentPreset: 'coding' })
588
+ const ctx = host({ live: true, turnReason: { kind: 'error', error: { message: 'provider refused max-tokens argument' } } })
589
+ const first = await requestPrivateConsolidation(ctx, 'fork-failcap', { force: true })
590
+ const second = await requestPrivateConsolidation(ctx, 'fork-failcap', { force: true })
591
+ assert.equal(first.ok, false)
592
+ assert.equal(second.ok, false)
593
+ assert.equal(ctx.rec.created.length, 2, 'two real attempts happen')
594
+ // 自动路径仍然受上限约束:同一快照连续失败 2 次后不再付第三次 fork 成本。
595
+ const third = await requestPrivateConsolidation(ctx, 'fork-failcap')
596
+ assert.equal(third.ok, true)
597
+ assert.equal(third.skipped, 'snapshot-failed')
598
+ assert.equal(ctx.rec.created.length, 2, 'the automatic call does not pay for the same snapshot again')
599
+ // 手动整理是明确的一次再决定:force 不受上限约束(否则冻结回放/用户重试会被永久卡住)。
600
+ const forcedAgain = await requestPrivateConsolidation(ctx, 'fork-failcap', { force: true })
601
+ assert.equal(forcedAgain.ok, false)
602
+ assert.equal(ctx.rec.created.length, 3, 'a manual retry is allowed past the cap')
603
+ })
604
+
605
+ for (const runner of ['fork', 'worker']) {
606
+ test(`${runner} preserves max-tokens pending and retries the same snapshot only after output configuration changes`, async () => {
607
+ state.updateSettings({ consolidationRunner: runner, consolidationModelMode: 'inherit', consolidationReasoningEffort: 'inherit' })
608
+ const id = 'output-limit-' + runner
609
+ state.ensureSession(id, { cwd: path.join(home, id), agentPreset: 'coding' })
610
+ const parentOptions = { provider: id, model: 'test-model', maxTokens: 4096, reasoningEffort: 'medium' }
611
+ markEffortRefused([id, 'test-model', 'medium'].join('|'))
612
+ const ctx = host({ live: true, parentOptions, turnReason: spec => spec.agentOptions.maxTokens <= 4096 ? { kind: 'max-tokens' } : { kind: 'completed' } })
613
+ try {
614
+ for (let i = 0; i < 2; i++) {
615
+ const failed = await requestPrivateConsolidation(ctx, id, { force: true })
616
+ assert.equal(failed.ok, false)
617
+ assert.equal(failed.settled, false)
618
+ assert.equal(failed.reasonCode, 'model-output-limit')
619
+ assert.equal(failed.retryable, true)
620
+ assert.equal(failed.configuredMaxTokens, 4096)
621
+ assert.match(failed.error, /输出预算不足/)
622
+ assert.equal(state.getSessionBinding(id).lastSleepSeq, undefined)
623
+ assert.ok(ledger.sessionState(id).pending)
624
+ assert.equal(parentOptions.maxTokens, 4096, 'the plugin never raises the parent limit')
625
+ assert.equal(parentOptions.reasoningEffort, 'medium')
626
+ assert.equal(ctx.rec.created.at(-1).agentOptions.reasoningEffort, undefined)
627
+ }
628
+ const suppressed = await requestPrivateConsolidation(ctx, id)
629
+ assert.equal(suppressed.skipped, 'snapshot-failed')
630
+ assert.equal(suppressed.settled, false)
631
+ assert.equal(ctx.rec.created.length, 2)
632
+ parentOptions.maxTokens = 32768
633
+ const recovered = await requestPrivateConsolidation(ctx, id)
634
+ assert.equal(recovered.ok, true, recovered.error || '')
635
+ assert.equal(recovered.settled, true)
636
+ assert.equal(ctx.rec.created.length, 3)
637
+ assert.equal(ctx.rec.created.at(-1).agentOptions.maxTokens, 32768)
638
+ assert.equal(state.getSessionBinding(id).lastSleepSeq, 2)
639
+ assert.equal(ledger.sessionState(id).pending, null)
640
+ } finally {
641
+ const worker = state.getSessionBinding(id)?.workerEpoch?.forkSessionId
642
+ if (worker) await retireWorker(ctx, worker, 'test-cleanup', { handoff: false })
643
+ state.updateSettings({ consolidationRunner: 'fork', consolidationModelMode: 'inherit' })
644
+ }
645
+ })
646
+ }
647
+
648
+ test('host-route output default changes unlock a truncated snapshot without inheriting a parent route or overriding its cap', async () => {
649
+ const id = 'output-default-host'
650
+ state.ensureSession(id, { cwd: path.join(home, id), agentPreset: 'coding' })
651
+ state.updateSettings({ consolidationRunner: 'fork', consolidationModelMode: 'host', consolidationModel: 'test-provider/test-model', consolidationReasoningEffort: 'inherit' })
652
+ let defaultMaxTokens = 4096
653
+ const ctx = host({ live: false, llm: { resolveModelInfo: async () => ({ defaultMaxTokens }) }, turnReason: () => defaultMaxTokens <= 4096 ? { kind: 'max-tokens' } : { kind: 'completed' } })
654
+ try {
655
+ for (let i = 0; i < 2; i++) {
656
+ const result = await requestPrivateConsolidation(ctx, id, { force: true })
657
+ assert.equal(result.reasonCode, 'model-output-limit')
658
+ assert.equal(result.configuredMaxTokens, 4096)
659
+ }
660
+ const frozen = await requestPrivateConsolidation(ctx, id)
661
+ assert.equal(frozen.skipped, 'snapshot-failed')
662
+ defaultMaxTokens = 32768
663
+ const resumed = await requestPrivateConsolidation(ctx, id)
664
+ assert.equal(resumed.ok, true, resumed.error || '')
665
+ assert.equal(resumed.settled, true)
666
+ assert.equal(ctx.rec.created.length, 3)
667
+ assert.ok(ctx.rec.created.every(spec => !Object.hasOwn(spec.agentOptions, 'maxTokens')))
668
+ } finally {
669
+ state.updateSettings({ consolidationModelMode: 'inherit', consolidationModel: '' })
670
+ }
671
+ })
672
+
673
+ test('a budget change during a truncated turn is not charged as a failed attempt of the new configuration', async () => {
674
+ const id = 'output-limit-mid-turn-change'
675
+ state.ensureSession(id, { cwd: path.join(home, id), agentPreset: 'coding' })
676
+ state.updateSettings({ consolidationRunner: 'fork', consolidationModelMode: 'inherit', consolidationReasoningEffort: 'inherit' })
677
+ const parentOptions = { provider: id, model: 'test-model', maxTokens: 4096 }
678
+ let oldAttempts = 0
679
+ let newAttempts = 0
680
+ const ctx = host({ live: true, parentOptions, turnReason: spec => {
681
+ if (spec.agentOptions.maxTokens === 4096) {
682
+ if (++oldAttempts === 2) parentOptions.maxTokens = 8192
683
+ return { kind: 'max-tokens' }
684
+ }
685
+ return ++newAttempts === 1 ? { kind: 'max-tokens' } : { kind: 'completed' }
686
+ } })
687
+ for (let i = 0; i < 2; i++) assert.equal((await requestPrivateConsolidation(ctx, id, { force: true })).reasonCode, 'model-output-limit')
688
+ assert.equal((await requestPrivateConsolidation(ctx, id)).reasonCode, 'model-output-limit')
689
+ const recovered = await requestPrivateConsolidation(ctx, id)
690
+ assert.equal(recovered.ok, true, recovered.error || '')
691
+ assert.equal(recovered.settled, true)
692
+ assert.equal(newAttempts, 2)
693
+ assert.equal(ctx.rec.created.length, 4)
694
+ assert.equal(state.getSessionBinding(id).lastSleepSeq, 2)
695
+ })
696
+
697
+ test('a provider default reasoning change reopens an output-limited host route without an explicit effort override', async () => {
698
+ const id = 'output-limit-default-reasoning'
699
+ state.ensureSession(id, { cwd: path.join(home, id), agentPreset: 'coding' })
700
+ state.updateSettings({ consolidationRunner: 'fork', consolidationModelMode: 'host', consolidationModel: id + '/test-model', consolidationReasoningEffort: 'inherit' })
701
+ let defaultEffort = 'high'
702
+ const ctx = host({ live: false, llm: { resolveModelInfo: async () => ({ defaultMaxTokens: 4096, reasoning: { defaultEffort } }) }, turnReason: () => defaultEffort === 'high' ? { kind: 'max-tokens' } : { kind: 'completed' } })
703
+ try {
704
+ for (let i = 0; i < 2; i++) assert.equal((await requestPrivateConsolidation(ctx, id, { force: true })).reasonCode, 'model-output-limit')
705
+ assert.equal((await requestPrivateConsolidation(ctx, id)).skipped, 'snapshot-failed')
706
+ defaultEffort = 'low'
707
+ const result = await requestPrivateConsolidation(ctx, id)
708
+ assert.equal(result.ok, true, result.error || '')
709
+ assert.equal(result.settled, true)
710
+ assert.equal(ctx.rec.created.length, 3)
711
+ assert.ok(ctx.rec.created.every(spec => !Object.hasOwn(spec.agentOptions, 'reasoningEffort')))
712
+ } finally {
713
+ state.updateSettings({ consolidationModelMode: 'inherit', consolidationModel: '' })
714
+ }
715
+ })
716
+
717
+ test('unavailable model metadata does not masquerade as an output configuration change', async () => {
718
+ const id = 'output-limit-unavailable-defaults'
719
+ state.ensureSession(id, { cwd: path.join(home, id), agentPreset: 'coding' })
720
+ state.updateSettings({ consolidationRunner: 'fork', consolidationModelMode: 'host', consolidationModel: id + '/test-model', consolidationReasoningEffort: 'inherit' })
721
+ let unavailable = false
722
+ let defaultMaxTokens = 4096
723
+ const ctx = host({ live: false, llm: { resolveModelInfo: async () => {
724
+ if (unavailable) throw new Error('model metadata unavailable')
725
+ return { defaultMaxTokens }
726
+ } }, turnReason: () => defaultMaxTokens <= 4096 ? { kind: 'max-tokens' } : { kind: 'completed' } })
727
+ try {
728
+ for (let i = 0; i < 2; i++) assert.equal((await requestPrivateConsolidation(ctx, id, { force: true })).reasonCode, 'model-output-limit')
729
+ unavailable = true
730
+ assert.equal((await requestPrivateConsolidation(ctx, id)).skipped, 'snapshot-failed')
731
+ unavailable = false
732
+ assert.equal((await requestPrivateConsolidation(ctx, id)).skipped, 'snapshot-failed')
733
+ assert.equal(ctx.rec.created.length, 2)
734
+ defaultMaxTokens = 32768
735
+ assert.equal((await requestPrivateConsolidation(ctx, id)).settled, true)
736
+ assert.equal(ctx.rec.created.length, 3)
737
+ } finally {
738
+ state.updateSettings({ consolidationModelMode: 'inherit', consolidationModel: '' })
739
+ }
740
+ })
741
+
742
+ test('an explicit live output limit supersedes a cached header budget only on the same route', async () => {
743
+ const id = 'output-limit-cached-header'
744
+ state.ensureSession(id, { cwd: path.join(home, id), agentPreset: 'coding' })
745
+ state.updateSettings({ consolidationRunner: 'fork', consolidationModelMode: 'inherit', consolidationReasoningEffort: 'inherit' })
746
+ const parentOptions = { provider: id, model: 'test-model', maxTokens: 4096 }
747
+ const requestConfig = Object.freeze({ provider: id, model: 'test-model', maxTokens: 4096 })
748
+ const ctx = host({ live: true, parentOptions, requestConfig, turnReason: spec => spec.agentOptions.maxTokens <= 4096 ? { kind: 'max-tokens' } : { kind: 'completed' } })
749
+ for (let i = 0; i < 2; i++) assert.equal((await requestPrivateConsolidation(ctx, id, { force: true })).reasonCode, 'model-output-limit')
750
+ assert.equal((await requestPrivateConsolidation(ctx, id)).skipped, 'snapshot-failed')
751
+ parentOptions.maxTokens = 32768
752
+ const result = await requestPrivateConsolidation(ctx, id)
753
+ assert.equal(result.ok, true, result.error || '')
754
+ assert.equal(result.settled, true)
755
+ assert.equal(ctx.rec.created.at(-1).agentOptions.maxTokens, 32768)
756
+ assert.equal(requestConfig.maxTokens, 4096)
757
+ assert.equal(ctx.rec.created.length, 3)
758
+ })
759
+
760
+ // ---------------------------------------------------------------- PTC 兼容
761
+ // PTC 模式下 request/header 的工具表只有 run_code,
762
+ // probe 曾据此判 unavailable(worker-tools-ptc-only),PTC 会话永远不被整理。宿主的
763
+ // PTC executor 明确 "only run_code is directly callable",其余工具走 run_code 程序里的
764
+ // SDK 绑定(tools.schemas(agent, toolSet) 枚举可见面)—— header 名单在 PTC 会话里
765
+ // 不承载"能不能写记忆"。修复后:PTC 不构成否证 + fork 时把 worker 的读写面
766
+ // (WORKER_WRITE_TOOLS + WORKER_READ_TOOLS)挂进 worker 自己的
767
+ // scope(注册表按 scope 链取可见面,不扩散到其它会话)。
768
+
769
+ test('a PTC session (run_code only header) is consolidated and the worker gets write tools on its own scope', async () => {
770
+ const registered = []
771
+ const disposals = []
772
+ state.ensureSession('fork-ptc', { cwd: path.join(home, 'proj-ptc'), agentPreset: 'tool-preset' })
773
+ const ctx = host({
774
+ live: true,
775
+ headerTools: ['run_code'],
776
+ extraEvents: [
777
+ { seq: 3, type: 'tool/ptc-dispatch-start', data: { rootCallId: 'r1', parentCallId: 'r1', subCallId: 'r1:ptc:1', name: 'read', arguments: {} } },
778
+ { seq: 4, type: 'tool/ptc-dispatch', data: { rootCallId: 'r1', parentCallId: 'r1', subCallId: 'r1:ptc:1', name: 'read', arguments: {}, isError: false, content: [] } },
779
+ ],
780
+ childCtxFactory: () => ({
781
+ tools: {
782
+ register: (tool) => {
783
+ registered.push(tool?.name)
784
+ return () => { disposals.push(tool?.name) }
785
+ },
786
+ },
787
+ }),
788
+ })
789
+ const result = await requestPrivateConsolidation(ctx, 'fork-ptc')
790
+ assert.equal(result.ok, true, 'a run_code header must not block consolidation: ' + String(result.error || ''))
791
+ assert.equal(result.settled, true)
792
+ assert.equal(ctx.rec.created.length, 1, 'the fork is created for the PTC conversation')
793
+ // 只挂 worker 真正用到的写面(remember/batch/update + link/link_suggest 裁决两件);
794
+ // lexicon、archive/delete/unpin 这些用不到或破坏性的工具不进 worker 面。
795
+ assert.deepEqual([...registered].sort(), ['memu_private_link', 'memu_private_link_suggest', 'memu_private_remember', 'memu_private_remember_batch', 'memu_private_update'])
796
+ // 整理结束(finally)必须卸载挂载,不能给这条一次性 worker 留常驻注册。
797
+ assert.deepEqual([...disposals].sort(), ['memu_private_link', 'memu_private_link_suggest', 'memu_private_remember', 'memu_private_remember_batch', 'memu_private_update'])
798
+ // 全量挂载的活动元数据:attached=实际子集(此处=完整 wanted)、requested=完整 wanted、
799
+ // partial=false。三件一起钉住"成功路径不再含糊"。
800
+ const started = startedEntryFor(ctx, 'fork-ptc')
801
+ assert.deepEqual([...started.detail.workerToolsAttached].sort(), ['memu_private_link', 'memu_private_link_suggest', 'memu_private_remember', 'memu_private_remember_batch', 'memu_private_update'])
802
+ assert.deepEqual([...started.detail.workerToolsRequested].sort(), ['memu_private_link', 'memu_private_link_suggest', 'memu_private_remember', 'memu_private_remember_batch', 'memu_private_update'])
803
+ assert.equal(started.detail.workerToolsPartial, false, 'a full mount is not partial')
804
+ const followup = ctx.rec.forkFollowups[0]?.message
805
+ const brief = Array.isArray(followup?.content)
806
+ ? followup.content.map((block) => block?.text || '').join('\n')
807
+ : String(followup || '')
808
+ assert.match(brief, /run_code/, 'the brief names the PTC transport')
809
+ assert.match(brief, /tools\.memu_private_remember/, 'the brief shows the SDK invocation shape')
810
+ })
811
+
812
+ // "整理已开始"那条活动日志:按 sessionId + phase=started 取,childId 对上这次的 fork。
813
+ function startedEntryFor(ctx, sessionId) {
814
+ const childId = ctx.rec.created[0]?.sessionId
815
+ const entry = activity.listEvents({ kind: 'consolidate', sessionId })
816
+ .find((row) => row.detail?.phase === 'started' && row.detail?.childId === childId)
817
+ assert.ok(entry, 'the consolidation-started activity entry exists')
818
+ return entry
819
+ }
820
+
821
+ test('a host registry refusing one write tool leaves a structured partial mount in the activity log', async () => {
822
+ // 宿主注册表对单件工具说"不"(重名、scope 锁定)是真实的部分挂载路径:registerTools
823
+ // 逐件 fail-open,其余工具照常挂上。活动日志必须记实际子集 + requested + partial,
824
+ // 而不是把 wanted 全量误报成已挂载(旧口径的缺陷)。
825
+ const registered = []
826
+ const disposals = []
827
+ state.ensureSession('fork-ptc-partial', { cwd: path.join(home, 'proj-ptc-partial'), agentPreset: 'tool-preset' })
828
+ const ctx = host({
829
+ live: true,
830
+ headerTools: ['run_code'],
831
+ childCtxFactory: () => ({
832
+ tools: {
833
+ register: (tool) => {
834
+ if (tool?.name === 'memu_private_remember') throw new Error('registry refused: name already bound')
835
+ registered.push(tool?.name)
836
+ return () => { disposals.push(tool?.name) }
837
+ },
838
+ },
839
+ }),
840
+ })
841
+ const result = await requestPrivateConsolidation(ctx, 'fork-ptc-partial')
842
+ assert.equal(result.ok, true, String(result.error || ''))
843
+ assert.equal(result.settled, true)
844
+ assert.deepEqual([...registered].sort(), ['memu_private_link', 'memu_private_link_suggest', 'memu_private_remember_batch', 'memu_private_update'],
845
+ 'exactly the tools that actually registered are mounted')
846
+ assert.deepEqual([...disposals].sort(), ['memu_private_link', 'memu_private_link_suggest', 'memu_private_remember_batch', 'memu_private_update'],
847
+ 'dispose unmounts exactly what was mounted')
848
+ const started = startedEntryFor(ctx, 'fork-ptc-partial')
849
+ assert.deepEqual([...started.detail.workerToolsAttached].sort(), ['memu_private_link', 'memu_private_link_suggest', 'memu_private_remember_batch', 'memu_private_update'],
850
+ 'the log records the actual subset, not the full wanted list')
851
+ assert.deepEqual([...started.detail.workerToolsRequested].sort(), ['memu_private_link', 'memu_private_link_suggest', 'memu_private_remember', 'memu_private_remember_batch', 'memu_private_update'])
852
+ assert.equal(started.detail.workerToolsPartial, true)
853
+ // 挂载为部分子集时任务书仍带 PTC 调用形态:worker 知道写记忆走 run_code 的 SDK 绑定。
854
+ const followup = ctx.rec.forkFollowups[0]?.message
855
+ const brief = Array.isArray(followup?.content)
856
+ ? followup.content.map((block) => block?.text || '').join('\n')
857
+ : String(followup || '')
858
+ assert.match(brief, /await tools\.memu_private_remember/, 'the brief keeps the PTC invocation shape on a partial mount')
859
+ })
860
+
861
+ test('a fork context without a tools service records a null mount, the request and the partial flag', async () => {
862
+ // 宿主不暴露 agent ctx(或 ctx 上没有 tools 服务)→ attachWorkerTools 的现有 warn 路径。
863
+ // 语义:workerToolsAttached=null = 挂载没有完成(与"挂全了"严格区分);requested 仍记
864
+ // 完整 wanted;workerToolsPartial=true —— "未证明拿到完整 wanted 集",一件都没有
865
+ // 是它最极端的形态。若这里标 false,false 会被一眼读成"全量挂载",元数据又不准了。
866
+ state.ensureSession('fork-ptc-notools', { cwd: path.join(home, 'proj-ptc-notools'), agentPreset: 'tool-preset' })
867
+ const ctx = host({ live: true, headerTools: ['run_code'] })
868
+ const result = await requestPrivateConsolidation(ctx, 'fork-ptc-notools')
869
+ assert.equal(result.ok, true, String(result.error || ''))
870
+ const started = startedEntryFor(ctx, 'fork-ptc-notools')
871
+ assert.equal(started.detail.workerToolsAttached, null, 'no mount completed, so the log must not claim one')
872
+ assert.deepEqual([...started.detail.workerToolsRequested].sort(), ['memu_private_link', 'memu_private_link_suggest', 'memu_private_remember', 'memu_private_remember_batch', 'memu_private_update'])
873
+ assert.equal(started.detail.workerToolsPartial, true)
874
+ })
875
+
876
+ test('a non-PTC header without write tools still refuses to fork', async () => {
877
+ state.ensureSession('fork-notools', { cwd: path.join(home, 'proj-notools'), agentPreset: 'coding' })
878
+ const ctx = host({ live: true, headerTools: ['read', 'shell', 'edit'] })
879
+ const result = await requestPrivateConsolidation(ctx, 'fork-notools')
880
+ assert.equal(result.ok, false)
881
+ assert.equal(result.reasonCode, 'worker-tools-missing')
882
+ assert.equal(ctx.rec.created.length, 0, 'no fork when the model surface provably lacks the write tools')
883
+ })
884
+
885
+ // 超时预算下限与封顶齐平为 600 s——预算恒为 600 s(10 分钟),不再随
886
+ // 事件数缩放。慢推理模型(GLM-5.3-Flash)+ 500 事件窗需要完整的 10 分钟余量;卡死的
887
+ // fork 仍会在 10 分钟到点后被收掉。显式 maxWaitMs 调用原样生效(另见 requestHistoricalConsolidation)。
888
+ test('the consolidation wait budget is a flat 600 s for the slow-reasoning window', () => {
889
+ assert.equal(CONSOLIDATION_WAIT_POLICY.minMs, 600_000)
890
+ assert.equal(CONSOLIDATION_WAIT_POLICY.maxMs, 600_000)
891
+ assert.equal(consolidationWaitBudget(0), 600_000, 'an empty range still gets the full budget')
892
+ assert.equal(consolidationWaitBudget(100), 600_000, 'small sessions get the full ten minutes')
893
+ assert.equal(consolidationWaitBudget(935), 600_000, 'the session that timed out gets the full ten minutes')
894
+ assert.equal(consolidationWaitBudget(5_000), 600_000, 'a wedged fork still dies inside ten minutes')
895
+ assert.equal(consolidationWaitBudget(undefined), 600_000)
896
+ assert.equal(consolidationWaitBudget('not-a-number'), 600_000)
897
+ assert.ok(CONSOLIDATION_WAIT_POLICY.minMs <= CONSOLIDATION_WAIT_POLICY.maxMs)
898
+ })
899
+
900
+ // ---------------------------------------------------------------- 整理 fork 的模型选择(三模式接线)
901
+ // lib/fork-model.js 的解析与 route 生命周期在 fork-model.test.mjs 单测;这里钉住接线行为:
902
+ // fork 真正拿到的 agentOptions、被拒时的 reasonCode、以及 inherit 模式与旧路径逐字节一致。
903
+
904
+ function servingLlm() {
905
+ const llm = {
906
+ registerAdapter: (routes) => {
907
+ const handle = () => {}
908
+ handle.replace = () => {}
909
+ return handle
910
+ },
911
+ listModels: async (provider) => [{ provider, id: 'any', name: 'route serves models', inputModalities: ['text'] }],
912
+ }
913
+ return llm
914
+ }
915
+
916
+ const CUSTOM = {
917
+ consolidationModelMode: 'custom',
918
+ consolidationCustomBaseURL: 'http://127.0.0.1:9100/v1',
919
+ consolidationCustomModel: 'gateway-model',
920
+ consolidationCustomApiKey: '',
921
+ }
922
+
923
+ function restoreSettings() {
924
+ state.updateSettings({
925
+ consolidationModelMode: 'inherit',
926
+ consolidationModel: null,
927
+ consolidationCustomBaseURL: '',
928
+ consolidationCustomApiKey: '',
929
+ consolidationCustomModel: '',
930
+ consolidationCustomApi: 'openai-completions',
931
+ })
932
+ }
933
+
934
+ test('custom mode puts the fork on the registered dsh-memu-custom route', async () => {
935
+ state.updateSettings(CUSTOM)
936
+ try {
937
+ state.ensureSession('fork-mode-custom', { cwd: path.join(home, 'proj-mode-custom'), agentPreset: 'coding' })
938
+ const ctx = host({ live: true, llm: servingLlm() })
939
+ const result = await requestPrivateConsolidation(ctx, 'fork-mode-custom')
940
+ assert.equal(result.ok, true, String(result.error || ''))
941
+ assert.equal(result.settled, true)
942
+ assert.equal(ctx.rec.created.length, 1)
943
+ assert.deepEqual(ctx.rec.created[0].agentOptions, { provider: 'dsh-memu-custom', model: 'gateway-model' }, 'the fork names the plugin-owned custom route')
944
+ const started = startedEntryFor(ctx, 'fork-mode-custom')
945
+ assert.equal(started.detail.modelMode, 'custom')
946
+ } finally {
947
+ forkModel.disposeConsolidationRoute()
948
+ restoreSettings()
949
+ }
950
+ })
951
+
952
+ test('custom mode falls back to the inherited route when the host cannot serve the custom route', async () => {
953
+ state.updateSettings(CUSTOM)
954
+ try {
955
+ state.ensureSession('fork-mode-fallback', { cwd: path.join(home, 'proj-mode-fallback'), agentPreset: 'coding' })
956
+ // 没有 llm service 的宿主:custom 不可用,降级回父会话 route,整理照常完成。
957
+ const ctx = host({ live: true, parentOptions: { provider: 'fallback-prov', model: 'fallback-model' } })
958
+ const result = await requestPrivateConsolidation(ctx, 'fork-mode-fallback')
959
+ assert.equal(result.ok, true, String(result.error || ''))
960
+ assert.deepEqual(ctx.rec.created[0].agentOptions, { provider: 'fallback-prov', model: 'fallback-model' }, 'the fork falls back to the parent route instead of dying')
961
+ const started = startedEntryFor(ctx, 'fork-mode-fallback')
962
+ assert.equal(started.detail.modelMode, 'inherit-fallback')
963
+ } finally {
964
+ restoreSettings()
965
+ }
966
+ })
967
+
968
+ test('custom mode without a usable custom route and without a parent route is refused', async () => {
969
+ state.updateSettings(CUSTOM)
970
+ try {
971
+ state.ensureSession('fork-mode-custom-dead', { cwd: path.join(home, 'proj-mode-dead'), agentPreset: 'coding' })
972
+ const ctx = host({ live: true, parentOptions: null })
973
+ const result = await requestPrivateConsolidation(ctx, 'fork-mode-custom-dead')
974
+ assert.equal(result.ok, false)
975
+ assert.equal(result.reasonCode, 'custom-route-unavailable')
976
+ assert.match(result.error, /custom consolidation route is unavailable/)
977
+ assert.equal(ctx.rec.created.length, 0)
978
+ } finally {
979
+ restoreSettings()
980
+ }
981
+ })
982
+
983
+ test('host mode resolves consolidationModel the same way the curator does', async () => {
984
+ state.updateSettings({ consolidationModelMode: 'host', consolidationModel: 'host-prov/host-model/nested' })
985
+ try {
986
+ state.ensureSession('fork-mode-host', { cwd: path.join(home, 'proj-mode-host'), agentPreset: 'coding' })
987
+ const ctx = host({ live: true, parentOptions: { provider: 'other', model: 'other-model' } })
988
+ const result = await requestPrivateConsolidation(ctx, 'fork-mode-host')
989
+ assert.equal(result.ok, true, String(result.error || ''))
990
+ assert.deepEqual(ctx.rec.created[0].agentOptions, { provider: 'host-prov', model: 'host-model/nested' }, 'everything after the first slash is the model id')
991
+ assert.equal(startedEntryFor(ctx, 'fork-mode-host').detail.modelMode, 'host')
992
+ } finally {
993
+ restoreSettings()
994
+ }
995
+ })
996
+
997
+ test('a bad host consolidationModel is refused with its own reason, not the parent one', async () => {
998
+ state.updateSettings({ consolidationModelMode: 'host', consolidationModel: 'no-slash' })
999
+ try {
1000
+ state.ensureSession('fork-mode-host-bad', { cwd: path.join(home, 'proj-mode-host-bad'), agentPreset: 'coding' })
1001
+ const ctx = host({ live: true })
1002
+ const result = await requestPrivateConsolidation(ctx, 'fork-mode-host-bad')
1003
+ assert.equal(result.ok, false)
1004
+ assert.equal(result.reasonCode, 'invalid-consolidation-model')
1005
+ assert.match(result.error, /consolidation model \(/, 'the new reasons name the bad configuration face, not the parent route')
1006
+ assert.equal(ctx.rec.created.length, 0)
1007
+ } finally {
1008
+ restoreSettings()
1009
+ }
1010
+ })
1011
+
1012
+ test('compactSeedEvents accepts the catalog and local recall as two read-only preludes', () => {
1013
+ const user = {
1014
+ seq: 10,
1015
+ type: 'user/message',
1016
+ time: 1,
1017
+ sceneTime: '2026-11-06T04:00:00+08:00',
1018
+ data: { source: { kind: 'user' }, content: [{ type: 'text', text: '明天码头见' }] },
1019
+ }
1020
+ const catalog = {
1021
+ seq: 0,
1022
+ type: 'user/message',
1023
+ time: 1,
1024
+ data: { source: { kind: 'plugin:dsh-memu-memory', form: 'notice', summary: 'memory-catalog' }, content: [{ type: 'text', text: '[memory-catalog]' }] },
1025
+ }
1026
+ const recall = {
1027
+ seq: 0,
1028
+ type: 'user/message',
1029
+ time: 1,
1030
+ data: { source: { kind: 'plugin:dsh-memu-memory', form: 'notice', summary: 'memory-recall' }, content: [{ type: 'text', text: '[memory-recall] [mem-1] 码头' }] },
1031
+ }
1032
+ const seed = compactSeedEvents([user], [catalog, recall])
1033
+ assert.equal(seed.length, 3)
1034
+ assert.deepEqual(seed.map((event) => event.seq), [0, 1, 2])
1035
+ assert.equal(seed[0].data.source.summary, 'memory-catalog')
1036
+ assert.equal(seed[1].data.source.summary, 'memory-recall')
1037
+ assert.equal(seed[2].type, 'user/message')
1038
+ assert.match(seed[2].data.content[0].text, /事件时间/)
1039
+ })
1040
+
1041
+ // ------------------------------------------------------- surface replacements
1042
+ // Mirrors @deepseek-ai/dsh-session 0.2.2-rc.1 Session.create for the fields a
1043
+ // consolidation seed touches: seq contiguity plus the surface fold. The host
1044
+ // rejects "seed event at index N has seq M" and every dangling replace citation,
1045
+ // so the assertion has to replay the fold, not just look at one event.
1046
+ const HOST_SURFACE_EVENT_TYPES = new Set(['system/message', 'developer/message', 'user/message', 'assistant/message', 'tool/result'])
1047
+ function assertSeedAcceptedByHost(seed, label = 'seed') {
1048
+ const nodes = []
1049
+ seed.forEach((event, index) => {
1050
+ assert.equal(event.seq, index, `${label}: event at index ${index} has seq ${event.seq}`)
1051
+ if (!HOST_SURFACE_EVENT_TYPES.has(event.type)) {
1052
+ assert.equal(event.surfaceOp, undefined, `${label}: ${event.type} cannot carry surfaceOp`)
1053
+ assert.equal(event.sourceEventSeqs, undefined, `${label}: ${event.type} cannot carry sourceEventSeqs`)
1054
+ return
1055
+ }
1056
+ const op = event.surfaceOp
1057
+ assert.ok(op !== undefined, `${label}: ${event.type} at ${index} requires a surfaceOp marker`)
1058
+ const sources = event.sourceEventSeqs
1059
+ if (sources !== undefined) {
1060
+ assert.ok(Array.isArray(sources) && sources.length > 0, `${label}: sourceEventSeqs must be a non-empty array`)
1061
+ assert.equal(new Set(sources).size, sources.length, `${label}: sourceEventSeqs must not repeat`)
1062
+ assert.ok(sources.every(seq => Number.isSafeInteger(seq) && seq < event.seq), `${label}: sourceEventSeqs must reference earlier events`)
1063
+ }
1064
+ if (op === 'append') {
1065
+ nodes.push(event.seq)
1066
+ return
1067
+ }
1068
+ assert.deepEqual(Object.keys(op).sort(), ['endSeq', 'op', 'startSeq'], `${label}: replace markers carry exactly op/startSeq/endSeq`)
1069
+ assert.ok(op.startSeq < event.seq && op.endSeq < event.seq, `${label}: surface replace at ${index} must reference earlier events`)
1070
+ const startIdx = nodes.indexOf(op.startSeq)
1071
+ const endIdx = nodes.indexOf(op.endSeq)
1072
+ assert.ok(startIdx >= 0, `${label}: replace start seq ${op.startSeq} is not on the surface`)
1073
+ assert.ok(endIdx >= startIdx, `${label}: replace range must be ordered`)
1074
+ const shadowed = nodes.slice(startIdx, endIdx + 1)
1075
+ if (event.type === 'tool/result') assert.equal(shadowed.length, 1, `${label}: tool/result replacement rewrites exactly one node`)
1076
+ assert.ok(Array.isArray(sources), `${label}: replace at ${index} needs sourceEventSeqs`)
1077
+ assert.deepEqual(shadowed.filter(seq => !sources.includes(seq)), [], `${label}: replace at ${index} must cite every shadowed node`)
1078
+ nodes.splice(startIdx, endIdx - startIdx + 1)
1079
+ nodes.push(event.seq)
1080
+ })
1081
+ }
1082
+
1083
+ const userEvent = (seq, text, extra = {}) => ({
1084
+ seq, type: 'user/message', surfaceOp: 'append',
1085
+ data: { source: { kind: 'user' }, content: [{ type: 'text', text }] }, ...extra,
1086
+ })
1087
+ const assistantEvent = (seq, text) => ({
1088
+ seq, type: 'assistant/message', surfaceOp: 'append',
1089
+ data: { message: { content: [{ type: 'text', text }] } },
1090
+ })
1091
+ const toolResultEvent = (seq, text, extra = {}) => ({
1092
+ seq, type: 'tool/result', surfaceOp: 'append',
1093
+ data: { message: { content: [{ type: 'text', text }] } }, ...extra,
1094
+ })
1095
+
1096
+ test('a surface replace is renumbered into the seed instead of citing original seqs', () => {
1097
+ const seed = compactSeedEvents([
1098
+ userEvent(0, '记住:周五交房租'),
1099
+ assistantEvent(1, '好'),
1100
+ toolResultEvent(2, '原始工具输出'),
1101
+ toolResultEvent(3, '[已裁剪]', {
1102
+ surfaceOp: { op: 'replace', startSeq: 2, endSeq: 2 },
1103
+ sourceEventSeqs: [2],
1104
+ }),
1105
+ userEvent(4, '继续'),
1106
+ ])
1107
+ assert.deepEqual(seed.map(event => event.seq), [0, 1, 2, 3, 4])
1108
+ assert.deepEqual(seed[3].surfaceOp, { op: 'replace', startSeq: 2, endSeq: 2 }, 'the citation follows the surviving node, not its original seq')
1109
+ assert.deepEqual(seed[3].sourceEventSeqs, [2])
1110
+ assertSeedAcceptedByHost(seed)
1111
+ })
1112
+
1113
+ test('a replace pointing outside the window is dropped and the seed stays contiguous', () => {
1114
+ // 窗口从父会话中间切出:seq 4 不在这一窗里;后面的 replace 又引用前面被丢的
1115
+ // replace。旧实现先编号后丢弃,留下 seq 空洞,宿主报 index 1 has seq 5。
1116
+ const seed = compactSeedEvents([
1117
+ userEvent(10, '这一窗的第一句'),
1118
+ toolResultEvent(11, '输出'),
1119
+ toolResultEvent(12, '[已裁剪]', {
1120
+ surfaceOp: { op: 'replace', startSeq: 4, endSeq: 4 },
1121
+ sourceEventSeqs: [4],
1122
+ }),
1123
+ assistantEvent(13, '回答'),
1124
+ toolResultEvent(14, '[已裁剪]', {
1125
+ surfaceOp: { op: 'replace', startSeq: 12, endSeq: 12 },
1126
+ sourceEventSeqs: [12],
1127
+ }),
1128
+ ])
1129
+ assert.deepEqual(seed.map(event => event.seq), [0, 1, 2], 'dropping a patch must renumber the survivors')
1130
+ assert.equal(seed.some(event => event.surfaceOp && typeof event.surfaceOp === 'object'), false)
1131
+ assertSeedAcceptedByHost(seed)
1132
+ })
1133
+
1134
+ test('a replacement that cites another replacement keeps both when their targets survive', () => {
1135
+ const seed = compactSeedEvents([
1136
+ userEvent(0, '开头'),
1137
+ toolResultEvent(1, '原始输出'),
1138
+ toolResultEvent(2, '[第一次裁剪]', {
1139
+ surfaceOp: { op: 'replace', startSeq: 1, endSeq: 1 },
1140
+ sourceEventSeqs: [1],
1141
+ }),
1142
+ assistantEvent(3, '中间'),
1143
+ toolResultEvent(4, '[第二次裁剪]', {
1144
+ surfaceOp: { op: 'replace', startSeq: 2, endSeq: 2 },
1145
+ sourceEventSeqs: [2],
1146
+ }),
1147
+ ])
1148
+ assert.deepEqual(seed.map(event => event.seq), [0, 1, 2, 3, 4])
1149
+ assert.deepEqual(seed[2].surfaceOp, { op: 'replace', startSeq: 1, endSeq: 1 })
1150
+ assert.deepEqual(seed[4].surfaceOp, { op: 'replace', startSeq: 2, endSeq: 2 })
1151
+ assertSeedAcceptedByHost(seed)
1152
+ })
1153
+
1154
+ test('a multi-node replace is remapped when every shadowed node survives', () => {
1155
+ const seed = compactSeedEvents([
1156
+ userEvent(0, 'A'),
1157
+ userEvent(1, 'X'),
1158
+ userEvent(2, 'B'),
1159
+ userEvent(3, '外层摘要', {
1160
+ surfaceOp: { op: 'replace', startSeq: 0, endSeq: 2 },
1161
+ sourceEventSeqs: [0, 1, 2],
1162
+ }),
1163
+ ])
1164
+ assert.deepEqual(seed.map(event => event.seq), [0, 1, 2, 3])
1165
+ assert.deepEqual(seed[3].surfaceOp, { op: 'replace', startSeq: 0, endSeq: 2 })
1166
+ assert.deepEqual(seed[3].sourceEventSeqs, [0, 1, 2])
1167
+ assertSeedAcceptedByHost(seed)
1168
+ })
1169
+
1170
+ test('a replace is dropped when filtering an inner checkpoint reveals a shadowed node', () => {
1171
+ // 内层压缩检查点(source.kind 不是 user)会被种子过滤器丢掉;它遮住的 X 因此
1172
+ // 重新出现在种子的 surface 上。外层替换写于 X 被遮住期间,引用里没有 X。
1173
+ // 宿主会要求外层补上 X 的引用——补不出来就只能丢外层,种子回到纯 append。
1174
+ const seed = compactSeedEvents([
1175
+ userEvent(0, 'A'),
1176
+ userEvent(1, 'X'),
1177
+ userEvent(2, 'B'),
1178
+ userEvent(3, '内层摘要', { data: { source: { kind: 'compact-checkpoint' }, content: [{ type: 'text', text: '内层摘要' }] }, surfaceOp: { op: 'replace', startSeq: 1, endSeq: 1 }, sourceEventSeqs: [1] }),
1179
+ userEvent(4, '外层摘要', {
1180
+ surfaceOp: { op: 'replace', startSeq: 0, endSeq: 2 },
1181
+ sourceEventSeqs: [0, 2],
1182
+ }),
1183
+ ])
1184
+ assert.deepEqual(seed.map(event => event.seq), [0, 1, 2])
1185
+ assert.deepEqual(seed.map(event => event.data.content[0].text), ['A', 'X', 'B'])
1186
+ assertSeedAcceptedByHost(seed)
1187
+ })
1188
+
1189
+
1190
+ // 思考强度被模型拒绝后,记录该组合、清除失败连击,后续 fork 不再指定该档。
1191
+ // 不支持的 medium 档不应导致同一快照反复失败并进入冻结。
1192
+ function rejectMedium(spec) {
1193
+ const { provider, model, reasoningEffort } = spec.agentOptions
1194
+ return reasoningEffort === 'medium'
1195
+ ? { kind: 'error', error: { message: `provider "${provider}" model "${model}" does not support reasoning effort "medium"` } }
1196
+ : { kind: 'completed' }
1197
+ }
1198
+
1199
+ function cleanupEffortHost(t, ctx, sessionId) {
1200
+ t.after(async () => {
1201
+ const forkId = state.getSessionBinding(sessionId)?.workerEpoch?.forkSessionId
1202
+ if (forkId) await retireWorker(ctx, forkId, 'test-finished', { handoff: false })
1203
+ state.updateSettings({ consolidationRunner: 'fork', consolidationReasoningEffort: 'inherit' })
1204
+ restoreSettings()
1205
+ })
1206
+ }
1207
+
1208
+ for (const runner of ['fork', 'worker']) {
1209
+ for (const mode of ['inherit', 'custom']) {
1210
+ for (const effort of ['inherit', 'medium']) {
1211
+ test(`${runner} learns inherited medium with ${mode} route / ${effort} setting and really succeeds on retry`, async (t) => {
1212
+ const id = `effort-${runner}-${mode}-${effort}`
1213
+ const parentOptions = Object.freeze({ provider: id, model: 'test-model', reasoningEffort: 'medium', maxTokens: 32768 })
1214
+ const key = `${id}|test-model|medium`
1215
+ const ctx = host({ live: true, parentOptions, turnReason: rejectMedium })
1216
+ ctx.permissionPresets = { set: t.mock.fn() }
1217
+ cleanupEffortHost(t, ctx, id)
1218
+ state.updateSettings({ ...(mode === 'custom' ? CUSTOM : {}), consolidationRunner: runner, consolidationReasoningEffort: effort })
1219
+ state.ensureSession(id, { cwd: home, agentPreset: 'coding' })
1220
+ assert.equal(effortRefusalOf(rejectMedium({ agentOptions: parentOptions }).error.message).key, key)
1221
+ assert.equal(isEffortRefused(key), false)
1222
+
1223
+ const first = await requestPrivateConsolidation(ctx, id, { force: true })
1224
+ assert.equal(first.ok, false)
1225
+ assert.equal(first.reasonCode, 'fork-turn-failed')
1226
+ assert.equal(state.getSessionBinding(id).lastSleepSeq, undefined)
1227
+ assert.equal(isEffortRefused(key), true)
1228
+ assert.deepEqual(ctx.rec.created[0].agentOptions, parentOptions)
1229
+ assert.ok(ctx.rec.disposed.includes(first.childId), 'the failed child was retired')
1230
+ assert.equal(state.getSessionBinding(first.childId), null, 'the failed child binding was removed')
1231
+ if (runner === 'worker') assert.equal(state.getSessionBinding(id).workerEpoch ?? null, null)
1232
+ if (mode === 'custom') assert.equal(startedEntryFor(ctx, id).detail.modelMode, 'inherit-fallback')
1233
+
1234
+ const second = await requestPrivateConsolidation(ctx, id)
1235
+ assert.equal(second.skipped, undefined, 'the automatic retry is not frozen')
1236
+ assert.equal(second.ok, true, second.error || '')
1237
+ assert.equal(second.settled, true, 'the parameter-dependent host completed and its receipt settled')
1238
+ assert.equal(state.getSessionBinding(id).lastSleepSeq, 2)
1239
+ assert.equal(ctx.rec.created.length, 2, 'retry really creates a fresh child')
1240
+ assert.notEqual(second.childId, first.childId)
1241
+ const secondOptions = ctx.rec.created[1].agentOptions
1242
+ assert.equal(Object.hasOwn(secondOptions, 'reasoningEffort'), false)
1243
+ assert.deepEqual(secondOptions, { provider: id, model: 'test-model', maxTokens: 32768 })
1244
+ assert.equal(ctx.get('agents').get(id).options, parentOptions, 'the parent object is not replaced')
1245
+ assert.equal(parentOptions.reasoningEffort, 'medium', 'the parent effort is untouched')
1246
+ assert.equal(ctx.permissionPresets.set.mock.callCount(), 0, 'no automatic permission elevation')
1247
+ })
1248
+ }
1249
+ }
1250
+
1251
+ test(`${runner} applies an allowed explicit effort after custom fallback and checks only the effective route`, async (t) => {
1252
+ const id = `effort-override-${runner}`
1253
+ const parentOptions = Object.freeze({ provider: id, model: 'model', reasoningEffort: 'medium', maxTokens: 4096 })
1254
+ const ctx = host({ live: true, parentOptions, turnReason: rejectMedium })
1255
+ cleanupEffortHost(t, ctx, id)
1256
+ state.updateSettings({ ...CUSTOM, consolidationRunner: runner, consolidationReasoningEffort: 'high' })
1257
+ state.ensureSession(id, { cwd: home, agentPreset: 'coding' })
1258
+ markEffortRefused(`${id}|model|medium`)
1259
+ markEffortRefused('dsh-memu-custom|gateway-model|high')
1260
+ const result = await requestPrivateConsolidation(ctx, id, { force: true })
1261
+ assert.equal(result.ok, true, result.error || '')
1262
+ assert.equal(result.settled, true)
1263
+ assert.equal(startedEntryFor(ctx, id).detail.modelMode, 'inherit-fallback')
1264
+ assert.deepEqual(ctx.rec.created[0].agentOptions, { ...parentOptions, reasoningEffort: 'high' })
1265
+ assert.equal(parentOptions.reasoningEffort, 'medium')
1266
+ })
1267
+ }
1268
+
1269
+ test('a fresh worker shares the refusal learned by a fork', async (t) => {
1270
+ const parentOptions = Object.freeze({ provider: 'shared-effort', model: 'model', reasoningEffort: 'medium', maxTokens: 8192 })
1271
+ const ctx = host({ live: true, parentOptions, turnReason: rejectMedium })
1272
+ cleanupEffortHost(t, ctx, 'effort-shared-worker')
1273
+ state.updateSettings({ consolidationRunner: 'fork', consolidationReasoningEffort: 'inherit' })
1274
+ state.ensureSession('effort-shared-fork', { cwd: home, agentPreset: 'coding' })
1275
+ const failed = await requestPrivateConsolidation(ctx, 'effort-shared-fork', { force: true })
1276
+ assert.equal(failed.reasonCode, 'fork-turn-failed')
1277
+ state.updateSettings({ consolidationRunner: 'worker' })
1278
+ state.ensureSession('effort-shared-worker', { cwd: home, agentPreset: 'coding' })
1279
+ const result = await requestPrivateConsolidation(ctx, 'effort-shared-worker', { force: true })
1280
+ assert.equal(result.ok, true, result.error || '')
1281
+ assert.equal(result.settled, true)
1282
+ assert.match(result.childId, /^memu-worker-/)
1283
+ assert.deepEqual(ctx.rec.created[1].agentOptions, { provider: 'shared-effort', model: 'model', maxTokens: 8192 })
1284
+ assert.equal(parentOptions.reasoningEffort, 'medium')
1285
+ })
1286
+
1287
+ // 学习表需要持久化,以保留服务商与模型组合拒绝的思考强度。
1288
+ // 重启后的首次整理不应重复触发已记录的 fork-turn-failed。
1289
+ test('a learned effort refusal survives a restart — it is persisted to the data dir', async (t) => {
1290
+ state.updateSettings({ consolidationReasoningEffort: 'medium' })
1291
+ state.ensureSession('fork-effort-persist', { cwd: path.join(home, 'proj-effort-persist'), agentPreset: 'coding' })
1292
+ const ctx = host({ live: true, parentOptions: { provider: 'persist-provider', model: 'persist-model' }, turnReason: rejectMedium })
1293
+ cleanupEffortHost(t, ctx, 'fork-effort-persist')
1294
+ const first = await requestPrivateConsolidation(ctx, 'fork-effort-persist', { force: true })
1295
+ assert.equal(first.ok, false)
1296
+ assert.equal(first.reasonCode, 'fork-turn-failed')
1297
+
1298
+ const persisted = JSON.parse(fs.readFileSync(path.join(dataDir(), 'effort-refusals.json'), 'utf8'))
1299
+ assert.ok(persisted.keys.includes('persist-provider|persist-model|medium'), 'the refusal was written to the data dir')
1300
+ const child = effortChild(t, home, `assert.equal(api.isEffortRefused('persist-provider|persist-model|medium'), true)`)
1301
+ await child.ready
1302
+ child.release()
1303
+ await child.done
1304
+ })
1305
+
1306
+ // 子进程只加载测试 loader + private.js,home/cwd 全部指向临时目录。
1307
+ // IPC 屏障保证并发用例里的两个进程先各自读完旧表,再同时开始 mark。
1308
+ function effortChild(t, dir, before, after = '') {
1309
+ const code = `
1310
+ import assert from 'node:assert/strict'
1311
+ const api = await import(${JSON.stringify(new URL('../lib/private.js', import.meta.url).href)})
1312
+ ${before}
1313
+ const released = new Promise(resolve => process.once('message', resolve))
1314
+ process.send('loaded')
1315
+ await released
1316
+ ${after}
1317
+ process.disconnect()
1318
+ `
1319
+ const child = spawn(process.execPath, ['--import', new URL('./loader-register.mjs', import.meta.url).href, '--input-type=module', '-e', code], {
1320
+ cwd: dir, windowsHide: true, timeout: 20_000,
1321
+ env: { ...process.env, DSH_HOME: dir, DSH_MEMU_HOME: dir, DSH_MEMU_MEMORY_HOME: dir },
1322
+ stdio: ['ignore', 'pipe', 'pipe', 'ipc'],
1323
+ })
1324
+ let errors = ''
1325
+ child.stdout.on('data', data => { errors += data })
1326
+ child.stderr.on('data', data => { errors += data })
1327
+ const ready = new Promise((resolve, reject) => {
1328
+ child.on('message', message => { if (message === 'loaded') resolve() })
1329
+ child.on('error', reject)
1330
+ child.on('close', () => reject(new Error('child exited before barrier: ' + errors)))
1331
+ })
1332
+ const done = new Promise((resolve, reject) => {
1333
+ child.on('error', reject)
1334
+ child.on('close', code => code === 0 ? resolve() : reject(new Error('effort child failed: ' + errors)))
1335
+ })
1336
+ // 在等待另一个进程抵达屏障时也接住早退;原 promise 仍供断言 await。
1337
+ ready.catch(() => {})
1338
+ done.catch(() => {})
1339
+ t.after(() => { if (child.exitCode === null) child.kill() })
1340
+ return { ready, done, release: () => child.send('mark') }
1341
+ }
1342
+
1343
+ function refusalStore(t) {
1344
+ state.flushState()
1345
+ const dir = fs.mkdtempSync(path.join(home, 'effort-store-'))
1346
+ const previous = [process.env.DSH_MEMU_HOME, process.env.DSH_MEMU_MEMORY_HOME]
1347
+ process.env.DSH_MEMU_HOME = process.env.DSH_MEMU_MEMORY_HOME = dir
1348
+ const warnings = []
1349
+ setWarnSink(message => warnings.push(message))
1350
+ t.after(() => {
1351
+ ;[process.env.DSH_MEMU_HOME, process.env.DSH_MEMU_MEMORY_HOME] = previous
1352
+ setWarnSink(null)
1353
+ })
1354
+ return { dir, file: path.join(dir, 'effort-refusals.json'), warnings }
1355
+ }
1356
+
1357
+ function seedRefusals(file, keys) {
1358
+ const raw = JSON.stringify({ version: 1, keys })
1359
+ fs.writeFileSync(file, raw)
1360
+ return raw
1361
+ }
1362
+
1363
+ function refusalKeys(file) {
1364
+ return JSON.parse(fs.readFileSync(file, 'utf8')).keys.sort()
1365
+ }
1366
+
1367
+ test('refusals load lazily once and clean queries/duplicate marks perform no file IO', async (t) => {
1368
+ const { file } = refusalStore(t)
1369
+ seedRefusals(file, ['initial|model|medium'])
1370
+ const read = t.mock.method(fs, 'readFileSync')
1371
+ const write = t.mock.method(fs, 'writeFileSync')
1372
+ const fresh = await import('../lib/private.js?effort-lazy')
1373
+ const tableReads = () => read.mock.calls.filter(call => call.arguments[0] === file).length
1374
+ assert.equal(tableReads(), 0, 'import does not capture or read a home')
1375
+ assert.equal(fresh.isEffortRefused('initial|model|medium'), true)
1376
+ assert.equal(tableReads(), 1)
1377
+ for (let i = 0; i < 20; i++) {
1378
+ assert.equal(fresh.isEffortRefused('initial|model|medium'), true)
1379
+ assert.equal(fresh.isEffortRefused('unknown|model|medium'), false)
1380
+ fresh.markEffortRefused('initial|model|medium')
1381
+ }
1382
+ assert.equal(tableReads(), 1, 'a clean cache never rescans the table')
1383
+ assert.equal(write.mock.callCount(), 0, 'queries and duplicate clean marks never rewrite the table')
1384
+ })
1385
+
1386
+ test('a failed initial read never replaces old keys and retries after IO recovers', (t) => {
1387
+ const { file, warnings } = refusalStore(t)
1388
+ const original = seedRefusals(file, ['old|model|medium'])
1389
+ const read = fs.readFileSync
1390
+ let failing = true
1391
+ t.mock.method(fs, 'readFileSync', function (target, ...args) {
1392
+ if (target === file && failing) throw Object.assign(new Error('read failed api_key=secret123456789'), { code: 'EIO' })
1393
+ return read.call(this, target, ...args)
1394
+ })
1395
+ assert.equal(isEffortRefused('old|model|medium'), false, 'an unreadable key is not yet known')
1396
+ markEffortRefused('new|model|medium')
1397
+ assert.equal(isEffortRefused('new|model|medium'), true, 'new knowledge survives the failed read')
1398
+ assert.equal(read(file, 'utf8'), original, 'read failure cannot be saved back as an empty table')
1399
+ assert.ok(warnings.length > 0)
1400
+ assert.ok(warnings.every(message => !message.includes('secret123456789')), 'warnings use the existing redaction sink')
1401
+ failing = false
1402
+ assert.equal(isEffortRefused('old|model|medium'), true, 'the query retries the pending merge')
1403
+ assert.deepEqual(refusalKeys(file), ['new|model|medium', 'old|model|medium'])
1404
+ })
1405
+
1406
+ for (const retry of ['same-key mark', 'query']) {
1407
+ test(`an atomic write failure keeps pending keys and recovers on ${retry}`, (t) => {
1408
+ const { dir, file, warnings } = refusalStore(t)
1409
+ const original = seedRefusals(file, ['old|model|medium'])
1410
+ assert.equal(isEffortRefused('old|model|medium'), true)
1411
+ const rename = fs.renameSync
1412
+ let failing = true
1413
+ t.mock.method(fs, 'renameSync', function (from, to) {
1414
+ if (to === file && failing) throw Object.assign(new Error('injected rename failure'), { code: 'EIO' })
1415
+ return rename.call(this, from, to)
1416
+ })
1417
+ markEffortRefused('new|model|medium')
1418
+ assert.equal(isEffortRefused('new|model|medium'), true)
1419
+ assert.equal(fs.readFileSync(file, 'utf8'), original, 'failed atomic replace preserves the previous bytes')
1420
+ assert.deepEqual(fs.readdirSync(dir), ['effort-refusals.json'], 'temporary files and locks are cleaned')
1421
+ assert.ok(warnings.some(message => message.includes('injected rename failure')))
1422
+ failing = false
1423
+ if (retry === 'same-key mark') markEffortRefused('new|model|medium')
1424
+ else assert.equal(isEffortRefused('old|model|medium'), true, 'even an unrelated lookup flushes pending knowledge')
1425
+ assert.deepEqual(refusalKeys(file), ['new|model|medium', 'old|model|medium'])
1426
+ const reads = t.mock.method(fs, 'readFileSync')
1427
+ const writes = t.mock.method(fs, 'writeFileSync')
1428
+ isEffortRefused('new|model|medium')
1429
+ markEffortRefused('new|model|medium')
1430
+ assert.equal(reads.mock.callCount(), 0, 'successful recovery clears the pending state')
1431
+ assert.equal(writes.mock.callCount(), 0)
1432
+ })
1433
+ }
1434
+
1435
+ for (const [label, raw] of [
1436
+ ['broken JSON', '{"version":1,"keys":['],
1437
+ ['invalid keys', JSON.stringify({ version: 1, keys: [123] })],
1438
+ ['unknown schema', JSON.stringify({ version: 2, keys: [] })],
1439
+ ]) {
1440
+ test(`${label} is never overwritten, and pending knowledge merges after repair`, (t) => {
1441
+ const { file, warnings } = refusalStore(t)
1442
+ fs.writeFileSync(file, raw)
1443
+ assert.equal(isEffortRefused('pending|model|medium'), false)
1444
+ markEffortRefused('pending|model|medium')
1445
+ assert.equal(isEffortRefused('pending|model|medium'), true)
1446
+ assert.equal(fs.readFileSync(file, 'utf8'), raw)
1447
+ assert.ok(warnings.length > 0)
1448
+ seedRefusals(file, ['restored|model|high'])
1449
+ assert.equal(isEffortRefused('restored|model|high'), true)
1450
+ assert.deepEqual(refusalKeys(file), ['pending|model|medium', 'restored|model|high'])
1451
+ })
1452
+ }
1453
+
1454
+ test('refusal caches and writes follow the current home without leaking keys', (t) => {
1455
+ const { file: firstFile } = refusalStore(t)
1456
+ assert.equal(isEffortRefused('first|model|medium'), false, 'ENOENT starts an empty table')
1457
+ markEffortRefused('first|model|medium')
1458
+ const secondDir = fs.mkdtempSync(path.join(home, 'effort-other-'))
1459
+ const secondFile = path.join(secondDir, 'effort-refusals.json')
1460
+ seedRefusals(secondFile, ['second|model|high'])
1461
+ process.env.DSH_MEMU_HOME = process.env.DSH_MEMU_MEMORY_HOME = secondDir
1462
+ assert.equal(isEffortRefused('first|model|medium'), false)
1463
+ assert.equal(isEffortRefused('second|model|high'), true)
1464
+ markEffortRefused('second|model|medium')
1465
+ process.env.DSH_MEMU_HOME = process.env.DSH_MEMU_MEMORY_HOME = path.dirname(firstFile)
1466
+ assert.equal(isEffortRefused('first|model|medium'), true)
1467
+ assert.equal(isEffortRefused('second|model|medium'), false)
1468
+ assert.deepEqual(refusalKeys(firstFile), ['first|model|medium'])
1469
+ assert.deepEqual(refusalKeys(secondFile), ['second|model|high', 'second|model|medium'])
1470
+ })
1471
+
1472
+ test('two processes merge stale refusal snapshots under the file lock', async (t) => {
1473
+ const { dir, file } = refusalStore(t)
1474
+ seedRefusals(file, ['old|model|medium'])
1475
+ const children = ['left', 'right'].map(name => effortChild(t, dir,
1476
+ `assert.equal(api.isEffortRefused('old|model|medium'), true)`,
1477
+ `api.markEffortRefused('${name}|model|medium'); assert.equal(api.isEffortRefused('${name}|model|medium'), true)`,
1478
+ ))
1479
+ await Promise.all(children.map(child => child.ready))
1480
+ for (const child of children) child.release()
1481
+ await Promise.all(children.map(child => child.done))
1482
+ assert.deepEqual(refusalKeys(file), ['left|model|medium', 'old|model|medium', 'right|model|medium'])
1483
+ })
1484
+
1485
+ test('missing buildForkSeed only disables fork; worker really completes without loading the seed API', async (t) => {
1486
+ const dir = fs.mkdtempSync(path.join(home, 'missing-seed-'))
1487
+ const before = `
1488
+ const { registerHooks } = await import('node:module')
1489
+ let seedImports = 0
1490
+ const hooks = registerHooks({ resolve(specifier, context, next) {
1491
+ if (specifier === '@deepseek-ai/dsh-session') {
1492
+ seedImports++
1493
+ return { url: 'data:text/javascript,export const unavailable = true', shortCircuit: true }
1494
+ }
1495
+ return next(specifier, context)
1496
+ } })
1497
+ const state = await import(${JSON.stringify(new URL('../lib/state.js', import.meta.url).href)})
1498
+ const home = ${JSON.stringify(dir)}
1499
+ const META_KEYS = ${JSON.stringify(META_KEYS)}
1500
+ const assertHostCreateAccepts = ${assertHostCreateAccepts.toString()}
1501
+ const host = ${host.toString()}
1502
+ const ctx = host({ live: true, cwd: home })
1503
+ state.ensureSession('missing-seed-fork', { cwd: home, agentPreset: 'coding' })
1504
+ state.updateSettings({ consolidationRunner: 'fork', consolidationReasoningEffort: 'inherit' })
1505
+ const fork = await api.requestPrivateConsolidation(ctx, 'missing-seed-fork', { force: true })
1506
+ assert.equal(fork.reasonCode, 'no-fork-seed')
1507
+ assert.equal(fork.settled, false)
1508
+ assert.equal(ctx.rec.created.length, 0)
1509
+ const afterFork = seedImports
1510
+ state.ensureSession('missing-seed-worker', { cwd: home, agentPreset: 'coding' })
1511
+ state.updateSettings({ consolidationRunner: 'worker' })
1512
+ const worker = await api.requestPrivateConsolidation(ctx, 'missing-seed-worker', { force: true })
1513
+ assert.equal(worker.ok, true, worker.error || '')
1514
+ assert.equal(worker.settled, true)
1515
+ assert.equal(ctx.rec.created.length, 1)
1516
+ assert.equal(ctx.rec.created[0].seed, undefined)
1517
+ assert.equal(state.getSessionBinding('missing-seed-worker').lastSleepSeq, 2)
1518
+ assert.equal(seedImports, afterFork, 'worker never imports the missing seed API')
1519
+ hooks.deregister()
1520
+ `
1521
+ const child = effortChild(t, dir, before)
1522
+ await child.ready
1523
+ child.release()
1524
+ await child.done
1525
+ })
1526
+
1527
+ test('coding seeds keep more tool output and arguments than the default caps', () => {
1528
+ const events = [
1529
+ { seq: 0, type: 'user/message', data: { source: { kind: 'user' }, content: [{ type: 'text', text: '改代码' }] } },
1530
+ { seq: 1, type: 'tool/call', data: { callId: 'c1', name: 'edit', arguments: '{"patch":"' + 'A'.repeat(1500) + '"}' } },
1531
+ { seq: 2, type: 'tool/result', data: { message: { callId: 'c1', content: [{ type: 'text', text: 'R'.repeat(3000) }] } } },
1532
+ { seq: 3, type: 'assistant/message', data: { message: { content: [{ type: 'text', text: '完成' }] } } },
1533
+ ]
1534
+ const sizes = (seed) => ({
1535
+ args: String(seed.find((event) => event.type === 'tool/call').data.arguments).length,
1536
+ result: String(seed.find((event) => event.type === 'tool/result').data.message.content[0].text).length,
1537
+ })
1538
+ const plain = sizes(compactSeedEvents(events))
1539
+ const coding = sizes(compactSeedEvents(events, null, seedLimitsFor('coding')))
1540
+ assert.ok(plain.args <= 510, 'the default argument cap is unchanged')
1541
+ assert.ok(coding.args > 1000, 'coding keeps a longer tool-call argument body')
1542
+ assert.ok(plain.result <= 1110, 'the default result cap is unchanged')
1543
+ assert.ok(coding.result > 2100 && coding.result < 2300, 'coding keeps 2200 chars of the tool result')
1544
+ })
1545
+
1546
+ // fork 必须继承会话当前选定的预设。
1547
+ // 的味儿。header.agentPreset 是创建事实(deep-frozen),真正的变更在
1548
+ // agent-preset/selected 事件里;fork 必须按宿主 agentPreset 投影的口径建。
1549
+ test('a fork inherits the preset the session selected, not the one in its header', async () => {
1550
+ const id = 'fork-preset-selected'
1551
+ state.ensureSession(id, { cwd: path.join(home, 'proj-preset'), agentPreset: 'standard' })
1552
+ const presets = {
1553
+ composedPreset: () => undefined,
1554
+ mount: async (childCtx, presetId) => { ctxForPreset.rec.mountedPresets.push(presetId); return { id: presetId } },
1555
+ }
1556
+ const ctxForPreset = host({
1557
+ live: true,
1558
+ cwd: path.join(home, 'proj-preset'),
1559
+ extraEvents: [{ seq: 0, type: 'agent-preset/selected', data: { agentPreset: 'custom-preset' } }],
1560
+ presets,
1561
+ })
1562
+ const ctx = ctxForPreset
1563
+ // 事件顺序:selected 必须在会话开头(宿主在空白期才允许改预设)。
1564
+ ctx.get('sessionQuery').readSession = async () => ({
1565
+ events: [
1566
+ { seq: 0, type: 'agent-preset/selected', data: { agentPreset: 'custom-preset' } },
1567
+ { seq: 1, type: 'turn/start', data: { turn: 1 } },
1568
+ { seq: 2, type: 'step/start', data: { turn: 1, step: 1 } },
1569
+ { seq: 3, type: 'user/message', data: { source: { kind: 'user' }, content: [{ type: 'text', text: '今天想聊聊那件事' }] } },
1570
+ { seq: 4, type: 'assistant/message', data: { message: { content: [{ type: 'text', text: '嗯,我在听' }] } } },
1571
+ { seq: 5, type: 'step/end', data: { turn: 1, step: 1 } },
1572
+ { seq: 6, type: 'turn/end', data: { turn: 1, reason: { kind: 'completed' } } },
1573
+ ],
1574
+ session: { cwd: path.join(home, 'proj-preset'), agentPreset: 'standard' },
1575
+ })
1576
+ const result = await requestPrivateConsolidation(ctx, id)
1577
+ assert.equal(result.ok, true)
1578
+ assert.equal(ctx.rec.created.length, 1, 'one scratch fork')
1579
+ // header 只是标签(agent-loop 从不读 meta.agentPreset);真正的行为在 setup → mount。
1580
+ assert.equal(ctx.rec.created[0].meta.agentPreset, 'custom-preset', 'the header names what the session actually runs')
1581
+ assert.equal(typeof ctx.rec.created[0].setup, 'function', 'the fork must carry a setup hook, or the preset is never mounted')
1582
+ assert.deepEqual(ctx.rec.mountedPresets, ['custom-preset'], 'and that hook has to actually mount the preset')
1583
+ assert.deepEqual(ctx.rec.forkLogLines.filter((line) => line.type === 'agent-preset/selected'),
1584
+ [{ type: 'agent-preset/selected', data: { agentPreset: 'custom-preset' } }],
1585
+ 'the fork log records the composition the model saw')
1586
+ })