dsh-memu-memory 1.4.2 → 1.4.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (389) hide show
  1. package/AGENTS.md +108 -110
  2. package/CHANGELOG.md +173 -868
  3. package/LICENSE +21 -21
  4. package/README.md +368 -374
  5. package/README.zh.md +354 -360
  6. package/assets/icon.svg +7 -7
  7. package/cordis.patch.yml +8 -8
  8. package/docs/active-memory-ab.md +279 -385
  9. package/docs/binding-lifecycle.md +99 -99
  10. package/docs/client-conventions.md +75 -75
  11. package/docs/contributing.md +217 -217
  12. package/docs/emotion-model-spec.md +247 -281
  13. package/docs/env-and-commands.md +149 -152
  14. package/docs/host-adaptation.md +339 -360
  15. package/docs/host-api.md +131 -137
  16. package/docs/host-versions.md +117 -120
  17. package/docs/mcp-porting.md +146 -146
  18. package/docs/memory-semantics.md +271 -259
  19. package/docs/pending-work.md +44 -51
  20. package/docs/troubleshooting.md +909 -854
  21. package/lib/active-memory.js +160 -165
  22. package/lib/activity-log.js +207 -207
  23. package/lib/auto-link/apply.js +248 -249
  24. package/lib/auto-link/candidates.js +163 -163
  25. package/lib/auto-link/decide.js +300 -300
  26. package/lib/auto-link/normalize.js +99 -99
  27. package/lib/auto-link/policy.js +42 -42
  28. package/lib/auto-link/suppression.js +101 -101
  29. package/lib/auto-link/terminology.js +311 -311
  30. package/lib/backup.js +1254 -1254
  31. package/lib/binding-diagnostics.js +634 -634
  32. package/lib/budget.js +118 -118
  33. package/lib/client.js +9820 -9751
  34. package/lib/commitment.js +178 -138
  35. package/lib/consolidation-ledger.js +434 -438
  36. package/lib/consolidation-receipt.js +386 -387
  37. package/lib/consolidation-snapshot.js +420 -405
  38. package/lib/consolidation-worker.js +240 -241
  39. package/lib/context.js +33 -33
  40. package/lib/curator-evidence.js +131 -131
  41. package/lib/curator-policy.js +198 -202
  42. package/lib/curator.js +1813 -1811
  43. package/lib/cycle.js +524 -513
  44. package/lib/diagnostics.js +524 -524
  45. package/lib/embedding-catalog.js +1051 -1055
  46. package/lib/embedding-download.js +637 -607
  47. package/lib/embedding-runtime.js +946 -946
  48. package/lib/engine.js +1103 -1103
  49. package/lib/entity-repair.js +285 -285
  50. package/lib/environment-check.js +394 -394
  51. package/lib/fork-model.js +312 -312
  52. package/lib/freshness.js +128 -121
  53. package/lib/global-graph.js +389 -389
  54. package/lib/graph.js +1193 -1193
  55. package/lib/host-surface.js +30 -30
  56. package/lib/inbound.js +284 -281
  57. package/lib/index.js +506 -511
  58. package/lib/inject.js +2639 -2619
  59. package/lib/lexicon-scope.js +143 -143
  60. package/lib/lexicon.js +1183 -1192
  61. package/lib/lifecycle-audit.js +37 -0
  62. package/lib/local-embedding-entry.js +145 -145
  63. package/lib/local-embedding-manager.js +306 -306
  64. package/lib/local-embedding-protocol.js +210 -210
  65. package/lib/local-embedding-worker.js +682 -682
  66. package/lib/local-vector-service.js +506 -453
  67. package/lib/maintenance-ledger.js +138 -0
  68. package/lib/maintenance-review.js +103 -0
  69. package/lib/maintenance-runner.js +267 -0
  70. package/lib/managed-runtime.js +118 -118
  71. package/lib/media.js +607 -513
  72. package/lib/memory.js +5035 -4941
  73. package/lib/memu-config.js +213 -213
  74. package/lib/memu.js +565 -565
  75. package/lib/migrate.js +200 -200
  76. package/lib/mood.js +300 -300
  77. package/lib/paths.js +453 -457
  78. package/lib/port-surface.js +82 -82
  79. package/lib/preset-mount.js +85 -0
  80. package/lib/preset-scope.js +126 -126
  81. package/lib/private-links.js +567 -567
  82. package/lib/private.js +2198 -2209
  83. package/lib/prompts/global-curator.md +135 -135
  84. package/lib/prompts/image-caption.md +1 -1
  85. package/lib/prompts/private-consolidation.coding.md +39 -39
  86. package/lib/prompts/private-consolidation.md +32 -32
  87. package/lib/prompts/private-consolidation.mixed.md +37 -37
  88. package/lib/prompts/private-consolidation.rp.md +47 -47
  89. package/lib/prompts/private-policy.coding.md +35 -35
  90. package/lib/prompts/private-policy.md +36 -36
  91. package/lib/prompts/private-policy.mixed.md +29 -29
  92. package/lib/prompts/private-policy.rp.md +43 -43
  93. package/lib/prompts/system-guide.coding.md +20 -20
  94. package/lib/prompts/system-guide.md +25 -25
  95. package/lib/prompts/system-guide.mixed.md +22 -22
  96. package/lib/prompts/system-guide.rp.md +23 -23
  97. package/lib/prompts.js +331 -331
  98. package/lib/recall-cache.js +212 -212
  99. package/lib/remote-summary.js +123 -123
  100. package/lib/rpc.js +2531 -2532
  101. package/lib/salient-wake.js +438 -438
  102. package/lib/snippet.js +125 -125
  103. package/lib/state.js +1948 -1928
  104. package/lib/stats.js +236 -236
  105. package/lib/temporal.js +345 -348
  106. package/lib/text-retrieval.js +992 -1001
  107. package/lib/text-similarity.js +305 -305
  108. package/lib/tokenizer-v2.js +271 -271
  109. package/lib/tools.js +1098 -1091
  110. package/lib/turn-log.js +545 -545
  111. package/lib/vector-migration.js +928 -930
  112. package/lib/vector-profile.js +1353 -1359
  113. package/lib/visibility.js +59 -59
  114. package/lib/webui/graph-LICENSE.txt +1 -1
  115. package/lib/webui/graph-view.bundle.js +2 -2
  116. package/lib/webui/graph-view.js +1171 -1175
  117. package/lib/webui/mark.svg +7 -7
  118. package/lib/webui/standalone.css +1178 -1178
  119. package/lib/webui/standalone.js +238 -238
  120. package/lib/webui.js +136 -136
  121. package/lib/worker-pool.js +1020 -979
  122. package/package.json +153 -153
  123. package/requirements.lock +34 -34
  124. package/scripts/acceptance-local.mjs +946 -946
  125. package/scripts/active-memory-ab-live.mjs +653 -655
  126. package/scripts/active-memory-ab.mjs +1302 -1302
  127. package/scripts/audit-memory-lifecycle.mjs +55 -0
  128. package/scripts/bench-recall.mjs +142 -142
  129. package/scripts/build-graph.mjs +44 -45
  130. package/scripts/chain-matrix.mjs +541 -541
  131. package/scripts/check-all.mjs +68 -74
  132. package/scripts/check-doc-drift.mjs +547 -547
  133. package/scripts/check-graph-browser.mjs +261 -261
  134. package/scripts/check-i18n.mjs +81 -83
  135. package/scripts/check-idle-compositing.mjs +61 -61
  136. package/scripts/check-seed-compat.mjs +115 -118
  137. package/scripts/check-text-format.mjs +55 -0
  138. package/scripts/curator-pair-calibrate.mjs +259 -259
  139. package/scripts/diagnose-bindings.mjs +176 -176
  140. package/scripts/drive-session.mjs +863 -864
  141. package/scripts/engine-smoke.mjs +69 -69
  142. package/scripts/entity-dedupe.mjs +110 -110
  143. package/scripts/lexicon-calibrate.mjs +230 -230
  144. package/scripts/lexicon-dedupe.mjs +318 -318
  145. package/scripts/local-runtime-install.mjs +142 -142
  146. package/scripts/local-runtime-verify.mjs +56 -56
  147. package/scripts/local-vector-verify.mjs +93 -93
  148. package/scripts/make-readme-shots.mjs +59 -59
  149. package/scripts/migrate-visibility.mjs +94 -94
  150. package/scripts/mock-llm.mjs +938 -903
  151. package/scripts/preview.mjs +58 -58
  152. package/scripts/prune-sessions.mjs +31 -34
  153. package/scripts/prune-turnlogs.mjs +29 -30
  154. package/scripts/prune-vectors.mjs +24 -24
  155. package/scripts/rebuild-auto-links.mjs +252 -252
  156. package/scripts/recall-bench.mjs +820 -820
  157. package/scripts/repetition-ab-scenarios.mjs +93 -93
  158. package/scripts/repetition-detector-snapshot.mjs +314 -314
  159. package/scripts/repetition-eval-live.mjs +360 -360
  160. package/scripts/repetition-eval.mjs +702 -702
  161. package/scripts/replay.mjs +705 -575
  162. package/scripts/setup.mjs +46 -46
  163. package/scripts/simulate-injection.mjs +299 -301
  164. package/tests/absorb-review.test.mjs +354 -354
  165. package/tests/activation.test.mjs +89 -89
  166. package/tests/active-memory-ab.test.mjs +745 -745
  167. package/tests/active-memory.test.mjs +129 -129
  168. package/tests/activity-log.test.mjs +126 -126
  169. package/tests/activity-wiring.test.mjs +155 -155
  170. package/tests/appendix-b.test.mjs +217 -217
  171. package/tests/appendix-b2.test.mjs +166 -166
  172. package/tests/audit-batch3.test.mjs +247 -247
  173. package/tests/audit-regression.test.mjs +275 -275
  174. package/tests/audit-safety.test.mjs +227 -227
  175. package/tests/auto-link-candidates.test.mjs +245 -245
  176. package/tests/auto-link-decide.test.mjs +512 -512
  177. package/tests/auto-link-migration.test.mjs +133 -133
  178. package/tests/backend-compensation.test.mjs +272 -272
  179. package/tests/backup.test.mjs +793 -793
  180. package/tests/binding-diagnostics.test.mjs +720 -720
  181. package/tests/browser.test.mjs +476 -476
  182. package/tests/client-export.test.mjs +521 -521
  183. package/tests/client-render.test.mjs +2008 -1728
  184. package/tests/coalesce.test.mjs +113 -113
  185. package/tests/commitment.test.mjs +243 -144
  186. package/tests/config.test.mjs +159 -159
  187. package/tests/consolidation-credential.test.mjs +330 -330
  188. package/tests/consolidation-feed.test.mjs +122 -122
  189. package/tests/consolidation-fork.test.mjs +1587 -1539
  190. package/tests/consolidation-ledger.test.mjs +389 -389
  191. package/tests/consolidation-snapshot.test.mjs +567 -505
  192. package/tests/consolidation-value.test.mjs +89 -89
  193. package/tests/context-scope.test.mjs +40 -40
  194. package/tests/cross-library-recall.test.mjs +269 -269
  195. package/tests/cue.test.mjs +58 -58
  196. package/tests/curator-absorb.test.mjs +444 -444
  197. package/tests/curator-calibrate.test.mjs +173 -173
  198. package/tests/curator-clusters.test.mjs +306 -306
  199. package/tests/curator-commit.test.mjs +325 -325
  200. package/tests/curator-contract.test.mjs +191 -191
  201. package/tests/curator-evidence.test.mjs +102 -102
  202. package/tests/curator-link.test.mjs +317 -317
  203. package/tests/curator-pairing.test.mjs +339 -339
  204. package/tests/curator-probe.test.mjs +490 -490
  205. package/tests/curator-review-mode.test.mjs +315 -315
  206. package/tests/curator.test.mjs +152 -152
  207. package/tests/cycle.test.mjs +567 -568
  208. package/tests/diagnostics.test.mjs +278 -278
  209. package/tests/disclosure.test.mjs +249 -249
  210. package/tests/doc-drift.test.mjs +342 -342
  211. package/tests/drive-session.test.mjs +152 -152
  212. package/tests/dynamic-rrf.test.mjs +182 -182
  213. package/tests/dynamic-threshold.test.mjs +52 -52
  214. package/tests/embedding-catalog.test.mjs +374 -374
  215. package/tests/embedding-download.test.mjs +529 -486
  216. package/tests/embedding-runtime.test.mjs +449 -449
  217. package/tests/emotion-chain.test.mjs +84 -84
  218. package/tests/emotion-contract.test.mjs +445 -445
  219. package/tests/engine.test.mjs +108 -108
  220. package/tests/entity-merge.test.mjs +278 -278
  221. package/tests/environment-check.test.mjs +187 -187
  222. package/tests/fact-version.test.mjs +146 -146
  223. package/tests/fixtures/active-memory-ab/README.md +56 -56
  224. package/tests/fixtures/active-memory-ab/cases/01-clean-dense-turn.json +351 -351
  225. package/tests/fixtures/active-memory-ab/cases/02-clean-thin-turn.json +122 -122
  226. package/tests/fixtures/active-memory-ab/cases/03-clean-starved-small.json +125 -125
  227. package/tests/fixtures/active-memory-ab/cases/04-clean-large-thin.json +137 -137
  228. package/tests/fixtures/active-memory-ab/cases/05-clean-half-step.json +166 -166
  229. package/tests/fixtures/active-memory-ab/cases/06-clean-duplicate-reread.json +197 -197
  230. package/tests/fixtures/active-memory-ab/cases/07-clean-recent-recall.json +125 -125
  231. package/tests/fixtures/active-memory-ab/cases/08-global-relevant.json +111 -111
  232. package/tests/fixtures/active-memory-ab/cases/09-global-irrelevant-conflict.json +158 -158
  233. package/tests/fixtures/active-memory-ab/cases/10-no-human-turn.json +97 -97
  234. package/tests/fixtures/active-memory-ab/cases/11-clean-scale-100.json +137 -137
  235. package/tests/fixtures/active-memory-ab/cases/12-clean-scale-1000.json +137 -137
  236. package/tests/fixtures/active-memory-ab/cases/13-clean-scale-5000.json +137 -137
  237. package/tests/fixtures/active-memory-ab/cases/14-clean-scale-20000.json +137 -137
  238. package/tests/fixtures/active-memory-ab/lead-ai-reviewed-reference.json +191 -191
  239. package/tests/fixtures/active-memory-ab/manifest.json +199 -199
  240. package/tests/fixtures/curator-pairs/labeled.v1.jsonl +90 -90
  241. package/tests/fixtures/lexicon-stub-hooks.mjs +15 -15
  242. package/tests/fixtures/lexicon-stub.mjs +284 -284
  243. package/tests/fixtures/mock-llm/reply.txt +1 -1
  244. package/tests/fixtures/recall-bench/01-paraphrase.json +183 -183
  245. package/tests/fixtures/recall-bench/02-exact.json +152 -152
  246. package/tests/fixtures/recall-bench/03-negation.json +172 -172
  247. package/tests/fixtures/recall-bench/04-no-answer.json +161 -161
  248. package/tests/fixtures/recall-bench/05-conflict.json +193 -193
  249. package/tests/fixtures/recall-bench/06-boundary.json +272 -272
  250. package/tests/fixtures/recall-bench/07-secret.json +190 -190
  251. package/tests/fixtures/recall-bench/08-coding.json +163 -163
  252. package/tests/fixtures/recall-bench-gold-candidates/01-paraphrase.json +193 -193
  253. package/tests/fixtures/recall-bench-gold-candidates/02-exact.json +197 -197
  254. package/tests/fixtures/recall-bench-gold-candidates/03-negation.json +244 -244
  255. package/tests/fixtures/recall-bench-gold-candidates/04-no-answer.json +189 -189
  256. package/tests/fixtures/recall-bench-gold-candidates/05-conflict.json +245 -245
  257. package/tests/fixtures/recall-bench-gold-candidates/06-boundary.json +279 -279
  258. package/tests/fixtures/recall-bench-gold-candidates/07-secret.json +224 -224
  259. package/tests/fixtures/recall-bench-gold-candidates/08-coding.json +218 -218
  260. package/tests/fixtures/repetition-eval/01-zh-rp.json +92 -92
  261. package/tests/fixtures/repetition-eval/02-en.json +96 -96
  262. package/tests/fixtures/repetition-eval/03-code.json +90 -90
  263. package/tests/fixtures/repetition-eval/04-names.json +115 -115
  264. package/tests/fixtures/repetition-eval/05-user-quote.json +95 -95
  265. package/tests/fixtures/repetition-eval/06-agreement.json +85 -85
  266. package/tests/fixtures/tokenizer-cases.mjs +27 -27
  267. package/tests/fork-model.test.mjs +345 -345
  268. package/tests/freshness.test.mjs +140 -140
  269. package/tests/global-graph.test.mjs +106 -106
  270. package/tests/global-lifecycle.test.mjs +149 -149
  271. package/tests/graph-cascade.test.mjs +363 -363
  272. package/tests/graph-view.test.mjs +414 -414
  273. package/tests/graph.test.mjs +371 -371
  274. package/tests/help-page.test.mjs +416 -416
  275. package/tests/hook-order.test.mjs +72 -72
  276. package/tests/humanlike.test.mjs +232 -232
  277. package/tests/hybrid-recall.test.mjs +610 -610
  278. package/tests/inbound.test.mjs +441 -441
  279. package/tests/inject-conflict.test.mjs +173 -173
  280. package/tests/inject-guide.test.mjs +513 -513
  281. package/tests/inject.test.mjs +384 -384
  282. package/tests/injection-budget-settings.test.mjs +35 -35
  283. package/tests/injection-budget.test.mjs +165 -165
  284. package/tests/injection-chain.test.mjs +442 -442
  285. package/tests/injection-intent-budget.test.mjs +92 -92
  286. package/tests/injection-rollback.test.mjs +428 -428
  287. package/tests/issue2-chain.test.mjs +169 -169
  288. package/tests/lexical-bm25.test.mjs +171 -171
  289. package/tests/lexicon-calibrate.test.mjs +48 -48
  290. package/tests/lexicon-dedupe.test.mjs +171 -171
  291. package/tests/lexicon-frequency.test.mjs +195 -195
  292. package/tests/lexicon-inject.test.mjs +459 -459
  293. package/tests/lexicon-perf.test.mjs +464 -464
  294. package/tests/lexicon-scope.test.mjs +256 -256
  295. package/tests/lexicon-ui.test.mjs +667 -667
  296. package/tests/lexicon.test.mjs +922 -922
  297. package/tests/lifecycle-audit.test.mjs +56 -0
  298. package/tests/loader-register.mjs +3 -3
  299. package/tests/loader.mjs +17 -17
  300. package/tests/local-embedding-entry.test.mjs +95 -95
  301. package/tests/local-embedding-env.test.mjs +51 -51
  302. package/tests/local-embedding-manager.test.mjs +494 -494
  303. package/tests/local-embedding-protocol.test.mjs +121 -121
  304. package/tests/local-embedding-worker.test.mjs +440 -440
  305. package/tests/local-vector-service.test.mjs +41 -0
  306. package/tests/maintenance-status.test.mjs +77 -0
  307. package/tests/maintenance.test.mjs +438 -0
  308. package/tests/managed-memory.test.mjs +1234 -1234
  309. package/tests/managed-runtime.test.mjs +72 -72
  310. package/tests/media-injection.test.mjs +225 -0
  311. package/tests/media.test.mjs +135 -135
  312. package/tests/memory-chain.test.mjs +169 -169
  313. package/tests/memory-fields.test.mjs +134 -134
  314. package/tests/memu-resident-route.test.mjs +130 -130
  315. package/tests/memu-resident.test.mjs +33 -33
  316. package/tests/migration-payload.test.mjs +40 -42
  317. package/tests/mock-llm.test.mjs +263 -225
  318. package/tests/mood.test.mjs +109 -109
  319. package/tests/multiprocess.test.mjs +29 -29
  320. package/tests/negation-polarity.test.mjs +135 -135
  321. package/tests/new-session-gate.test.mjs +617 -617
  322. package/tests/open-loop-date.test.mjs +416 -416
  323. package/tests/ops-hardening.test.mjs +209 -209
  324. package/tests/package-shipping.test.mjs +88 -88
  325. package/tests/pending-injection.test.mjs +107 -107
  326. package/tests/port-surface.test.mjs +138 -138
  327. package/tests/preset-mount.test.mjs +132 -0
  328. package/tests/preset-scope.test.mjs +212 -212
  329. package/tests/private-links.test.mjs +493 -493
  330. package/tests/prompt-semantics.test.mjs +51 -51
  331. package/tests/prompts.test.mjs +315 -315
  332. package/tests/query-decompose.test.mjs +62 -62
  333. package/tests/react-snapshot.test.mjs +24 -24
  334. package/tests/recall-bench.test.mjs +317 -317
  335. package/tests/recall-cache.test.mjs +292 -292
  336. package/tests/recall-corpus-eligibility.test.mjs +51 -51
  337. package/tests/recall-dedup.test.mjs +446 -446
  338. package/tests/recall-intent.test.mjs +172 -172
  339. package/tests/regression-sweep.test.mjs +311 -311
  340. package/tests/reminder-fairness.test.mjs +55 -0
  341. package/tests/remote.test.mjs +140 -140
  342. package/tests/rename.test.mjs +30 -30
  343. package/tests/repetition-detector-snapshot.test.mjs +231 -231
  344. package/tests/repetition-eval-live.test.mjs +177 -177
  345. package/tests/repetition-eval.test.mjs +373 -373
  346. package/tests/salience-domain.test.mjs +173 -173
  347. package/tests/salient-date.test.mjs +142 -142
  348. package/tests/salient-wake.test.mjs +389 -389
  349. package/tests/settings-beat.test.mjs +222 -222
  350. package/tests/settings-coverage.test.mjs +97 -97
  351. package/tests/settings-plumbing.test.mjs +79 -79
  352. package/tests/short-term.test.mjs +182 -166
  353. package/tests/sidebar-beat.test.mjs +213 -213
  354. package/tests/sidebar-refresh.test.mjs +123 -123
  355. package/tests/sidebar.test.mjs +102 -74
  356. package/tests/simulate-injection.test.mjs +76 -76
  357. package/tests/slot-similarity.test.mjs +153 -153
  358. package/tests/snippet.test.mjs +79 -79
  359. package/tests/source-kind.test.mjs +52 -52
  360. package/tests/speaker-provenance.test.mjs +120 -120
  361. package/tests/stale-maintenance.test.mjs +206 -131
  362. package/tests/state-gc.test.mjs +34 -34
  363. package/tests/state.test.mjs +155 -155
  364. package/tests/stats.test.mjs +112 -112
  365. package/tests/storage.test.mjs +125 -125
  366. package/tests/stubs/child-process-spy.mjs +14 -14
  367. package/tests/stubs/dsh-llm-pi-ai.js +13 -13
  368. package/tests/stubs/dsh-llm.js +5 -5
  369. package/tests/stubs/dsh-schedule.js +140 -140
  370. package/tests/stubs/dsh-session-query.js +26 -26
  371. package/tests/stubs/dsh-session.js +7 -7
  372. package/tests/stubs/dsh-tools.js +101 -101
  373. package/tests/temporal-repair.test.mjs +78 -0
  374. package/tests/temporal.test.mjs +124 -124
  375. package/tests/text-format.test.mjs +24 -0
  376. package/tests/tokenizer-v2.test.mjs +142 -142
  377. package/tests/tool-schema.test.mjs +126 -126
  378. package/tests/tools.test.mjs +810 -810
  379. package/tests/turn-log.test.mjs +487 -487
  380. package/tests/ui-defaults.test.mjs +57 -57
  381. package/tests/update-fields.test.mjs +138 -138
  382. package/tests/vector-gc.test.mjs +37 -37
  383. package/tests/vector-migration.test.mjs +810 -810
  384. package/tests/vector-profile.test.mjs +449 -449
  385. package/tests/visibility-migration.test.mjs +152 -152
  386. package/tests/webui-auth.test.mjs +963 -963
  387. package/tests/webui.test.mjs +421 -421
  388. package/tests/windows-env.test.mjs +89 -89
  389. package/tests/worker-lifecycle.test.mjs +1522 -1429
package/lib/private.js CHANGED
@@ -1,2209 +1,2198 @@
1
- import { createUserMessage } from '@deepseek-ai/dsh-llm'
2
- import crypto from 'node:crypto'
3
- import fs from 'node:fs'
4
- import path from 'node:path'
5
- import { getSessionBinding, getLibrary, getSettings, setSessionBinding, deleteSessionBinding, loadPrivateIndex, effectiveScope } from './state.js'
6
- import { domainOf, privateRemember, isMemoryEligible, visibleToSession, overdueOpenCommitments } from './memory.js'
7
- import { loadPromptForDomain, CONSOLIDATION_CONTRACTS } from './prompts.js'
8
- import { summarizeRemote } from './remote-summary.js'
9
- import { condenseEvents, condenseLimitsFor, readSessionSnapshot } from './curator.js'
10
- import { record } from './activity-log.js'
11
- import { ACTIVE_MEMORY_POLICY, assessWake, collectEvidence } from './active-memory.js'
12
- import { entryFingerprint } from './consolidation-receipt.js'
13
- import { DEFAULT_TIME_ZONE } from './temporal.js'
14
-
15
- // The consolidation worker only sees the transcript as text. Without a visible
16
- // per-turn clock it falls back to the wall clock (or a single batch sceneTime),
17
- // which is exactly how "前天" gets written months away from the scene. The seed
18
- // event keeps the replayed logical time; surface it as a leading text block so
19
- // the worker can pass that turn's observed_at to the write tools.
20
- function eventTimeLabel(event) {
21
- const explicit = event?.data?.sceneTime
22
- const at = explicit ? new Date(explicit) : (Number.isFinite(event?.time) ? new Date(event.time) : null)
23
- if (!at || !Number.isFinite(at.getTime())) return null
24
- const parts = new Intl.DateTimeFormat('en-CA', {
25
- timeZone: DEFAULT_TIME_ZONE,
26
- year: 'numeric', month: '2-digit', day: '2-digit',
27
- hour: '2-digit', minute: '2-digit', hour12: false,
28
- }).formatToParts(at)
29
- const pick = (type) => parts.find((part) => part.type === type)?.value || ''
30
- return `${pick('year')}-${pick('month')}-${pick('day')} ${pick('hour')}:${pick('minute')}`
31
- }
32
-
33
- // Short-term entries expire on a clock, so the idle pass is the last moment anyone
34
- // can decide what they were worth. The list is generated in code rather than added
35
- // to the editable prompt body: it is per-library data plus a protocol (which tool
36
- // call means "promote"), and a user editing the template must not be able to break
37
- // the tool names the model is told to use.
38
- export function shortTermBrief(binding, { now = Date.now() } = {}) {
39
- if (!binding?.libraryId || binding.useLibrary === false) return ''
40
- let index = null
41
- try { index = loadPrivateIndex(binding.libraryId) } catch { return '' }
42
- const rows = Object.entries(index.entries || {})
43
- .filter(([, e]) => e && e.layer === 'short_term' && isMemoryEligible(e, { automatic: true, now }) && visibleToSession(e, binding.sessionId))
44
- .map(([id, e]) => ({
45
- id,
46
- title: e.title || '(untitled)',
47
- left: Math.max(0, Math.round(((Date.parse(e.expiresAt || '') || 0) - now) / 3_600_000)),
48
- }))
49
- .filter((row) => row.left > 0)
50
- .sort((a, b) => a.left - b.left)
51
- .slice(0, 20)
52
- if (rows.length === 0) return ''
53
- return [
54
- '[short_term · 快到期了]',
55
- '下面这些是你近期记下的短期条目,到期会自己消失。逐条决定:',
56
- '值得留下的升级 —— memu_private_update id=<id> layer=long_term(要补充的正文这次一并写上);',
57
- '不重要的归档 —— memu_private_update id=<id> status=archived;',
58
- '还说不清的别动,它自己会过期。',
59
- ...rows.map((row) => `- [${row.id}] ${row.title} · 约 ${row.left} 小时后过期`),
60
- ].join('\n')
61
- }
62
-
63
- export function buildPrivateConsolidationPrompt(sessionId) {
64
- const binding = getSessionBinding(sessionId)
65
- const library = binding?.libraryId ? getLibrary(binding.libraryId) : null
66
- const settings = getSettings()
67
- // One shared body for both backends; only the output contract differs.
68
- return [
69
- loadPromptForDomain('private-consolidation', {
70
- libraryName: library ? `${library.name} (${library.id})` : '(unbound)',
71
- domain: domainOf(binding),
72
- mustRememberCap: settings.mustRememberCap,
73
- shortTermTtlHours: settings.shortTermTtlHours ?? 72,
74
- }, domainOf(binding)).text,
75
- '',
76
- CONSOLIDATION_CONTRACTS.local,
77
- shortTermBrief({ ...binding, sessionId }),
78
- ].filter((part) => part && part.trim()).join('\n')
79
- }
80
-
81
- /**
82
- * 一句话说清一个失败原因。
83
- *
84
- * 早先这里只写 "... failed" 就返回:诊断页照着这条去查什么也查不到,等于把
85
- * 报错留在原地。带上 code + message,诊断记录本身就有可复制的证据。
86
- */
87
- function describeError(error) {
88
- if (!error) return 'unknown error'
89
- const code = typeof error.code === 'string' ? error.code : ''
90
- const message = String(error.message || error)
91
- return code && !message.startsWith(code) ? code + ': ' + message : message
92
- }
93
- function noticeMessage(text, summary) {
94
- return createUserMessage({
95
- content: [{ type: 'text', text }],
96
- source: { kind: 'plugin:dsh-memu-memory', form: 'notice', summary },
97
- })
98
- }
99
-
100
- // "There were new turns" is not the same question as "there is something worth
101
- // keeping". A conversation of greetings, acknowledgements and one-line lookups costs
102
- // a fork (a whole seeded transcript, one model turn) and returns nothing; doing that
103
- // after every idle window is how an automatic pass becomes noise the user turns off.
104
- // This answers the cheap half of the question locally, before a fork exists: is the
105
- // part of the transcript since the last consolidation substantive at all? It has to
106
- // err on the side of running — a false "worth it" costs one model turn, a false
107
- // "skip" silently throws away the only record of a decision — so the bar is low and
108
- // deliberately structural rather than semantic: a single short human message with no
109
- // tool work in it is the only thing it refuses.
110
- // The gate this replaces counted characters. That was wrong in the one direction
111
- // that matters: "我不吃香菜" is five characters and is exactly the kind of durable
112
- // fact the library exists to keep, while "好的,继续" is also short and is worth
113
- // nothing. Length is not the signal — an acknowledgement is. So this is a shape
114
- // match on the *only* message in the tail, not a size test, and anything that is not
115
- // literally an acknowledgement goes to the fork and lets the prompt decide.
116
- const SMALL_TALK = /^(谢(谢|了)?|多谢|感谢|好(的|吧|嘞)?|ok|okay|收到|明白(了)?|了解(了)?|嗯+|哦+|啊+|行|可以|没问题|继续|你好|hi|hello|hey|thanks?(you)?|thx)+$/i
117
- const ASSESS_MIN_HUMAN_CHARS = 4
118
-
119
- function isSmallTalk(text) {
120
- // Punctuation and spacing are not content: "好的,继续" is one acknowledgement, not
121
- // two words with a comma in the middle.
122
- return SMALL_TALK.test(String(text || '').replace(/[\s!!。.,,、~~👍]/g, ''))
123
- }
124
-
125
- function textOfContent(content) {
126
- if (typeof content === 'string') return content.trim()
127
- if (!Array.isArray(content)) return ''
128
- return content
129
- .map((block) => (block && typeof block === 'object' && typeof block.text === 'string' ? block.text : ''))
130
- .join(' ')
131
- .trim()
132
- }
133
-
134
- // Only the events after the last consolidation: a session that has been asleep once
135
- // already keeps all of its old material in the transcript, and scoring the whole file
136
- // again would make every later turn "worth it" forever.
137
- export function unconsolidatedEvents(binding, events) {
138
- const since = Number(binding?.lastSleepSeq)
139
- if (!Number.isFinite(since) || since < 0) return Array.isArray(events) ? events : []
140
- return (events || []).filter((event) => Number(event?.seq) > since)
141
- }
142
-
143
- export function assessConsolidationValue(events) {
144
- let humanTurns = 0
145
- let humanChars = 0
146
- let humanText = ''
147
- let toolCalls = 0
148
- for (const event of events || []) {
149
- if (event?.type === 'user/message') {
150
- // The same rule the transcript condenser uses: only a message the person
151
- // actually typed counts. Plugin notices, tool output and heartbeats all arrive
152
- // as messages too, and none of them is a reason to spend a fork.
153
- if (event.data?.source?.kind !== 'user') continue
154
- const text = textOfContent(event.data?.content)
155
- if (!text) continue
156
- humanTurns += 1
157
- humanChars += text.length
158
- humanText = text
159
- continue
160
- }
161
- if (event?.type === 'assistant/message') {
162
- const blocks = event.data?.message?.content
163
- if (Array.isArray(blocks)) toolCalls += blocks.filter((block) => block?.type === 'tool-call').length
164
- continue
165
- }
166
- if (event?.type === 'tool/call') toolCalls += 1
167
- }
168
- const facts = { humanTurns, humanChars, toolCalls }
169
- if (humanTurns === 0) return { worth: false, reason: 'no-human-turn', ...facts }
170
- if (toolCalls === 0 && humanTurns === 1 && (isSmallTalk(humanText) || humanChars < ASSESS_MIN_HUMAN_CHARS)) {
171
- return { worth: false, reason: 'small-talk', ...facts }
172
- }
173
- return { worth: true, reason: 'substantive', ...facts }
174
- }
175
-
176
- // ---- incremental consolidation window --------------------------------------
177
- // A consolidation fork used to seed the whole transcript up to the snapshot cut,
178
- // so every run re-read the same old tool logs and the model's attention spread
179
- // thinner as the conversation grew (the 56-turn QQ session was re-read 6-10
180
- // times). The policy below keeps each fork bounded: seed only the unconsolidated
181
- // tail, compact the noise, and leave the rest for the next window.
182
- export const CONSOLIDATION_BACKLOG_EVENTS = 200
183
- export const CONSOLIDATION_BACKLOG_TURNS = 10
184
- // 小增量顺延:非手动整理时,少于 3 个真人回合的增量先不 fork。它不推进游标,
185
- // 下一次触发会把顺延的事件一起带上;上限仍由上面的水位常量兜底,饥饿时放行。
186
- export const CONSOLIDATION_MIN_HUMAN_TURNS = 3
187
- // A checkpoint is measured in session events, and six of them are pure turn/step
188
- // wrappers. 300 events therefore bought only ~50 turns of transcript. 500 keeps
189
- // the same seed size in practice but cuts one fork for a 200-turn catch-up.
190
- // 2026-11-15:窗口定回 500,配套把整理预算抬到 600s(见 CONSOLIDATION_WAIT_POLICY)——
191
- // 慢推理模型(GLM-5.3-Flash)下 500 事件需要更长的单窗时间,靠加时长而非砍窗解决;
192
- // 剩余区间留在 pending,下一扫继续(selectConsolidationWindow 按游标推进),
193
- // 重试窗减半到 250。
194
- export const CONSOLIDATION_WINDOW_EVENTS = 500
195
- // worker 模式按回合扩展窗口:500 事件切在回合中间时,向后补到该回合的 turn/end。
196
- // worker 的包是 turn-log 记录(单条最多 4000 字符),扩展窗口不会放大模型上下文;
197
- // 它只避免同一回合被连续两窗整条重发。20k 事件是防御上限,正常回合远小于它。
198
- export const WORKER_WINDOW_EXTEND_EVENTS = 20_000
199
- export const CONSOLIDATION_PROBE_MINUTES = 15
200
- export const CONSOLIDATION_SNAPSHOT_FAILURE_LIMIT = 2
201
- // 冻结冷却(issue #4 缺陷 1):同一快照失败到上限后熔断——但熔断不该是永久锁死。
202
- // 外部条件可能恢复(归档被解除、服务商恢复、effortRefusal 自愈),冷却到期后清零
203
- // 连击、放行一次真实重试;仍失败则按上限重新冻结并重新计时。每个冷却期最多
204
- // LIMIT 次真实 fork,成本有界。
205
- export const CONSOLIDATION_SNAPSHOT_FAILURE_COOLDOWN_MS = 6 * 60 * 60 * 1000
206
- const SEED_TOOL_RESULT_CHARS = 1_100
207
- const SEED_TOOL_CALL_CHARS = 500
208
- // 编码域的修改重点就在工具结果与调用参数(diff、错误签名、编译输出)里;
209
- // 1.1k/0.5k 只够留下开头。放宽后整窗仍有 ≤500 事件与 12k 文本/条的上限兜着。
210
- const SEED_TOOL_RESULT_CHARS_CODING = 2_200
211
- const SEED_TOOL_CALL_CHARS_CODING = 1_000
212
- const SEED_TEXT_CHARS = 12_000
213
- const SEED_CATALOG_ENTRIES = 18
214
-
215
- export function seedLimitsFor(domain) {
216
- return String(domain) === 'coding'
217
- ? { toolResultChars: SEED_TOOL_RESULT_CHARS_CODING, toolCallChars: SEED_TOOL_CALL_CHARS_CODING }
218
- : { toolResultChars: SEED_TOOL_RESULT_CHARS, toolCallChars: SEED_TOOL_CALL_CHARS }
219
- }
220
-
221
- // Types that carry conversation, plus the structural events a seeded Session
222
- // replays. Everything else is host bookkeeping: request headers, permissions,
223
- // runtime snapshots and the plugin's own recall messages. Feeding those to the
224
- // summarizer is how a memory ends up citing its own earlier injection as a user
225
- // fact, so they never enter the seed.
226
- const SEED_EVENT_TYPES = new Set([
227
- 'user/message', 'assistant/message', 'tool/call', 'tool/result',
228
- 'turn/start', 'turn/end', 'step/start', 'step/end',
229
- ])
230
-
231
- // The subset that joins the host's model-visible surface: every one of these
232
- // must carry a surfaceOp marker, and their seqs form the fold a replacement cites.
233
- const SEED_SURFACE_TYPES = new Set(['user/message', 'assistant/message', 'tool/result'])
234
-
235
- function capSeedText(value, limit = SEED_TEXT_CHARS) {
236
- const text = String(value ?? '')
237
- return text.length > limit ? text.slice(0, limit) + '…[已截断]' : text
238
- }
239
-
240
- function cloneSeedBlocks(blocks, caps = {}, seenToolText = null) {
241
- const textCap = Number(caps.text) > 0 ? Number(caps.text) : SEED_TEXT_CHARS
242
- const toolCap = Number(caps.tool) > 0 ? Number(caps.tool) : SEED_TOOL_CALL_CHARS
243
- const out = []
244
- for (const block of Array.isArray(blocks) ? blocks : []) {
245
- if (!block || typeof block !== 'object') continue
246
- if (block.type === 'reasoning') continue
247
- if (block.type === 'image') { out.push({ type: 'text', text: '[图片/附件]' }); continue }
248
- if (block.type !== 'text' && block.type !== 'tool-call') { out.push(block); continue }
249
- if (block.type === 'tool-call') {
250
- out.push({ ...block, arguments: capSeedText(block.arguments, toolCap) })
251
- continue
252
- }
253
- const text = String(block.text || '')
254
- // Role cards, emoji catalogs and full unread snapshots repeat verbatim across
255
- // turns; one copy is enough to summarise what the tool returned.
256
- if (seenToolText && text && seenToolText.has(text)) {
257
- out.push({ ...block, text: '[与前面相同的工具输出,已省略]' })
258
- continue
259
- }
260
- if (seenToolText && text) seenToolText.add(text)
261
- out.push({ ...block, text: capSeedText(text, textCap) })
262
- }
263
- return out
264
- }
265
-
266
- // Renumber survivors and rewrite every citation to its final index. A replace
267
- // whose endpoints did not survive cannot be replayed at all; report it so the
268
- // caller drops it before seqs are handed out (dropping after renumbering is what
269
- // left holes the host rejected with "seed event at index N has seq M").
270
- function buildSeedEvents(pending, offset) {
271
- const index = new Map()
272
- pending.forEach((event, i) => index.set(Number(event.seq), i + offset))
273
- const prepared = []
274
- const origins = []
275
- let dropped = false
276
- pending.forEach((event, origin) => {
277
- const next = { ...event, seq: index.get(Number(event.seq)) }
278
- if (Array.isArray(next.sourceEventSeqs)) {
279
- const mapped = [...new Set(next.sourceEventSeqs
280
- .map(value => index.get(Number(value)))
281
- .filter(value => Number.isInteger(value) && value < next.seq))]
282
- .sort((a, b) => a - b)
283
- if (mapped.length) next.sourceEventSeqs = mapped
284
- else delete next.sourceEventSeqs
285
- }
286
- if (next.surfaceOp && typeof next.surfaceOp === 'object' && !Array.isArray(next.surfaceOp)) {
287
- const start = index.get(Number(next.surfaceOp.startSeq))
288
- const end = index.get(Number(next.surfaceOp.endSeq))
289
- if (!Number.isInteger(start) || !Number.isInteger(end) || start > end || !Array.isArray(next.sourceEventSeqs)) {
290
- dropped = true
291
- return
292
- }
293
- next.surfaceOp = { op: 'replace', startSeq: start, endSeq: end }
294
- }
295
- prepared.push(next)
296
- origins.push(origin)
297
- })
298
- return { prepared, origins, dropped }
299
- }
300
-
301
- // Mirror the host's surface-fold checks (session `validateNext`) over a candidate
302
- // seed. A replacement is only accepted when both endpoints are current nodes and
303
- // sourceEventSeqs cite every node the range shadows — dropping a replacement can
304
- // reveal nodes it had shadowed, which is why this must run on the whole seed and
305
- // not just the event being rewritten. Returns the prepared indices that failed.
306
- function seedSurfaceIssues(events) {
307
- const nodes = []
308
- const issues = []
309
- events.forEach((event, index) => {
310
- if (!SEED_SURFACE_TYPES.has(event.type)) return
311
- const op = event.surfaceOp
312
- if (op === 'append') {
313
- nodes.push(event.seq)
314
- return
315
- }
316
- if (!op || typeof op !== 'object' || Array.isArray(op) || op.op !== 'replace') {
317
- issues.push(index)
318
- return
319
- }
320
- const startSeq = Number(op.startSeq)
321
- const endSeq = Number(op.endSeq)
322
- const startIdx = nodes.indexOf(startSeq)
323
- const endIdx = nodes.indexOf(endSeq)
324
- const sources = Array.isArray(event.sourceEventSeqs) ? event.sourceEventSeqs : []
325
- const cited = new Set(sources)
326
- if (startSeq >= event.seq || endSeq >= event.seq
327
- || startIdx < 0 || endIdx < startIdx
328
- || sources.length === 0 || sources.length !== cited.size
329
- || sources.some(seq => Number(seq) >= event.seq)
330
- || nodes.slice(startIdx, endIdx + 1).some(seq => !cited.has(seq))) {
331
- issues.push(index)
332
- return
333
- }
334
- nodes.splice(startIdx, endIdx - startIdx + 1)
335
- nodes.push(event.seq)
336
- })
337
- return issues
338
- }
339
-
340
- /**
341
- * Build the seed body for one window: only conversation events, with reasoning /
342
- * replay state / repeated tool output removed, then renumbered seq 0..n so
343
- * Session's "contiguous from zero" rule holds. The optional catalog event takes
344
- * seq 0 and is the only synthetic message.
345
- *
346
- * Surface replacements are not append-only: their surfaceOp cites the range they
347
- * shadow, and the host validates those citations while replaying the seed. When
348
- * the noise filter drops neighbours (or the window starts inside a compacted
349
- * range), an unremapped startSeq/endSeq points forward or at a node the seed no
350
- * longer contains and the whole fork is refused. Resolve every replacement
351
- * against the surviving events, drop the ones that cannot be replayed, and only
352
- * renumber once the survivor set is stable.
353
- */
354
- export function compactSeedEvents(events, prelude = null, options = {}) {
355
- const toolResultChars = Number(options.toolResultChars) > 0 ? Number(options.toolResultChars) : SEED_TOOL_RESULT_CHARS
356
- const toolCallChars = Number(options.toolCallChars) > 0 ? Number(options.toolCallChars) : SEED_TOOL_CALL_CHARS
357
- const preludeEvents = (Array.isArray(prelude) ? prelude : (prelude ? [prelude] : []))
358
- .filter((event) => event && typeof event === 'object')
359
- .map((event, index) => {
360
- // Preludes are synthetic and sit at the head, so they can only append: a
361
- // replacement marker there would cite positions that do not exist yet. The
362
- // host also refuses a surface-eligible event without a marker at all.
363
- const surfaceOp = SEED_SURFACE_TYPES.has(event.type) ? 'append' : event.surfaceOp
364
- return { ...event, seq: index, surfaceOp }
365
- })
366
- const offset = preludeEvents.length
367
- const kept = []
368
- const seenToolText = new Set()
369
- for (const event of Array.isArray(events) ? events : []) {
370
- if (!event || typeof event !== 'object' || !SEED_EVENT_TYPES.has(event.type)) continue
371
- if (event.type === 'user/message' && event.data?.source?.kind !== 'user') continue
372
- const clone = { ...event, data: { ...(event.data || {}) } }
373
- if (event.type === 'assistant/message') {
374
- const message = { ...(event.data?.message || {}) }
375
- const source = { ...(message.source || {}) }
376
- // The replay state duplicates the response body; it is not conversation.
377
- delete source.replayState
378
- message.source = source
379
- message.content = cloneSeedBlocks(message.content, { text: SEED_TEXT_CHARS, tool: toolCallChars })
380
- if (message.content.length === 0) message.content = [{ type: 'text', text: '(本轮没有可读的正文)' }]
381
- clone.data.message = message
382
- // data.stream is the raw chunk log, not the message the model saw. It must
383
- // stay present as an (empty) array: DSH 0.2.2-rc.1's seed validation
384
- // (assertAssistantSettlementShape) requires data.stream to be an array, and
385
- // deleting it made every consolidation fork seed fail with "invalid
386
- // settlement fields". An empty array keeps the noise-down intent — the
387
- // chunks never enter the seed — while satisfying the newer host check;
388
- // older hosts don't validate the field at all, so this is inert there.
389
- // 实测(0.2.2-rc.1 自带 Session + 真实会话事件):删 stream → 拒;[] → 过。
390
- clone.data.stream = []
391
- } else if (event.type === 'tool/result') {
392
- const message = { ...(event.data?.message || {}) }
393
- message.content = cloneSeedBlocks(message.content, { text: toolResultChars, tool: toolCallChars }, seenToolText)
394
- if (message.content.length === 0) message.content = [{ type: 'text', text: '[空工具输出]' }]
395
- clone.data.message = message
396
- } else if (event.type === 'tool/call') {
397
- clone.data.arguments = capSeedText(event.data?.arguments, toolCallChars)
398
- } else if (event.type === 'user/message') {
399
- clone.data.content = cloneSeedBlocks(event.data?.content, { text: SEED_TEXT_CHARS })
400
- const timeLabel = eventTimeLabel(event)
401
- if (timeLabel) clone.data.content.unshift({ type: 'text', text: `[事件时间 ${timeLabel}]` })
402
- }
403
- // Old logs and fixtures can omit the marker; the host refuses a
404
- // surface-eligible event without one, and inside a seed it can only append.
405
- if (clone.surfaceOp === undefined && SEED_SURFACE_TYPES.has(clone.type)) clone.surfaceOp = 'append'
406
- kept.push(clone)
407
- }
408
-
409
- let pending = kept
410
- for (;;) {
411
- const { prepared, origins, dropped } = buildSeedEvents(pending, offset)
412
- const issues = seedSurfaceIssues([...preludeEvents, ...prepared])
413
- if (!dropped && issues.length === 0) return [...preludeEvents, ...prepared]
414
- // Each pass removes at least one event, so this converges; two passes cover
415
- // the replacement-cites-a-replacement case the host rejects first.
416
- const survivors = new Set(origins)
417
- const doomed = new Set()
418
- pending.forEach((_, origin) => { if (!survivors.has(origin)) doomed.add(origin) })
419
- for (const index of issues) doomed.add(origins[index - offset])
420
- pending = pending.filter((_, origin) => !doomed.has(origin))
421
- }
422
- }
423
-
424
- // P3: spend the worker's context on turns that can produce a durable memory.
425
- // Zero-token local filter: strong signals (dates, promises, corrections,
426
- // identities) count double; generic preference/social words count once. Whole
427
- // turns are kept, plus the turn before/after for context. If nothing looks
428
- // salient, keep everything rather than silently dropping the window.
429
- //
430
- // §6.1 分域强度词表:domain 取 domainOf(binding)(general/rp/coding/mixed,
431
- // 未知域回退 general)。CJK 词条保持子串匹配——general/rp 的 CJK 部分与旧
432
- // 全域表逐字一致,默认行为下中文得分不变;Latin 词条统一 `\b` 词边界 +
433
- // 大小写不敏感(fix 不命中 fixture/prefix,FIX/Fixed 要命中)。分数语义
434
- // 不变:强 ×2 + 弱 ×1。
435
- const latin = (words) => words.map((word) => `\\b(?:${word})\\b`)
436
-
437
- // 生活/中性对话:现状全域表逐字保留(顺序不变,保证中文得分与旧代码一致)+ 英文补充。
438
- const GENERAL_STRONG = [
439
- '今天', '明天', '昨天', '前天', '后天', '大后天', '下周', '上周', '这周', '月底', '月初', '年初', '年底',
440
- '生日', '纪念日', '周年', '星期[一二三四五六日天]', '周[一二三四五六日天]',
441
- '\\d{1,2}\\s*[月日号]', '\\d{4}\\s*[-/年]', '\\d{1,2}\\s*[点时]',
442
- '答应', '约定', '说好', '提醒', '帮我', '帮忙', '欠', '借', '还', '截止', '到期', '记得', '别忘', '改口', '说错', '更正', '其实', '矛盾', '两版', '之前说',
443
- ...latin(['birthday', 'anniversary', 'promised?', 'deadline', 'due', 'owe', 'borrowed', 'changed my mind', 'corrected', 'actually']),
444
- ]
445
- const GENERAL_WEAK = [
446
- '喜欢', '讨厌', '不吃', '不要', '不能', '不想', '边界', '秘密', '别说', '打算', '计划', '准备', '要去', '想去', '叫', '称呼', '名字', '岁', '住', '工作', '职业', '负责', '接手', '登记', '换', '孩子', '父亲', '母亲', '老公', '老婆', '朋友', '同事', '邻居',
447
- ...latin(['prefers?', 'allergic', "can['’]t eat", 'boundaries?', 'secrets?', 'plans?', 'planned', 'called', 'named', 'ages?', 'lives at', 'works at', 'friends?', 'colleagues?']),
448
- ]
449
- // 剧情人际:现状表即 rp 向(沿用 general 的生活词 + 现有人际词),补剧情词与英文同人词。
450
- const RP_STRONG = [...GENERAL_STRONG]
451
- const RP_WEAK = [
452
- ...GENERAL_WEAK,
453
- '上位', '下位', '设定', '世界观', '剧情', '人设',
454
- ...latin(['personas?', 'canon', 'lore', 'headcanons?', 'backstory', 'in character', 'out of character']),
455
- ]
456
- // 工程事实(新表):改了什么/为什么/什么时候上线。bugs 与截止日来自 §6.1 设计表。
457
- const CODING_STRONG = [
458
- '修复', '修好', '发布', '上线', '部署', '版本', '回滚', '迁移', '破坏性', '依赖升级', '环境变量', '报错', '崩溃', '回归', '截止日',
459
- ...latin([
460
- 'bugs?', 'fixed', 'fixes', 'fix\\b(?!ture|ing)', 'broke', 'broken', 'deploy(?:ed|s|ing)?', 'release[ds]?',
461
- 'shipped?', 'hotfix(?:es|ed)?', 'rollback(?:ed|s)?', 'migrat(?:e|ed|ion|ing)s?', 'breaking changes?', 'root causes?', 'crash(?:ed|es)?', 'regressions?',
462
- ]),
463
- ]
464
- const CODING_WEAK = [
465
- '重构', '优化', '测试', '文档', '依赖', '配置', '接口', '日志', '构建', '打包', '命名',
466
- ...latin(['refactor(?:ed|s|ing)?', 'optimiz(?:e|ed|ing)', 'config(?:s|uration)?', 'env', 'dependenc(?:y|ies)', 'builds?', 'lints?', 'rename[ds]?', 'apis?']),
467
- ]
468
- // mixed:rp ∪ coding 并集去重。
469
- const MIXED_STRONG = [...new Set([...RP_STRONG, ...CODING_STRONG])]
470
- const MIXED_WEAK = [...new Set([...RP_WEAK, ...CODING_WEAK])]
471
- const compileSalience = (parts) => new RegExp(parts.join('|'), 'gi')
472
- const SALIENCE_TABLE = {
473
- general: { strong: compileSalience(GENERAL_STRONG), weak: compileSalience(GENERAL_WEAK) },
474
- rp: { strong: compileSalience(RP_STRONG), weak: compileSalience(RP_WEAK) },
475
- coding: { strong: compileSalience(CODING_STRONG), weak: compileSalience(CODING_WEAK) },
476
- mixed: { strong: compileSalience(MIXED_STRONG), weak: compileSalience(MIXED_WEAK) },
477
- }
478
-
479
- function turnText(events) {
480
- const parts = []
481
- for (const event of events) {
482
- if (event.type === 'user/message') {
483
- for (const block of event.data?.content || []) if (block?.type === 'text' && typeof block.text === 'string') parts.push(block.text)
484
- } else if (event.type === 'assistant/message') {
485
- for (const block of event.data?.message?.content || []) if (block?.type === 'text' && typeof block.text === 'string') parts.push(block.text)
486
- }
487
- }
488
- return parts.join('\n')
489
- }
490
-
491
- /** 强 ×2 + 弱 ×1;domain 取 domainOf(binding)(四域),未知域回退 general。 */
492
- export function salienceScore(text, domain = 'general') {
493
- const table = SALIENCE_TABLE[domain] || SALIENCE_TABLE.general
494
- const value = String(text)
495
- const strong = (value.match(table.strong) || []).length
496
- const weak = (value.match(table.weak) || []).length
497
- return strong * 2 + weak
498
- }
499
-
500
- /**
501
- * Keep salient complete turns and one neighbour on each side. Coding keeps more:
502
- * weak signals, every turn that touched a tool, and a doubled turn cap — the
503
- * change itself lives in the tool calls, not in the prose around them.
504
- */
505
- export function candidateSeedEvents(events, { maxTurns = 60, domain = 'general' } = {}) {
506
- const coding = String(domain) === 'coding'
507
- // 编码域的改动发生在工具调用里,正文常常只有一句「改这个函数」;salience 词表
508
- // 命中不了就整回合丢掉,种子只剩关键词最多的闲聊。coding 因此放宽:弱词也算数,
509
- // 带工具调用的回合一律保留,回合上限翻倍。
510
- const threshold = coding ? 1 : 2
511
- const cap = coding ? Math.max(Number(maxTurns) || 0, 120) : maxTurns
512
- const groups = []
513
- let current = null
514
- for (const event of Array.isArray(events) ? events : []) {
515
- if (event?.type === 'turn/start' || current === null) {
516
- current = []
517
- groups.push(current)
518
- }
519
- current.push(event)
520
- if (event?.type === 'turn/end') current = null
521
- }
522
- const kept = new Set()
523
- groups.forEach((group, index) => {
524
- const scored = salienceScore(turnText(group), domain) >= threshold
525
- const worked = coding && group.some((event) => event?.type === 'tool/call')
526
- if (scored || worked) kept.add(index)
527
- })
528
- if (kept.size === 0) return Array.isArray(events) ? [...events] : []
529
- const expanded = new Set(kept)
530
- for (const index of kept) {
531
- if (index > 0) expanded.add(index - 1)
532
- if (index + 1 < groups.length) expanded.add(index + 1)
533
- }
534
- const selected = [...expanded].sort((a, b) => a - b).slice(0, cap)
535
- const covered = selected.reduce((sum, index) => sum + groups[index].length, 0)
536
- if (covered >= events.length * 0.8) return [...events]
537
- return selected.flatMap((index) => groups[index])
538
- }
539
-
540
- // P4:本地零 Token 抽「本窗必写候选」。worker 的任务选择常常只覆盖带日期/数字的
541
- // 几条,新人物、换人接手、只有一句约定的轮次会被漏掉;这些轮次在 salience 里分数
542
- // 不低,却在模型的 topic selection 里没有位置。给它就是一份带 seq 的短清单:要么
543
- // 写,要么在回执里说明为什么不写,不能静默跳过。
544
- const MUST_COVER_PERSON = /叫|自称|称呼|换|接手|改成|换成|新来|同事|师傅|阿姨|房东|店长|老板|邻居|朋友|家人/
545
- export function mustCoverCandidates(events, { max = 8, minScore = 3, domain = 'general' } = {}) {
546
- const groups = []
547
- let current = null
548
- for (const event of Array.isArray(events) ? events : []) {
549
- if (event?.type === 'turn/start' || current === null) {
550
- current = []
551
- groups.push(current)
552
- }
553
- current.push(event)
554
- if (event?.type === 'turn/end') current = null
555
- }
556
- const rows = []
557
- const seen = new Set()
558
- groups.forEach((group) => {
559
- const text = turnText(group)
560
- const score = salienceScore(text, domain)
561
- if (score < minScore) return
562
- const userText = group
563
- .filter((event) => event?.type === 'user/message' && event.data?.source?.kind === 'user')
564
- .flatMap((event) => (event.data?.content || []).filter((block) => block?.type === 'text').map((block) => String(block.text || '')))
565
- .join(' ')
566
- const source = (userText || text).replace(/\s+/g, ' ').trim().slice(0, 90)
567
- if (!source || seen.has(source)) return
568
- seen.add(source)
569
- const observedAt = group
570
- .filter((event) => event?.type === 'user/message' && event.data?.source?.kind === 'user')
571
- .map((event) => event.data?.sceneTime)
572
- .find((value) => typeof value === 'string' && value) || null
573
- rows.push({
574
- fromSeq: Number(group[0]?.seq),
575
- throughSeq: Number(group[group.length - 1]?.seq),
576
- score,
577
- tag: MUST_COVER_PERSON.test(text) ? '人物/关系' : '事实',
578
- text: source,
579
- observedAt,
580
- })
581
- })
582
- return rows
583
- .sort((a, b) => b.score - a.score)
584
- .slice(0, Math.max(1, Number(max) || 8))
585
- .sort((a, b) => a.fromSeq - b.fromSeq)
586
- }
587
-
588
- /** 顺延候选优先占位,但最多 4 条;其余名额留给本窗新候选。 */
589
- export function mergeMustCover(carry, fresh, { max = 8, carryMax = 4 } = {}) {
590
- const rows = []
591
- const seen = new Set()
592
- const add = (row) => {
593
- if (!row || typeof row.text !== 'string') return
594
- const key = row.text.replace(/\s+/g, '').slice(0, 60)
595
- if (!key || seen.has(key)) return
596
- seen.add(key)
597
- rows.push(row)
598
- }
599
- for (const row of (Array.isArray(carry) ? carry : []).slice(0, Math.max(0, Number(carryMax) || 0))) {
600
- add({ ...row, carried: true })
601
- }
602
- for (const row of Array.isArray(fresh) ? fresh : []) add(row)
603
- return rows.slice(0, Math.max(1, Number(max) || 8))
604
- }
605
-
606
- const COVER_DATE_RE = /\d{4}-\d{2}-\d{2}|\d{1,2}\s*月\s*\d{1,2}\s*[日号]?|\d{1,2}\s*[月日号]/g
607
- const COVER_STOP = new Set([
608
- '我们', '他们', '你们', '现在', '已经', '可以', '什么', '这个', '那个',
609
- '时候', '今天', '明天', '昨天', '一下', '一个', '还是', '不是', '就是',
610
- ])
611
- const COVER_TOKEN_RECALL = 0.55
612
- function coverText(text) {
613
- return String(text || '').normalize('NFKC').toLowerCase().replace(COVER_DATE_RE, ' ')
614
- }
615
- function coverTokens(text) {
616
- return new Set(tokenize(text)
617
- .filter((token) => typeof token === 'string' && token.length >= 2 && !/\d/.test(token) && !COVER_STOP.has(token)))
618
- }
619
- function coverAtoms(text) {
620
- return new Set(text.match(/[\p{Script=Han}]|[a-z]+/gu) || [])
621
- }
622
- /** Conservative local evidence check; uncertainty keeps the candidate in carry. */
623
- export function candidateCovered(candidate, writtenIds, index) {
624
- const entries = index?.entries || {}
625
- const text = String(candidate?.text || '')
626
- if (!text) return true
627
- const normalized = coverText(text)
628
- const wanted = coverTokens(normalized)
629
- const atoms = coverAtoms(normalized)
630
- const values = numericSet(text)
631
- // A date or an uninformative fragment cannot prove a fact was written.
632
- if (wanted.size < 2 || atoms.size === 0) return false
633
- for (const id of Array.isArray(writtenIds) ? writtenIds : []) {
634
- const entry = entries[id]
635
- if (!entry) continue
636
- const body = String(entry.title || '') + ' ' + String(entry.content || '')
637
- const haveValues = numericSet(body)
638
- if ([...values].some((value) => !haveValues.has(value))) continue
639
- const normalizedBody = coverText(body)
640
- const haveAtoms = coverAtoms(normalizedBody)
641
- // Missing names, actions or objects are not covered by a matching topic/date.
642
- if ([...atoms].some((atom) => !haveAtoms.has(atom))) continue
643
- const have = coverTokens(normalizedBody)
644
- const shared = [...wanted].filter((token) => have.has(token))
645
- if (shared.length < Math.min(3, wanted.size) || shared.length / wanted.size < COVER_TOKEN_RECALL) continue
646
- if (shared.some((token) => polarityAt(text, token) !== polarityAt(body, token))) continue
647
- return true
648
- }
649
- return false
650
- }
651
-
652
- /** Existing entries, compact, for dedupe/update instead of duplicate writes. */
653
- export function memoryCatalogEvent(binding, now = Date.now()) {
654
- if (!binding?.libraryId) return null
655
- let entries = []
656
- try { entries = Object.entries(loadPrivateIndex(binding.libraryId).entries || {}) } catch { return null }
657
- const rows = entries
658
- .filter(([, entry]) => entry && isMemoryEligible(entry, { automatic: true, now }))
659
- .filter(([, entry]) => visibleToSession(entry, binding.sessionId))
660
- .sort((a, b) => String(b[1].updatedAt || b[1].createdAt || '').localeCompare(String(a[1].updatedAt || a[1].createdAt || '')))
661
- .slice(0, SEED_CATALOG_ENTRIES)
662
- .map(([id, entry]) => `- [${id}] ${capSeedText(entry.title || '(untitled)', 120)} · ${entry.layer || 'long_term'} · ${entry.status || 'active'}`)
663
- // 欠账单列:目录按更新时间截断,逾期的承诺很可能不在前 N 条里,而整理必须看见它。
664
- const overdueRows = overdueOpenCommitments({ libraryId: binding.libraryId, now, minOverdueDays: 0, limit: 8 })
665
- .filter(({ entry }) => visibleToSession(entry, binding.sessionId))
666
- .map(({ id, entry, commitment, dueAt, daysOverdue }) => {
667
- const who = commitment.counterparty ? `对 ${capSeedText(commitment.counterparty, 40)}:` : ''
668
- return `- [${id}] ${capSeedText(entry.title || '(untitled)', 80)} · due=${dueAt} · 已逾期 ${daysOverdue} 天 · ${who}${capSeedText(commitment.action, 120)}`
669
- })
670
- if (rows.length === 0 && overdueRows.length === 0) return null
671
- const text = [
672
- '[memory-catalog · 已有记忆目录(只读上下文,不是用户发言,也不属于本轮转录)]',
673
- '下面这些是本次整理之前已经写入本库的条目。不要当作用户说过的话,也不要重复创建;同一事实用 memu_private_update id=<id> 合并,真正新增的内容才用 memu_private_remember。',
674
- ...rows,
675
- ...(overdueRows.length > 0
676
- ? ['欠账(status=open 且已过 due_at):整理时按本轮转录证据结案——兑现写 done、明确取消写 cancelled、确实作废写 expired;没有证据就保留 open,并在正文写明仍欠着谁。',
677
- ...overdueRows]
678
- : []),
679
- ].join('\n')
680
- return {
681
- type: 'user/message',
682
- seq: 0,
683
- time: now,
684
- data: createUserMessage({
685
- content: [{ type: 'text', text }],
686
- source: { kind: 'plugin:dsh-memu-memory', form: 'notice', summary: 'memory-catalog' },
687
- }),
688
- surfaceOp: 'append',
689
- }
690
- }
691
-
692
- function recentUserText(events, limit = 6) {
693
- const parts = []
694
- for (const event of Array.isArray(events) ? events : []) {
695
- if (event?.type !== 'user/message' || event.data?.source?.kind !== 'user') continue
696
- for (const block of event.data?.content || []) {
697
- if (block?.type === 'text' && typeof block.text === 'string' && block.text.trim()) parts.push(block.text.trim())
698
- }
699
- }
700
- return parts.slice(-limit).join('\n')
701
- }
702
-
703
- /**
704
- * 1.3.1:本窗候选的本地召回命中。worker 不再获得 recall/list 工具,去重所需的
705
- * 旧条目必须在种子里就给出;这里用插件现有的 BM25 词法腿做零 Token 预召回,
706
- * 只给 id + 标题 + 一段正文,够 worker 判断 update 还是 remember。
707
- */
708
- export function memoryRecallEvent({ binding = null, candidates = [], events = [], now = Date.now(), topK = 6 } = {}) {
709
- if (!binding?.libraryId) return null
710
- let rows = []
711
- try {
712
- rows = Object.entries(loadPrivateIndex(binding.libraryId).entries || {})
713
- .filter(([, entry]) => entry && isMemoryEligible(entry, { automatic: true, now }))
714
- .filter(([, entry]) => visibleToSession(entry, binding.sessionId))
715
- .map(([id, entry]) => ({ ...entry, id }))
716
- } catch { return null }
717
- if (rows.length === 0) return null
718
- const query = [
719
- ...(Array.isArray(candidates) ? candidates.map((item) => item?.text) : []),
720
- recentUserText(events),
721
- ].filter(Boolean).join('\n')
722
- const tokens = tokenize(query)
723
- if (tokens.length === 0) return null
724
- const corpus = buildCorpus(rows)
725
- const scored = rows
726
- .map((entry) => ({ entry, score: bm25(tokens, corpus.docs.get(entry.id), corpus) }))
727
- .filter((item) => item.score > 0)
728
- .sort((a, b) => b.score - a.score)
729
- .slice(0, Math.max(1, Number(topK) || 6))
730
- if (scored.length === 0) return null
731
- const text = [
732
- '[memory-recall · 本地召回命中(只读上下文,不是用户发言,也不属于本轮转录)]',
733
- '下面是与本窗候选最相关的已有条目;只用于去重/合并,不是用户说过的话,也不是新证据。',
734
- ...scored.map(({ entry }) => `- [${entry.id}] ${capSeedText(entry.title || '(untitled)', 80)} — ${capSeedText(entry.content || '', 90)}`),
735
- ].join('\n')
736
- return {
737
- type: 'user/message',
738
- seq: 0,
739
- time: now,
740
- data: createUserMessage({
741
- content: [{ type: 'text', text }],
742
- source: { kind: 'plugin:dsh-memu-memory', form: 'notice', summary: 'memory-recall' },
743
- }),
744
- surfaceOp: 'append',
745
- }
746
- }
747
-
748
- /** First `limit` events, trimmed back to a complete turn so a fork never sees half a step. */
749
- export function selectConsolidationWindow(events, limit = CONSOLIDATION_WINDOW_EVENTS) {
750
- const list = (Array.isArray(events) ? events : []).filter(event => eventSeq(event) !== null)
751
- if (list.length === 0) return { events: [], fromSeq: null, throughSeq: null, remaining: 0 }
752
- if (list.length <= limit) return { events: list, fromSeq: eventSeq(list[0]), throughSeq: eventSeq(list[list.length - 1]), remaining: 0 }
753
- const cutSeq = eventSeq(list[Math.max(0, limit - 1)])
754
- const sliced = list.filter(event => eventSeq(event) <= cutSeq)
755
- const safe = safePrefix(sliced, { requireClosedTurn: false })
756
- const window = safe.ok && safe.events.length > 0 ? safe.events : sliced
757
- const throughSeq = eventSeq(window[window.length - 1])
758
- return {
759
- events: window,
760
- fromSeq: eventSeq(window[0]),
761
- throughSeq,
762
- remaining: list.filter(event => eventSeq(event) > throughSeq).length,
763
- }
764
- }
765
-
766
- /** worker 模式把窗口对齐到最后一个完整回合(§3.3,A5):切在回合中间的窗口回退到
767
- * 窗内最后一个 turn/end,跨骑回合整条推到下窗。这样快照 throughSeq = 游标落在回合边界,
768
- * 增量不会把同一回合连续两窗整条重发。窗内没有闭合回合时原样返回(交上层兜底)。
769
- * 仅 worker 路径调用;fork 路径窗口定义不变。
770
- *
771
- * 尾部只有一个 session 级事件(例如 session/end-seed)时不能回退:那会把游标从 5099
772
- * 拉回 5098。只有「最后 turn/end 之后又出现了 turn/start」才是真的切在新回合中间。 */
773
- export function alignWindowToTurn(window) {
774
- const events = Array.isArray(window?.events) ? window.events : []
775
- let lastEnd = null
776
- for (const event of events) {
777
- if (event?.type !== 'turn/end') continue
778
- const seq = eventSeq(event)
779
- if (seq !== null && (lastEnd === null || seq > lastEnd)) lastEnd = seq
780
- }
781
- if (lastEnd === null || lastEnd === window.throughSeq) return window
782
- const trailing = events.filter((event) => {
783
- const seq = eventSeq(event)
784
- return seq !== null && seq > lastEnd
785
- })
786
- // 最后回合结束后只剩宿主元数据:整段保留,别为了对齐丢掉转录末尾的事件。
787
- if (!trailing.some((event) => event?.type === 'turn/start')) return window
788
- const aligned = events.filter((event) => {
789
- const seq = eventSeq(event)
790
- return seq !== null && seq <= lastEnd
791
- })
792
- if (aligned.length === 0) return window
793
- return {
794
- events: aligned,
795
- fromSeq: window.fromSeq,
796
- throughSeq: lastEnd,
797
- remaining: (Number(window.remaining) || 0) + (events.length - aligned.length),
798
- }
799
- }
800
-
801
- /**
802
- * worker 窗口:先按事件数取窗,再向后补到当前回合的 turn/end。500 事件切在回合中间时,
803
- * 旧路径会把这个回合整条留给下一窗;turn-log 记录是整回合单位,于是同一回合被连续
804
- * 两窗整条重发(实测 556 事件回合)。worker 的包按记录算字符,向后补齐不会放大上下文,
805
- * 所以这里直接补到回合末。补不到(超过防御上限)就退回旧行为。
806
- */
807
- export function selectWorkerWindow(events, limit = CONSOLIDATION_WINDOW_EVENTS, maxExtend = WORKER_WINDOW_EXTEND_EVENTS) {
808
- const list = (Array.isArray(events) ? events : []).filter((event) => eventSeq(event) !== null)
809
- const initial = selectConsolidationWindow(list, limit)
810
- if (!initial.events || initial.events.length === 0) return initial
811
- const lastEndIndex = (() => {
812
- for (let i = initial.events.length - 1; i >= 0; i -= 1) {
813
- if (initial.events[i]?.type === 'turn/end') return i
814
- }
815
- return -1
816
- })()
817
- const openAfter = lastEndIndex < 0
818
- || initial.events.slice(lastEndIndex + 1).some((event) => event?.type === 'turn/start')
819
- if (!openAfter) return alignWindowToTurn(initial)
820
- const extraBudget = Math.max(0, Number(maxExtend) || 0)
821
- if (extraBudget === 0) return alignWindowToTurn(initial)
822
- const nextEnd = list
823
- .filter((event) => eventSeq(event) > initial.throughSeq)
824
- .slice(0, extraBudget)
825
- .find((event) => event?.type === 'turn/end')
826
- if (!nextEnd) return alignWindowToTurn(initial)
827
- const through = eventSeq(nextEnd)
828
- const extended = list.filter((event) => {
829
- const seq = eventSeq(event)
830
- return seq >= initial.fromSeq && seq <= through
831
- })
832
- const safe = safePrefix(extended, { requireClosedTurn: false })
833
- const chosen = safe.ok && safe.events.length > 0 ? safe.events : extended
834
- const chosenThrough = eventSeq(chosen[chosen.length - 1])
835
- return {
836
- events: chosen,
837
- fromSeq: eventSeq(chosen[0]),
838
- throughSeq: chosenThrough,
839
- remaining: list.filter((event) => eventSeq(event) > chosenThrough).length,
840
- }
841
- }
842
-
843
- /** Last complete turn window, for a manual re-check when the cursor is already at the end. */
844
- export function selectTailTurnWindow(events, limit = CONSOLIDATION_WINDOW_EVENTS) {
845
- const list = (Array.isArray(events) ? events : []).filter(event => eventSeq(event) !== null)
846
- const slice = list.slice(-limit)
847
- if (slice.length === 0) return { events: [], fromSeq: null, throughSeq: null, remaining: 0 }
848
- let start = slice.findIndex(event => event.type === 'turn/start')
849
- if (start < 0) start = slice.findIndex(event => event.type === 'user/message')
850
- if (start < 0) return { events: [], fromSeq: null, throughSeq: null, remaining: 0 }
851
- for (let i = start - 1; i >= 0; i -= 1) {
852
- if (slice[i].type === 'user/message' && slice[i].data?.source?.kind === 'user') { start = i; break }
853
- if (slice[i].type === 'turn/end' || slice[i].type === 'turn/start') break
854
- }
855
- const window = slice.slice(start)
856
- const safe = safePrefix(window, { requireClosedTurn: false })
857
- const chosen = safe.ok && safe.events.length > 0 ? safe.events : window
858
- return { events: chosen, fromSeq: eventSeq(chosen[0]), throughSeq: eventSeq(chosen[chosen.length - 1]), remaining: 0 }
859
- }
860
-
861
- /**
862
- * 整理游标只能前进:尾部人工重检选中最后一个回合时,窗口可能比已有游标更靠前
863
- * (例如已经结算过 turn/end 后的 session/end-seed),直接写回会把 lastSleepSeq
864
- * 从 5099 拉回 5098。统一走这里,取当前值与新值的较大者。
865
- */
866
- function advanceSleepCursor(sessionId, seq, patch = {}) {
867
- const next = Number(seq)
868
- if (!Number.isSafeInteger(next) || next < 0) return null
869
- const current = (() => {
870
- try { return Number(getSessionBinding(sessionId)?.lastSleepSeq) } catch { return NaN }
871
- })()
872
- const value = Number.isSafeInteger(current) && current >= 0 ? Math.max(current, next) : next
873
- setSessionBinding(sessionId, { lastSleepSeq: value, ...patch })
874
- return value
875
- }
876
-
877
- // 归档会话集合(issue #4 缺陷 3):宿主 workspaceRegistry 的 archivedSessionIds 是
878
- // 使命名数组;包装成 Set 供 cycle.js 与 private.js 入口共用。注册表缺失/异常时返回
879
- // null(无信息,不做拦截),与 rpc.js 的读法一致。
880
- export function archivedSessionIdsOf(ctx) {
881
- try {
882
- return new Set((ctx?.get?.('workspaceRegistry')?.archivedSessionIds || []).map(String))
883
- } catch {
884
- return null
885
- }
886
- }
887
-
888
- export async function requestPrivateConsolidation(ctx, sessionId, options = {}) {
889
- const binding = getSessionBinding(sessionId)
890
- if (!binding) return { ok: false, error: 'session is not bound to a memory library; bind it first' }
891
- if (!binding.libraryId || !effectiveScope(binding).useLibrary) return { ok: false, error: 'private memory is disabled for this session or folder' }
892
- // 归档会话在宿主 agent/pre-step 必被拒("the fork turn ended blocked"),fork 只会
893
- // 白建一次再计两次失败踩进冻结。cycle.js 已在候选阶段事前跳过;这里拦手动调用,
894
- // 给出明确的 reasonCode 而不是让用户等到失败回执。
895
- const archived = archivedSessionIdsOf(ctx)
896
- if (archived?.size && archived.has(String(sessionId))) {
897
- return {
898
- ok: false, skipped: 'session-archived', settled: false, reasonCode: 'session-archived',
899
- error: 'session is archived; unarchive it before consolidating',
900
- }
901
- }
902
- // Always a fork, never the live session's own inbox. `agent.followup` on the
903
- // chat the user is looking at does queue a real turn — but the host renders a
904
- // queued next-turn message as a pending draft above the composer (editable,
905
- // deletable, sent on demand), and once it runs it stays in that transcript
906
- // forever, re-sent on every later turn. A live session is no exception: the
907
- // fork seeds the same transcript, so recall quality is unchanged, while the
908
- // housekeeping turn lands in a scratch subagent session (origin: subagent —
909
- // out of the window list and out of the injection path) that is disposed.
910
- return requestHistoricalConsolidation(ctx, sessionId, options)
911
- }
912
-
913
- // Remote mode: the configured remote chat endpoint writes the memories, then they
914
- // are committed through the same backend. No local agent or tool chain is touched.
915
- export async function requestRemoteConsolidation(ctx, sessionId, { signal, timeoutMs, force = false } = {}) {
916
- const binding = getSessionBinding(sessionId)
917
- if (!binding) return { ok: false, error: 'session is not bound to a memory library; bind it first' }
918
- if (!binding.libraryId || !effectiveScope(binding).useLibrary) return { ok: false, error: 'private memory is disabled for this session or folder' }
919
- const sessionQuery = ctx.get?.('sessionQuery')
920
- if (!sessionQuery) return { ok: false, error: 'host has no sessionQuery; cannot read this conversation' }
921
- try {
922
- const snapshot = await readSessionSnapshot(sessionQuery, sessionId)
923
- const events = Array.isArray(snapshot?.events) ? snapshot.events : []
924
- if (events.length === 0) return { ok: false, error: 'this session has no content to consolidate' }
925
- const fresh = unconsolidatedEvents(binding, events)
926
- if (!force) {
927
- const value = assessConsolidationValue(fresh)
928
- if (!value.worth) return { ok: true, sessionId, backend: 'api', count: 0, skipped: value.reason, assessment: value }
929
- }
930
- const transcript = condenseEvents(fresh, 60_000, condenseLimitsFor(domainOf(binding)))
931
- const library = binding.libraryId ? getLibrary(binding.libraryId) : null
932
- const memories = await summarizeRemote({
933
- transcript,
934
- libraryName: library ? `${library.name} (${library.id})` : '(unbound)',
935
- domain: domainOf(binding),
936
- signal,
937
- timeoutMs,
938
- })
939
- // 写入计数必须说真话:`memories` 是模型给的清单,逐条 privateRemember 可能被
940
- // 事实级去重拒绝(deduped,不落库)或因矛盾暂扣(pending_review,仅入索引)。
941
- // count 只数真正落库的;被拒/暂扣分列进 detail,否则"写入 N 条"就是误报。
942
- let written = 0
943
- let deduped = 0
944
- let held = 0
945
- for (const memory of memories) {
946
- const outcome = await privateRemember({
947
- ...memory,
948
- exec: { agent: { session: { header: { id: sessionId } } } },
949
- content: memory.content,
950
- title: memory.title || memory.content,
951
- tags: memory.tags,
952
- openLoop: memory.openLoop,
953
- confidence: memory.confidence,
954
- source: memory.source || 'inferred',
955
- })
956
- if (outcome?.deduped === true) deduped += 1
957
- else if (outcome?.entry?.status === 'pending_review') held += 1
958
- else written += 1
959
- }
960
- advanceSleepCursor(sessionId, events[events.length - 1]?.seq)
961
- const result = { ok: true, sessionId, backend: 'api', count: written, deduped, held }
962
- record({
963
- kind: 'consolidate', scope: 'private', sessionId, libraryId: binding.libraryId || null, ok: true,
964
- message: `整理完成(远程)· 写入 ${written}`
965
- + (deduped ? ` · 去重拦下 ${deduped}` : '')
966
- + (held ? ` · 待复核 ${held}` : ''),
967
- detail: { ...result, forced: force },
968
- })
969
- return result
970
- } catch (error) {
971
- record({
972
- kind: 'consolidate', scope: 'private', sessionId, libraryId: binding.libraryId || null, ok: false, level: 'error',
973
- message: '整理失败(远程):' + String(error?.message || error),
974
- detail: { forced: force },
975
- })
976
- return { ok: false, error: String(error?.message || error) }
977
- }
978
- }
979
-
980
- // `buildForkSeed` lives in dsh-session, which this plugin does not need for
981
- // anything else. Imported lazily so a host that does not expose it loses only
982
- // historical consolidation, not the whole plugin half.
983
- async function loadBuildForkSeed() {
984
- try {
985
- const mod = await import('@deepseek-ai/dsh-session')
986
- return typeof mod?.buildForkSeed === 'function' ? mod.buildForkSeed : null
987
- } catch {
988
- return null
989
- }
990
- }
991
-
992
- function agentOptionsFromConfig(config) {
993
- if (!config || typeof config !== 'object') return null
994
- const provider = typeof config.provider === 'string' ? config.provider.trim() : ''
995
- const model = typeof config.model === 'string' ? config.model.trim() : ''
996
- if (!provider || !model) return null
997
- const options = { provider, model }
998
- if (typeof config.reasoningEffort === 'string' && config.reasoningEffort) options.reasoningEffort = config.reasoningEffort
999
- if (Number.isSafeInteger(config.maxTokens) && config.maxTokens > 0) options.maxTokens = config.maxTokens
1000
- return options
1001
- }
1002
-
1003
- // A fork starts a fresh agent loop, so it does not inherit the parent's Agent options.
1004
- // The parent's live request header is the route that actually served its latest turn;
1005
- // an older request/header event is the only equivalent for a closed session. Without
1006
- // one of these, the standard preset cannot resolve {{model}} and every fork dies before
1007
- // its first step, so refuse to create that fork instead of queueing another doomed seed.
1008
- //
1009
- // 第四路(2026-11-14,bench P16 实测):纯 RPC 追加历史的种子会话(seed 流程只 append
1010
- // 不跑回合)连一个 request/header 都不会有;宿主重启或驱动被杀还会把 agent 从进程内
1011
- // 注册表注销——前三路全空,继承必然失败。resume() 是公开的重挂路径:只重新注册该
1012
- // 会话自己的 agent loop(不跑回合、不发模型调用),让它的路由重新可读。探测不可用
1013
- // 或失败一律降级回原行为(返回 null 拒绝 fork)。
1014
- async function inheritedAgentOptions(ctx, sessionId, events) {
1015
- let agents = null
1016
- try { agents = ctx.get?.('agents') || null } catch {}
1017
- const probe = (agent) => {
1018
- try {
1019
- const fromRequest = liveAgentOptions(agent)
1020
- if (fromRequest) return fromRequest
1021
- } catch {}
1022
- return agentOptionsFromConfig(agent?.options)
1023
- }
1024
- let live = null
1025
- try { live = agents?.get?.(sessionId) || null } catch {}
1026
- const direct = probe(live)
1027
- if (direct) return direct
1028
- if (agents && typeof agents.resume === 'function') {
1029
- try {
1030
- const resumed = await agents.resume({ resumeSessionId: sessionId })
1031
- const fromResumed = probe(resumed?.agent || resumed)
1032
- if (fromResumed) return fromResumed
1033
- } catch {}
1034
- }
1035
- for (let i = events.length - 1; i >= 0; i -= 1) {
1036
- if (events[i]?.type !== 'request/header') continue
1037
- const fromEvent = agentOptionsFromConfig(events[i]?.data?.header?.config)
1038
- if (fromEvent) return fromEvent
1039
- }
1040
- return null
1041
- }
1042
-
1043
- function turnEndFailure(event) {
1044
- const reason = event?.data?.reason
1045
- if (!reason || typeof reason !== 'object') return 'the fork produced no turn/end event'
1046
- if (reason.kind === 'completed') return null
1047
- const message = reason?.error?.message || reason?.reason?.message || reason?.message
1048
- return 'the fork turn ended ' + (reason.kind || 'without a reason') + (message ? ': ' + message : '')
1049
- }
1050
-
1051
- // attachWorkerTools / restrictWorkerTools 已迁到 lib/worker-pool.js(T1 持久整理 worker
1052
- // 与 'fork' 路径共用同一份实现,见 worker-pool.js 顶部说明);本文件经 import 使用。
1053
-
1054
- // 活动日志"整理已开始"条目的挂载元数据口径(workerTools* 三件):
1055
- // workerToolsAttached 实际注册成功的工具名数组;null = 挂载没有完成或无法确认
1056
- // (fork ctx 无 tools 服务、register 抛错、宿主没回名单),
1057
- // 与"挂全了"严格区分——这正是旧字段把 wanted 全量误报成
1058
- // 已挂载的教训。
1059
- // workerToolsRequested 请求挂载的完整 wanted 名单;与 attached 全等才是全量挂载。
1060
- // workerToolsPartial true = 未证明 worker 拿到完整 wanted 集(子集、空集、或挂载
1061
- // 整体失败)。刻意把"一件都没挂上"也标 true:若失败标 false,
1062
- // false 会被一眼读成"全量挂载",元数据又不准了。
1063
- function workerToolsMeta(workerTools) {
1064
- const wanted = [...WORKER_WRITE_TOOLS, ...WORKER_READ_TOOLS]
1065
- if (!workerTools) {
1066
- return { workerToolsAttached: null, workerToolsRequested: wanted, workerToolsPartial: true }
1067
- }
1068
- return {
1069
- workerToolsAttached: Array.isArray(workerTools.attached) ? workerTools.attached : null,
1070
- workerToolsRequested: Array.isArray(workerTools.requested) ? workerTools.requested : wanted,
1071
- workerToolsPartial: workerTools.partial === true,
1072
- }
1073
- }
1074
-
1075
- const inFlight = new Map()
1076
- // How long a cancelled fork gets to finish the tool call it was in the middle of.
1077
- // Bounded on purpose: a child that ignores the cancel must not hang the sweep, and
1078
- // the alternative — disposing immediately — is what let a write land after the range
1079
- // was already handed back to pending.
1080
- const WORKER_STOP_GRACE_MS = 5_000
1081
-
1082
- // 这里的 import 刻意写在语句之后:lib/binding-diagnostics.js 的 RUNTIME_STATE 把 `inFlight`
1083
- // 的 file:line 当成诊断契约(当前 lib/private.js:1014),修改位置时同步更新该诊断映射,
1084
- // 而那是别人的文件、本包不改。ESM 的 import 声明是提升的,写在语句之后合法。
1085
- import { warn, dataDir, readJsonStrict, withFileLock, writeJson } from './paths.js'
1086
- import { captureSessionSnapshot, eventSeq, safePrefix, snapshotHash } from './consolidation-snapshot.js'
1087
- import {
1088
- beginJob, completeJob, failJob, findOperation, noteEvidence, operationKey, sessionState,
1089
- recoverStaleJobs, recordOperation, scopeGenerationOf, clearSessionState, skipRange,
1090
- readCarryCandidates, setCarryCandidates,
1091
- } from './consolidation-ledger.js'
1092
- import { decideCompletion, receiptContractText } from './consolidation-receipt.js'
1093
- import { buildWorkerBrief, probeToolSurface, WORKER_READ_TOOLS, WORKER_WRITE_TOOLS, WORKER_WRAPUP_ROUND, WORKER_HARD_STOP_ROUND, workerRoundGuidance } from './consolidation-worker.js'
1094
- // T1 持久整理 worker(lib/worker-pool.js):三级试活/退役/epoch 记账/包组装都在那里;
1095
- // attachWorkerTools/restrictWorkerTools 也已迁到该模块,'fork' 路径调用同一份实现。
1096
- import {
1097
- acquireWorker, attachWorkerTools, buildHandoffPack, buildIncrementPack, loadWorkerIncrement,
1098
- recordEpochProgress, retireWorker, restrictWorkerTools, WORKER_TIMEOUT_LIMIT,
1099
- resolveConsolidationCwd, measurePacket, packetBudgetFit, createConsolidationMeasurement,
1100
- } from './worker-pool.js'
1101
- import { tokenize, buildCorpus, bm25, numericSet, polarityAt } from './text-retrieval.js'
1102
- import { isGoneSessionError } from './cycle.js'
1103
- import { autoLinkPrivateMemories } from './private-links.js'
1104
- import { resolveConsolidationAgentOptions, ensureConsolidationRoute } from './fork-model.js'
1105
-
1106
- function liveAgentOptions(agent) {
1107
- const options = agent?.options
1108
- let request = null
1109
- try { request = agentOptionsFromConfig(agent?.session?.requestHeader?.()?.config) } catch {}
1110
- if (!request) return agentOptionsFromConfig(options)
1111
- const sameRoute = (!options?.provider || options.provider.trim() === request.provider) && (!options?.model || options.model.trim() === request.model)
1112
- if (sameRoute && Number.isSafeInteger(options?.maxTokens) && options.maxTokens > 0) return { ...request, maxTokens: options.maxTokens }
1113
- return request
1114
- }
1115
-
1116
- async function consolidationExecutionContext(ctx, sessionId, settings, events, inheritedOptions = null) {
1117
- const mode = settings.consolidationModelMode || 'inherit'
1118
- let inherited = inheritedOptions
1119
- if (mode !== 'host' && mode !== 'custom' && !inherited) {
1120
- try {
1121
- const agent = ctx.get?.('agents')?.get?.(sessionId)
1122
- inherited = liveAgentOptions(agent)
1123
- } catch {}
1124
- if (!inherited) {
1125
- for (let i = events.length - 1; i >= 0; i -= 1) {
1126
- if (events[i]?.type !== 'request/header') continue
1127
- inherited = agentOptionsFromConfig(events[i]?.data?.header?.config)
1128
- if (inherited) break
1129
- }
1130
- }
1131
- }
1132
- const { options } = resolveConsolidationAgentOptions(settings, inherited)
1133
- const configuredEffort = settings.consolidationReasoningEffort
1134
- let effort = configuredEffort && configuredEffort !== 'inherit' ? configuredEffort : options?.reasoningEffort ?? null
1135
- if (options && effort && isEffortRefused([options.provider, options.model, effort].join('|'))) effort = null
1136
- let maxTokens = options?.maxTokens ?? null
1137
- const settingsKey = crypto.createHash('sha256').update(JSON.stringify({
1138
- mode, runner: settings.consolidationRunner || 'fork',
1139
- provider: options?.provider ?? null, model: options?.model ?? null, maxTokens, effort,
1140
- })).digest('hex')
1141
- let defaultsComparable = maxTokens !== null && effort !== null
1142
- if (options && !defaultsComparable) {
1143
- try {
1144
- const info = await ctx.get?.('llm')?.resolveModelInfo?.(options.provider, options.model)
1145
- defaultsComparable = !!info && typeof info === 'object'
1146
- if (maxTokens === null && Number.isSafeInteger(info?.defaultMaxTokens) && info.defaultMaxTokens > 0) maxTokens = info.defaultMaxTokens
1147
- if (effort === null && typeof info?.reasoning?.defaultEffort === 'string') effort = info.reasoning.defaultEffort
1148
- } catch {}
1149
- }
1150
- const key = crypto.createHash('sha256').update(JSON.stringify({ settingsKey, maxTokens, effort })).digest('hex')
1151
- return { key, settingsKey, defaultsComparable, maxTokens }
1152
- }
1153
-
1154
- // 账本异常必须可见;调用方只有拿到明确的持久租约才可启动 worker。
1155
- // 其余读写失败返回保守结果,不得据此推进已确认边界。
1156
- function safeLedger(action, fallback = null) {
1157
- try {
1158
- return action()
1159
- } catch (error) {
1160
- try { warn('consolidation ledger: ' + String(error?.message || error)) } catch {}
1161
- return fallback
1162
- }
1163
- }
1164
-
1165
- // 交给结果日志的快照身份:有 hash、有边界、没有正文。
1166
- function snapshotMetaOf(snapshot) {
1167
- if (!snapshot) return null
1168
- return {
1169
- hash: snapshot.hash,
1170
- source: snapshot.source,
1171
- fromSeq: snapshot.fromSeq,
1172
- throughSeq: snapshot.throughSeq,
1173
- eventCount: snapshot.eventCount,
1174
- droppedEvents: snapshot.droppedEvents,
1175
- capturedAt: snapshot.capturedAt,
1176
- }
1177
- }
1178
-
1179
- // Every agent-backend consolidation runs here, live sessions included: the same
1180
- // main agent, on a seeded copy of the transcript, writing into the library the
1181
- // original used. In-place consolidation would append a housekeeping turn to the
1182
- // user's own chat — a queued draft until it runs, then a permanent resident of
1183
- // that transcript — so the one visible difference between a live and a closed
1184
- // session is that a closed one has to be read back from disk first.
1185
- // 一次整理要等多长时间,取决于它要读多少转录:fork 的种子是整段会话,worker 读完才
1186
- // 开始写。实测(2026-11-02,935 条事件的会话):第一次 180 s 到点时刚写完 3 条、
1187
- // 退避重试 131 s 完成——即约 0.14–0.2 s/事件。这里按 0.35 s/事件(≈2 倍余量)推预算。
1188
- // 2026-11-15:下限抬到 600 s 与封顶齐平——预算恒为 600 s(10 分钟)。慢推理模型
1189
- // (GLM-5.3-Flash 实测)单次 worker 回合就能吃满旧下限且一个工具都没调,500 事件窗
1190
- // 需要完整的 10 分钟余量;卡死的 fork 仍会在 10 分钟到点后被收掉,租约跟随预算 +90s。
1191
- // 显式传 maxWaitMs 的调用(含工具/测试)原样生效。
1192
- export const CONSOLIDATION_WAIT_POLICY = Object.freeze({
1193
- baseMs: 120_000,
1194
- perEventMs: 350,
1195
- minMs: 600_000,
1196
- maxMs: 600_000,
1197
- })
1198
-
1199
- // 2026-11-15 扫雷:整理 fork 的思考强度被模型拒绝的学习表(provider|model|effort)。
1200
- // 实测:wb/glm-5.3-flash 不支持 medium,带档起 fork 必失败(fork-turn-failed),
1201
- // 同一快照失败 2 次后被 snapshot-failed-too-many 冻结数天。这里学习一次拒绝,
1202
- // 之后同组合不再带 effort 起 fork。
1203
- // 2026-11-18 起持久化到数据目录:进程重启曾把表清零,而反代服务商的签名各不相同
1204
- // (raccoon/sn-deepseek-v4-1-flash-1017 拒 medium 实测),于是每次重启后的第一次
1205
- // 手动整理都会再吃一次 fork-turn-failed——用户看到的就是"反代服务商老是失败"。
1206
- // 拒绝不是转录有病、也不是服务商不可达,是参数不匹配,落盘完全安全。
1207
- // 按当前 home 惰性加载;干净缓存只查 Set,失败的读/写留到下一次调用重试。
1208
- const effortRefusalCaches = new Map()
1209
- // snapshot-failed 冻结期内的活动日志去重(issue #4 缺陷 1):同一份冻结记录
1210
- // (操作键 → 冻结时间戳)只落一条日志,重复 sweep 扫入静默返回。进程重启清空,
1211
- // 重启后多落一条,无害。
1212
- const frozenLogStamps = new Map()
1213
-
1214
- function effortRefusalCache() {
1215
- const file = path.resolve(dataDir(), 'effort-refusals.json')
1216
- if (!effortRefusalCaches.has(file)) {
1217
- effortRefusalCaches.set(file, { file, keys: new Set(), loaded: false, dirty: false })
1218
- }
1219
- return effortRefusalCaches.get(file)
1220
- }
1221
-
1222
- function readEffortRefusals(file) {
1223
- const result = readJsonStrict(file)
1224
- if (result.missing) return []
1225
- if (!result.ok) throw result.error || new Error('cannot read effort refusals')
1226
- const raw = result.value
1227
- if (raw?.version !== 1 || !Array.isArray(raw.keys) || !raw.keys.every(key => typeof key === 'string')) {
1228
- throw new Error('invalid effort refusals schema')
1229
- }
1230
- return raw.keys
1231
- }
1232
-
1233
- function syncEffortRefusals(cache) {
1234
- try {
1235
- if (cache.dirty) {
1236
- withFileLock(cache.file, () => {
1237
- // 必须在锁内重读:其它进程可能已写入本缓存尚未见过的键。
1238
- // 读错/坏 schema 直接退出,绝不把它当空表覆盖;写失败仍保留 dirty。
1239
- const keys = new Set([...readEffortRefusals(cache.file), ...cache.keys])
1240
- writeJson(cache.file, { version: 1, keys: [...keys] })
1241
- cache.keys = keys
1242
- cache.loaded = true
1243
- cache.dirty = false
1244
- })
1245
- } else if (!cache.loaded) {
1246
- cache.keys = new Set(readEffortRefusals(cache.file))
1247
- cache.loaded = true
1248
- }
1249
- } catch (error) {
1250
- warn('consolidation effort refusals: ' + String(error?.message || error))
1251
- }
1252
- }
1253
-
1254
- /** 从 fork 失败信息里识别『该模型不支持这个思考强度』并给出学习键。 */
1255
- export function effortRefusalOf(failure) {
1256
- const m = /provider "([^"]+)" model "([^"]+)" does not support reasoning effort "([^"]+)"/.exec(String(failure || ''))
1257
- return m ? { provider: m[1], model: m[2], effort: m[3], key: [m[1], m[2], m[3]].join('|') } : null
1258
- }
1259
- export function markEffortRefused(key) {
1260
- const cache = effortRefusalCache()
1261
- const k = String(key)
1262
- if (!cache.keys.has(k)) {
1263
- cache.keys.add(k)
1264
- cache.dirty = true
1265
- }
1266
- syncEffortRefusals(cache)
1267
- }
1268
- export function isEffortRefused(key) {
1269
- const cache = effortRefusalCache()
1270
- syncEffortRefusals(cache)
1271
- return cache.keys.has(String(key))
1272
- }
1273
-
1274
- export function consolidationWaitBudget(eventCount, policy = CONSOLIDATION_WAIT_POLICY) {
1275
- const count = Number.isFinite(Number(eventCount)) ? Math.max(0, Math.floor(Number(eventCount))) : 0
1276
- const raw = policy.baseMs + count * policy.perEventMs
1277
- return Math.min(policy.maxMs, Math.max(policy.minMs, raw))
1278
- }
1279
-
1280
- export async function requestHistoricalConsolidation(ctx, sessionId, options = {}) {
1281
- const { maxWaitMs = null, force = false, trigger = null } = options
1282
- const binding = getSessionBinding(sessionId)
1283
- if (!binding) return { ok: false, error: 'session is not bound to a memory library; bind it first' }
1284
- if (!binding.libraryId || !effectiveScope(binding).useLibrary) return { ok: false, error: 'private memory is disabled for this session or folder' }
1285
- if (inFlight.has(sessionId)) return { ok: false, error: 'this session is already being consolidated', running: true }
1286
-
1287
- // The session is claimed before the first await. readSession and agents.create
1288
- // both yield, so two callers arriving in the same tick used to pass the guard
1289
- // together and fork the same transcript twice.
1290
- const abort = new AbortController()
1291
- inFlight.set(sessionId, abort)
1292
- let handle = null
1293
- let offSession = null
1294
- // N3:worker 工具循环的软/硬上限。软上限追加收尾提示,硬上限停掉 fork;
1295
- // 已经写入库的条目不会因为硬停被撤销(游标不推进,下一窗重试剩余范围)。
1296
- let workerToolRounds = 0
1297
- let idle = null
1298
- // Stopped once, callable twice: the timeout path and `finally` both need it.
1299
- let stopped = false
1300
- // The host's own order is cancel -> whenIdle -> dispose. dispose() alone does not
1301
- // wait for a tool call in flight, and this fork writes memories *through tools*, so
1302
- // "the fork was stopped" was not true when the timeout path returned: failJob had
1303
- // already handed the range back and the next pass could fork the same window while
1304
- // the old child was still writing. Bounded, because a child that ignores the cancel
1305
- // must not hang the sweep.
1306
- const stopWorker = async () => {
1307
- if (stopped) return
1308
- stopped = true
1309
- try { abort.abort() } catch {}
1310
- try { offSession?.() } catch {}
1311
- if (idle) {
1312
- try {
1313
- await Promise.race([
1314
- idle.then(() => {}, () => {}),
1315
- // Deliberately NOT unref'd: this promise is what we are awaiting, so an
1316
- // unref'd timer lets the event loop drain while the await is still pending
1317
- // and the caller (or the test runner) is left holding a promise that can
1318
- // never settle. A <=5s hold on the loop is the correct trade.
1319
- new Promise((resolve) => setTimeout(resolve, WORKER_STOP_GRACE_MS)),
1320
- ])
1321
- } catch {}
1322
- }
1323
- try { await handle?.dispose?.() } catch {}
1324
- }
1325
- let turnEnd = null
1326
- let jobId = null
1327
- let scopeChanged = null
1328
- let workerTools = null
1329
- let workerRestriction = null
1330
- // 执行器选择在 try 内赋值;finally 需要 workerMode 来决定清理口径(worker 模式
1331
- // 不销毁 worker——它的生命周期归 epoch,见 §15.2 改动点 6)。
1332
- let workerMode = false
1333
- // A2:worker 生命周期上绑定的 epoch abort(acquireWorker 返回)。续窗的硬停/重验必须
1334
- // abort 它才停得住持久 worker——窗口级 abort 只在出生那次被宿主接进生命周期。
1335
- let workerEpochAbort = null
1336
- const assistantTexts = []
1337
- let childId = null
1338
- let accounting = null
1339
- let executionContext = null
1340
- // 每次整理都要在活动日志里留一条:谁触发(手动/空闲)、fork 有没有建、结果是完成、
1341
- // 超时还是失败。否则"点了没反应"只能靠翻会话文件才知道发生了什么。
1342
- const finish = (result) => {
1343
- result = { ...result, runner: workerMode ? 'worker' : 'fork', measurement: accounting?.measurement || null }
1344
- const ok = result?.ok === true
1345
- const skipped = Boolean(result?.skipped)
1346
- const skipText = !skipped
1347
- ? ''
1348
- : (['small-talk', 'no-human-turn', 'no-value', 'no-new-events'].includes(result.skipped)
1349
- ? '跳过(没有值得记的内容)'
1350
- : '跳过 · ' + result.skipped)
1351
- record({
1352
- kind: 'consolidate',
1353
- scope: 'private',
1354
- sessionId,
1355
- libraryId: binding.libraryId || null,
1356
- ok,
1357
- level: ok ? 'info' : (result?.timedOut ? 'warn' : 'error'),
1358
- message: '整理' + (ok ? (skipped ? skipText : '完成') : (result?.timedOut ? '超时' : '失败'))
1359
- + (force ? ' · 手动' : (options.trigger === 'backlog' ? ' · 水位' : ' · 空闲'))
1360
- + (result?.childId ? ' · fork ' + result.childId.slice(-8) : '')
1361
- + (result?.reasonCode ? ' · ' + result.reasonCode : '')
1362
- + (result?.error ? ':' + String(result.error) : '')
1363
- + (result?.count !== undefined ? ' · 写入 ' + result.count : '')
1364
- + (result?.wrote !== null && result?.wrote !== undefined ? ' · 索引 +' + result.wrote : '')
1365
- + (result?.scanned !== undefined ? ' · 扫描 ' + result.scanned + ' 事件 / 新 ' + (result.fresh ?? '?') : ''),
1366
- detail: { force, jobId, ...result },
1367
- refs: [],
1368
- })
1369
- return result
1370
- }
1371
- try {
1372
- const settings = getSettings()
1373
- workerMode = settings.consolidationRunner === 'worker'
1374
- accounting = createConsolidationMeasurement(workerMode ? 'worker' : 'fork')
1375
- // 僵尸租约先回收:进程被杀之后 inflight 会留在账本里,不能让一条死记录永久挡住这个会话。
1376
- safeLedger(() => {
1377
- const recovered = recoverStaleJobs()
1378
- if (recovered.length > 0) {
1379
- record({ kind: 'check', scope: 'private', ok: true, message: '回收 ' + recovered.length + ' 个过期整理租约', detail: { recovered } })
1380
- }
1381
- return recovered
1382
- })
1383
-
1384
- // 读不到会话就什么都不用谈,所以先确认快照能力,再确认 fork 能力——
1385
- // 失败信息要说清缺的是哪一个(readSession/observeSession 还是 agents.create)。
1386
- const sessionQuery = (() => { try { return ctx.get?.('sessionQuery') || null } catch { return null } })()
1387
- if (!sessionQuery || (typeof sessionQuery.readSession !== 'function' && typeof sessionQuery.observeSession !== 'function')) {
1388
- return finish({
1389
- ok: false, sessionId, code: 'unavailable', reasonCode: 'no-session-query', settled: false,
1390
- error: 'host has no sessionQuery.readSession / observeSession; historical consolidation is unavailable',
1391
- })
1392
- }
1393
- const agents = ctx.get?.('agents')
1394
- if (typeof agents?.create !== 'function') {
1395
- return finish({ ok: false, sessionId, code: 'unavailable', reasonCode: 'no-agents-service', settled: false, error: 'host has no agents.create; historical consolidation is unavailable' })
1396
- }
1397
- const buildForkSeed = workerMode ? null : await loadBuildForkSeed()
1398
- if (!workerMode && !buildForkSeed) {
1399
- return finish({ ok: false, sessionId, code: 'unavailable', reasonCode: 'no-fork-seed', settled: false, error: 'dsh-session buildForkSeed is unavailable' })
1400
- }
1401
-
1402
- // 安全快照:cut 固定、身份可核验。未闭合的回合、没配对的工具调用、半截 step 在这里就被挡住,
1403
- // 而不是被当成内容喂给 worker(C 包第 1、2 条)。拿不到就 deferred,不收编。
1404
- const captured = await captureSessionSnapshot(ctx, sessionId, { signal: abort.signal })
1405
- if (!captured.ok) {
1406
- if (captured.code === 'deferred') {
1407
- return finish({ ok: true, sessionId, skipped: captured.reasonCode, settled: false, deferred: true, reasonCode: captured.reasonCode, detail: captured.error })
1408
- }
1409
- // 会话已被删除(host 回答 not found)是正常生命周期,不是整理故障:标记
1410
- // sessionGone(空闲扫描从此跳过)、记 info 级 check 而不是 error——删除的
1411
- // 对话不该在整理提醒里挂一条失败(2026-10-31 用户报告)。
1412
- if (isGoneSessionError(captured.error)) {
1413
- setSessionBinding(sessionId, { sessionGone: true, sessionGoneAt: new Date().toISOString(), sleepRetryAt: null, sleepAttempts: 0, lastSleepError: null })
1414
- try { clearSessionState(sessionId) } catch {}
1415
- record({
1416
- kind: 'check', scope: 'private', sessionId, libraryId: binding.libraryId || null, ok: true,
1417
- message: '对话已删除,不再整理(session not found)',
1418
- detail: { reasonCode: 'session-gone' },
1419
- })
1420
- return { ok: false, sessionId, code: 'session-gone', reasonCode: 'session-gone', settled: false, retryable: false, error: captured.error }
1421
- }
1422
- return finish({
1423
- ok: false, sessionId, code: captured.code, reasonCode: captured.reasonCode, settled: false,
1424
- retryable: captured.retryable === true, error: captured.error,
1425
- })
1426
- }
1427
- const fullSnapshot = captured.snapshot
1428
- const events = captured.events
1429
- const fresh = unconsolidatedEvents(binding, events)
1430
- if (events.length === 0) return finish({ ok: false, sessionId, reasonCode: 'empty-snapshot', settled: false, error: 'this session has no content to consolidate' })
1431
- // A manual click on an already-settled session still re-checks the tail instead
1432
- // of replaying megabytes; automatic runs only look at what the cursor has not
1433
- // covered. Either way the fork gets one bounded window, not the whole log.
1434
- const candidateEvents = force && fresh.length === 0 ? selectTailTurnWindow(events).events : fresh
1435
- if (candidateEvents.length === 0) {
1436
- return finish({ ok: true, sessionId, skipped: 'no-new-events', settled: true, snapshot: snapshotMetaOf(fullSnapshot) })
1437
- }
1438
- const generationAtStart = scopeGenerationOf(binding)
1439
- // 待检查边界与已确认边界分开记:证据到达就记一次,失败不回退。
1440
- safeLedger(() => noteEvidence({ sessionId, fromSeq: fullSnapshot.fromSeq, throughSeq: fullSnapshot.throughSeq }))
1441
-
1442
- let value = null
1443
- if (!force) {
1444
- value = assessConsolidationValue(candidateEvents)
1445
- // 这一批里没有真人回合、或只有一句「好的继续」:这一段确实没什么可整理的,
1446
- // 是终态而不是 deferral——写入完成边界由 cycle 落到 lastSleepAt,下一次真人
1447
- // 消息到达前不再重扫同一个寒暄窗口。
1448
- if (!value.worth) {
1449
- // A terminal policy skip advances the coarse cursor and checked range:
1450
- // otherwise the same greetings stay pending forever and the sweep keeps
1451
- // treating them as a real backlog.
1452
- safeLedger(() => skipRange({ sessionId, snapshot: fullSnapshot, reasonCode: value.reason }))
1453
- advanceSleepCursor(sessionId, fullSnapshot.throughSeq)
1454
- return finish({
1455
- ok: true, sessionId, skipped: value.reason, settled: true, deferred: false,
1456
- reasonCode: value.reason, assessment: value, snapshot: snapshotMetaOf(fullSnapshot),
1457
- })
1458
- }
1459
- // 事件/回合水位:积压到一定规模就直接整理,不再等评分。它和空闲触发是
1460
- // 两条腿:空闲保证收尾,水位保证一场持续几小时的会话不会攒到几千条才动。
1461
- const backlog = candidateEvents.length >= CONSOLIDATION_BACKLOG_EVENTS
1462
- || Number(value.humanTurns) >= CONSOLIDATION_BACKLOG_TURNS
1463
- if (options.trigger === 'backlog' && !backlog) {
1464
- return finish({
1465
- ok: true, sessionId, skipped: 'backlog-below-threshold', settled: false, deferred: true,
1466
- reasonCode: 'backlog-below-threshold', assessment: value, snapshot: snapshotMetaOf(fullSnapshot),
1467
- trigger: options.trigger,
1468
- })
1469
- }
1470
- if (!backlog) {
1471
- // 加权判定:短空闲要求分数达标,长空闲(饥饿阈值)无条件放行;
1472
- // 阈值与权重集中在 lib/active-memory.js,可根据回放标定。
1473
- const idleMinutes = binding.lastTurnAt ? (Date.now() - (Date.parse(binding.lastTurnAt) || Date.now())) / 60_000 : Infinity
1474
- const starved = idleMinutes >= Number(settings.activeMemoryStarvationMinutes ?? ACTIVE_MEMORY_POLICY.starvationMinutes)
1475
- // 小增量顺延:不 fork、不推进游标;下一次触发把这段一起带上。
1476
- // 首次整理(还没有成功游标)不受限,尽快建立记忆基线;饥饿(长时间空闲)
1477
- // 仍然放行,保证收尾;force 手动路径不经过这里。
1478
- const firstPass = !binding.lastSleepSeq
1479
- if (!starved && !firstPass && Number(value.humanTurns) < CONSOLIDATION_MIN_HUMAN_TURNS) {
1480
- return finish({
1481
- ok: true, sessionId, skipped: 'below-min-turns', settled: false, deferred: true,
1482
- reasonCode: 'below-min-turns', assessment: value, snapshot: snapshotMetaOf(fullSnapshot),
1483
- trigger: options.trigger,
1484
- })
1485
- }
1486
- const evidence = collectEvidence(candidateEvents)
1487
- const wake = assessWake({
1488
- evidence,
1489
- starved,
1490
- transcriptEvents: events.length,
1491
- pendingEvents: candidateEvents.length,
1492
- policy: { ...ACTIVE_MEMORY_POLICY, minScore: Number(settings.activeMemoryMinScore ?? ACTIVE_MEMORY_POLICY.minScore) },
1493
- })
1494
- record({
1495
- kind: 'check',
1496
- scope: 'private',
1497
- sessionId,
1498
- libraryId: binding.libraryId || null,
1499
- ok: wake.wake,
1500
- message: (wake.wake ? '主动检查触发' : '主动检查跳过')
1501
- + ' · score ' + wake.score
1502
- + ' · ' + wake.reason
1503
- + ' · 空闲 ' + (Number.isFinite(idleMinutes) ? Math.round(idleMinutes) + ' 分钟' : '未知')
1504
- + ' · 会话 ' + events.length + ' 事件'
1505
- + ' · 待整理 ' + candidateEvents.length + ' 事件'
1506
- + ' · 快照 ' + fullSnapshot.hash,
1507
- detail: { trigger: options.trigger || 'idle', reason: wake.reason, score: wake.score, parts: wake.parts, starved, transcriptEvents: events.length, pendingEvents: candidateEvents.length, snapshot: snapshotMetaOf(fullSnapshot) },
1508
- })
1509
- if (!wake.wake) return finish({ ok: true, sessionId, skipped: 'low-score', settled: false, assessment: value, score: wake.score, parts: wake.parts, snapshot: snapshotMetaOf(fullSnapshot) })
1510
- }
1511
- }
1512
-
1513
- // One bounded window per run: the next sweep continues from the new cursor.
1514
- // 失败重试(sleepAttempts>0)时窗口减半:同一游标反复超时不该每次都付整窗成本,
1515
- // 前半段先结算,剩余留给下一次。
1516
- const sleepAttempt = Number(binding.sleepAttempts || 0)
1517
- const windowLimit = sleepAttempt > 0 ? Math.floor(CONSOLIDATION_WINDOW_EVENTS / 2) : CONSOLIDATION_WINDOW_EVENTS
1518
- // Runner and model route use the same settings snapshot captured before awaits.
1519
- // A5:worker 模式按回合取窗(切在回合中间时向后补到 turn/end,避免同一回合
1520
- // 被连续两窗整条重发);fork 路径窗口定义不变。
1521
- let window = workerMode
1522
- ? selectWorkerWindow(candidateEvents, windowLimit)
1523
- : selectConsolidationWindow(candidateEvents, windowLimit)
1524
- if (window.events.length === 0) {
1525
- return finish({ ok: true, sessionId, skipped: 'empty-window', settled: true, snapshot: snapshotMetaOf(fullSnapshot) })
1526
- }
1527
- const windowSnapshot = {
1528
- ...fullSnapshot,
1529
- fromSeq: window.fromSeq,
1530
- throughSeq: window.throughSeq,
1531
- eventCount: window.events.length,
1532
- hash: snapshotHash(window.events, window.fromSeq, window.throughSeq),
1533
- }
1534
- const snapshot = windowSnapshot
1535
- const snapshotMeta = snapshotMetaOf(windowSnapshot)
1536
- // 范围大小决定等多久:显式给了就听调用方的,没给按这一窗的事件数推。
1537
- const budgetMs = Number.isInteger(maxWaitMs) && maxWaitMs > 0 ? maxWaitMs : consolidationWaitBudget(window.events.length)
1538
- // 1.3.1:目录与本地召回命中在种子开头一次给全,worker 不再开只读回合。
1539
- const carry = safeLedger(() => readCarryCandidates(sessionId), [])
1540
- const domain = domainOf(binding)
1541
- const mustCover = mergeMustCover(carry, mustCoverCandidates(window.events, { domain }))
1542
- const seedEvents = workerMode ? null : compactSeedEvents(candidateSeedEvents(window.events, { domain }), [
1543
- memoryCatalogEvent({ ...binding, sessionId }),
1544
- memoryRecallEvent({ binding: { ...binding, sessionId }, candidates: mustCover, events: window.events }),
1545
- ], seedLimitsFor(domain))
1546
- if (!workerMode && seedEvents.length === 0) {
1547
- return finish({ ok: true, sessionId, skipped: 'empty-seed', settled: true, snapshot: snapshotMeta })
1548
- }
1549
-
1550
- // 幂等:同一份固定快照已经结算过就不再 fork 一次(失败的部分写入靠操作键判同再试,
1551
- // 而不是靠"同一个主题就跳过")。
1552
- const opKey = operationKey({ sessionId, libraryId: binding.libraryId, snapshotHash: windowSnapshot.hash, scopeGeneration: generationAtStart })
1553
- const previous = safeLedger(() => findOperation(sessionId, opKey))
1554
- if (previous && (previous.outcome === 'completed' || previous.outcome === 'skipped')) {
1555
- return finish({ ok: true, sessionId, skipped: 'already-consolidated', settled: true, snapshot: snapshotMeta, credential: previous })
1556
- }
1557
- // 同一份快照连续失败到上限就不再「自动」重跑:窗口已经很小,重试成本可控,但
1558
- // 没有新事件的同一段转录不值得无限重试。手动整理(force)是明确的一次再决定,
1559
- // 不受上限约束——否则冻结回放/用户重试都会被永久卡在同一个窗口。新消息会改变
1560
- // 快照哈希,自动路径也重新获得机会。
1561
- if (!force && previous?.outcome === 'failed' && Number(previous.failures) >= CONSOLIDATION_SNAPSHOT_FAILURE_LIMIT) {
1562
- // 2026-11-15:冻结原因若是思考强度被模型拒(账本 lastError 可见),就地学习组合并
1563
- // 清连击,本次直接放行 fork(fork 起点读不到拒绝表就会带档失败——放行前先学习,
1564
- // effort 应用处读到拒绝表即不带档)。已冻结的会话由此自愈,不必等手动 force。
1565
- const failureState = safeLedger(() => sessionState(sessionId), null)
1566
- const lastError = failureState?.lastError ?? null
1567
- const staleRefusal = effortRefusalOf(lastError)
1568
- const newRefusal = staleRefusal && !isEffortRefused(staleRefusal.key)
1569
- const legacyOutputLimit = (previous.reasonCode ?? failureState?.lastReasonCode) === 'fork-turn-failed'
1570
- && /^the fork turn ended max-tokens(?::|$)/.test(String(lastError || ''))
1571
- const outputLimited = previous.reasonCode === 'model-output-limit' || legacyOutputLimit
1572
- const execution = outputLimited ? await consolidationExecutionContext(ctx, sessionId, settings, events) : null
1573
- const changedExecution = execution && (!previous.executionSettingsKey || execution.settingsKey !== previous.executionSettingsKey
1574
- || execution.defaultsComparable && execution.key !== previous.executionKey)
1575
- if (!newRefusal && !changedExecution) {
1576
- // 冷却(issue #4 缺陷 1):冻结超过冷却期就放行一次真实重试——连击清零交给
1577
- // 下方与 newRefusal/changedExecution 共用的 recordOperation;否则维持熔断。
1578
- const frozenAt = Date.parse(previous.at || '') || 0
1579
- if (Date.now() - frozenAt >= CONSOLIDATION_SNAPSHOT_FAILURE_COOLDOWN_MS) {
1580
- warn('consolidation freeze expired: ' + String(previous.reasonCode || 'snapshot-failed') + ' streak reset after cooldown; retrying this window')
1581
- } else {
1582
- // settled: false(不再假装这段已整理——那是失败熔断,不是终态跳过):
1583
- // cycle.js 走 deferred 路径,不推 lastSleepAt、不清 lastSleepError,
1584
- // 「整理提醒」里保持可见;冷却到期后闸门自动放行重试。
1585
- const result = {
1586
- ok: true, sessionId, skipped: 'snapshot-failed', settled: false, deferred: true,
1587
- reasonCode: 'snapshot-failed-too-many', cooldownUntil: new Date(frozenAt + CONSOLIDATION_SNAPSHOT_FAILURE_COOLDOWN_MS).toISOString(),
1588
- frozenAt: previous.at || null, snapshot: snapshotMeta, failures: Number(previous.failures) || 0, lastError,
1589
- }
1590
- // 冻结期活动日志去重:同一份冻结记录(按 previous.at 判同)只落一条。
1591
- // cycle.js 现已用 sleepFrozenUntil 在候选阶段退避,正常不再每扫扫入;这里的
1592
- // 去重兜住「冻结期新活动让路后、同哈希再次冻结」的重复返回,避免刷屏。
1593
- const freezeStamp = String(previous.at || '')
1594
- if (frozenLogStamps.get(opKey) !== freezeStamp) {
1595
- frozenLogStamps.set(opKey, freezeStamp)
1596
- return finish(result)
1597
- }
1598
- return result
1599
- }
1600
- }
1601
- if (newRefusal) {
1602
- warn('consolidation unfrozen: ' + staleRefusal.key + ' was refused by the model; retrying this window without the effort')
1603
- markEffortRefused(staleRefusal.key)
1604
- }
1605
- if (changedExecution) warn('consolidation output-limit retry: execution configuration changed or needs its first fingerprint')
1606
- safeLedger(() => recordOperation({ sessionId, key: opKey, outcome: 'failed', ids: previous.ids || [] }))
1607
- }
1608
-
1609
- // 工具面必须可验证:父会话这一轮真实发给模型的工具表里若没有记忆写工具,
1610
- // fork 同样不会有——那就不 fork,明确 unavailable(C 包第 3 条)。
1611
- const probe = probeToolSurface({ ctx, sessionId, events })
1612
- if (!probe.ok) {
1613
- return finish({
1614
- ok: false, sessionId, code: 'unavailable', reasonCode: probe.reasonCode, settled: false, retryable: false,
1615
- toolSurface: probe.tools || null, ptc: probe.ptcObserved === true,
1616
- error: 'this conversation exposes no memory write tool to the model (' + String(probe.source || 'unknown') + '), so a consolidation worker could not write anything; consolidation is unavailable until the session has memu_private_remember / memu_private_update',
1617
- })
1618
- }
1619
-
1620
- jobId = 'cons-' + Date.now().toString(36) + '-' + crypto.randomBytes(3).toString('hex')
1621
- // 2026-11-15 扫雷:租约跟随本次预算(+90s 余量),不再固定 15 分钟——
1622
- // 走不到超时路径就死的任务(插件重启 / fork 被外力杀掉)不会调 failJob,
1623
- // 固定 15 分钟租约让该会话的重试一直撞 lease-held;预算封顶 600s,
1624
- // 租约最迟在真死后 ~90s 由 recoverStaleJobs 回收,而不是再等 9 分钟。
1625
- const begun = safeLedger(() => beginJob({ sessionId, jobId, snapshot, binding, leaseMs: budgetMs + 90_000 }))
1626
- if (!begun) {
1627
- return finish({
1628
- ok: false, sessionId, settled: false, retryable: true, reasonCode: 'ledger-unavailable',
1629
- error: 'the consolidation lease could not be persisted; no worker was created',
1630
- })
1631
- }
1632
- if (begun.ok !== true) {
1633
- return finish({
1634
- ok: false, sessionId, running: true, settled: false, reasonCode: 'lease-held',
1635
- error: 'this session already holds a consolidation lease (' + String(begun.jobId) + ' until ' + new Date(begun.leaseUntil).toISOString() + '); the previous run is still unaccounted for — the lease self-heals when it expires, then the range is retried on the next sweep',
1636
- })
1637
- }
1638
-
1639
- const header = captured.header || {}
1640
- // 每次整理都留"看了多少、新的多少、真正写了几条",否则"0 记忆"无法定位是
1641
- // 没触发、被门挡住还是提取空转。
1642
- const freshCount = fresh.length
1643
- let beforeIds = null
1644
- let beforeEntries = null
1645
- try {
1646
- const beforeIndex = loadPrivateIndex(binding.libraryId)
1647
- beforeIds = new Set(Object.keys(beforeIndex.entries))
1648
- beforeEntries = Object.fromEntries(Object.entries(beforeIndex.entries).map(([id, entry]) => [id, entryFingerprint(entry)]))
1649
- } catch { beforeIds = null; beforeEntries = null }
1650
-
1651
- // 整理 fork 的模型选择(三模式,lib/fork-model.js)。inherit 保持原路径逐字节一致;
1652
- // host 直接指名宿主已激活 route;custom 要先在宿主 llm 注册表确认本插件私有 route
1653
- // 可用(能力缺失/注册失败/服务性探测不过 → 降级回 inherit 或拒绝本次整理,warn 一
1654
- // 行,绝不 fail closed)。fork 的 AgentOptions 没有 baseURL/apiKey 通道,custom 的
1655
- // 自定义端点只能走注册 route。(settings 已在窗口选择处读取。)
1656
- //
1657
- // host/custom 不需要父会话 route:这里不探测父会话,也避免 inheritedAgentOptions 的
1658
- // resume 回退把父会话挂成宿主活视图——活视图会钉住 sessionQuery 的快照,外部追加的
1659
- // 持久日志(bench 种子)就再也读不到(S1 冻结)。custom 真失败时才惰性回退探测。
1660
- const modelModeSetting = settings.consolidationModelMode || 'inherit'
1661
- let inherited = null
1662
- if (modelModeSetting !== 'host' && modelModeSetting !== 'custom') {
1663
- inherited = await inheritedAgentOptions(ctx, sessionId, events)
1664
- }
1665
- const resolved = resolveConsolidationAgentOptions(settings, inherited)
1666
- let agentOptions = resolved.options
1667
- let modelMode = resolved.reason
1668
- if (!agentOptions) {
1669
- // no-inherited-route 与旧失败路径逐字节一致(inherit 模式语义不变);host/custom
1670
- // 的坏配置各自带 reasonCode,整理提醒能直接说清是哪个配置面写错了。
1671
- if (resolved.reason === 'no-inherited-route') {
1672
- safeLedger(() => failJob({ sessionId, jobId, reasonCode: 'no-parent-route', retryable: true, error: 'cannot inherit the parent model/provider' }))
1673
- return finish({ ok: false, sessionId, reasonCode: 'no-parent-route', settled: false, error: 'cannot inherit the parent model/provider; consolidation fork was not created' })
1674
- }
1675
- safeLedger(() => failJob({ sessionId, jobId, reasonCode: resolved.reason, retryable: true, error: 'cannot resolve the consolidation model (' + resolved.reason + ')' }))
1676
- return finish({ ok: false, sessionId, reasonCode: resolved.reason, settled: false, error: 'cannot resolve the consolidation model (' + resolved.reason + '); consolidation fork was not created' })
1677
- }
1678
- if (resolved.reason === 'custom') {
1679
- // 每次整理都重挂一次(先卸旧再注册,设置变更自然生效);成功后才允许 fork 指名
1680
- // dsh-memu-custom。失败降级:有父 route 就回 inherit,没有就只能拒绝。
1681
- const ensured = await ensureConsolidationRoute(ctx, settings)
1682
- if (!ensured.ok) {
1683
- warn('consolidation custom model route unavailable (' + ensured.reason + (ensured.error ? ': ' + ensured.error : '') + '); falling back to the inherited route')
1684
- if (!inherited) inherited = await inheritedAgentOptions(ctx, sessionId, events)
1685
- if (inherited) {
1686
- agentOptions = inherited
1687
- modelMode = 'inherit-fallback'
1688
- } else {
1689
- safeLedger(() => failJob({ sessionId, jobId, reasonCode: 'custom-route-unavailable', retryable: true, error: 'the custom consolidation route is unavailable (' + ensured.reason + ')' }))
1690
- return finish({ ok: false, sessionId, reasonCode: 'custom-route-unavailable', settled: false, error: 'the custom consolidation route is unavailable (' + ensured.reason + '); consolidation fork was not created' })
1691
- }
1692
- }
1693
- }
1694
-
1695
- // 最终 route(含 custom 回退)确定后再覆盖档位、过滤实际生效的组合。
1696
- // inherit 也可能从父 options 带入被拒档位;只克隆子 options,不改父对象或其它参数。
1697
- const effort = settings.consolidationReasoningEffort
1698
- if (effort && effort !== 'inherit') agentOptions = { ...agentOptions, reasoningEffort: effort }
1699
- const effectiveEffort = agentOptions.reasoningEffort
1700
- if (effectiveEffort && isEffortRefused([agentOptions.provider, agentOptions.model, effectiveEffort].join('|'))) {
1701
- warn('consolidation reasoning effort ' + effectiveEffort + ' previously refused by ' + agentOptions.provider + '/' + agentOptions.model + ' — starting the worker/fork without it')
1702
- agentOptions = { ...agentOptions }
1703
- delete agentOptions.reasoningEffort
1704
- }
1705
-
1706
- // 执行器分叉(T1,设计文档 §10.2):workerMode 已在窗口选择处确定(A5)。
1707
- // 默认 'fork'(现状路径,逐字节不变);显式 'worker' 走持久整理 worker(lib/worker-pool.js)。
1708
- executionContext = await consolidationExecutionContext(ctx, sessionId, settings, events, modelMode === 'inherit' ? agentOptions : null)
1709
- let workerAcquired = null
1710
- let workerEpochRecord = null
1711
- let workerIncrement = null
1712
- let dispatchText = null
1713
- let dispatchKind = 'fork'
1714
- if (workerMode) {
1715
- const workerBinding = { ...binding, sessionId }
1716
- workerIncrement = loadWorkerIncrement({ sessionId, binding: workerBinding, window, events: window.events })
1717
- if (!workerIncrement.text.trim()) {
1718
- safeLedger(() => failJob({ sessionId, jobId, reasonCode: 'empty-increment', retryable: true }))
1719
- return finish({ ok: false, sessionId, settled: false, retryable: true, reasonCode: 'empty-increment', error: 'no readable worker increment; the range stays pending' })
1720
- }
1721
- const current = getSessionBinding(sessionId) || binding
1722
- const privatePrompt = buildPrivateConsolidationPrompt(sessionId)
1723
- const common = {
1724
- sessionId, binding: workerBinding, snapshot, probe, jobId,
1725
- reason: force ? 'manual' : 'auto', singleOnly: Boolean(binding.consolidationSingleOnly), mustCover,
1726
- contract: receiptContractText({ jobId, snapshotHash: snapshot.hash, autoReceipt: true }),
1727
- incrementRecords: workerIncrement.records,
1728
- incrementText: workerIncrement.source === 'fallback' ? workerIncrement.text : null,
1729
- digest: workerIncrement.digest, catalog: memoryCatalogEvent(workerBinding),
1730
- domain,
1731
- sceneTime: current.sceneTime || binding.sceneTime || null,
1732
- pendingNote: Boolean(current.consolidationPending), pendingHash: current.consolidationPending?.snapshotHash || null,
1733
- carry: mustCover, lastSleepSeq: binding.lastSleepSeq ?? null,
1734
- }
1735
- const buildPacket = (acquired) => {
1736
- dispatchKind = acquired.birth ? 'handoff' : 'increment'
1737
- const pack = acquired.birth ? buildHandoffPack({
1738
- ...common, includeTail: acquired.handoff !== false, writtenRows: acquired.handoff === false ? [] : null,
1739
- }) : buildIncrementPack(common)
1740
- return acquired.birth ? [privatePrompt, '', pack].join('\n') : pack
1741
- }
1742
- const acquireOptions = { settings, probe, agentOptions, header }
1743
- workerAcquired = await acquireWorker(ctx, workerBinding, acquireOptions)
1744
- if (workerAcquired.ok) {
1745
- dispatchText = buildPacket(workerAcquired)
1746
- let packet = measurePacket(dispatchText, dispatchKind)
1747
- if (!packetBudgetFit(workerAcquired.epoch, packet, settings) && !workerAcquired.birth) {
1748
- // The final text, not just the pending increment, must fit. Rebuild at
1749
- // most once, since a handoff includes extra identity/settled-tail text.
1750
- await retireWorker(ctx, workerAcquired.forkId, 'packet-budget', { handoff: true })
1751
- workerAcquired = await acquireWorker(ctx, workerBinding, { ...acquireOptions, afterEpochIndex: workerAcquired.epoch.index })
1752
- if (workerAcquired.ok) {
1753
- dispatchText = buildPacket(workerAcquired)
1754
- packet = measurePacket(dispatchText, dispatchKind)
1755
- }
1756
- }
1757
- if (workerAcquired.ok && !packetBudgetFit(workerAcquired.epoch, packet, settings)) {
1758
- accounting.measurement.packet = { ...packet, dispatched: false }
1759
- await retireWorker(ctx, workerAcquired.forkId, 'packet-too-large', { handoff: false })
1760
- safeLedger(() => failJob({ sessionId, jobId, reasonCode: 'packet-too-large', retryable: true, error: 'the complete first packet exceeds the worker epoch budget' }))
1761
- return finish({ ok: false, sessionId, childId: workerAcquired.forkId, settled: false, retryable: true, reasonCode: 'packet-too-large', error: 'the complete worker packet is too large; the range stays pending (no automatic unsafe truncation)' })
1762
- }
1763
- }
1764
- if (!workerAcquired.ok) {
1765
- safeLedger(() => failJob({ sessionId, jobId, reasonCode: workerAcquired.reasonCode || 'worker-acquire-failed', retryable: true, error: workerAcquired.error || null }))
1766
- return finish({
1767
- ok: false, sessionId, settled: false, retryable: true,
1768
- reasonCode: workerAcquired.reasonCode || 'worker-acquire-failed',
1769
- error: workerAcquired.error || 'the consolidation worker could not be acquired',
1770
- })
1771
- }
1772
- childId = workerAcquired.forkId
1773
- handle = workerAcquired.handle
1774
- workerTools = workerAcquired.tools
1775
- workerRestriction = workerAcquired.restriction
1776
- workerEpochRecord = workerAcquired.epoch
1777
- workerEpochAbort = workerAcquired.epochAbort || null
1778
- accounting = createConsolidationMeasurement('worker', { sessionId: childId, afterSeq: workerAcquired.eventCursor ?? workerEpochRecord.lastEventSeq })
1779
- } else {
1780
- childId = 'memu-consolidate-' + Date.now().toString(36) + '-' + crypto.randomBytes(3).toString('hex')
1781
- // 种子只种这一窗:worker 看到的世界就是它要对账的那一段,窗口之外的事件
1782
- // 留给下一批。seq 已按 compactSeedEvents 重排成从 0 连续,inheritedEventCount
1783
- // 必须等于种子长度(不是父会话的 throughSeq),否则宿主会拒绝这份种子。
1784
- // 保留仍存在的会话 cwd;旧目录失效时回退 dataDir,避免宿主拒绝启动回合。
1785
- const forkCwd = resolveConsolidationCwd(header.cwd)
1786
- try {
1787
- handle = await agents.create({
1788
- sessionId: childId,
1789
- meta: {
1790
- cwd: forkCwd,
1791
- parentSession: sessionId,
1792
- isSeeded: true,
1793
- // Without this the fork is treated as an ordinary user conversation by
1794
- // the injection path and the sidebar session lists.
1795
- origin: 'subagent',
1796
- agentPreset: header.agentPreset,
1797
- },
1798
- inheritedEventCount: seedEvents.length,
1799
- seed: buildForkSeed(seedEvents, seedEvents.length - 1),
1800
- agentOptions,
1801
- signal: abort.signal,
1802
- })
1803
- } catch (error) {
1804
- // 宿主拒绝种子时最需要的诊断信息就在这条错误里("seed event at index …"),
1805
- // 用独立 reasonCode 写进活动日志,别让它塌成一句 exception。
1806
- const failure = String(error?.message || error)
1807
- safeLedger(() => failJob({ sessionId, jobId, reasonCode: 'fork-create-failed', retryable: true, error: failure }))
1808
- return finish({
1809
- ok: false, sessionId, childId, settled: false, retryable: true,
1810
- reasonCode: 'fork-create-failed',
1811
- error: 'the host rejected the consolidation fork: ' + failure,
1812
- })
1813
- }
1814
- }
1815
-
1816
- // header 无法证明 worker 有写工具时(PTC 会话名单只有 run_code / 旧会话没有名单),
1817
- // 把 worker 读写面挂进 fork 自己的 scope,保证 SDK 面(PTC)与原生面(普通会话)都真能写入。
1818
- // 标准 preset 的 fork 名单里已有 memu_*(probe.hasWrite === true),不重复挂。
1819
- // worker 模式:工具面只在初生挂一次(acquireWorker 内部处理),续窗跳过(§15.2 改动点 2)。
1820
- if (!workerMode) {
1821
- if (probe.hasWrite !== true) {
1822
- workerTools = await attachWorkerTools(agents, childId, sessionId)
1823
- }
1824
- workerRestriction = await restrictWorkerTools(agents, childId, sessionId)
1825
- }
1826
- // Counters are shared by fork/worker; only the latter persists an epoch.
1827
- if (!workerMode) {
1828
- accounting = createConsolidationMeasurement('fork', { sessionId: childId })
1829
- const brief = buildWorkerBrief({
1830
- snapshot, probe, jobId, mustCover, autoReceipt: true, domain,
1831
- contract: receiptContractText({ jobId, snapshotHash: snapshot.hash, autoReceipt: true }),
1832
- reason: force ? 'manual' : 'auto', singleOnly: Boolean(binding.consolidationSingleOnly),
1833
- })
1834
- dispatchText = [buildPrivateConsolidationPrompt(sessionId), '', brief].join('\n')
1835
- }
1836
- accounting.measurement.packet = measurePacket(dispatchText, dispatchKind)
1837
-
1838
- // 先记"已开始"再等结果:一个大会话的 fork 可能跑好几分钟,没有这条记录,
1839
- // 侧边栏和日志页在等待期间只会显示上一次的结果,用户会以为按钮没生效。
1840
- record({
1841
- kind: 'consolidate',
1842
- scope: 'private',
1843
- sessionId,
1844
- libraryId: binding.libraryId || null,
1845
- ok: true,
1846
- message: '整理已开始 · ' + (force ? '手动' : (options.trigger === 'backlog' ? '水位' : '空闲'))
1847
- + ' · fork ' + childId.slice(-8)
1848
- + ' · 窗口 ' + window.events.length + ' 条事件(父会话 ' + events.length + ' 条 / 新 ' + freshCount + ' 条)'
1849
- + (window.remaining > 0 ? ' · 还余 ' + window.remaining : '')
1850
- + ' · 预算 ' + Math.round(budgetMs / 1000) + 's · 快照 ' + snapshot.hash,
1851
- detail: { childId, jobId, force, trigger: options.trigger || 'idle', events: window.events.length, transcriptEvents: events.length, fresh: freshCount, remaining: window.remaining, budgetMs, phase: 'started', snapshot: snapshotMeta,
1852
- modelMode, runner: workerMode ? 'worker' : 'fork', measurement: accounting.measurement,
1853
- probe: { source: probe.source, hasWrite: probe.hasWrite, ptc: probe.ptcObserved === true },
1854
- ...workerToolsMeta(workerTools) },
1855
- })
1856
-
1857
- // turn/end 是这一轮的唯一权威结果;whenIdle 只说明 driver 停了(失败的回合也停)。
1858
- // 顺带从同一个公共事件流里收三样东西:worker 的正文(回执在里面)、
1859
- // 它的工具动作(用来在写入途中重验父授权),以及父会话自己是否动过。
1860
- const childSession = handle?.agent?.session
1861
- const parentAgent = (() => { try { return agents.get?.(sessionId) || null } catch { return null } })()
1862
- const parentLive = parentAgent?.session || null
1863
- const isParentSession = (session) => session === parentLive || (session && parentLive === null && session?.id === sessionId)
1864
- const revalidate = (source) => {
1865
- if (scopeChanged) return
1866
- const now = scopeGenerationOf(getSessionBinding(sessionId))
1867
- if (!generationAtStart || now === generationAtStart) return
1868
- scopeChanged = { source, expected: generationAtStart, actual: now }
1869
- record({
1870
- kind: 'consolidate', scope: 'private', sessionId, libraryId: binding.libraryId || null, ok: false, level: 'warn',
1871
- message: '整理作废:父会话授权变化(' + source + ')',
1872
- detail: { jobId, childId, ...scopeChanged },
1873
- })
1874
- try { (workerMode && workerEpochAbort ? workerEpochAbort : abort).abort() } catch {}
1875
- }
1876
- if (typeof ctx.on === 'function' && childSession) {
1877
- try {
1878
- offSession = ctx.on('session/event', (session, event) => {
1879
- if (session === childSession) {
1880
- if (!accounting.observe(event)) return
1881
- if (event?.type === 'turn/end') { turnEnd = event; return }
1882
- if (event?.type === 'assistant/message') {
1883
- const blocks = event?.data?.message?.content
1884
- if (Array.isArray(blocks)) {
1885
- for (const block of blocks) {
1886
- if (block?.type === 'text' && typeof block.text === 'string' && block.text.trim()) {
1887
- assistantTexts.push(block.text)
1888
- }
1889
- }
1890
- }
1891
- return
1892
- }
1893
- // 工具动作是写入的落点:每出现一次就重验一次父授权,变了立刻停掉这条 fork。
1894
- if (event?.type === 'tool/call' || event?.type === 'tool/result' || event?.type === 'tool/ptc-dispatch' || event?.type === 'tool/ptc-dispatch-start') {
1895
- revalidate('worker-write')
1896
- workerToolRounds += 1
1897
- if (workerToolRounds >= WORKER_HARD_STOP_ROUND) {
1898
- // A2:worker 模式 abort 的是绑在生命周期上的 epoch 控制器,硬停才真正生效;
1899
- // 回合以 aborted 收尾 → turnEndFailure → 退役。fork 模式仍 abort 窗口 signal。
1900
- try { (workerMode && workerEpochAbort ? workerEpochAbort : abort).abort() } catch {}
1901
- } else {
1902
- const guidance = workerRoundGuidance(workerToolRounds)
1903
- if (guidance && workerToolRounds === WORKER_WRAPUP_ROUND) {
1904
- try {
1905
- const queued = handle.agent.followup(noticeMessage(guidance.text, '整理收尾提示'))
1906
- accounting.dispatch(guidance.text, 'wrapup')
1907
- Promise.resolve(queued).catch((error) => warn('consolidation wrapup followup failed: ' + describeError(error)))
1908
- } catch (error) { warn('consolidation wrapup followup failed: ' + describeError(error)) }
1909
- }
1910
- }
1911
- return
1912
- }
1913
- return
1914
- }
1915
- // 用户又说话了:父会话的库/域/上下文可能已经被切换,重新比一次指纹。
1916
- if (isParentSession(session) && (event?.type === 'turn/start' || event?.type === 'user/message')) revalidate('parent-activity')
1917
- })
1918
- } catch {}
1919
- }
1920
-
1921
- // The fork must write into the parent's library, not derive one from its own
1922
- // freshly minted session id.
1923
- setSessionBinding(childId, {
1924
- libraryId: binding.libraryId,
1925
- consolidationFork: true,
1926
- // 整理发生在几小时后,父会话此刻的心境不是这段转录里那件事的情绪,所以 fork
1927
- // 不继承 mood。显式写 null 而不是留空:缺字段和「这一刻是中性」在写入时都走
1928
- // 同一条兜底,但只有 null 能把「后台 worker 没有当下心境」说清楚。
1929
- mood: null,
1930
- // The fork writes memories on the same logical clock as its parent. Without
1931
- // this the worker falls back to the wall clock at fork time; the per-turn
1932
- // [事件时间] markers in the seed remain the authoritative override.
1933
- sceneTime: binding.sceneTime || null,
1934
- parentSessionId: sessionId,
1935
- parentScopeGeneration: generationAtStart,
1936
- snapshotHash: snapshot.hash,
1937
- // 调试/测试用:worker 的回执范围必须和这两项一致,否则 completeJob 不会推进。
1938
- snapshotFromSeq: snapshot.fromSeq,
1939
- snapshotThroughSeq: snapshot.throughSeq,
1940
- snapshotEventCount: snapshot.eventCount,
1941
- jobId,
1942
- scopeKey: binding.scopeKey,
1943
- memoryOwnerSessionId: binding.memoryOwnerSessionId || sessionId,
1944
- memoryContext: binding.memoryContext || {},
1945
- useLibrary: true,
1946
- useGlobal: binding.useGlobal === true,
1947
- domain: binding.domain,
1948
- domainOverride: binding.domainOverride || null,
1949
- })
1950
- // worker 模式(§15.2 改动点 3):子绑定补 epoch 副本;sceneTime 每窗重读父绑定
1951
- // (RP 剧情可能推进;现状 fork 是诞生时定死一次,worker 路径每窗刷新,§6)。
1952
- if (workerMode && workerEpochRecord) {
1953
- const sceneTimeNow = (() => {
1954
- try { return getSessionBinding(sessionId)?.sceneTime || binding.sceneTime || null } catch { return binding.sceneTime || null }
1955
- })()
1956
- setSessionBinding(childId, { workerEpoch: workerEpochRecord, sceneTime: sceneTimeNow })
1957
- }
1958
-
1959
- // 写入前最后一次重验:这次的授权还成立吗?不成立就别把 prompt 发出去。
1960
- revalidate('pre-dispatch')
1961
- if (scopeChanged) {
1962
- // worker 模式:scope 已污染,立即退役且不交接(§4.5 条件 1)。
1963
- if (workerMode && childId) { try { await retireWorker(ctx, childId, 'scope-change', { handoff: false }) } catch {} }
1964
- safeLedger(() => failJob({ sessionId, jobId, reasonCode: 'parent-scope-changed', retryable: false, error: 'the parent conversation changed scope before dispatch' }))
1965
- return finish({
1966
- ok: false, sessionId, childId, settled: false, retryable: false, reasonCode: 'parent-scope-changed',
1967
- error: 'the parent conversation switched library, scope or memory context before the worker was dispatched; nothing was credited',
1968
- })
1969
- }
1970
-
1971
- // Measure exactly the final followup text, including all separators/briefs.
1972
- handle.agent.followup(noticeMessage(dispatchText, '整理这场对话的私有记忆'))
1973
- accounting.dispatch(dispatchText, dispatchKind)
1974
- // followup only queues. whenIdle says the driver stopped; turn/end says
1975
- // whether that turn actually succeeded, so both are checked below.
1976
- idle = typeof handle.agent.whenIdle === 'function' ? handle.agent.whenIdle() : Promise.resolve()
1977
- let timer = null
1978
- let outcome
1979
- try {
1980
- const wait = new Promise((resolve) => { timer = setTimeout(() => resolve('timeout'), budgetMs) })
1981
- outcome = await Promise.race([idle.then(() => 'done'), wait])
1982
- } finally { clearTimeout(timer) }
1983
-
1984
- // worker 模式 epoch 记账(§4.5/§15.2 改动点 3):本窗增量 + 观测到的 worker 产出
1985
- // 并入 chars、windows +1;whenIdle 正常完成记 lastIdleAt(条件 4 的 TTL 起算点)。
1986
- // 结算成功后的超时清零在 completeJob 之后单独落一次。
1987
- if (workerMode) {
1988
- workerEpochRecord = recordEpochProgress({ sessionId }, {
1989
- measurement: accounting.measurement,
1990
- idleAt: outcome === 'done' ? Date.now() : null,
1991
- }) || workerEpochRecord
1992
- }
1993
-
1994
- let wrote = null
1995
- let decision = null
1996
- let completion = null
1997
- if (outcome === 'done') {
1998
- const failure = turnEndFailure(turnEnd)
1999
- if (failure) {
2000
- // batch 参数的 JSON 畸形是模型生成问题,不是整理逻辑故障:标记下一次
2001
- // 只用逐条 remember,并让重试路径接住(consolidateAll 已有 2 次重试)。
2002
- const batchJsonInvalid = /memu_private_remember_batch/.test(String(failure))
2003
- && /JSON|Expected ','|after array element/.test(String(failure))
2004
- const outputLimited = turnEnd?.data?.reason?.kind === 'max-tokens'
2005
- const execution = outputLimited ? executionContext : null
2006
- const reasonCode = outputLimited ? 'model-output-limit' : batchJsonInvalid ? 'batch-json-invalid' : 'fork-turn-failed'
2007
- const outputLimitError = outputLimited
2008
- ? failure + '; 输出预算不足(含思考/剩余上下文限制),请调整宿主最大输出 token 或使用模型支持的思考档位;待处理范围未结算'
2009
- : failure
2010
- // 思考强度不被支持 = 配置与模型不匹配,失败发生在回合起点、代价极小:
2011
- // 学习该组合(下次 fork 不带档)并把本次标记可重试,让下一次扫描很快接住。
2012
- const effortRefusal = effortRefusalOf(failure)
2013
- if (effortRefusal) {
2014
- markEffortRefused(effortRefusal.key)
2015
- // 同时清掉该快照的失败连击:失败是配置不匹配(已学习),不是这段转录有病——
2016
- // 不清零的话 snapshot-failed-too-many 闸门会让自动重试永远进不来。
2017
- safeLedger(() => recordOperation({ sessionId, key: opKey, outcome: 'failed', ids: [] }))
2018
- }
2019
- if (batchJsonInvalid) setSessionBinding(sessionId, { consolidationSingleOnly: true })
2020
- // worker 模式:回合失败即退役条件 5,不带病工作、不做交接(§4.5)。
2021
- if (workerMode && childId) { try { await retireWorker(ctx, childId, 'failure', { handoff: false }) } catch {} }
2022
- const retryable = outputLimited || batchJsonInvalid || Boolean(effortRefusal)
2023
- safeLedger(() => failJob({ sessionId, jobId, reasonCode, retryable, error: outputLimitError, executionKey: execution?.key || null, executionSettingsKey: execution?.settingsKey || null, executionDefaultsComparable: execution?.defaultsComparable ?? true }))
2024
- return finish({
2025
- ok: false, error: 'consolidation fork failed: ' + outputLimitError, sessionId, childId,
2026
- settled: false, timedOut: false, retryable, reasonCode,
2027
- ...(outputLimited ? { configuredMaxTokens: agentOptions.maxTokens ?? execution.maxTokens } : {}),
2028
- })
2029
- }
2030
- // 父授权重验:写入可能已经落了一部分,但凭证只有在授权还成立时才算数。
2031
- const generationNow = scopeGenerationOf(getSessionBinding(sessionId))
2032
- if (scopeChanged || (generationAtStart && generationNow !== generationAtStart)) {
2033
- if (workerMode && childId) { try { await retireWorker(ctx, childId, 'scope-change', { handoff: false }) } catch {} }
2034
- safeLedger(() => failJob({ sessionId, jobId, reasonCode: 'parent-scope-changed', retryable: false, error: 'the parent conversation changed scope during consolidation' }))
2035
- return finish({
2036
- ok: false, sessionId, childId, settled: false, retryable: false, reasonCode: 'parent-scope-changed',
2037
- error: 'the parent conversation switched library, scope or memory context while the worker was running; the result was not credited (writes that already landed stay in the library, the range stays pending)',
2038
- })
2039
- }
2040
- // 兼容字段 lastSleepSeq 只能跟着凭证走:没有对账过的结果就不算整理过,
2041
- // 否则旧游标会把「失败」记成「已整理」,正是 C 包要消灭的那类谎。
2042
- if (beforeIds) {
2043
- try {
2044
- const afterIds = Object.keys(loadPrivateIndex(binding.libraryId).entries)
2045
- wrote = afterIds.filter((id) => !beforeIds.has(id)).length
2046
- } catch { wrote = null }
2047
- }
2048
- let index = null
2049
- try { index = loadPrivateIndex(binding.libraryId) } catch { index = null }
2050
- // 完成不是"没报错":worker 的回执 + 库里的真实变化,两边对上才结算。
2051
- const workerText = assistantTexts.join('\n')
2052
- decision = decideCompletion({
2053
- text: workerText,
2054
- wrote,
2055
- index,
2056
- beforeIds,
2057
- beforeEntries,
2058
- expectedJobId: jobId,
2059
- expectedSnapshotHash: snapshot.hash,
2060
- autoReceipt: { jobId, snapshotHash: snapshot.hash, checkedRange: { fromSeq: snapshot.fromSeq, throughSeq: snapshot.throughSeq } },
2061
- })
2062
-
2063
- if (!decision.advance) {
2064
- // worker 模式:对账不过 = 退役条件 5(无交接);已写入的条目保留,区间回 pending。
2065
- if (workerMode && childId) { try { await retireWorker(ctx, childId, 'failure', { handoff: false }) } catch {} }
2066
- safeLedger(() => failJob({
2067
- sessionId, jobId, reasonCode: decision.reasonCode || 'not-settled',
2068
- retryable: decision.retryable !== false, error: decision.error || null,
2069
- }))
2070
- return finish({
2071
- ok: false, sessionId, childId, settled: false, retryable: decision.retryable !== false,
2072
- status: decision.status, outcome: decision.outcome, reasonCode: decision.reasonCode,
2073
- counts: decision.counted || null, snapshot: snapshotMeta,
2074
- error: decision.error || ('consolidation result was not verified: ' + String(decision.reasonCode || 'unknown')),
2075
- })
2076
- }
2077
- completion = safeLedger(() => completeJob({
2078
- sessionId, jobId, snapshot,
2079
- covered: decision.covered,
2080
- status: decision.status,
2081
- outcome: decision.outcome,
2082
- reasonCode: decision.reasonCode,
2083
- retryable: decision.retryable === true,
2084
- counts: decision.counted,
2085
- receipt: decision.receipt,
2086
- }))
2087
- if (!completion?.advanced) {
2088
- return finish({ ok: false, sessionId, childId, settled: false, retryable: true,
2089
- reasonCode: 'ledger-not-advanced', snapshot: snapshotMeta,
2090
- error: 'the consolidation ledger could not verify the covered snapshot range' })
2091
- }
2092
- advanceSleepCursor(sessionId, snapshot.throughSeq, { consolidationSingleOnly: false })
2093
- // worker 模式:结算成功清超时连击、清「上窗未结算」标记(下一窗增量包不再带核对说明)。
2094
- if (workerMode) {
2095
- workerEpochRecord = recordEpochProgress({ sessionId }, { settled: true, progress: false }) || workerEpochRecord
2096
- setSessionBinding(sessionId, { consolidationPending: null })
2097
- }
2098
- // 候选跨窗顺延:本窗没写进库的候选留给下一窗的必写清单;最后一窗也在同一份
2099
- // brief 里见到它们,不需要为了补写再开一次整窗 fork。核验纯本地,0 Token。
2100
- const writtenIds = [...(decision.createdIds || []), ...(decision.updatedIds || []), ...(decision.heldIds || [])]
2101
- const missed = mustCover.filter((candidate) => !candidateCovered(candidate, writtenIds, index))
2102
- safeLedger(() => setCarryCandidates(sessionId, missed))
2103
- // A8:摘要要覆盖 created/updated/held 全部落库 id(设计 §4.2),不只 created——
2104
- // 否则续窗 worker 看不到已 update/held 的条目,可能重复尝试。ids 仅供摘要,不参与判同。
2105
- safeLedger(() => recordOperation({ sessionId, key: opKey, outcome: decision.status, ids: writtenIds }))
2106
- // 私有自动关联(§5.6 兜底):只在整理真的对账并推进边界之后跑,纯算法,
2107
- // 0 token。worker 若已调用 memu_private_link_suggest,这一遍是幂等的(已有的
2108
- // relation/person 边会跳过)。link 只是图元数据:失败只记 warn,绝不能让一次
2109
- // 已经成功的整理变成失败;timeout / unsettled / ledger-not-advanced 三条路径
2110
- // 走不到这里,所以它们不会触发自动关联。
2111
- const linkIds = [...(decision.createdIds || []), ...(decision.updatedIds || [])]
2112
- if (linkIds.length) {
2113
- try {
2114
- await autoLinkPrivateMemories({ libraryId: binding.libraryId, sessionId, ids: linkIds })
2115
- } catch (error) {
2116
- // autoLinkPrivateMemories 自己已捕获操作性失败;这里只兜"意料之外"的抛错。
2117
- try { warn('private auto-link after consolidation skipped: ' + String(error?.message || error)) } catch {}
2118
- }
2119
- }
2120
- }
2121
- // A timeout is not success: the fork may still be mid-write. It has to come
2122
- // back with a message, not just `timedOut` — the settings button renders
2123
- // `result.error` and an empty string there is indistinguishable from a click
2124
- // that did nothing at all (observed: two clicks, no feedback, no memories).
2125
- if (outcome === 'timeout') {
2126
- if (workerMode) {
2127
- // 持久模式(§4.4):超时 = 废弃本回合的结算,不废弃 worker。已写入的条目保留
2128
- // (本来如此);游标不进(failJob 照旧);区间回 pending;下一窗增量包开头带
2129
- // 「上窗未结算」核对说明(consolidationPending 标记)。连续 2 次超时升级退役
2130
- // (防反复卡死吃窗口),退役允许交接——worker 上下文没坏,只是慢。
2131
- workerEpochRecord = recordEpochProgress({ sessionId }, { timeout: true, progress: false }) || workerEpochRecord
2132
- setSessionBinding(sessionId, { consolidationPending: { snapshotHash: snapshot.hash, jobId, at: new Date().toISOString() } })
2133
- if ((Number(workerEpochRecord?.timeouts) || 0) >= WORKER_TIMEOUT_LIMIT) {
2134
- try { await retireWorker(ctx, childId, 'timeout-x2', { handoff: true }) } catch {}
2135
- }
2136
- } else {
2137
- // Stop the writer before releasing the range, not after. Waiting matters here
2138
- // because a tool call already in flight can still land a memory on disk, and the
2139
- // range going back to pending is what lets the next pass redo this window.
2140
- await stopWorker()
2141
- }
2142
- safeLedger(() => failJob({
2143
- sessionId, jobId, reasonCode: 'timeout',
2144
- error: workerMode
2145
- ? 'timed out before a receipt; the turn was abandoned and the range is pending again (a tool call already in flight may have written; the worker is kept for the next window)'
2146
- : 'timed out before a receipt; the worker was stopped first, but a tool call already in flight may have written',
2147
- }))
2148
- return finish({
2149
- ok: false,
2150
- sessionId,
2151
- childId,
2152
- settled: false,
2153
- timedOut: true,
2154
- reasonCode: 'timeout',
2155
- // The next pass must not assume this window left nothing behind: the range is
2156
- // pending again and some writes may already have landed.
2157
- partialWritesPossible: true,
2158
- error: workerMode
2159
- ? 'consolidation timed out after ' + Math.round(budgetMs / 1000) + 's over ' + window.events.length + ' events; the turn was abandoned and the range was released (memories written before the timeout are kept, the worker is kept). Retry, or consolidate a shorter conversation.'
2160
- : 'consolidation timed out after ' + Math.round(budgetMs / 1000) + 's over ' + window.events.length + ' events; the fork was stopped before the range was released (memories written before the timeout are kept). Retry, or consolidate a shorter conversation.',
2161
- })
2162
- }
2163
- return finish({
2164
- ok: outcome === 'done',
2165
- sessionId,
2166
- childId,
2167
- settled: outcome === 'done',
2168
- timedOut: false,
2169
- status: decision?.status || null,
2170
- outcome: decision?.outcome || null,
2171
- reasonCode: decision?.reasonCode || null,
2172
- counts: decision?.counted || null,
2173
- createdIds: decision?.createdIds || [],
2174
- updatedIds: decision?.updatedIds || [],
2175
- heldIds: decision?.heldIds || [],
2176
- receipt: decision?.receipt
2177
- ? { status: decision.receipt.status, outcome: decision.receipt.outcome, reasonCode: decision.receipt.reasonCode }
2178
- : null,
2179
- credential: completion?.checked ? { checked: completion.checked, pending: completion.pending } : null,
2180
- snapshot: snapshotMeta,
2181
- scanned: window.events.length,
2182
- fresh: freshCount,
2183
- remaining: window.remaining,
2184
- window: { fromSeq: window.fromSeq, throughSeq: window.throughSeq },
2185
- wrote,
2186
- })
2187
- } catch (error) {
2188
- // worker 模式:异常 = 退役条件 5(无交接);fork 模式的销毁留给 finally。
2189
- if (workerMode && childId && handle) { try { await retireWorker(ctx, childId, 'failure', { handoff: false }) } catch {} }
2190
- if (jobId) safeLedger(() => failJob({ sessionId, jobId, reasonCode: 'exception', error: String(error?.message || error) }))
2191
- return finish({ ok: false, sessionId, settled: false, reasonCode: 'exception', error: String(error?.message || error) })
2192
- } finally {
2193
- inFlight.delete(sessionId)
2194
- if (workerMode) {
2195
- // 持久 worker(§15.2 改动点 6):每窗 finally 只清 inFlight 与本轮局部资源——
2196
- // per-window 重验监听随窗摘除;worker 本体、工具面与子绑定留给 epoch
2197
- // (retireWorker 与插件停用负责销毁)。'fork' 路径的清理原样保留。
2198
- try { offSession?.() } catch {}
2199
- } else {
2200
- try { await stopWorker() } catch {}
2201
- try { workerTools?.dispose?.() } catch {}
2202
- try { workerRestriction?.dispose?.() } catch {}
2203
- try { if (childId) deleteSessionBinding(childId) } catch {}
2204
- }
2205
- }
2206
- }
2207
- export function isConsolidating(sessionId) {
2208
- return inFlight.has(sessionId)
2209
- }
1
+ import { createUserMessage } from '@deepseek-ai/dsh-llm'
2
+ import crypto from 'node:crypto'
3
+ import fs from 'node:fs'
4
+ import path from 'node:path'
5
+ import { getSessionBinding, getLibrary, getSettings, setSessionBinding, deleteSessionBinding, loadPrivateIndex, effectiveScope } from './state.js'
6
+ import { domainOf, privateRemember, isMemoryEligible, visibleToSession, overdueOpenCommitments } from './memory.js'
7
+ import { presetSetupFor, resolveConsolidationPreset } from './preset-mount.js'
8
+ import { loadPromptForDomain, CONSOLIDATION_CONTRACTS } from './prompts.js'
9
+ import { summarizeRemote } from './remote-summary.js'
10
+ import { condenseEvents, condenseLimitsFor, readSessionSnapshot } from './curator.js'
11
+ import { record } from './activity-log.js'
12
+ import { ACTIVE_MEMORY_POLICY, assessWake, collectEvidence } from './active-memory.js'
13
+ import { entryFingerprint } from './consolidation-receipt.js'
14
+ import { DEFAULT_TIME_ZONE } from './temporal.js'
15
+
16
+ // The consolidation worker only sees the transcript as text. Without a visible
17
+ // per-turn clock it falls back to the wall clock (or a single batch sceneTime),
18
+ // which is exactly how "前天" gets written months away from the scene. The seed
19
+ // event keeps the replayed logical time; surface it as a leading text block so
20
+ // the worker can pass that turn's observed_at to the write tools.
21
+ function eventTimeLabel(event) {
22
+ const explicit = event?.data?.sceneTime
23
+ const at = explicit ? new Date(explicit) : (Number.isFinite(event?.time) ? new Date(event.time) : null)
24
+ if (!at || !Number.isFinite(at.getTime())) return null
25
+ const parts = new Intl.DateTimeFormat('en-CA', {
26
+ timeZone: DEFAULT_TIME_ZONE,
27
+ year: 'numeric', month: '2-digit', day: '2-digit',
28
+ hour: '2-digit', minute: '2-digit', hour12: false,
29
+ }).formatToParts(at)
30
+ const pick = (type) => parts.find((part) => part.type === type)?.value || ''
31
+ return `${pick('year')}-${pick('month')}-${pick('day')} ${pick('hour')}:${pick('minute')}`
32
+ }
33
+
34
+ // Short-term entries expire on a clock, so the idle pass is the last moment anyone
35
+ // can decide what they were worth. The list is generated in code rather than added
36
+ // to the editable prompt body: it is per-library data plus a protocol (which tool
37
+ // call means "promote"), and a user editing the template must not be able to break
38
+ // the tool names the model is told to use.
39
+ export function shortTermBrief(binding, { now = Date.now() } = {}) {
40
+ if (!binding?.libraryId || binding.useLibrary === false) return ''
41
+ let index = null
42
+ try { index = loadPrivateIndex(binding.libraryId) } catch { return '' }
43
+ const rows = Object.entries(index.entries || {})
44
+ .filter(([, e]) => e && e.layer === 'short_term' && isMemoryEligible(e, { automatic: true, now }) && visibleToSession(e, binding.sessionId))
45
+ .map(([id, e]) => ({
46
+ id,
47
+ title: e.title || '(untitled)',
48
+ left: Math.max(0, Math.round(((Date.parse(e.expiresAt || '') || 0) - now) / 3_600_000)),
49
+ }))
50
+ .filter((row) => row.left > 0)
51
+ .sort((a, b) => a.left - b.left)
52
+ .slice(0, 20)
53
+ if (rows.length === 0) return ''
54
+ return [
55
+ '[short_term · 快到期了]',
56
+ '下面这些是你近期记下的短期条目,到期会自己消失。逐条决定:',
57
+ '值得留下的升级 —— memu_private_update id=<id> layer=long_term(要补充的正文这次一并写上);',
58
+ '不重要的归档 —— memu_private_update id=<id> status=archived;',
59
+ '还说不清的别动,它自己会过期。',
60
+ ...rows.map((row) => `- [${row.id}] ${row.title} · 约 ${row.left} 小时后过期`),
61
+ ].join('\n')
62
+ }
63
+
64
+ export function buildPrivateConsolidationPrompt(sessionId) {
65
+ const binding = getSessionBinding(sessionId)
66
+ const library = binding?.libraryId ? getLibrary(binding.libraryId) : null
67
+ const settings = getSettings()
68
+ // One shared body for both backends; only the output contract differs.
69
+ return [
70
+ loadPromptForDomain('private-consolidation', {
71
+ libraryName: library ? `${library.name} (${library.id})` : '(unbound)',
72
+ domain: domainOf(binding),
73
+ mustRememberCap: settings.mustRememberCap,
74
+ shortTermTtlHours: settings.shortTermTtlHours ?? 72,
75
+ }, domainOf(binding)).text,
76
+ '',
77
+ CONSOLIDATION_CONTRACTS.local,
78
+ shortTermBrief({ ...binding, sessionId }),
79
+ ].filter((part) => part && part.trim()).join('\n')
80
+ }
81
+
82
+ /**
83
+ * 一句话说清一个失败原因。
84
+ *
85
+ * 早先这里只写 "... failed" 就返回:诊断页照着这条去查什么也查不到,等于把
86
+ * 报错留在原地。带上 code + message,诊断记录本身就有可复制的证据。
87
+ */
88
+ function describeError(error) {
89
+ if (!error) return 'unknown error'
90
+ const code = typeof error.code === 'string' ? error.code : ''
91
+ const message = String(error.message || error)
92
+ return code && !message.startsWith(code) ? code + ': ' + message : message
93
+ }
94
+ function noticeMessage(text, summary) {
95
+ return createUserMessage({
96
+ content: [{ type: 'text', text }],
97
+ source: { kind: 'plugin:dsh-memu-memory', form: 'notice', summary },
98
+ })
99
+ }
100
+
101
+ // "There were new turns" is not the same question as "there is something worth
102
+ // keeping". A conversation of greetings, acknowledgements and one-line lookups costs
103
+ // a fork (a whole seeded transcript, one model turn) and returns nothing; doing that
104
+ // after every idle window is how an automatic pass becomes noise the user turns off.
105
+ // This answers the cheap half of the question locally, before a fork exists: is the
106
+ // part of the transcript since the last consolidation substantive at all? It has to
107
+ // err on the side of running — a false "worth it" costs one model turn, a false
108
+ // "skip" silently throws away the only record of a decision — so the bar is low and
109
+ // deliberately structural rather than semantic: a single short human message with no
110
+ // tool work in it is the only thing it refuses.
111
+ // The gate this replaces counted characters. That was wrong in the one direction
112
+ // that matters: "我不吃香菜" is five characters and is exactly the kind of durable
113
+ // fact the library exists to keep, while "好的,继续" is also short and is worth
114
+ // nothing. Length is not the signal — an acknowledgement is. So this is a shape
115
+ // match on the *only* message in the tail, not a size test, and anything that is not
116
+ // literally an acknowledgement goes to the fork and lets the prompt decide.
117
+ const SMALL_TALK = /^(谢(谢|了)?|多谢|感谢|好(的|吧|嘞)?|ok|okay|收到|明白(了)?|了解(了)?|嗯+|哦+|啊+|行|可以|没问题|继续|你好|hi|hello|hey|thanks?(you)?|thx)+$/i
118
+ const ASSESS_MIN_HUMAN_CHARS = 4
119
+
120
+ function isSmallTalk(text) {
121
+ // Punctuation and spacing are not content: "好的,继续" is one acknowledgement, not
122
+ // two words with a comma in the middle.
123
+ return SMALL_TALK.test(String(text || '').replace(/[\s!!。.,,、~~👍]/g, ''))
124
+ }
125
+
126
+ function textOfContent(content) {
127
+ if (typeof content === 'string') return content.trim()
128
+ if (!Array.isArray(content)) return ''
129
+ return content
130
+ .map((block) => (block && typeof block === 'object' && typeof block.text === 'string' ? block.text : ''))
131
+ .join(' ')
132
+ .trim()
133
+ }
134
+
135
+ // Only the events after the last consolidation: a session that has been asleep once
136
+ // already keeps all of its old material in the transcript, and scoring the whole file
137
+ // again would make every later turn "worth it" forever.
138
+ export function unconsolidatedEvents(binding, events) {
139
+ const since = Number(binding?.lastSleepSeq)
140
+ if (!Number.isFinite(since) || since < 0) return Array.isArray(events) ? events : []
141
+ return (events || []).filter((event) => Number(event?.seq) > since)
142
+ }
143
+
144
+ export function assessConsolidationValue(events) {
145
+ let humanTurns = 0
146
+ let humanChars = 0
147
+ let humanText = ''
148
+ let toolCalls = 0
149
+ for (const event of events || []) {
150
+ if (event?.type === 'user/message') {
151
+ // The same rule the transcript condenser uses: only a message the person
152
+ // actually typed counts. Plugin notices, tool output and heartbeats all arrive
153
+ // as messages too, and none of them is a reason to spend a fork.
154
+ if (event.data?.source?.kind !== 'user') continue
155
+ const text = textOfContent(event.data?.content)
156
+ if (!text) continue
157
+ humanTurns += 1
158
+ humanChars += text.length
159
+ humanText = text
160
+ continue
161
+ }
162
+ if (event?.type === 'assistant/message') {
163
+ const blocks = event.data?.message?.content
164
+ if (Array.isArray(blocks)) toolCalls += blocks.filter((block) => block?.type === 'tool-call').length
165
+ continue
166
+ }
167
+ if (event?.type === 'tool/call') toolCalls += 1
168
+ }
169
+ const facts = { humanTurns, humanChars, toolCalls }
170
+ if (humanTurns === 0) return { worth: false, reason: 'no-human-turn', ...facts }
171
+ if (toolCalls === 0 && humanTurns === 1 && (isSmallTalk(humanText) || humanChars < ASSESS_MIN_HUMAN_CHARS)) {
172
+ return { worth: false, reason: 'small-talk', ...facts }
173
+ }
174
+ return { worth: true, reason: 'substantive', ...facts }
175
+ }
176
+
177
+ // ---- incremental consolidation window --------------------------------------
178
+ // A consolidation fork used to seed the whole transcript up to the snapshot cut,
179
+ // so every run re-read the same old tool logs and the model's attention spread
180
+ // Forks may reread prior context as conversations grow. Keep each fork bounded: seed
181
+ // only the unconsolidated tail, compact noise, and leave the remaining range for the
182
+ // next window.
183
+ export const CONSOLIDATION_BACKLOG_EVENTS = 200
184
+ export const CONSOLIDATION_BACKLOG_TURNS = 10
185
+ // 小增量顺延:非手动整理时,少于 3 个真人回合的增量先不 fork。它不推进游标,
186
+ // 下一次触发会把顺延的事件一起带上;上限仍由上面的水位常量兜底,饥饿时放行。
187
+ export const CONSOLIDATION_MIN_HUMAN_TURNS = 3
188
+ // Use a 500-event window and a 600-second budget so slower reasoning can complete a
189
+ // window without reducing its scope. Unprocessed events remain pending; retry windows
190
+ // use 250 events.
191
+ export const CONSOLIDATION_WINDOW_EVENTS = 500
192
+ // worker 模式按回合扩展窗口:500 事件切在回合中间时,向后补到该回合的 turn/end。
193
+ // worker 的包是 turn-log 记录(单条最多 4000 字符),扩展窗口不会放大模型上下文;
194
+ // 它只避免同一回合被连续两窗整条重发。20k 事件是防御上限,正常回合远小于它。
195
+ export const WORKER_WINDOW_EXTEND_EVENTS = 20_000
196
+ export const CONSOLIDATION_PROBE_MINUTES = 15
197
+ export const CONSOLIDATION_SNAPSHOT_FAILURE_LIMIT = 2
198
+ // 冻结冷却(issue #4 缺陷 1):同一快照失败到上限后熔断——但熔断不该是永久锁死。
199
+ // 外部条件可能恢复(归档被解除、服务商恢复、effortRefusal 自愈),冷却到期后清零
200
+ // 连击、放行一次真实重试;仍失败则按上限重新冻结并重新计时。每个冷却期最多
201
+ // LIMIT 次真实 fork,成本有界。
202
+ export const CONSOLIDATION_SNAPSHOT_FAILURE_COOLDOWN_MS = 6 * 60 * 60 * 1000
203
+ const SEED_TOOL_RESULT_CHARS = 1_100
204
+ const SEED_TOOL_CALL_CHARS = 500
205
+ // 编码域的修改重点就在工具结果与调用参数(diff、错误签名、编译输出)里;
206
+ // 1.1k/0.5k 只够留下开头。放宽后整窗仍有 ≤500 事件与 12k 文本/条的上限兜着。
207
+ const SEED_TOOL_RESULT_CHARS_CODING = 2_200
208
+ const SEED_TOOL_CALL_CHARS_CODING = 1_000
209
+ const SEED_TEXT_CHARS = 12_000
210
+ const SEED_CATALOG_ENTRIES = 18
211
+
212
+ export function seedLimitsFor(domain) {
213
+ return String(domain) === 'coding'
214
+ ? { toolResultChars: SEED_TOOL_RESULT_CHARS_CODING, toolCallChars: SEED_TOOL_CALL_CHARS_CODING }
215
+ : { toolResultChars: SEED_TOOL_RESULT_CHARS, toolCallChars: SEED_TOOL_CALL_CHARS }
216
+ }
217
+
218
+ // Types that carry conversation, plus the structural events a seeded Session
219
+ // replays. Everything else is host bookkeeping: request headers, permissions,
220
+ // runtime snapshots and the plugin's own recall messages. Feeding those to the
221
+ // summarizer is how a memory ends up citing its own earlier injection as a user
222
+ // fact, so they never enter the seed.
223
+ const SEED_EVENT_TYPES = new Set([
224
+ 'user/message', 'assistant/message', 'tool/call', 'tool/result',
225
+ 'turn/start', 'turn/end', 'step/start', 'step/end',
226
+ ])
227
+
228
+ // The subset that joins the host's model-visible surface: every one of these
229
+ // must carry a surfaceOp marker, and their seqs form the fold a replacement cites.
230
+ const SEED_SURFACE_TYPES = new Set(['user/message', 'assistant/message', 'tool/result'])
231
+
232
+ function capSeedText(value, limit = SEED_TEXT_CHARS) {
233
+ const text = String(value ?? '')
234
+ return text.length > limit ? text.slice(0, limit) + '…[已截断]' : text
235
+ }
236
+
237
+ function cloneSeedBlocks(blocks, caps = {}, seenToolText = null) {
238
+ const textCap = Number(caps.text) > 0 ? Number(caps.text) : SEED_TEXT_CHARS
239
+ const toolCap = Number(caps.tool) > 0 ? Number(caps.tool) : SEED_TOOL_CALL_CHARS
240
+ const out = []
241
+ for (const block of Array.isArray(blocks) ? blocks : []) {
242
+ if (!block || typeof block !== 'object') continue
243
+ if (block.type === 'reasoning') continue
244
+ if (block.type === 'image') { out.push({ type: 'text', text: '[图片/附件]' }); continue }
245
+ if (block.type !== 'text' && block.type !== 'tool-call') { out.push(block); continue }
246
+ if (block.type === 'tool-call') {
247
+ out.push({ ...block, arguments: capSeedText(block.arguments, toolCap) })
248
+ continue
249
+ }
250
+ const text = String(block.text || '')
251
+ // Role cards, emoji catalogs and full unread snapshots repeat verbatim across
252
+ // turns; one copy is enough to summarise what the tool returned.
253
+ if (seenToolText && text && seenToolText.has(text)) {
254
+ out.push({ ...block, text: '[与前面相同的工具输出,已省略]' })
255
+ continue
256
+ }
257
+ if (seenToolText && text) seenToolText.add(text)
258
+ out.push({ ...block, text: capSeedText(text, textCap) })
259
+ }
260
+ return out
261
+ }
262
+
263
+ // Renumber survivors and rewrite every citation to its final index. A replace
264
+ // whose endpoints did not survive cannot be replayed at all; report it so the
265
+ // caller drops it before seqs are handed out (dropping after renumbering is what
266
+ // left holes the host rejected with "seed event at index N has seq M").
267
+ function buildSeedEvents(pending, offset) {
268
+ const index = new Map()
269
+ pending.forEach((event, i) => index.set(Number(event.seq), i + offset))
270
+ const prepared = []
271
+ const origins = []
272
+ let dropped = false
273
+ pending.forEach((event, origin) => {
274
+ const next = { ...event, seq: index.get(Number(event.seq)) }
275
+ if (Array.isArray(next.sourceEventSeqs)) {
276
+ const mapped = [...new Set(next.sourceEventSeqs
277
+ .map(value => index.get(Number(value)))
278
+ .filter(value => Number.isInteger(value) && value < next.seq))]
279
+ .sort((a, b) => a - b)
280
+ if (mapped.length) next.sourceEventSeqs = mapped
281
+ else delete next.sourceEventSeqs
282
+ }
283
+ if (next.surfaceOp && typeof next.surfaceOp === 'object' && !Array.isArray(next.surfaceOp)) {
284
+ const start = index.get(Number(next.surfaceOp.startSeq))
285
+ const end = index.get(Number(next.surfaceOp.endSeq))
286
+ if (!Number.isInteger(start) || !Number.isInteger(end) || start > end || !Array.isArray(next.sourceEventSeqs)) {
287
+ dropped = true
288
+ return
289
+ }
290
+ next.surfaceOp = { op: 'replace', startSeq: start, endSeq: end }
291
+ }
292
+ prepared.push(next)
293
+ origins.push(origin)
294
+ })
295
+ return { prepared, origins, dropped }
296
+ }
297
+
298
+ // Mirror the host's surface-fold checks (session `validateNext`) over a candidate
299
+ // seed. A replacement is only accepted when both endpoints are current nodes and
300
+ // sourceEventSeqs cite every node the range shadows — dropping a replacement can
301
+ // reveal nodes it had shadowed, which is why this must run on the whole seed and
302
+ // not just the event being rewritten. Returns the prepared indices that failed.
303
+ function seedSurfaceIssues(events) {
304
+ const nodes = []
305
+ const issues = []
306
+ events.forEach((event, index) => {
307
+ if (!SEED_SURFACE_TYPES.has(event.type)) return
308
+ const op = event.surfaceOp
309
+ if (op === 'append') {
310
+ nodes.push(event.seq)
311
+ return
312
+ }
313
+ if (!op || typeof op !== 'object' || Array.isArray(op) || op.op !== 'replace') {
314
+ issues.push(index)
315
+ return
316
+ }
317
+ const startSeq = Number(op.startSeq)
318
+ const endSeq = Number(op.endSeq)
319
+ const startIdx = nodes.indexOf(startSeq)
320
+ const endIdx = nodes.indexOf(endSeq)
321
+ const sources = Array.isArray(event.sourceEventSeqs) ? event.sourceEventSeqs : []
322
+ const cited = new Set(sources)
323
+ if (startSeq >= event.seq || endSeq >= event.seq
324
+ || startIdx < 0 || endIdx < startIdx
325
+ || sources.length === 0 || sources.length !== cited.size
326
+ || sources.some(seq => Number(seq) >= event.seq)
327
+ || nodes.slice(startIdx, endIdx + 1).some(seq => !cited.has(seq))) {
328
+ issues.push(index)
329
+ return
330
+ }
331
+ nodes.splice(startIdx, endIdx - startIdx + 1)
332
+ nodes.push(event.seq)
333
+ })
334
+ return issues
335
+ }
336
+
337
+ /**
338
+ * Build the seed body for one window: only conversation events, with reasoning /
339
+ * replay state / repeated tool output removed, then renumbered seq 0..n so
340
+ * Session's "contiguous from zero" rule holds. The optional catalog event takes
341
+ * seq 0 and is the only synthetic message.
342
+ *
343
+ * Surface replacements are not append-only: their surfaceOp cites the range they
344
+ * shadow, and the host validates those citations while replaying the seed. When
345
+ * the noise filter drops neighbours (or the window starts inside a compacted
346
+ * range), an unremapped startSeq/endSeq points forward or at a node the seed no
347
+ * longer contains and the whole fork is refused. Resolve every replacement
348
+ * against the surviving events, drop the ones that cannot be replayed, and only
349
+ * renumber once the survivor set is stable.
350
+ */
351
+ export function compactSeedEvents(events, prelude = null, options = {}) {
352
+ const toolResultChars = Number(options.toolResultChars) > 0 ? Number(options.toolResultChars) : SEED_TOOL_RESULT_CHARS
353
+ const toolCallChars = Number(options.toolCallChars) > 0 ? Number(options.toolCallChars) : SEED_TOOL_CALL_CHARS
354
+ const preludeEvents = (Array.isArray(prelude) ? prelude : (prelude ? [prelude] : []))
355
+ .filter((event) => event && typeof event === 'object')
356
+ .map((event, index) => {
357
+ // Preludes are synthetic and sit at the head, so they can only append: a
358
+ // replacement marker there would cite positions that do not exist yet. The
359
+ // host also refuses a surface-eligible event without a marker at all.
360
+ const surfaceOp = SEED_SURFACE_TYPES.has(event.type) ? 'append' : event.surfaceOp
361
+ return { ...event, seq: index, surfaceOp }
362
+ })
363
+ const offset = preludeEvents.length
364
+ const kept = []
365
+ const seenToolText = new Set()
366
+ for (const event of Array.isArray(events) ? events : []) {
367
+ if (!event || typeof event !== 'object' || !SEED_EVENT_TYPES.has(event.type)) continue
368
+ if (event.type === 'user/message' && event.data?.source?.kind !== 'user') continue
369
+ const clone = { ...event, data: { ...(event.data || {}) } }
370
+ if (event.type === 'assistant/message') {
371
+ const message = { ...(event.data?.message || {}) }
372
+ const source = { ...(message.source || {}) }
373
+ // The replay state duplicates the response body; it is not conversation.
374
+ delete source.replayState
375
+ message.source = source
376
+ message.content = cloneSeedBlocks(message.content, { text: SEED_TEXT_CHARS, tool: toolCallChars })
377
+ if (message.content.length === 0) message.content = [{ type: 'text', text: '(本轮没有可读的正文)' }]
378
+ clone.data.message = message
379
+ // data.stream is the raw chunk log, not the message the model saw. It must
380
+ // stay present as an (empty) array: DSH 0.2.2-rc.1's seed validation
381
+ // (assertAssistantSettlementShape) requires data.stream to be an array, and
382
+ // deleting it made every consolidation fork seed fail with "invalid
383
+ // settlement fields". An empty array keeps the noise-down intent — the
384
+ // chunks never enter the seed — while satisfying the newer host check;
385
+ // older hosts don't validate the field at all, so this is inert there.
386
+ // Keep an empty array to satisfy the host's assistant-settlement validation.
387
+ clone.data.stream = []
388
+ } else if (event.type === 'tool/result') {
389
+ const message = { ...(event.data?.message || {}) }
390
+ message.content = cloneSeedBlocks(message.content, { text: toolResultChars, tool: toolCallChars }, seenToolText)
391
+ if (message.content.length === 0) message.content = [{ type: 'text', text: '[空工具输出]' }]
392
+ clone.data.message = message
393
+ } else if (event.type === 'tool/call') {
394
+ clone.data.arguments = capSeedText(event.data?.arguments, toolCallChars)
395
+ } else if (event.type === 'user/message') {
396
+ clone.data.content = cloneSeedBlocks(event.data?.content, { text: SEED_TEXT_CHARS })
397
+ const timeLabel = eventTimeLabel(event)
398
+ if (timeLabel) clone.data.content.unshift({ type: 'text', text: `[事件时间 ${timeLabel}]` })
399
+ }
400
+ // Legacy logs can omit the marker; the host refuses a
401
+ // surface-eligible event without one, and inside a seed it can only append.
402
+ if (clone.surfaceOp === undefined && SEED_SURFACE_TYPES.has(clone.type)) clone.surfaceOp = 'append'
403
+ kept.push(clone)
404
+ }
405
+
406
+ let pending = kept
407
+ for (;;) {
408
+ const { prepared, origins, dropped } = buildSeedEvents(pending, offset)
409
+ const issues = seedSurfaceIssues([...preludeEvents, ...prepared])
410
+ if (!dropped && issues.length === 0) return [...preludeEvents, ...prepared]
411
+ // Each pass removes at least one event, so this converges; two passes cover
412
+ // the replacement-cites-a-replacement case the host rejects first.
413
+ const survivors = new Set(origins)
414
+ const doomed = new Set()
415
+ pending.forEach((_, origin) => { if (!survivors.has(origin)) doomed.add(origin) })
416
+ for (const index of issues) doomed.add(origins[index - offset])
417
+ pending = pending.filter((_, origin) => !doomed.has(origin))
418
+ }
419
+ }
420
+
421
+ // A zero-token local filter prioritizes turns likely to produce durable memories.
422
+ // Strong signals (dates, promises, corrections, identities) count double; generic
423
+ // preference and social words count once. Keep whole turns with adjacent context. If
424
+ // nothing stands out, keep the full window rather than silently dropping it.
425
+ //
426
+ // Select strength terms by domainOf(binding), with unknown domains falling back to
427
+ // general. Keep CJK substring matching and use case-insensitive word boundaries for
428
+ // Latin terms. Preserve score weights: strong signals count double, weak signals once.
429
+ const latin = (words) => words.map((word) => `\\b(?:${word})\\b`)
430
+
431
+ // 生活/中性对话:现状全域表逐字保留(顺序不变,保证中文得分与旧代码一致)+ 英文补充。
432
+ const GENERAL_STRONG = [
433
+ '今天', '明天', '昨天', '前天', '后天', '大后天', '下周', '上周', '这周', '月底', '月初', '年初', '年底',
434
+ '生日', '纪念日', '周年', '星期[一二三四五六日天]', '周[一二三四五六日天]',
435
+ '\\d{1,2}\\s*[月日号]', '\\d{4}\\s*[-/年]', '\\d{1,2}\\s*[点时]',
436
+ '答应', '约定', '说好', '提醒', '帮我', '帮忙', '欠', '借', '还', '截止', '到期', '记得', '别忘', '改口', '说错', '更正', '其实', '矛盾', '两版', '之前说',
437
+ ...latin(['birthday', 'anniversary', 'promised?', 'deadline', 'due', 'owe', 'borrowed', 'changed my mind', 'corrected', 'actually']),
438
+ ]
439
+ const GENERAL_WEAK = [
440
+ '喜欢', '讨厌', '不吃', '不要', '不能', '不想', '边界', '秘密', '别说', '打算', '计划', '准备', '要去', '想去', '叫', '称呼', '名字', '岁', '住', '工作', '职业', '负责', '接手', '登记', '换', '孩子', '父亲', '母亲', '老公', '老婆', '朋友', '同事', '邻居',
441
+ ...latin(['prefers?', 'allergic', "can['’]t eat", 'boundaries?', 'secrets?', 'plans?', 'planned', 'called', 'named', 'ages?', 'lives at', 'works at', 'friends?', 'colleagues?']),
442
+ ]
443
+ // 剧情人际:现状表即 rp 向(沿用 general 的生活词 + 现有人际词),补剧情词与英文同人词。
444
+ const RP_STRONG = [...GENERAL_STRONG]
445
+ const RP_WEAK = [
446
+ ...GENERAL_WEAK,
447
+ '上位', '下位', '设定', '世界观', '剧情', '人设',
448
+ ...latin(['personas?', 'canon', 'lore', 'headcanons?', 'backstory', 'in character', 'out of character']),
449
+ ]
450
+ // 工程事实(新表):改了什么/为什么/什么时候上线。bugs 与截止日来自 §6.1 设计表。
451
+ const CODING_STRONG = [
452
+ '修复', '修好', '发布', '上线', '部署', '版本', '回滚', '迁移', '破坏性', '依赖升级', '环境变量', '报错', '崩溃', '回归', '截止日',
453
+ ...latin([
454
+ 'bugs?', 'fixed', 'fixes', 'fix\\b(?!ture|ing)', 'broke', 'broken', 'deploy(?:ed|s|ing)?', 'release[ds]?',
455
+ 'shipped?', 'hotfix(?:es|ed)?', 'rollback(?:ed|s)?', 'migrat(?:e|ed|ion|ing)s?', 'breaking changes?', 'root causes?', 'crash(?:ed|es)?', 'regressions?',
456
+ ]),
457
+ ]
458
+ const CODING_WEAK = [
459
+ '重构', '优化', '测试', '文档', '依赖', '配置', '接口', '日志', '构建', '打包', '命名',
460
+ ...latin(['refactor(?:ed|s|ing)?', 'optimiz(?:e|ed|ing)', 'config(?:s|uration)?', 'env', 'dependenc(?:y|ies)', 'builds?', 'lints?', 'rename[ds]?', 'apis?']),
461
+ ]
462
+ // mixed:rp ∪ coding 并集去重。
463
+ const MIXED_STRONG = [...new Set([...RP_STRONG, ...CODING_STRONG])]
464
+ const MIXED_WEAK = [...new Set([...RP_WEAK, ...CODING_WEAK])]
465
+ const compileSalience = (parts) => new RegExp(parts.join('|'), 'gi')
466
+ const SALIENCE_TABLE = {
467
+ general: { strong: compileSalience(GENERAL_STRONG), weak: compileSalience(GENERAL_WEAK) },
468
+ rp: { strong: compileSalience(RP_STRONG), weak: compileSalience(RP_WEAK) },
469
+ coding: { strong: compileSalience(CODING_STRONG), weak: compileSalience(CODING_WEAK) },
470
+ mixed: { strong: compileSalience(MIXED_STRONG), weak: compileSalience(MIXED_WEAK) },
471
+ }
472
+
473
+ function turnText(events) {
474
+ const parts = []
475
+ for (const event of events) {
476
+ if (event.type === 'user/message') {
477
+ for (const block of event.data?.content || []) if (block?.type === 'text' && typeof block.text === 'string') parts.push(block.text)
478
+ } else if (event.type === 'assistant/message') {
479
+ for (const block of event.data?.message?.content || []) if (block?.type === 'text' && typeof block.text === 'string') parts.push(block.text)
480
+ }
481
+ }
482
+ return parts.join('\n')
483
+ }
484
+
485
+ /** 强 ×2 + 弱 ×1;domain 取 domainOf(binding)(四域),未知域回退 general。 */
486
+ export function salienceScore(text, domain = 'general') {
487
+ const table = SALIENCE_TABLE[domain] || SALIENCE_TABLE.general
488
+ const value = String(text)
489
+ const strong = (value.match(table.strong) || []).length
490
+ const weak = (value.match(table.weak) || []).length
491
+ return strong * 2 + weak
492
+ }
493
+
494
+ /**
495
+ * Keep salient complete turns and one neighbour on each side. Coding keeps more:
496
+ * weak signals, every turn that touched a tool, and a doubled turn cap — the
497
+ * change itself lives in the tool calls, not in the prose around them.
498
+ */
499
+ export function candidateSeedEvents(events, { maxTurns = 60, domain = 'general' } = {}) {
500
+ const coding = String(domain) === 'coding'
501
+ // 编码域的改动发生在工具调用里,正文常常只有一句「改这个函数」;salience 词表
502
+ // 命中不了就整回合丢掉,种子只剩关键词最多的闲聊。coding 因此放宽:弱词也算数,
503
+ // 带工具调用的回合一律保留,回合上限翻倍。
504
+ const threshold = coding ? 1 : 2
505
+ const cap = coding ? Math.max(Number(maxTurns) || 0, 120) : maxTurns
506
+ const groups = []
507
+ let current = null
508
+ for (const event of Array.isArray(events) ? events : []) {
509
+ if (event?.type === 'turn/start' || current === null) {
510
+ current = []
511
+ groups.push(current)
512
+ }
513
+ current.push(event)
514
+ if (event?.type === 'turn/end') current = null
515
+ }
516
+ const kept = new Set()
517
+ groups.forEach((group, index) => {
518
+ const scored = salienceScore(turnText(group), domain) >= threshold
519
+ const worked = coding && group.some((event) => event?.type === 'tool/call')
520
+ if (scored || worked) kept.add(index)
521
+ })
522
+ if (kept.size === 0) return Array.isArray(events) ? [...events] : []
523
+ const expanded = new Set(kept)
524
+ for (const index of kept) {
525
+ if (index > 0) expanded.add(index - 1)
526
+ if (index + 1 < groups.length) expanded.add(index + 1)
527
+ }
528
+ const selected = [...expanded].sort((a, b) => a - b).slice(0, cap)
529
+ const covered = selected.reduce((sum, index) => sum + groups[index].length, 0)
530
+ if (covered >= events.length * 0.8) return [...events]
531
+ return selected.flatMap((index) => groups[index])
532
+ }
533
+
534
+ // Build a zero-token list of required candidates for this window. Topic selection can
535
+ // omit new people, handoffs, or brief agreements even when their salience is high. Give
536
+ // the worker a short seq-keyed list and require each item to be written or explicitly
537
+ // accounted for in the receipt.
538
+ const MUST_COVER_PERSON = /叫|自称|称呼|换|接手|改成|换成|新来|同事|师傅|阿姨|房东|店长|老板|邻居|朋友|家人/
539
+ export function mustCoverCandidates(events, { max = 8, minScore = 3, domain = 'general' } = {}) {
540
+ const groups = []
541
+ let current = null
542
+ for (const event of Array.isArray(events) ? events : []) {
543
+ if (event?.type === 'turn/start' || current === null) {
544
+ current = []
545
+ groups.push(current)
546
+ }
547
+ current.push(event)
548
+ if (event?.type === 'turn/end') current = null
549
+ }
550
+ const rows = []
551
+ const seen = new Set()
552
+ groups.forEach((group) => {
553
+ const text = turnText(group)
554
+ const score = salienceScore(text, domain)
555
+ if (score < minScore) return
556
+ const userText = group
557
+ .filter((event) => event?.type === 'user/message' && event.data?.source?.kind === 'user')
558
+ .flatMap((event) => (event.data?.content || []).filter((block) => block?.type === 'text').map((block) => String(block.text || '')))
559
+ .join(' ')
560
+ const source = (userText || text).replace(/\s+/g, ' ').trim().slice(0, 90)
561
+ if (!source || seen.has(source)) return
562
+ seen.add(source)
563
+ const observedAt = group
564
+ .filter((event) => event?.type === 'user/message' && event.data?.source?.kind === 'user')
565
+ .map((event) => event.data?.sceneTime)
566
+ .find((value) => typeof value === 'string' && value) || null
567
+ rows.push({
568
+ fromSeq: Number(group[0]?.seq),
569
+ throughSeq: Number(group[group.length - 1]?.seq),
570
+ score,
571
+ tag: MUST_COVER_PERSON.test(text) ? '人物/关系' : '事实',
572
+ text: source,
573
+ observedAt,
574
+ })
575
+ })
576
+ return rows
577
+ .sort((a, b) => b.score - a.score)
578
+ .slice(0, Math.max(1, Number(max) || 8))
579
+ .sort((a, b) => a.fromSeq - b.fromSeq)
580
+ }
581
+
582
+ /** 顺延候选优先占位,但最多 4 条;其余名额留给本窗新候选。 */
583
+ export function mergeMustCover(carry, fresh, { max = 8, carryMax = 4 } = {}) {
584
+ const rows = []
585
+ const seen = new Set()
586
+ const add = (row) => {
587
+ if (!row || typeof row.text !== 'string') return
588
+ const key = row.text.replace(/\s+/g, '').slice(0, 60)
589
+ if (!key || seen.has(key)) return
590
+ seen.add(key)
591
+ rows.push(row)
592
+ }
593
+ for (const row of (Array.isArray(carry) ? carry : []).slice(0, Math.max(0, Number(carryMax) || 0))) {
594
+ add({ ...row, carried: true })
595
+ }
596
+ for (const row of Array.isArray(fresh) ? fresh : []) add(row)
597
+ return rows.slice(0, Math.max(1, Number(max) || 8))
598
+ }
599
+
600
+ const COVER_DATE_RE = /\d{4}-\d{2}-\d{2}|\d{1,2}\s*月\s*\d{1,2}\s*[日号]?|\d{1,2}\s*[月日号]/g
601
+ const COVER_STOP = new Set([
602
+ '我们', '他们', '你们', '现在', '已经', '可以', '什么', '这个', '那个',
603
+ '时候', '今天', '明天', '昨天', '一下', '一个', '还是', '不是', '就是',
604
+ ])
605
+ const COVER_TOKEN_RECALL = 0.55
606
+ function coverText(text) {
607
+ return String(text || '').normalize('NFKC').toLowerCase().replace(COVER_DATE_RE, ' ')
608
+ }
609
+ function coverTokens(text) {
610
+ return new Set(tokenize(text)
611
+ .filter((token) => typeof token === 'string' && token.length >= 2 && !/\d/.test(token) && !COVER_STOP.has(token)))
612
+ }
613
+ function coverAtoms(text) {
614
+ return new Set(text.match(/[\p{Script=Han}]|[a-z]+/gu) || [])
615
+ }
616
+ /** Conservative local evidence check; uncertainty keeps the candidate in carry. */
617
+ export function candidateCovered(candidate, writtenIds, index) {
618
+ const entries = index?.entries || {}
619
+ const text = String(candidate?.text || '')
620
+ if (!text) return true
621
+ const normalized = coverText(text)
622
+ const wanted = coverTokens(normalized)
623
+ const atoms = coverAtoms(normalized)
624
+ const values = numericSet(text)
625
+ // A date or an uninformative fragment cannot prove a fact was written.
626
+ if (wanted.size < 2 || atoms.size === 0) return false
627
+ for (const id of Array.isArray(writtenIds) ? writtenIds : []) {
628
+ const entry = entries[id]
629
+ if (!entry) continue
630
+ const body = String(entry.title || '') + ' ' + String(entry.content || '')
631
+ const haveValues = numericSet(body)
632
+ if ([...values].some((value) => !haveValues.has(value))) continue
633
+ const normalizedBody = coverText(body)
634
+ const haveAtoms = coverAtoms(normalizedBody)
635
+ // Missing names, actions or objects are not covered by a matching topic/date.
636
+ if ([...atoms].some((atom) => !haveAtoms.has(atom))) continue
637
+ const have = coverTokens(normalizedBody)
638
+ const shared = [...wanted].filter((token) => have.has(token))
639
+ if (shared.length < Math.min(3, wanted.size) || shared.length / wanted.size < COVER_TOKEN_RECALL) continue
640
+ if (shared.some((token) => polarityAt(text, token) !== polarityAt(body, token))) continue
641
+ return true
642
+ }
643
+ return false
644
+ }
645
+
646
+ /** Existing entries, compact, for dedupe/update instead of duplicate writes. */
647
+ export function memoryCatalogEvent(binding, now = Date.now()) {
648
+ if (!binding?.libraryId) return null
649
+ let entries = []
650
+ try { entries = Object.entries(loadPrivateIndex(binding.libraryId).entries || {}) } catch { return null }
651
+ const rows = entries
652
+ .filter(([, entry]) => entry && isMemoryEligible(entry, { automatic: true, now }))
653
+ .filter(([, entry]) => visibleToSession(entry, binding.sessionId))
654
+ .sort((a, b) => String(b[1].updatedAt || b[1].createdAt || '').localeCompare(String(a[1].updatedAt || a[1].createdAt || '')))
655
+ .slice(0, SEED_CATALOG_ENTRIES)
656
+ .map(([id, entry]) => `- [${id}] ${capSeedText(entry.title || '(untitled)', 120)} · ${entry.layer || 'long_term'} · ${entry.status || 'active'}`)
657
+ // 欠账单列:目录按更新时间截断,逾期的承诺很可能不在前 N 条里,而整理必须看见它。
658
+ const overdueRows = overdueOpenCommitments({ libraryId: binding.libraryId, now, minOverdueDays: 0, limit: 8, sessionId: binding.sessionId })
659
+ .filter(({ entry }) => visibleToSession(entry, binding.sessionId))
660
+ .map(({ id, entry, commitment, dueAt, daysOverdue }) => {
661
+ const who = commitment.counterparty ? `对 ${capSeedText(commitment.counterparty, 40)}:` : ''
662
+ return `- [${id}] ${capSeedText(entry.title || '(untitled)', 80)} · due=${dueAt} · 已逾期 ${daysOverdue} 天 · ${who}${capSeedText(commitment.action, 120)}`
663
+ })
664
+ if (rows.length === 0 && overdueRows.length === 0) return null
665
+ const text = [
666
+ '[memory-catalog · 已有记忆目录(只读上下文,不是用户发言,也不属于本轮转录)]',
667
+ '下面这些是本次整理之前已经写入本库的条目。不要当作用户说过的话,也不要重复创建;同一事实用 memu_private_update id=<id> 合并,真正新增的内容才用 memu_private_remember。',
668
+ ...rows,
669
+ ...(overdueRows.length > 0
670
+ ? ['欠账(status=open 且已过 due_at):整理时按本轮转录证据结案——兑现写 done、明确取消写 cancelled、确实作废写 expired;没有证据就保留 open,并在正文写明仍欠着谁。',
671
+ ...overdueRows]
672
+ : []),
673
+ ].join('\n')
674
+ return {
675
+ type: 'user/message',
676
+ seq: 0,
677
+ time: now,
678
+ data: createUserMessage({
679
+ content: [{ type: 'text', text }],
680
+ source: { kind: 'plugin:dsh-memu-memory', form: 'notice', summary: 'memory-catalog' },
681
+ }),
682
+ surfaceOp: 'append',
683
+ }
684
+ }
685
+
686
+ function recentUserText(events, limit = 6) {
687
+ const parts = []
688
+ for (const event of Array.isArray(events) ? events : []) {
689
+ if (event?.type !== 'user/message' || event.data?.source?.kind !== 'user') continue
690
+ for (const block of event.data?.content || []) {
691
+ if (block?.type === 'text' && typeof block.text === 'string' && block.text.trim()) parts.push(block.text.trim())
692
+ }
693
+ }
694
+ return parts.slice(-limit).join('\n')
695
+ }
696
+
697
+ /**
698
+ * 1.3.1:本窗候选的本地召回命中。worker 不再获得 recall/list 工具,去重所需的
699
+ * 旧条目必须在种子里就给出;这里用插件现有的 BM25 词法腿做零 Token 预召回,
700
+ * 只给 id + 标题 + 一段正文,够 worker 判断 update 还是 remember。
701
+ */
702
+ export function memoryRecallEvent({ binding = null, candidates = [], events = [], now = Date.now(), topK = 6 } = {}) {
703
+ if (!binding?.libraryId) return null
704
+ let rows = []
705
+ try {
706
+ rows = Object.entries(loadPrivateIndex(binding.libraryId).entries || {})
707
+ .filter(([, entry]) => entry && isMemoryEligible(entry, { automatic: true, now }))
708
+ .filter(([, entry]) => visibleToSession(entry, binding.sessionId))
709
+ .map(([id, entry]) => ({ ...entry, id }))
710
+ } catch { return null }
711
+ if (rows.length === 0) return null
712
+ const query = [
713
+ ...(Array.isArray(candidates) ? candidates.map((item) => item?.text) : []),
714
+ recentUserText(events),
715
+ ].filter(Boolean).join('\n')
716
+ const tokens = tokenize(query)
717
+ if (tokens.length === 0) return null
718
+ const corpus = buildCorpus(rows)
719
+ const scored = rows
720
+ .map((entry) => ({ entry, score: bm25(tokens, corpus.docs.get(entry.id), corpus) }))
721
+ .filter((item) => item.score > 0)
722
+ .sort((a, b) => b.score - a.score)
723
+ .slice(0, Math.max(1, Number(topK) || 6))
724
+ if (scored.length === 0) return null
725
+ const text = [
726
+ '[memory-recall · 本地召回命中(只读上下文,不是用户发言,也不属于本轮转录)]',
727
+ '下面是与本窗候选最相关的已有条目;只用于去重/合并,不是用户说过的话,也不是新证据。',
728
+ ...scored.map(({ entry }) => `- [${entry.id}] ${capSeedText(entry.title || '(untitled)', 80)} — ${capSeedText(entry.content || '', 90)}`),
729
+ ].join('\n')
730
+ return {
731
+ type: 'user/message',
732
+ seq: 0,
733
+ time: now,
734
+ data: createUserMessage({
735
+ content: [{ type: 'text', text }],
736
+ source: { kind: 'plugin:dsh-memu-memory', form: 'notice', summary: 'memory-recall' },
737
+ }),
738
+ surfaceOp: 'append',
739
+ }
740
+ }
741
+
742
+ /** First `limit` events, trimmed back to a complete turn so a fork never sees half a step. */
743
+ export function selectConsolidationWindow(events, limit = CONSOLIDATION_WINDOW_EVENTS) {
744
+ const list = (Array.isArray(events) ? events : []).filter(event => eventSeq(event) !== null)
745
+ if (list.length === 0) return { events: [], fromSeq: null, throughSeq: null, remaining: 0 }
746
+ if (list.length <= limit) return { events: list, fromSeq: eventSeq(list[0]), throughSeq: eventSeq(list[list.length - 1]), remaining: 0 }
747
+ const cutSeq = eventSeq(list[Math.max(0, limit - 1)])
748
+ const sliced = list.filter(event => eventSeq(event) <= cutSeq)
749
+ const safe = safePrefix(sliced, { requireClosedTurn: false })
750
+ const window = safe.ok && safe.events.length > 0 ? safe.events : sliced
751
+ const throughSeq = eventSeq(window[window.length - 1])
752
+ return {
753
+ events: window,
754
+ fromSeq: eventSeq(window[0]),
755
+ throughSeq,
756
+ remaining: list.filter(event => eventSeq(event) > throughSeq).length,
757
+ }
758
+ }
759
+
760
+ /** Align worker windows to completed turns. If a window ends mid-turn, move that
761
+ * turn to the next window so adjacent windows do not resend it. Return the original
762
+ * range when there is no completed turn for alignment; the caller handles fallback.
763
+ * This applies only to the worker path. Do not move the cursor backward when only a
764
+ * session-level event follows the last turn; a new turn has started only if a
765
+ * turn/start follows the last turn/end. */
766
+ export function alignWindowToTurn(window) {
767
+ const events = Array.isArray(window?.events) ? window.events : []
768
+ let lastEnd = null
769
+ for (const event of events) {
770
+ if (event?.type !== 'turn/end') continue
771
+ const seq = eventSeq(event)
772
+ if (seq !== null && (lastEnd === null || seq > lastEnd)) lastEnd = seq
773
+ }
774
+ if (lastEnd === null || lastEnd === window.throughSeq) return window
775
+ const trailing = events.filter((event) => {
776
+ const seq = eventSeq(event)
777
+ return seq !== null && seq > lastEnd
778
+ })
779
+ // 最后回合结束后只剩宿主元数据:整段保留,别为了对齐丢掉转录末尾的事件。
780
+ if (!trailing.some((event) => event?.type === 'turn/start')) return window
781
+ const aligned = events.filter((event) => {
782
+ const seq = eventSeq(event)
783
+ return seq !== null && seq <= lastEnd
784
+ })
785
+ if (aligned.length === 0) return window
786
+ return {
787
+ events: aligned,
788
+ fromSeq: window.fromSeq,
789
+ throughSeq: lastEnd,
790
+ remaining: (Number(window.remaining) || 0) + (events.length - aligned.length),
791
+ }
792
+ }
793
+
794
+ /** Select a worker window by event count, then extend it through the current turn's
795
+ * turn/end. Turn-log entries represent whole turns, so leaving a partial turn for the
796
+ * next window would resend that turn in full. The worker package is bounded by record
797
+ * size, so completing the turn does not enlarge its context. If the extension exceeds
798
+ * the defensive limit, retain the original window.
799
+ */
800
+ export function selectWorkerWindow(events, limit = CONSOLIDATION_WINDOW_EVENTS, maxExtend = WORKER_WINDOW_EXTEND_EVENTS) {
801
+ const list = (Array.isArray(events) ? events : []).filter((event) => eventSeq(event) !== null)
802
+ const initial = selectConsolidationWindow(list, limit)
803
+ if (!initial.events || initial.events.length === 0) return initial
804
+ const lastEndIndex = (() => {
805
+ for (let i = initial.events.length - 1; i >= 0; i -= 1) {
806
+ if (initial.events[i]?.type === 'turn/end') return i
807
+ }
808
+ return -1
809
+ })()
810
+ const openAfter = lastEndIndex < 0
811
+ || initial.events.slice(lastEndIndex + 1).some((event) => event?.type === 'turn/start')
812
+ if (!openAfter) return alignWindowToTurn(initial)
813
+ const extraBudget = Math.max(0, Number(maxExtend) || 0)
814
+ if (extraBudget === 0) return alignWindowToTurn(initial)
815
+ const nextEnd = list
816
+ .filter((event) => eventSeq(event) > initial.throughSeq)
817
+ .slice(0, extraBudget)
818
+ .find((event) => event?.type === 'turn/end')
819
+ if (!nextEnd) return alignWindowToTurn(initial)
820
+ const through = eventSeq(nextEnd)
821
+ const extended = list.filter((event) => {
822
+ const seq = eventSeq(event)
823
+ return seq >= initial.fromSeq && seq <= through
824
+ })
825
+ const safe = safePrefix(extended, { requireClosedTurn: false })
826
+ const chosen = safe.ok && safe.events.length > 0 ? safe.events : extended
827
+ const chosenThrough = eventSeq(chosen[chosen.length - 1])
828
+ return {
829
+ events: chosen,
830
+ fromSeq: eventSeq(chosen[0]),
831
+ throughSeq: chosenThrough,
832
+ remaining: list.filter((event) => eventSeq(event) > chosenThrough).length,
833
+ }
834
+ }
835
+
836
+ /** Last complete turn window, for a manual re-check when the cursor is already at the end. */
837
+ export function selectTailTurnWindow(events, limit = CONSOLIDATION_WINDOW_EVENTS) {
838
+ const list = (Array.isArray(events) ? events : []).filter(event => eventSeq(event) !== null)
839
+ const slice = list.slice(-limit)
840
+ if (slice.length === 0) return { events: [], fromSeq: null, throughSeq: null, remaining: 0 }
841
+ let start = slice.findIndex(event => event.type === 'turn/start')
842
+ if (start < 0) start = slice.findIndex(event => event.type === 'user/message')
843
+ if (start < 0) return { events: [], fromSeq: null, throughSeq: null, remaining: 0 }
844
+ for (let i = start - 1; i >= 0; i -= 1) {
845
+ if (slice[i].type === 'user/message' && slice[i].data?.source?.kind === 'user') { start = i; break }
846
+ if (slice[i].type === 'turn/end' || slice[i].type === 'turn/start') break
847
+ }
848
+ const window = slice.slice(start)
849
+ const safe = safePrefix(window, { requireClosedTurn: false })
850
+ const chosen = safe.ok && safe.events.length > 0 ? safe.events : window
851
+ return { events: chosen, fromSeq: eventSeq(chosen[0]), throughSeq: eventSeq(chosen[chosen.length - 1]), remaining: 0 }
852
+ }
853
+
854
+ /**
855
+ * 整理游标只能前进:尾部人工重检选中最后一个回合时,窗口可能比已有游标更靠前
856
+ * (例如已经结算过 turn/end 后的 session/end-seed),直接写回会把 lastSleepSeq
857
+ * 从 5099 拉回 5098。统一走这里,取当前值与新值的较大者。
858
+ */
859
+ function advanceSleepCursor(sessionId, seq, patch = {}) {
860
+ const next = Number(seq)
861
+ if (!Number.isSafeInteger(next) || next < 0) return null
862
+ const current = (() => {
863
+ try { return Number(getSessionBinding(sessionId)?.lastSleepSeq) } catch { return NaN }
864
+ })()
865
+ const value = Number.isSafeInteger(current) && current >= 0 ? Math.max(current, next) : next
866
+ setSessionBinding(sessionId, { lastSleepSeq: value, ...patch })
867
+ return value
868
+ }
869
+
870
+ // 归档会话集合(issue #4 缺陷 3):宿主 workspaceRegistry 的 archivedSessionIds 是
871
+ // 使命名数组;包装成 Set 供 cycle.js 与 private.js 入口共用。注册表缺失/异常时返回
872
+ // null(无信息,不做拦截),与 rpc.js 的读法一致。
873
+ export function archivedSessionIdsOf(ctx) {
874
+ try {
875
+ return new Set((ctx?.get?.('workspaceRegistry')?.archivedSessionIds || []).map(String))
876
+ } catch {
877
+ return null
878
+ }
879
+ }
880
+
881
+ export async function requestPrivateConsolidation(ctx, sessionId, options = {}) {
882
+ const binding = getSessionBinding(sessionId)
883
+ if (!binding) return { ok: false, error: 'session is not bound to a memory library; bind it first' }
884
+ if (!binding.libraryId || !effectiveScope(binding).useLibrary) return { ok: false, error: 'private memory is disabled for this session or folder' }
885
+ // 归档会话在宿主 agent/pre-step 必被拒("the fork turn ended blocked"),fork 只会
886
+ // 白建一次再计两次失败踩进冻结。cycle.js 已在候选阶段事前跳过;这里拦手动调用,
887
+ // 给出明确的 reasonCode 而不是让用户等到失败回执。
888
+ const archived = archivedSessionIdsOf(ctx)
889
+ if (archived?.size && archived.has(String(sessionId))) {
890
+ return {
891
+ ok: false, skipped: 'session-archived', settled: false, reasonCode: 'session-archived',
892
+ error: 'session is archived; unarchive it before consolidating',
893
+ }
894
+ }
895
+ // Always a fork, never the live session's own inbox. `agent.followup` on the
896
+ // chat the user is looking at does queue a real turn — but the host renders a
897
+ // queued next-turn message as a pending draft above the composer (editable,
898
+ // deletable, sent on demand), and once it runs it stays in that transcript
899
+ // forever, re-sent on every later turn. A live session is no exception: the
900
+ // fork seeds the same transcript, so recall quality is unchanged, while the
901
+ // housekeeping turn lands in a scratch subagent session (origin: subagent —
902
+ // out of the window list and out of the injection path) that is disposed.
903
+ return requestHistoricalConsolidation(ctx, sessionId, options)
904
+ }
905
+
906
+ // Remote mode: the configured remote chat endpoint writes the memories, then they
907
+ // are committed through the same backend. No local agent or tool chain is touched.
908
+ export async function requestRemoteConsolidation(ctx, sessionId, { signal, timeoutMs, force = false } = {}) {
909
+ const binding = getSessionBinding(sessionId)
910
+ if (!binding) return { ok: false, error: 'session is not bound to a memory library; bind it first' }
911
+ if (!binding.libraryId || !effectiveScope(binding).useLibrary) return { ok: false, error: 'private memory is disabled for this session or folder' }
912
+ const sessionQuery = ctx.get?.('sessionQuery')
913
+ if (!sessionQuery) return { ok: false, error: 'host has no sessionQuery; cannot read this conversation' }
914
+ try {
915
+ const snapshot = await readSessionSnapshot(sessionQuery, sessionId)
916
+ const events = Array.isArray(snapshot?.events) ? snapshot.events : []
917
+ if (events.length === 0) return { ok: false, error: 'this session has no content to consolidate' }
918
+ const fresh = unconsolidatedEvents(binding, events)
919
+ if (!force) {
920
+ const value = assessConsolidationValue(fresh)
921
+ if (!value.worth) return { ok: true, sessionId, backend: 'api', count: 0, skipped: value.reason, assessment: value }
922
+ }
923
+ const transcript = condenseEvents(fresh, 60_000, condenseLimitsFor(domainOf(binding)))
924
+ const library = binding.libraryId ? getLibrary(binding.libraryId) : null
925
+ const memories = await summarizeRemote({
926
+ transcript,
927
+ libraryName: library ? `${library.name} (${library.id})` : '(unbound)',
928
+ domain: domainOf(binding),
929
+ signal,
930
+ timeoutMs,
931
+ })
932
+ // 写入计数必须说真话:`memories` 是模型给的清单,逐条 privateRemember 可能被
933
+ // 事实级去重拒绝(deduped,不落库)或因矛盾暂扣(pending_review,仅入索引)。
934
+ // count 只数真正落库的;被拒/暂扣分列进 detail,否则"写入 N 条"就是误报。
935
+ let written = 0
936
+ let deduped = 0
937
+ let held = 0
938
+ for (const memory of memories) {
939
+ const outcome = await privateRemember({
940
+ ...memory,
941
+ exec: { agent: { session: { header: { id: sessionId } } } },
942
+ content: memory.content,
943
+ title: memory.title || memory.content,
944
+ tags: memory.tags,
945
+ openLoop: memory.openLoop,
946
+ confidence: memory.confidence,
947
+ source: memory.source || 'inferred',
948
+ })
949
+ if (outcome?.deduped === true) deduped += 1
950
+ else if (outcome?.entry?.status === 'pending_review') held += 1
951
+ else written += 1
952
+ }
953
+ advanceSleepCursor(sessionId, events[events.length - 1]?.seq)
954
+ const result = { ok: true, sessionId, backend: 'api', count: written, deduped, held }
955
+ record({
956
+ kind: 'consolidate', scope: 'private', sessionId, libraryId: binding.libraryId || null, ok: true,
957
+ message: `整理完成(远程)· 写入 ${written}`
958
+ + (deduped ? ` · 去重拦下 ${deduped}` : '')
959
+ + (held ? ` · 待复核 ${held}` : ''),
960
+ detail: { ...result, forced: force },
961
+ })
962
+ return result
963
+ } catch (error) {
964
+ record({
965
+ kind: 'consolidate', scope: 'private', sessionId, libraryId: binding.libraryId || null, ok: false, level: 'error',
966
+ message: '整理失败(远程):' + String(error?.message || error),
967
+ detail: { forced: force },
968
+ })
969
+ return { ok: false, error: String(error?.message || error) }
970
+ }
971
+ }
972
+
973
+ // `buildForkSeed` lives in dsh-session, which this plugin does not need for
974
+ // anything else. Imported lazily so a host that does not expose it loses only
975
+ // historical consolidation, not the whole plugin half.
976
+ async function loadBuildForkSeed() {
977
+ try {
978
+ const mod = await import('@deepseek-ai/dsh-session')
979
+ return typeof mod?.buildForkSeed === 'function' ? mod.buildForkSeed : null
980
+ } catch {
981
+ return null
982
+ }
983
+ }
984
+
985
+ function agentOptionsFromConfig(config) {
986
+ if (!config || typeof config !== 'object') return null
987
+ const provider = typeof config.provider === 'string' ? config.provider.trim() : ''
988
+ const model = typeof config.model === 'string' ? config.model.trim() : ''
989
+ if (!provider || !model) return null
990
+ const options = { provider, model }
991
+ if (typeof config.reasoningEffort === 'string' && config.reasoningEffort) options.reasoningEffort = config.reasoningEffort
992
+ if (Number.isSafeInteger(config.maxTokens) && config.maxTokens > 0) options.maxTokens = config.maxTokens
993
+ return options
994
+ }
995
+
996
+ // A fork starts a new agent loop and does not inherit the parent's Agent options.
997
+ // Use the live request header for an active session or its latest recorded request for
998
+ // a closed session. If neither is available, the standard preset cannot resolve
999
+ // {{model}}, so do not create the fork. A session with externally appended history may
1000
+ // have no request header; use the public resume() API to re-register its own loop when
1001
+ // available. If that capability is unavailable or fails, return null and refuse the fork.
1002
+ async function inheritedAgentOptions(ctx, sessionId, events) {
1003
+ let agents = null
1004
+ try { agents = ctx.get?.('agents') || null } catch {}
1005
+ const probe = (agent) => {
1006
+ try {
1007
+ const fromRequest = liveAgentOptions(agent)
1008
+ if (fromRequest) return fromRequest
1009
+ } catch {}
1010
+ return agentOptionsFromConfig(agent?.options)
1011
+ }
1012
+ let live = null
1013
+ try { live = agents?.get?.(sessionId) || null } catch {}
1014
+ const direct = probe(live)
1015
+ if (direct) return direct
1016
+ if (agents && typeof agents.resume === 'function') {
1017
+ try {
1018
+ const resumed = await agents.resume({ resumeSessionId: sessionId })
1019
+ const fromResumed = probe(resumed?.agent || resumed)
1020
+ if (fromResumed) return fromResumed
1021
+ } catch {}
1022
+ }
1023
+ for (let i = events.length - 1; i >= 0; i -= 1) {
1024
+ if (events[i]?.type !== 'request/header') continue
1025
+ const fromEvent = agentOptionsFromConfig(events[i]?.data?.header?.config)
1026
+ if (fromEvent) return fromEvent
1027
+ }
1028
+ return null
1029
+ }
1030
+
1031
+ function turnEndFailure(event) {
1032
+ const reason = event?.data?.reason
1033
+ if (!reason || typeof reason !== 'object') return 'the fork produced no turn/end event'
1034
+ if (reason.kind === 'completed') return null
1035
+ const message = reason?.error?.message || reason?.reason?.message || reason?.message
1036
+ return 'the fork turn ended ' + (reason.kind || 'without a reason') + (message ? ': ' + message : '')
1037
+ }
1038
+
1039
+ // attachWorkerTools / restrictWorkerTools are shared implementations in worker-pool.js;
1040
+ // both persistent workers and the 'fork' path import them from that module.
1041
+
1042
+ // 活动日志"整理已开始"条目的挂载元数据口径(workerTools* 三件):
1043
+ // workerToolsAttached 实际注册成功的工具名数组;null = 挂载没有完成或无法确认
1044
+ // (fork ctx 无 tools 服务、register 抛错、宿主没回名单),
1045
+ // 与"挂全了"严格区分——这正是旧字段把 wanted 全量误报成
1046
+ // 已挂载的教训。
1047
+ // workerToolsRequested 请求挂载的完整 wanted 名单;与 attached 全等才是全量挂载。
1048
+ // workerToolsPartial true = 未证明 worker 拿到完整 wanted 集(子集、空集、或挂载
1049
+ // 整体失败)。刻意把"一件都没挂上"也标 true:若失败标 false,
1050
+ // false 会被一眼读成"全量挂载",元数据又不准了。
1051
+ function workerToolsMeta(workerTools) {
1052
+ const wanted = [...WORKER_WRITE_TOOLS, ...WORKER_READ_TOOLS]
1053
+ if (!workerTools) {
1054
+ return { workerToolsAttached: null, workerToolsRequested: wanted, workerToolsPartial: true }
1055
+ }
1056
+ return {
1057
+ workerToolsAttached: Array.isArray(workerTools.attached) ? workerTools.attached : null,
1058
+ workerToolsRequested: Array.isArray(workerTools.requested) ? workerTools.requested : wanted,
1059
+ workerToolsPartial: workerTools.partial === true,
1060
+ }
1061
+ }
1062
+
1063
+ const inFlight = new Map()
1064
+ // How long a cancelled fork gets to finish the tool call it was in the middle of.
1065
+ // Bounded on purpose: a child that ignores the cancel must not hang the sweep, and
1066
+ // the alternative — disposing immediately — is what let a write land after the range
1067
+ // was already handed back to pending.
1068
+ const WORKER_STOP_GRACE_MS = 5_000
1069
+
1070
+ // 这里的 import 刻意写在语句之后:lib/binding-diagnostics.js 的 RUNTIME_STATE 把 `inFlight`
1071
+ // 的 file:line 当成诊断契约(当前 lib/private.js:1014),修改位置时同步更新该诊断映射,
1072
+ // ESM imports are hoisted; synchronize diagnostic source mappings after relocation.
1073
+ import { warn, dataDir, readJsonStrict, withFileLock, writeJson } from './paths.js'
1074
+ import { captureSessionSnapshot, eventSeq, safePrefix, snapshotHash } from './consolidation-snapshot.js'
1075
+ import {
1076
+ beginJob, completeJob, failJob, findOperation, noteEvidence, operationKey, sessionState,
1077
+ recoverStaleJobs, recordOperation, scopeGenerationOf, clearSessionState, skipRange,
1078
+ readCarryCandidates, setCarryCandidates,
1079
+ } from './consolidation-ledger.js'
1080
+ import { decideCompletion, receiptContractText } from './consolidation-receipt.js'
1081
+ import { buildWorkerBrief, probeToolSurface, WORKER_READ_TOOLS, WORKER_WRITE_TOOLS, WORKER_WRAPUP_ROUND, WORKER_HARD_STOP_ROUND, workerRoundGuidance } from './consolidation-worker.js'
1082
+ // worker-pool.js owns worker acquisition, retirement, epoch tracking, package assembly,
1083
+ // and tool mounting; the 'fork' path uses the same tool-mount implementation.
1084
+ import {
1085
+ acquireWorker, attachWorkerTools, buildHandoffPack, buildIncrementPack, loadWorkerIncrement,
1086
+ recordEpochProgress, retireWorker, restrictWorkerTools, WORKER_TIMEOUT_LIMIT,
1087
+ resolveConsolidationCwd, measurePacket, packetBudgetFit, createConsolidationMeasurement,
1088
+ } from './worker-pool.js'
1089
+ import { tokenize, buildCorpus, bm25, numericSet, polarityAt } from './text-retrieval.js'
1090
+ import { isGoneSessionError } from './cycle.js'
1091
+ import { autoLinkPrivateMemories } from './private-links.js'
1092
+ import { resolveConsolidationAgentOptions, ensureConsolidationRoute } from './fork-model.js'
1093
+
1094
+ function liveAgentOptions(agent) {
1095
+ const options = agent?.options
1096
+ let request = null
1097
+ try { request = agentOptionsFromConfig(agent?.session?.requestHeader?.()?.config) } catch {}
1098
+ if (!request) return agentOptionsFromConfig(options)
1099
+ const sameRoute = (!options?.provider || options.provider.trim() === request.provider) && (!options?.model || options.model.trim() === request.model)
1100
+ if (sameRoute && Number.isSafeInteger(options?.maxTokens) && options.maxTokens > 0) return { ...request, maxTokens: options.maxTokens }
1101
+ return request
1102
+ }
1103
+
1104
+ async function consolidationExecutionContext(ctx, sessionId, settings, events, inheritedOptions = null) {
1105
+ const mode = settings.consolidationModelMode || 'inherit'
1106
+ let inherited = inheritedOptions
1107
+ if (mode !== 'host' && mode !== 'custom' && !inherited) {
1108
+ try {
1109
+ const agent = ctx.get?.('agents')?.get?.(sessionId)
1110
+ inherited = liveAgentOptions(agent)
1111
+ } catch {}
1112
+ if (!inherited) {
1113
+ for (let i = events.length - 1; i >= 0; i -= 1) {
1114
+ if (events[i]?.type !== 'request/header') continue
1115
+ inherited = agentOptionsFromConfig(events[i]?.data?.header?.config)
1116
+ if (inherited) break
1117
+ }
1118
+ }
1119
+ }
1120
+ const { options } = resolveConsolidationAgentOptions(settings, inherited)
1121
+ const configuredEffort = settings.consolidationReasoningEffort
1122
+ let effort = configuredEffort && configuredEffort !== 'inherit' ? configuredEffort : options?.reasoningEffort ?? null
1123
+ if (options && effort && isEffortRefused([options.provider, options.model, effort].join('|'))) effort = null
1124
+ let maxTokens = options?.maxTokens ?? null
1125
+ const settingsKey = crypto.createHash('sha256').update(JSON.stringify({
1126
+ mode, runner: settings.consolidationRunner || 'fork',
1127
+ provider: options?.provider ?? null, model: options?.model ?? null, maxTokens, effort,
1128
+ })).digest('hex')
1129
+ let defaultsComparable = maxTokens !== null && effort !== null
1130
+ if (options && !defaultsComparable) {
1131
+ try {
1132
+ const info = await ctx.get?.('llm')?.resolveModelInfo?.(options.provider, options.model)
1133
+ defaultsComparable = !!info && typeof info === 'object'
1134
+ if (maxTokens === null && Number.isSafeInteger(info?.defaultMaxTokens) && info.defaultMaxTokens > 0) maxTokens = info.defaultMaxTokens
1135
+ if (effort === null && typeof info?.reasoning?.defaultEffort === 'string') effort = info.reasoning.defaultEffort
1136
+ } catch {}
1137
+ }
1138
+ const key = crypto.createHash('sha256').update(JSON.stringify({ settingsKey, maxTokens, effort })).digest('hex')
1139
+ return { key, settingsKey, defaultsComparable, maxTokens }
1140
+ }
1141
+
1142
+ // 账本异常必须可见;调用方只有拿到明确的持久租约才可启动 worker。
1143
+ // 其余读写失败返回保守结果,不得据此推进已确认边界。
1144
+ function safeLedger(action, fallback = null) {
1145
+ try {
1146
+ return action()
1147
+ } catch (error) {
1148
+ try { warn('consolidation ledger: ' + String(error?.message || error)) } catch {}
1149
+ return fallback
1150
+ }
1151
+ }
1152
+
1153
+ // 交给结果日志的快照身份:有 hash、有边界、没有正文。
1154
+ function snapshotMetaOf(snapshot) {
1155
+ if (!snapshot) return null
1156
+ return {
1157
+ hash: snapshot.hash,
1158
+ source: snapshot.source,
1159
+ fromSeq: snapshot.fromSeq,
1160
+ throughSeq: snapshot.throughSeq,
1161
+ eventCount: snapshot.eventCount,
1162
+ droppedEvents: snapshot.droppedEvents,
1163
+ capturedAt: snapshot.capturedAt,
1164
+ }
1165
+ }
1166
+
1167
+ // Every agent-backend consolidation runs here, live sessions included: the same
1168
+ // main agent, on a seeded copy of the transcript, writing into the library the
1169
+ // original used. In-place consolidation would append a housekeeping turn to the
1170
+ // user's own chat — a queued draft until it runs, then a permanent resident of
1171
+ // that transcript — so the one visible difference between a live and a closed
1172
+ // session is that a closed one has to be read back from disk first.
1173
+ // 一次整理要等多长时间,取决于它要读多少转录:fork 的种子是整段会话,worker 读完才
1174
+ // Forks read the seeded transcript before writing, so the wait budget must account for
1175
+ // window size. The 600-second budget covers the configured window; the worker lease
1176
+ // extends 90 seconds beyond it so stale work can be recovered. Calls that explicitly
1177
+ // pass maxWaitMs retain that override.
1178
+ export const CONSOLIDATION_WAIT_POLICY = Object.freeze({
1179
+ baseMs: 120_000,
1180
+ perEventMs: 350,
1181
+ minMs: 600_000,
1182
+ maxMs: 600_000,
1183
+ })
1184
+
1185
+ // Remember rejected provider/model/effort combinations so later forks do not repeat an
1186
+ // unsupported effort setting. Persist this information across restarts; a refusal is a
1187
+ // configuration incompatibility, not a transcript or provider outage. Load lazily, and
1188
+ // retry failed reads or writes on the next call.
1189
+ const effortRefusalCaches = new Map()
1190
+ // Deduplicate activity logs during a snapshot-failure freeze: record one entry per
1191
+ // operation key and timestamp, then ignore repeated sweeps. The in-memory cache may
1192
+ // reset on restart, allowing one additional record.
1193
+ const frozenLogStamps = new Map()
1194
+
1195
+ function effortRefusalCache() {
1196
+ const file = path.resolve(dataDir(), 'effort-refusals.json')
1197
+ if (!effortRefusalCaches.has(file)) {
1198
+ effortRefusalCaches.set(file, { file, keys: new Set(), loaded: false, dirty: false })
1199
+ }
1200
+ return effortRefusalCaches.get(file)
1201
+ }
1202
+
1203
+ function readEffortRefusals(file) {
1204
+ const result = readJsonStrict(file)
1205
+ if (result.missing) return []
1206
+ if (!result.ok) throw result.error || new Error('cannot read effort refusals')
1207
+ const raw = result.value
1208
+ if (raw?.version !== 1 || !Array.isArray(raw.keys) || !raw.keys.every(key => typeof key === 'string')) {
1209
+ throw new Error('invalid effort refusals schema')
1210
+ }
1211
+ return raw.keys
1212
+ }
1213
+
1214
+ function syncEffortRefusals(cache) {
1215
+ try {
1216
+ if (cache.dirty) {
1217
+ withFileLock(cache.file, () => {
1218
+ // 必须在锁内重读:其它进程可能已写入本缓存尚未见过的键。
1219
+ // 读错/坏 schema 直接退出,绝不把它当空表覆盖;写失败仍保留 dirty。
1220
+ const keys = new Set([...readEffortRefusals(cache.file), ...cache.keys])
1221
+ writeJson(cache.file, { version: 1, keys: [...keys] })
1222
+ cache.keys = keys
1223
+ cache.loaded = true
1224
+ cache.dirty = false
1225
+ })
1226
+ } else if (!cache.loaded) {
1227
+ cache.keys = new Set(readEffortRefusals(cache.file))
1228
+ cache.loaded = true
1229
+ }
1230
+ } catch (error) {
1231
+ warn('consolidation effort refusals: ' + String(error?.message || error))
1232
+ }
1233
+ }
1234
+
1235
+ /** 从 fork 失败信息里识别『该模型不支持这个思考强度』并给出学习键。 */
1236
+ export function effortRefusalOf(failure) {
1237
+ const m = /provider "([^"]+)" model "([^"]+)" does not support reasoning effort "([^"]+)"/.exec(String(failure || ''))
1238
+ return m ? { provider: m[1], model: m[2], effort: m[3], key: [m[1], m[2], m[3]].join('|') } : null
1239
+ }
1240
+ export function markEffortRefused(key) {
1241
+ const cache = effortRefusalCache()
1242
+ const k = String(key)
1243
+ if (!cache.keys.has(k)) {
1244
+ cache.keys.add(k)
1245
+ cache.dirty = true
1246
+ }
1247
+ syncEffortRefusals(cache)
1248
+ }
1249
+ export function isEffortRefused(key) {
1250
+ const cache = effortRefusalCache()
1251
+ syncEffortRefusals(cache)
1252
+ return cache.keys.has(String(key))
1253
+ }
1254
+
1255
+ export function consolidationWaitBudget(eventCount, policy = CONSOLIDATION_WAIT_POLICY) {
1256
+ const count = Number.isFinite(Number(eventCount)) ? Math.max(0, Math.floor(Number(eventCount))) : 0
1257
+ const raw = policy.baseMs + count * policy.perEventMs
1258
+ return Math.min(policy.maxMs, Math.max(policy.minMs, raw))
1259
+ }
1260
+
1261
+ export async function requestHistoricalConsolidation(ctx, sessionId, options = {}) {
1262
+ const { maxWaitMs = null, force = false, trigger = null } = options
1263
+ const binding = getSessionBinding(sessionId)
1264
+ if (!binding) return { ok: false, error: 'session is not bound to a memory library; bind it first' }
1265
+ if (!binding.libraryId || !effectiveScope(binding).useLibrary) return { ok: false, error: 'private memory is disabled for this session or folder' }
1266
+ if (inFlight.has(sessionId)) return { ok: false, error: 'this session is already being consolidated', running: true }
1267
+
1268
+ // The session is claimed before the first await. readSession and agents.create
1269
+ // both yield, so two callers arriving in the same tick used to pass the guard
1270
+ // together and fork the same transcript twice.
1271
+ const abort = new AbortController()
1272
+ inFlight.set(sessionId, abort)
1273
+ let handle = null
1274
+ let offSession = null
1275
+ // N3:worker 工具循环的软/硬上限。软上限追加收尾提示,硬上限停掉 fork;
1276
+ // 已经写入库的条目不会因为硬停被撤销(游标不推进,下一窗重试剩余范围)。
1277
+ let workerToolRounds = 0
1278
+ let idle = null
1279
+ // Stopped once, callable twice: the timeout path and `finally` both need it.
1280
+ let stopped = false
1281
+ // The host's own order is cancel -> whenIdle -> dispose. dispose() alone does not
1282
+ // wait for a tool call in flight, and this fork writes memories *through tools*, so
1283
+ // "the fork was stopped" was not true when the timeout path returned: failJob had
1284
+ // already handed the range back and the next pass could fork the same window while
1285
+ // the old child was still writing. Bounded, because a child that ignores the cancel
1286
+ // must not hang the sweep.
1287
+ const stopWorker = async () => {
1288
+ if (stopped) return
1289
+ stopped = true
1290
+ try { abort.abort() } catch {}
1291
+ try { offSession?.() } catch {}
1292
+ if (idle) {
1293
+ try {
1294
+ await Promise.race([
1295
+ idle.then(() => {}, () => {}),
1296
+ // Deliberately NOT unref'd: this promise is what we are awaiting, so an
1297
+ // unref'd timer lets the event loop drain while the await is still pending
1298
+ // and the caller (or the test runner) is left holding a promise that can
1299
+ // never settle. A <=5s hold on the loop is the correct trade.
1300
+ new Promise((resolve) => setTimeout(resolve, WORKER_STOP_GRACE_MS)),
1301
+ ])
1302
+ } catch {}
1303
+ }
1304
+ try { await handle?.dispose?.() } catch {}
1305
+ }
1306
+ let turnEnd = null
1307
+ let jobId = null
1308
+ let scopeChanged = null
1309
+ let workerTools = null
1310
+ let workerRestriction = null
1311
+ // 执行器选择在 try 内赋值;finally 需要 workerMode 来决定清理口径(worker 模式
1312
+ // 不销毁 worker——它的生命周期归 epoch,见 §15.2 改动点 6)。
1313
+ let workerMode = false
1314
+ // worker 生命周期上绑定的 epoch abort(acquireWorker 返回)。续窗的硬停/重验必须
1315
+ // abort 它才停得住持久 worker——窗口级 abort 只在出生那次被宿主接进生命周期。
1316
+ let workerEpochAbort = null
1317
+ const assistantTexts = []
1318
+ let childId = null
1319
+ let accounting = null
1320
+ let executionContext = null
1321
+ // 每次整理都要在活动日志里留一条:谁触发(手动/空闲)、fork 有没有建、结果是完成、
1322
+ // 超时还是失败。否则"点了没反应"只能靠翻会话文件才知道发生了什么。
1323
+ const finish = (result) => {
1324
+ result = { ...result, runner: workerMode ? 'worker' : 'fork', measurement: accounting?.measurement || null }
1325
+ const ok = result?.ok === true
1326
+ const skipped = Boolean(result?.skipped)
1327
+ const skipText = !skipped
1328
+ ? ''
1329
+ : (['small-talk', 'no-human-turn', 'no-value', 'no-new-events'].includes(result.skipped)
1330
+ ? '跳过(没有值得记的内容)'
1331
+ : '跳过 · ' + result.skipped)
1332
+ record({
1333
+ kind: 'consolidate',
1334
+ scope: 'private',
1335
+ sessionId,
1336
+ libraryId: binding.libraryId || null,
1337
+ ok,
1338
+ level: ok ? 'info' : (result?.timedOut ? 'warn' : 'error'),
1339
+ message: '整理' + (ok ? (skipped ? skipText : '完成') : (result?.timedOut ? '超时' : '失败'))
1340
+ + (force ? ' · 手动' : (options.trigger === 'backlog' ? ' · 水位' : ' · 空闲'))
1341
+ + (result?.childId ? ' · fork ' + result.childId.slice(-8) : '')
1342
+ + (result?.reasonCode ? ' · ' + result.reasonCode : '')
1343
+ + (result?.error ? ':' + String(result.error) : '')
1344
+ + (result?.count !== undefined ? ' · 写入 ' + result.count : '')
1345
+ + (result?.wrote !== null && result?.wrote !== undefined ? ' · 索引 +' + result.wrote : '')
1346
+ + (result?.scanned !== undefined ? ' · 扫描 ' + result.scanned + ' 事件 / 新 ' + (result.fresh ?? '?') : ''),
1347
+ detail: { force, jobId, ...result },
1348
+ refs: [],
1349
+ })
1350
+ return result
1351
+ }
1352
+ try {
1353
+ const settings = getSettings()
1354
+ workerMode = settings.consolidationRunner === 'worker'
1355
+ accounting = createConsolidationMeasurement(workerMode ? 'worker' : 'fork')
1356
+ // 僵尸租约先回收:进程被杀之后 inflight 会留在账本里,不能让一条死记录永久挡住这个会话。
1357
+ safeLedger(() => {
1358
+ const recovered = recoverStaleJobs()
1359
+ if (recovered.length > 0) {
1360
+ record({ kind: 'check', scope: 'private', ok: true, message: '回收 ' + recovered.length + ' 个过期整理租约', detail: { recovered } })
1361
+ }
1362
+ return recovered
1363
+ })
1364
+
1365
+ // 读不到会话就什么都不用谈,所以先确认快照能力,再确认 fork 能力——
1366
+ // 失败信息要说清缺的是哪一个(readSession/observeSession 还是 agents.create)。
1367
+ const sessionQuery = (() => { try { return ctx.get?.('sessionQuery') || null } catch { return null } })()
1368
+ if (!sessionQuery || (typeof sessionQuery.readSession !== 'function' && typeof sessionQuery.observeSession !== 'function')) {
1369
+ return finish({
1370
+ ok: false, sessionId, code: 'unavailable', reasonCode: 'no-session-query', settled: false,
1371
+ error: 'host has no sessionQuery.readSession / observeSession; historical consolidation is unavailable',
1372
+ })
1373
+ }
1374
+ const agents = ctx.get?.('agents')
1375
+ if (typeof agents?.create !== 'function') {
1376
+ return finish({ ok: false, sessionId, code: 'unavailable', reasonCode: 'no-agents-service', settled: false, error: 'host has no agents.create; historical consolidation is unavailable' })
1377
+ }
1378
+ const buildForkSeed = workerMode ? null : await loadBuildForkSeed()
1379
+ if (!workerMode && !buildForkSeed) {
1380
+ return finish({ ok: false, sessionId, code: 'unavailable', reasonCode: 'no-fork-seed', settled: false, error: 'dsh-session buildForkSeed is unavailable' })
1381
+ }
1382
+
1383
+ // 安全快照:cut 固定、身份可核验。未闭合的回合、没配对的工具调用、半截 step 在这里就被挡住,
1384
+ // rather than pass them to the worker as evidence. If a safe snapshot is unavailable,
1385
+ // defer the job.
1386
+ const captured = await captureSessionSnapshot(ctx, sessionId, { signal: abort.signal })
1387
+ if (!captured.ok) {
1388
+ if (captured.code === 'deferred') {
1389
+ return finish({ ok: true, sessionId, skipped: captured.reasonCode, settled: false, deferred: true, reasonCode: captured.reasonCode, detail: captured.error })
1390
+ }
1391
+ // 会话已被删除(host 回答 not found)是正常生命周期,不是整理故障:标记
1392
+ // sessionGone(空闲扫描从此跳过)、记 info 级 check 而不是 error——删除的
1393
+ // Deleted sessions are a normal lifecycle state, not a consolidation failure.
1394
+ if (isGoneSessionError(captured.error)) {
1395
+ setSessionBinding(sessionId, { sessionGone: true, sessionGoneAt: new Date().toISOString(), sleepRetryAt: null, sleepAttempts: 0, lastSleepError: null })
1396
+ try { clearSessionState(sessionId) } catch {}
1397
+ record({
1398
+ kind: 'check', scope: 'private', sessionId, libraryId: binding.libraryId || null, ok: true,
1399
+ message: '对话已删除,不再整理(session not found)',
1400
+ detail: { reasonCode: 'session-gone' },
1401
+ })
1402
+ return { ok: false, sessionId, code: 'session-gone', reasonCode: 'session-gone', settled: false, retryable: false, error: captured.error }
1403
+ }
1404
+ return finish({
1405
+ ok: false, sessionId, code: captured.code, reasonCode: captured.reasonCode, settled: false,
1406
+ retryable: captured.retryable === true, error: captured.error,
1407
+ })
1408
+ }
1409
+ const fullSnapshot = captured.snapshot
1410
+ const events = captured.events
1411
+ const fresh = unconsolidatedEvents(binding, events)
1412
+ if (events.length === 0) return finish({ ok: false, sessionId, reasonCode: 'empty-snapshot', settled: false, error: 'this session has no content to consolidate' })
1413
+ // A manual click on an already-settled session still re-checks the tail instead
1414
+ // of replaying megabytes; automatic runs only look at what the cursor has not
1415
+ // covered. Either way the fork gets one bounded window, not the whole log.
1416
+ const candidateEvents = force && fresh.length === 0 ? selectTailTurnWindow(events).events : fresh
1417
+ if (candidateEvents.length === 0) {
1418
+ return finish({ ok: true, sessionId, skipped: 'no-new-events', settled: true, snapshot: snapshotMetaOf(fullSnapshot) })
1419
+ }
1420
+ const generationAtStart = scopeGenerationOf(binding)
1421
+ // 待检查边界与已确认边界分开记:证据到达就记一次,失败不回退。
1422
+ safeLedger(() => noteEvidence({ sessionId, fromSeq: fullSnapshot.fromSeq, throughSeq: fullSnapshot.throughSeq }))
1423
+
1424
+ let value = null
1425
+ if (!force) {
1426
+ value = assessConsolidationValue(candidateEvents)
1427
+ // 这一批里没有真人回合、或只有一句「好的继续」:这一段确实没什么可整理的,
1428
+ // 是终态而不是 deferral——写入完成边界由 cycle 落到 lastSleepAt,下一次真人
1429
+ // 消息到达前不再重扫同一个寒暄窗口。
1430
+ if (!value.worth) {
1431
+ // A terminal policy skip advances the coarse cursor and checked range:
1432
+ // otherwise the same greetings stay pending forever and the sweep keeps
1433
+ // treating them as a real backlog.
1434
+ safeLedger(() => skipRange({ sessionId, snapshot: fullSnapshot, reasonCode: value.reason }))
1435
+ advanceSleepCursor(sessionId, fullSnapshot.throughSeq)
1436
+ return finish({
1437
+ ok: true, sessionId, skipped: value.reason, settled: true, deferred: false,
1438
+ reasonCode: value.reason, assessment: value, snapshot: snapshotMetaOf(fullSnapshot),
1439
+ })
1440
+ }
1441
+ // 事件/回合水位:积压到一定规模就直接整理,不再等评分。它和空闲触发是
1442
+ // 两条腿:空闲保证收尾,水位保证一场持续几小时的会话不会攒到几千条才动。
1443
+ const backlog = candidateEvents.length >= CONSOLIDATION_BACKLOG_EVENTS
1444
+ || Number(value.humanTurns) >= CONSOLIDATION_BACKLOG_TURNS
1445
+ if (options.trigger === 'backlog' && !backlog) {
1446
+ return finish({
1447
+ ok: true, sessionId, skipped: 'backlog-below-threshold', settled: false, deferred: true,
1448
+ reasonCode: 'backlog-below-threshold', assessment: value, snapshot: snapshotMetaOf(fullSnapshot),
1449
+ trigger: options.trigger,
1450
+ })
1451
+ }
1452
+ if (!backlog) {
1453
+ // 加权判定:短空闲要求分数达标,长空闲(饥饿阈值)无条件放行;
1454
+ // 阈值与权重集中在 lib/active-memory.js,可根据回放标定。
1455
+ const idleMinutes = binding.lastTurnAt ? (Date.now() - (Date.parse(binding.lastTurnAt) || Date.now())) / 60_000 : Infinity
1456
+ const starved = idleMinutes >= Number(settings.activeMemoryStarvationMinutes ?? ACTIVE_MEMORY_POLICY.starvationMinutes)
1457
+ // 小增量顺延:不 fork、不推进游标;下一次触发把这段一起带上。
1458
+ // 首次整理(还没有成功游标)不受限,尽快建立记忆基线;饥饿(长时间空闲)
1459
+ // 仍然放行,保证收尾;force 手动路径不经过这里。
1460
+ const firstPass = !binding.lastSleepSeq
1461
+ if (!starved && !firstPass && Number(value.humanTurns) < CONSOLIDATION_MIN_HUMAN_TURNS) {
1462
+ return finish({
1463
+ ok: true, sessionId, skipped: 'below-min-turns', settled: false, deferred: true,
1464
+ reasonCode: 'below-min-turns', assessment: value, snapshot: snapshotMetaOf(fullSnapshot),
1465
+ trigger: options.trigger,
1466
+ })
1467
+ }
1468
+ const evidence = collectEvidence(candidateEvents)
1469
+ const wake = assessWake({
1470
+ evidence,
1471
+ starved,
1472
+ transcriptEvents: events.length,
1473
+ pendingEvents: candidateEvents.length,
1474
+ policy: { ...ACTIVE_MEMORY_POLICY, minScore: Number(settings.activeMemoryMinScore ?? ACTIVE_MEMORY_POLICY.minScore) },
1475
+ })
1476
+ record({
1477
+ kind: 'check',
1478
+ scope: 'private',
1479
+ sessionId,
1480
+ libraryId: binding.libraryId || null,
1481
+ ok: wake.wake,
1482
+ message: (wake.wake ? '主动检查触发' : '主动检查跳过')
1483
+ + ' · score ' + wake.score
1484
+ + ' · ' + wake.reason
1485
+ + ' · 空闲 ' + (Number.isFinite(idleMinutes) ? Math.round(idleMinutes) + ' 分钟' : '未知')
1486
+ + ' · 会话 ' + events.length + ' 事件'
1487
+ + ' · 待整理 ' + candidateEvents.length + ' 事件'
1488
+ + ' · 快照 ' + fullSnapshot.hash,
1489
+ detail: { trigger: options.trigger || 'idle', reason: wake.reason, score: wake.score, parts: wake.parts, starved, transcriptEvents: events.length, pendingEvents: candidateEvents.length, snapshot: snapshotMetaOf(fullSnapshot) },
1490
+ })
1491
+ if (!wake.wake) return finish({ ok: true, sessionId, skipped: 'low-score', settled: false, assessment: value, score: wake.score, parts: wake.parts, snapshot: snapshotMetaOf(fullSnapshot) })
1492
+ }
1493
+ }
1494
+
1495
+ // One bounded window per run: the next sweep continues from the new cursor.
1496
+ // 失败重试(sleepAttempts>0)时窗口减半:同一游标反复超时不该每次都付整窗成本,
1497
+ // 前半段先结算,剩余留给下一次。
1498
+ const sleepAttempt = Number(binding.sleepAttempts || 0)
1499
+ const windowLimit = sleepAttempt > 0 ? Math.floor(CONSOLIDATION_WINDOW_EVENTS / 2) : CONSOLIDATION_WINDOW_EVENTS
1500
+ // Runner and model route use the same settings snapshot captured before awaits.
1501
+ // worker 模式按回合取窗(切在回合中间时向后补到 turn/end,避免同一回合
1502
+ // 被连续两窗整条重发);fork 路径窗口定义不变。
1503
+ let window = workerMode
1504
+ ? selectWorkerWindow(candidateEvents, windowLimit)
1505
+ : selectConsolidationWindow(candidateEvents, windowLimit)
1506
+ if (window.events.length === 0) {
1507
+ return finish({ ok: true, sessionId, skipped: 'empty-window', settled: true, snapshot: snapshotMetaOf(fullSnapshot) })
1508
+ }
1509
+ const windowSnapshot = {
1510
+ ...fullSnapshot,
1511
+ fromSeq: window.fromSeq,
1512
+ throughSeq: window.throughSeq,
1513
+ eventCount: window.events.length,
1514
+ hash: snapshotHash(window.events, window.fromSeq, window.throughSeq),
1515
+ }
1516
+ const snapshot = windowSnapshot
1517
+ const snapshotMeta = snapshotMetaOf(windowSnapshot)
1518
+ // 范围大小决定等多久:显式给了就听调用方的,没给按这一窗的事件数推。
1519
+ const budgetMs = Number.isInteger(maxWaitMs) && maxWaitMs > 0 ? maxWaitMs : consolidationWaitBudget(window.events.length)
1520
+ // 1.3.1:目录与本地召回命中在种子开头一次给全,worker 不再开只读回合。
1521
+ const carry = safeLedger(() => readCarryCandidates(sessionId), [])
1522
+ const domain = domainOf(binding)
1523
+ const mustCover = mergeMustCover(carry, mustCoverCandidates(window.events, { domain }))
1524
+ const seedEvents = workerMode ? null : compactSeedEvents(candidateSeedEvents(window.events, { domain }), [
1525
+ memoryCatalogEvent({ ...binding, sessionId }),
1526
+ memoryRecallEvent({ binding: { ...binding, sessionId }, candidates: mustCover, events: window.events }),
1527
+ ], seedLimitsFor(domain))
1528
+ if (!workerMode && seedEvents.length === 0) {
1529
+ return finish({ ok: true, sessionId, skipped: 'empty-seed', settled: true, snapshot: snapshotMeta })
1530
+ }
1531
+
1532
+ // 幂等:同一份固定快照已经结算过就不再 fork 一次(失败的部分写入靠操作键判同再试,
1533
+ // 而不是靠"同一个主题就跳过")。
1534
+ const opKey = operationKey({ sessionId, libraryId: binding.libraryId, snapshotHash: windowSnapshot.hash, scopeGeneration: generationAtStart })
1535
+ const previous = safeLedger(() => findOperation(sessionId, opKey))
1536
+ if (previous && (previous.outcome === 'completed' || previous.outcome === 'skipped')) {
1537
+ return finish({ ok: true, sessionId, skipped: 'already-consolidated', settled: true, snapshot: snapshotMeta, credential: previous })
1538
+ }
1539
+ // 同一份快照连续失败到上限就不再「自动」重跑:窗口已经很小,重试成本可控,但
1540
+ // 没有新事件的同一段转录不值得无限重试。手动整理(force)是明确的一次再决定,
1541
+ // 不受上限约束——否则冻结回放/用户重试都会被永久卡在同一个窗口。新消息会改变
1542
+ // 快照哈希,自动路径也重新获得机会。
1543
+ if (!force && previous?.outcome === 'failed' && Number(previous.failures) >= CONSOLIDATION_SNAPSHOT_FAILURE_LIMIT) {
1544
+ // Learn unsupported effort combinations before clearing the freeze and retrying.
1545
+ // 清连击,本次直接放行 fork(fork 起点读不到拒绝表就会带档失败——放行前先学习,
1546
+ // effort 应用处读到拒绝表即不带档)。已冻结的会话由此自愈,不必等手动 force。
1547
+ const failureState = safeLedger(() => sessionState(sessionId), null)
1548
+ const lastError = failureState?.lastError ?? null
1549
+ const staleRefusal = effortRefusalOf(lastError)
1550
+ const newRefusal = staleRefusal && !isEffortRefused(staleRefusal.key)
1551
+ const legacyOutputLimit = (previous.reasonCode ?? failureState?.lastReasonCode) === 'fork-turn-failed'
1552
+ && /^the fork turn ended max-tokens(?::|$)/.test(String(lastError || ''))
1553
+ const outputLimited = previous.reasonCode === 'model-output-limit' || legacyOutputLimit
1554
+ const execution = outputLimited ? await consolidationExecutionContext(ctx, sessionId, settings, events) : null
1555
+ const changedExecution = execution && (!previous.executionSettingsKey || execution.settingsKey !== previous.executionSettingsKey
1556
+ || execution.defaultsComparable && execution.key !== previous.executionKey)
1557
+ if (!newRefusal && !changedExecution) {
1558
+ // 冷却(issue #4 缺陷 1):冻结超过冷却期就放行一次真实重试——连击清零交给
1559
+ // 下方与 newRefusal/changedExecution 共用的 recordOperation;否则维持熔断。
1560
+ const frozenAt = Date.parse(previous.at || '') || 0
1561
+ if (Date.now() - frozenAt >= CONSOLIDATION_SNAPSHOT_FAILURE_COOLDOWN_MS) {
1562
+ warn('consolidation freeze expired: ' + String(previous.reasonCode || 'snapshot-failed') + ' streak reset after cooldown; retrying this window')
1563
+ } else {
1564
+ // settled: false(不再假装这段已整理——那是失败熔断,不是终态跳过):
1565
+ // cycle.js 走 deferred 路径,不推 lastSleepAt、不清 lastSleepError,
1566
+ // 「整理提醒」里保持可见;冷却到期后闸门自动放行重试。
1567
+ const result = {
1568
+ ok: true, sessionId, skipped: 'snapshot-failed', settled: false, deferred: true,
1569
+ reasonCode: 'snapshot-failed-too-many', cooldownUntil: new Date(frozenAt + CONSOLIDATION_SNAPSHOT_FAILURE_COOLDOWN_MS).toISOString(),
1570
+ frozenAt: previous.at || null, snapshot: snapshotMeta, failures: Number(previous.failures) || 0, lastError,
1571
+ }
1572
+ // 冻结期活动日志去重:同一份冻结记录(按 previous.at 判同)只落一条。
1573
+ // cycle.js 现已用 sleepFrozenUntil 在候选阶段退避,正常不再每扫扫入;这里的
1574
+ // 去重兜住「冻结期新活动让路后、同哈希再次冻结」的重复返回,避免刷屏。
1575
+ const freezeStamp = String(previous.at || '')
1576
+ if (frozenLogStamps.get(opKey) !== freezeStamp) {
1577
+ frozenLogStamps.set(opKey, freezeStamp)
1578
+ return finish(result)
1579
+ }
1580
+ return result
1581
+ }
1582
+ }
1583
+ if (newRefusal) {
1584
+ warn('consolidation unfrozen: ' + staleRefusal.key + ' was refused by the model; retrying this window without the effort')
1585
+ markEffortRefused(staleRefusal.key)
1586
+ }
1587
+ if (changedExecution) warn('consolidation output-limit retry: execution configuration changed or needs its first fingerprint')
1588
+ safeLedger(() => recordOperation({ sessionId, key: opKey, outcome: 'failed', ids: previous.ids || [] }))
1589
+ }
1590
+
1591
+ // 工具面必须可验证:父会话这一轮真实发给模型的工具表里若没有记忆写工具,
1592
+ // A safe snapshot and a verified write-tool surface are required before starting work.
1593
+ const probe = probeToolSurface({ ctx, sessionId, events })
1594
+ if (!probe.ok) {
1595
+ return finish({
1596
+ ok: false, sessionId, code: 'unavailable', reasonCode: probe.reasonCode, settled: false, retryable: false,
1597
+ toolSurface: probe.tools || null, ptc: probe.ptcObserved === true,
1598
+ error: 'this conversation exposes no memory write tool to the model (' + String(probe.source || 'unknown') + '), so a consolidation worker could not write anything; consolidation is unavailable until the session has memu_private_remember / memu_private_update',
1599
+ })
1600
+ }
1601
+
1602
+ jobId = 'cons-' + Date.now().toString(36) + '-' + crypto.randomBytes(3).toString('hex')
1603
+ // Let the lease track the execution budget plus its recovery margin.
1604
+ // 走不到超时路径就死的任务(插件重启 / fork 被外力杀掉)不会调 failJob,
1605
+ // 固定 15 分钟租约让该会话的重试一直撞 lease-held;预算封顶 600s,
1606
+ // 租约最迟在真死后 ~90s 由 recoverStaleJobs 回收,而不是再等 9 分钟。
1607
+ const begun = safeLedger(() => beginJob({ sessionId, jobId, snapshot, binding, leaseMs: budgetMs + 90_000 }))
1608
+ if (!begun) {
1609
+ return finish({
1610
+ ok: false, sessionId, settled: false, retryable: true, reasonCode: 'ledger-unavailable',
1611
+ error: 'the consolidation lease could not be persisted; no worker was created',
1612
+ })
1613
+ }
1614
+ if (begun.ok !== true) {
1615
+ return finish({
1616
+ ok: false, sessionId, running: true, settled: false, reasonCode: 'lease-held',
1617
+ error: 'this session already holds a consolidation lease (' + String(begun.jobId) + ' until ' + new Date(begun.leaseUntil).toISOString() + '); the previous run is still unaccounted for — the lease self-heals when it expires, then the range is retried on the next sweep',
1618
+ })
1619
+ }
1620
+
1621
+ const header = captured.header || {}
1622
+ // 每次整理都留"看了多少、新的多少、真正写了几条",否则"0 记忆"无法定位是
1623
+ // 没触发、被门挡住还是提取空转。
1624
+ const freshCount = fresh.length
1625
+ let beforeIds = null
1626
+ let beforeEntries = null
1627
+ try {
1628
+ const beforeIndex = loadPrivateIndex(binding.libraryId)
1629
+ beforeIds = new Set(Object.keys(beforeIndex.entries))
1630
+ beforeEntries = Object.fromEntries(Object.entries(beforeIndex.entries).map(([id, entry]) => [id, entryFingerprint(entry)]))
1631
+ } catch { beforeIds = null; beforeEntries = null }
1632
+
1633
+ // 整理 fork 的模型选择(三模式,lib/fork-model.js)。inherit 保持原路径逐字节一致;
1634
+ // host 直接指名宿主已激活 route;custom 要先在宿主 llm 注册表确认本插件私有 route
1635
+ // 可用(能力缺失/注册失败/服务性探测不过 → 降级回 inherit 或拒绝本次整理,warn 一
1636
+ // 行,绝不 fail closed)。fork 的 AgentOptions 没有 baseURL/apiKey 通道,custom 的
1637
+ // 自定义端点只能走注册 route。(settings 已在窗口选择处读取。)
1638
+ //
1639
+ // host/custom 不需要父会话 route:这里不探测父会话,也避免 inheritedAgentOptions 的
1640
+ // resume 回退把父会话挂成宿主活视图——活视图会钉住 sessionQuery 的快照,外部追加的
1641
+ // persistent log would remain unread. Probe lazily only if the custom route fails.
1642
+ const modelModeSetting = settings.consolidationModelMode || 'inherit'
1643
+ let inherited = null
1644
+ if (modelModeSetting !== 'host' && modelModeSetting !== 'custom') {
1645
+ inherited = await inheritedAgentOptions(ctx, sessionId, events)
1646
+ }
1647
+ const resolved = resolveConsolidationAgentOptions(settings, inherited)
1648
+ let agentOptions = resolved.options
1649
+ let modelMode = resolved.reason
1650
+ if (!agentOptions) {
1651
+ // no-inherited-route 与旧失败路径逐字节一致(inherit 模式语义不变);host/custom
1652
+ // 的坏配置各自带 reasonCode,整理提醒能直接说清是哪个配置面写错了。
1653
+ if (resolved.reason === 'no-inherited-route') {
1654
+ safeLedger(() => failJob({ sessionId, jobId, reasonCode: 'no-parent-route', retryable: true, error: 'cannot inherit the parent model/provider' }))
1655
+ return finish({ ok: false, sessionId, reasonCode: 'no-parent-route', settled: false, error: 'cannot inherit the parent model/provider; consolidation fork was not created' })
1656
+ }
1657
+ safeLedger(() => failJob({ sessionId, jobId, reasonCode: resolved.reason, retryable: true, error: 'cannot resolve the consolidation model (' + resolved.reason + ')' }))
1658
+ return finish({ ok: false, sessionId, reasonCode: resolved.reason, settled: false, error: 'cannot resolve the consolidation model (' + resolved.reason + '); consolidation fork was not created' })
1659
+ }
1660
+ if (resolved.reason === 'custom') {
1661
+ // 每次整理都重挂一次(先卸旧再注册,设置变更自然生效);成功后才允许 fork 指名
1662
+ // dsh-memu-custom。失败降级:有父 route 就回 inherit,没有就只能拒绝。
1663
+ const ensured = await ensureConsolidationRoute(ctx, settings)
1664
+ if (!ensured.ok) {
1665
+ warn('consolidation custom model route unavailable (' + ensured.reason + (ensured.error ? ': ' + ensured.error : '') + '); falling back to the inherited route')
1666
+ if (!inherited) inherited = await inheritedAgentOptions(ctx, sessionId, events)
1667
+ if (inherited) {
1668
+ agentOptions = inherited
1669
+ modelMode = 'inherit-fallback'
1670
+ } else {
1671
+ safeLedger(() => failJob({ sessionId, jobId, reasonCode: 'custom-route-unavailable', retryable: true, error: 'the custom consolidation route is unavailable (' + ensured.reason + ')' }))
1672
+ return finish({ ok: false, sessionId, reasonCode: 'custom-route-unavailable', settled: false, error: 'the custom consolidation route is unavailable (' + ensured.reason + '); consolidation fork was not created' })
1673
+ }
1674
+ }
1675
+ }
1676
+
1677
+ // 最终 route(含 custom 回退)确定后再覆盖档位、过滤实际生效的组合。
1678
+ // inherit 也可能从父 options 带入被拒档位;只克隆子 options,不改父对象或其它参数。
1679
+ const effort = settings.consolidationReasoningEffort
1680
+ if (effort && effort !== 'inherit') agentOptions = { ...agentOptions, reasoningEffort: effort }
1681
+ const effectiveEffort = agentOptions.reasoningEffort
1682
+ if (effectiveEffort && isEffortRefused([agentOptions.provider, agentOptions.model, effectiveEffort].join('|'))) {
1683
+ warn('consolidation reasoning effort ' + effectiveEffort + ' previously refused by ' + agentOptions.provider + '/' + agentOptions.model + ' — starting the worker/fork without it')
1684
+ agentOptions = { ...agentOptions }
1685
+ delete agentOptions.reasoningEffort
1686
+ }
1687
+
1688
+ // The executor mode is determined when the window is selected. 'fork' remains the
1689
+ // default; an explicit 'worker' selection uses the persistent worker pool.
1690
+ executionContext = await consolidationExecutionContext(ctx, sessionId, settings, events, modelMode === 'inherit' ? agentOptions : null)
1691
+ let workerAcquired = null
1692
+ let workerEpochRecord = null
1693
+ let workerIncrement = null
1694
+ let dispatchText = null
1695
+ let dispatchKind = 'fork'
1696
+ if (workerMode) {
1697
+ const workerBinding = { ...binding, sessionId }
1698
+ workerIncrement = loadWorkerIncrement({ sessionId, binding: workerBinding, window, events: window.events })
1699
+ if (!workerIncrement.text.trim()) {
1700
+ safeLedger(() => failJob({ sessionId, jobId, reasonCode: 'empty-increment', retryable: true }))
1701
+ return finish({ ok: false, sessionId, settled: false, retryable: true, reasonCode: 'empty-increment', error: 'no readable worker increment; the range stays pending' })
1702
+ }
1703
+ const current = getSessionBinding(sessionId) || binding
1704
+ const privatePrompt = buildPrivateConsolidationPrompt(sessionId)
1705
+ const common = {
1706
+ sessionId, binding: workerBinding, snapshot, probe, jobId,
1707
+ reason: force ? 'manual' : 'auto', singleOnly: Boolean(binding.consolidationSingleOnly), mustCover,
1708
+ contract: receiptContractText({ jobId, snapshotHash: snapshot.hash, autoReceipt: true }),
1709
+ incrementRecords: workerIncrement.records,
1710
+ incrementText: workerIncrement.source === 'fallback' ? workerIncrement.text : null,
1711
+ digest: workerIncrement.digest, catalog: memoryCatalogEvent(workerBinding),
1712
+ domain,
1713
+ sceneTime: current.sceneTime || binding.sceneTime || null,
1714
+ pendingNote: Boolean(current.consolidationPending), pendingHash: current.consolidationPending?.snapshotHash || null,
1715
+ carry: mustCover, lastSleepSeq: binding.lastSleepSeq ?? null,
1716
+ }
1717
+ const buildPacket = (acquired) => {
1718
+ dispatchKind = acquired.birth ? 'handoff' : 'increment'
1719
+ const pack = acquired.birth ? buildHandoffPack({
1720
+ ...common, includeTail: acquired.handoff !== false, writtenRows: acquired.handoff === false ? [] : null,
1721
+ }) : buildIncrementPack(common)
1722
+ return acquired.birth ? [privatePrompt, '', pack].join('\n') : pack
1723
+ }
1724
+ const acquireOptions = { settings, probe, agentOptions, header, agentPreset: captured.agentPreset }
1725
+ workerAcquired = await acquireWorker(ctx, workerBinding, acquireOptions)
1726
+ if (workerAcquired.ok) {
1727
+ dispatchText = buildPacket(workerAcquired)
1728
+ let packet = measurePacket(dispatchText, dispatchKind)
1729
+ if (!packetBudgetFit(workerAcquired.epoch, packet, settings) && !workerAcquired.birth) {
1730
+ // The final text, not just the pending increment, must fit. Rebuild at
1731
+ // most once, since a handoff includes extra identity/settled-tail text.
1732
+ await retireWorker(ctx, workerAcquired.forkId, 'packet-budget', { handoff: true })
1733
+ workerAcquired = await acquireWorker(ctx, workerBinding, { ...acquireOptions, afterEpochIndex: workerAcquired.epoch.index })
1734
+ if (workerAcquired.ok) {
1735
+ dispatchText = buildPacket(workerAcquired)
1736
+ packet = measurePacket(dispatchText, dispatchKind)
1737
+ }
1738
+ }
1739
+ if (workerAcquired.ok && !packetBudgetFit(workerAcquired.epoch, packet, settings)) {
1740
+ accounting.measurement.packet = { ...packet, dispatched: false }
1741
+ await retireWorker(ctx, workerAcquired.forkId, 'packet-too-large', { handoff: false })
1742
+ safeLedger(() => failJob({ sessionId, jobId, reasonCode: 'packet-too-large', retryable: true, error: 'the complete first packet exceeds the worker epoch budget' }))
1743
+ return finish({ ok: false, sessionId, childId: workerAcquired.forkId, settled: false, retryable: true, reasonCode: 'packet-too-large', error: 'the complete worker packet is too large; the range stays pending (no automatic unsafe truncation)' })
1744
+ }
1745
+ }
1746
+ if (!workerAcquired.ok) {
1747
+ safeLedger(() => failJob({ sessionId, jobId, reasonCode: workerAcquired.reasonCode || 'worker-acquire-failed', retryable: true, error: workerAcquired.error || null }))
1748
+ return finish({
1749
+ ok: false, sessionId, settled: false, retryable: true,
1750
+ reasonCode: workerAcquired.reasonCode || 'worker-acquire-failed',
1751
+ error: workerAcquired.error || 'the consolidation worker could not be acquired',
1752
+ })
1753
+ }
1754
+ childId = workerAcquired.forkId
1755
+ handle = workerAcquired.handle
1756
+ workerTools = workerAcquired.tools
1757
+ workerRestriction = workerAcquired.restriction
1758
+ workerEpochRecord = workerAcquired.epoch
1759
+ workerEpochAbort = workerAcquired.epochAbort || null
1760
+ accounting = createConsolidationMeasurement('worker', { sessionId: childId, afterSeq: workerAcquired.eventCursor ?? workerEpochRecord.lastEventSeq })
1761
+ } else {
1762
+ childId = 'memu-consolidate-' + Date.now().toString(36) + '-' + crypto.randomBytes(3).toString('hex')
1763
+ // 种子只种这一窗:worker 看到的世界就是它要对账的那一段,窗口之外的事件
1764
+ // 留给下一批。seq 已按 compactSeedEvents 重排成从 0 连续,inheritedEventCount
1765
+ // 必须等于种子长度(不是父会话的 throughSeq),否则宿主会拒绝这份种子。
1766
+ // 保留仍存在的会话 cwd;旧目录失效时回退 dataDir,避免宿主拒绝启动回合。
1767
+ const forkCwd = resolveConsolidationCwd(header.cwd)
1768
+ const presetSelection = resolveConsolidationPreset(ctx, { sessionId, presetId: captured.agentPreset })
1769
+ try {
1770
+ handle = await agents.create({
1771
+ sessionId: childId,
1772
+ meta: {
1773
+ cwd: forkCwd,
1774
+ parentSession: sessionId,
1775
+ isSeeded: true,
1776
+ // Without this the fork is treated as an ordinary user conversation by
1777
+ // the injection path and the sidebar session lists.
1778
+ origin: 'subagent',
1779
+ // Use the session's active preset rather than immutable creation metadata.
1780
+ // Later preset selections are recorded by agent-preset/selected events.
1781
+ // Apply the event projection when choosing the fork preset.
1782
+ agentPreset: presetSelection.presetId,
1783
+ },
1784
+ inheritedEventCount: seedEvents.length,
1785
+ seed: buildForkSeed(seedEvents, seedEvents.length - 1),
1786
+ agentOptions,
1787
+ // 只写 meta.agentPreset 不会挂载预设(agent-loop 从不读它),fork 会跑根组合、
1788
+ // 整理出来的记忆不带那个人格的口吻。setup 里 mount 才是真挂上。
1789
+ setup: presetSetupFor(ctx, { selection: presetSelection, log: message => { try { ctx.logger?.warn?.('dsh-memu-memory: ' + message) } catch {} }, }),
1790
+ signal: abort.signal,
1791
+ })
1792
+ } catch (error) {
1793
+ // 宿主拒绝种子时最需要的诊断信息就在这条错误里("seed event at index …"),
1794
+ // 用独立 reasonCode 写进活动日志,别让它塌成一句 exception。
1795
+ const failure = String(error?.message || error)
1796
+ safeLedger(() => failJob({ sessionId, jobId, reasonCode: 'fork-create-failed', retryable: true, error: failure }))
1797
+ return finish({
1798
+ ok: false, sessionId, childId, settled: false, retryable: true,
1799
+ reasonCode: 'fork-create-failed',
1800
+ error: 'the host rejected the consolidation fork: ' + failure,
1801
+ })
1802
+ }
1803
+ }
1804
+
1805
+ // header 无法证明 worker 有写工具时(PTC 会话名单只有 run_code / 旧会话没有名单),
1806
+ // 把 worker 读写面挂进 fork 自己的 scope,保证 SDK 面(PTC)与原生面(普通会话)都真能写入。
1807
+ // 标准 preset 的 fork 名单里已有 memu_*(probe.hasWrite === true),不重复挂。
1808
+ // worker 模式:工具面只在初生挂一次(acquireWorker 内部处理),续窗跳过(§15.2 改动点 2)。
1809
+ if (!workerMode) {
1810
+ if (probe.hasWrite !== true) {
1811
+ workerTools = await attachWorkerTools(agents, childId, sessionId)
1812
+ }
1813
+ workerRestriction = await restrictWorkerTools(agents, childId, sessionId)
1814
+ }
1815
+ // Counters are shared by fork/worker; only the latter persists an epoch.
1816
+ if (!workerMode) {
1817
+ accounting = createConsolidationMeasurement('fork', { sessionId: childId })
1818
+ const brief = buildWorkerBrief({
1819
+ snapshot, probe, jobId, mustCover, autoReceipt: true, domain,
1820
+ contract: receiptContractText({ jobId, snapshotHash: snapshot.hash, autoReceipt: true }),
1821
+ reason: force ? 'manual' : 'auto', singleOnly: Boolean(binding.consolidationSingleOnly),
1822
+ })
1823
+ dispatchText = [buildPrivateConsolidationPrompt(sessionId), '', brief].join('\n')
1824
+ }
1825
+ accounting.measurement.packet = measurePacket(dispatchText, dispatchKind)
1826
+
1827
+ // 先记"已开始"再等结果:一个大会话的 fork 可能跑好几分钟,没有这条记录,
1828
+ // 侧边栏和日志页在等待期间只会显示上一次的结果,用户会以为按钮没生效。
1829
+ record({
1830
+ kind: 'consolidate',
1831
+ scope: 'private',
1832
+ sessionId,
1833
+ libraryId: binding.libraryId || null,
1834
+ ok: true,
1835
+ message: '整理已开始 · ' + (force ? '手动' : (options.trigger === 'backlog' ? '水位' : '空闲'))
1836
+ + ' · fork ' + childId.slice(-8)
1837
+ + ' · 窗口 ' + window.events.length + ' 条事件(父会话 ' + events.length + ' 条 / 新 ' + freshCount + ' 条)'
1838
+ + (window.remaining > 0 ? ' · 还余 ' + window.remaining : '')
1839
+ + ' · 预算 ' + Math.round(budgetMs / 1000) + 's · 快照 ' + snapshot.hash,
1840
+ detail: { childId, jobId, force, trigger: options.trigger || 'idle', events: window.events.length, transcriptEvents: events.length, fresh: freshCount, remaining: window.remaining, budgetMs, phase: 'started', snapshot: snapshotMeta,
1841
+ modelMode, runner: workerMode ? 'worker' : 'fork', measurement: accounting.measurement,
1842
+ probe: { source: probe.source, hasWrite: probe.hasWrite, ptc: probe.ptcObserved === true },
1843
+ ...workerToolsMeta(workerTools) },
1844
+ })
1845
+
1846
+ // turn/end 是这一轮的唯一权威结果;whenIdle 只说明 driver 停了(失败的回合也停)。
1847
+ // 顺带从同一个公共事件流里收三样东西:worker 的正文(回执在里面)、
1848
+ // 它的工具动作(用来在写入途中重验父授权),以及父会话自己是否动过。
1849
+ const childSession = handle?.agent?.session
1850
+ const parentAgent = (() => { try { return agents.get?.(sessionId) || null } catch { return null } })()
1851
+ const parentLive = parentAgent?.session || null
1852
+ const isParentSession = (session) => session === parentLive || (session && parentLive === null && session?.id === sessionId)
1853
+ const revalidate = (source) => {
1854
+ if (scopeChanged) return
1855
+ const now = scopeGenerationOf(getSessionBinding(sessionId))
1856
+ if (!generationAtStart || now === generationAtStart) return
1857
+ scopeChanged = { source, expected: generationAtStart, actual: now }
1858
+ record({
1859
+ kind: 'consolidate', scope: 'private', sessionId, libraryId: binding.libraryId || null, ok: false, level: 'warn',
1860
+ message: '整理作废:父会话授权变化(' + source + ')',
1861
+ detail: { jobId, childId, ...scopeChanged },
1862
+ })
1863
+ try { (workerMode && workerEpochAbort ? workerEpochAbort : abort).abort() } catch {}
1864
+ }
1865
+ if (typeof ctx.on === 'function' && childSession) {
1866
+ try {
1867
+ offSession = ctx.on('session/event', (session, event) => {
1868
+ if (session === childSession) {
1869
+ if (!accounting.observe(event)) return
1870
+ if (event?.type === 'turn/end') { turnEnd = event; return }
1871
+ if (event?.type === 'assistant/message') {
1872
+ const blocks = event?.data?.message?.content
1873
+ if (Array.isArray(blocks)) {
1874
+ for (const block of blocks) {
1875
+ if (block?.type === 'text' && typeof block.text === 'string' && block.text.trim()) {
1876
+ assistantTexts.push(block.text)
1877
+ }
1878
+ }
1879
+ }
1880
+ return
1881
+ }
1882
+ // 工具动作是写入的落点:每出现一次就重验一次父授权,变了立刻停掉这条 fork。
1883
+ if (event?.type === 'tool/call' || event?.type === 'tool/result' || event?.type === 'tool/ptc-dispatch' || event?.type === 'tool/ptc-dispatch-start') {
1884
+ revalidate('worker-write')
1885
+ workerToolRounds += 1
1886
+ if (workerToolRounds >= WORKER_HARD_STOP_ROUND) {
1887
+ // worker 模式 abort 的是绑在生命周期上的 epoch 控制器,硬停才真正生效;
1888
+ // 回合以 aborted 收尾 → turnEndFailure → 退役。fork 模式仍 abort 窗口 signal。
1889
+ try { (workerMode && workerEpochAbort ? workerEpochAbort : abort).abort() } catch {}
1890
+ } else {
1891
+ const guidance = workerRoundGuidance(workerToolRounds)
1892
+ if (guidance && workerToolRounds === WORKER_WRAPUP_ROUND) {
1893
+ try {
1894
+ const queued = handle.agent.followup(noticeMessage(guidance.text, '整理收尾提示'))
1895
+ accounting.dispatch(guidance.text, 'wrapup')
1896
+ Promise.resolve(queued).catch((error) => warn('consolidation wrapup followup failed: ' + describeError(error)))
1897
+ } catch (error) { warn('consolidation wrapup followup failed: ' + describeError(error)) }
1898
+ }
1899
+ }
1900
+ return
1901
+ }
1902
+ return
1903
+ }
1904
+ // 用户又说话了:父会话的库/域/上下文可能已经被切换,重新比一次指纹。
1905
+ if (isParentSession(session) && (event?.type === 'turn/start' || event?.type === 'user/message')) revalidate('parent-activity')
1906
+ })
1907
+ } catch {}
1908
+ }
1909
+
1910
+ // The fork must write into the parent's library, not derive one from its own
1911
+ // freshly minted session id.
1912
+ setSessionBinding(childId, {
1913
+ libraryId: binding.libraryId,
1914
+ consolidationFork: true,
1915
+ // 整理发生在几小时后,父会话此刻的心境不是这段转录里那件事的情绪,所以 fork
1916
+ // 不继承 mood。显式写 null 而不是留空:缺字段和「这一刻是中性」在写入时都走
1917
+ // 同一条兜底,但只有 null 能把「后台 worker 没有当下心境」说清楚。
1918
+ mood: null,
1919
+ // The fork writes memories on the same logical clock as its parent. Without
1920
+ // this the worker falls back to the wall clock at fork time; the per-turn
1921
+ // [事件时间] markers in the seed remain the authoritative override.
1922
+ sceneTime: binding.sceneTime || null,
1923
+ parentSessionId: sessionId,
1924
+ parentScopeGeneration: generationAtStart,
1925
+ snapshotHash: snapshot.hash,
1926
+ // 调试/测试用:worker 的回执范围必须和这两项一致,否则 completeJob 不会推进。
1927
+ snapshotFromSeq: snapshot.fromSeq,
1928
+ snapshotThroughSeq: snapshot.throughSeq,
1929
+ snapshotEventCount: snapshot.eventCount,
1930
+ jobId,
1931
+ scopeKey: binding.scopeKey,
1932
+ memoryOwnerSessionId: binding.memoryOwnerSessionId || sessionId,
1933
+ memoryContext: binding.memoryContext || {},
1934
+ useLibrary: true,
1935
+ useGlobal: binding.useGlobal === true,
1936
+ domain: binding.domain,
1937
+ domainOverride: binding.domainOverride || null,
1938
+ })
1939
+ // worker 模式(§15.2 改动点 3):子绑定补 epoch 副本;sceneTime 每窗重读父绑定
1940
+ // (RP 剧情可能推进;现状 fork 是诞生时定死一次,worker 路径每窗刷新,§6)。
1941
+ if (workerMode && workerEpochRecord) {
1942
+ const sceneTimeNow = (() => {
1943
+ try { return getSessionBinding(sessionId)?.sceneTime || binding.sceneTime || null } catch { return binding.sceneTime || null }
1944
+ })()
1945
+ setSessionBinding(childId, { workerEpoch: workerEpochRecord, sceneTime: sceneTimeNow })
1946
+ }
1947
+
1948
+ // 写入前最后一次重验:这次的授权还成立吗?不成立就别把 prompt 发出去。
1949
+ revalidate('pre-dispatch')
1950
+ if (scopeChanged) {
1951
+ // worker 模式:scope 已污染,立即退役且不交接(§4.5 条件 1)。
1952
+ if (workerMode && childId) { try { await retireWorker(ctx, childId, 'scope-change', { handoff: false }) } catch {} }
1953
+ safeLedger(() => failJob({ sessionId, jobId, reasonCode: 'parent-scope-changed', retryable: false, error: 'the parent conversation changed scope before dispatch' }))
1954
+ return finish({
1955
+ ok: false, sessionId, childId, settled: false, retryable: false, reasonCode: 'parent-scope-changed',
1956
+ error: 'the parent conversation switched library, scope or memory context before the worker was dispatched; nothing was credited',
1957
+ })
1958
+ }
1959
+
1960
+ // Measure exactly the final followup text, including all separators/briefs.
1961
+ handle.agent.followup(noticeMessage(dispatchText, '整理这场对话的私有记忆'))
1962
+ accounting.dispatch(dispatchText, dispatchKind)
1963
+ // followup only queues. whenIdle says the driver stopped; turn/end says
1964
+ // whether that turn actually succeeded, so both are checked below.
1965
+ idle = typeof handle.agent.whenIdle === 'function' ? handle.agent.whenIdle() : Promise.resolve()
1966
+ let timer = null
1967
+ let outcome
1968
+ try {
1969
+ const wait = new Promise((resolve) => { timer = setTimeout(() => resolve('timeout'), budgetMs) })
1970
+ outcome = await Promise.race([idle.then(() => 'done'), wait])
1971
+ } finally { clearTimeout(timer) }
1972
+
1973
+ // worker 模式 epoch 记账(§4.5/§15.2 改动点 3):本窗增量 + 观测到的 worker 产出
1974
+ // 并入 chars、windows +1;whenIdle 正常完成记 lastIdleAt(条件 4 的 TTL 起算点)。
1975
+ // 结算成功后的超时清零在 completeJob 之后单独落一次。
1976
+ if (workerMode) {
1977
+ workerEpochRecord = recordEpochProgress({ sessionId }, {
1978
+ measurement: accounting.measurement,
1979
+ idleAt: outcome === 'done' ? Date.now() : null,
1980
+ }) || workerEpochRecord
1981
+ }
1982
+
1983
+ let wrote = null
1984
+ let decision = null
1985
+ let completion = null
1986
+ if (outcome === 'done') {
1987
+ const failure = turnEndFailure(turnEnd)
1988
+ if (failure) {
1989
+ // batch 参数的 JSON 畸形是模型生成问题,不是整理逻辑故障:标记下一次
1990
+ // 只用逐条 remember,并让重试路径接住(consolidateAll 已有 2 次重试)。
1991
+ const batchJsonInvalid = /memu_private_remember_batch/.test(String(failure))
1992
+ && /JSON|Expected ','|after array element/.test(String(failure))
1993
+ const outputLimited = turnEnd?.data?.reason?.kind === 'max-tokens'
1994
+ const execution = outputLimited ? executionContext : null
1995
+ const reasonCode = outputLimited ? 'model-output-limit' : batchJsonInvalid ? 'batch-json-invalid' : 'fork-turn-failed'
1996
+ const outputLimitError = outputLimited
1997
+ ? failure + '; 输出预算不足(含思考/剩余上下文限制),请调整宿主最大输出 token 或使用模型支持的思考档位;待处理范围未结算'
1998
+ : failure
1999
+ // 思考强度不被支持 = 配置与模型不匹配,失败发生在回合起点、代价极小:
2000
+ // 学习该组合(下次 fork 不带档)并把本次标记可重试,让下一次扫描很快接住。
2001
+ const effortRefusal = effortRefusalOf(failure)
2002
+ if (effortRefusal) {
2003
+ markEffortRefused(effortRefusal.key)
2004
+ // 同时清掉该快照的失败连击:失败是配置不匹配(已学习),不是这段转录有病——
2005
+ // 不清零的话 snapshot-failed-too-many 闸门会让自动重试永远进不来。
2006
+ safeLedger(() => recordOperation({ sessionId, key: opKey, outcome: 'failed', ids: [] }))
2007
+ }
2008
+ if (batchJsonInvalid) setSessionBinding(sessionId, { consolidationSingleOnly: true })
2009
+ // worker 模式:回合失败即退役条件 5,不带病工作、不做交接(§4.5)。
2010
+ if (workerMode && childId) { try { await retireWorker(ctx, childId, 'failure', { handoff: false }) } catch {} }
2011
+ const retryable = outputLimited || batchJsonInvalid || Boolean(effortRefusal)
2012
+ safeLedger(() => failJob({ sessionId, jobId, reasonCode, retryable, error: outputLimitError, executionKey: execution?.key || null, executionSettingsKey: execution?.settingsKey || null, executionDefaultsComparable: execution?.defaultsComparable ?? true }))
2013
+ return finish({
2014
+ ok: false, error: 'consolidation fork failed: ' + outputLimitError, sessionId, childId,
2015
+ settled: false, timedOut: false, retryable, reasonCode,
2016
+ ...(outputLimited ? { configuredMaxTokens: agentOptions.maxTokens ?? execution.maxTokens } : {}),
2017
+ })
2018
+ }
2019
+ // 父授权重验:写入可能已经落了一部分,但凭证只有在授权还成立时才算数。
2020
+ const generationNow = scopeGenerationOf(getSessionBinding(sessionId))
2021
+ if (scopeChanged || (generationAtStart && generationNow !== generationAtStart)) {
2022
+ if (workerMode && childId) { try { await retireWorker(ctx, childId, 'scope-change', { handoff: false }) } catch {} }
2023
+ safeLedger(() => failJob({ sessionId, jobId, reasonCode: 'parent-scope-changed', retryable: false, error: 'the parent conversation changed scope during consolidation' }))
2024
+ return finish({
2025
+ ok: false, sessionId, childId, settled: false, retryable: false, reasonCode: 'parent-scope-changed',
2026
+ error: 'the parent conversation switched library, scope or memory context while the worker was running; the result was not credited (writes that already landed stay in the library, the range stays pending)',
2027
+ })
2028
+ }
2029
+ // 兼容字段 lastSleepSeq 只能跟着凭证走:没有对账过的结果就不算整理过,
2030
+ // Otherwise the legacy cursor could mark failed work as completed.
2031
+ if (beforeIds) {
2032
+ try {
2033
+ const afterIds = Object.keys(loadPrivateIndex(binding.libraryId).entries)
2034
+ wrote = afterIds.filter((id) => !beforeIds.has(id)).length
2035
+ } catch { wrote = null }
2036
+ }
2037
+ let index = null
2038
+ try { index = loadPrivateIndex(binding.libraryId) } catch { index = null }
2039
+ // 完成不是"没报错":worker 的回执 + 库里的真实变化,两边对上才结算。
2040
+ const workerText = assistantTexts.join('\n')
2041
+ decision = decideCompletion({
2042
+ text: workerText,
2043
+ wrote,
2044
+ index,
2045
+ beforeIds,
2046
+ beforeEntries,
2047
+ expectedJobId: jobId,
2048
+ expectedSnapshotHash: snapshot.hash,
2049
+ autoReceipt: { jobId, snapshotHash: snapshot.hash, checkedRange: { fromSeq: snapshot.fromSeq, throughSeq: snapshot.throughSeq } },
2050
+ })
2051
+
2052
+ if (!decision.advance) {
2053
+ // worker 模式:对账不过 = 退役条件 5(无交接);已写入的条目保留,区间回 pending。
2054
+ if (workerMode && childId) { try { await retireWorker(ctx, childId, 'failure', { handoff: false }) } catch {} }
2055
+ safeLedger(() => failJob({
2056
+ sessionId, jobId, reasonCode: decision.reasonCode || 'not-settled',
2057
+ retryable: decision.retryable !== false, error: decision.error || null,
2058
+ }))
2059
+ return finish({
2060
+ ok: false, sessionId, childId, settled: false, retryable: decision.retryable !== false,
2061
+ status: decision.status, outcome: decision.outcome, reasonCode: decision.reasonCode,
2062
+ counts: decision.counted || null, snapshot: snapshotMeta,
2063
+ error: decision.error || ('consolidation result was not verified: ' + String(decision.reasonCode || 'unknown')),
2064
+ })
2065
+ }
2066
+ completion = safeLedger(() => completeJob({
2067
+ sessionId, jobId, snapshot,
2068
+ covered: decision.covered,
2069
+ status: decision.status,
2070
+ outcome: decision.outcome,
2071
+ reasonCode: decision.reasonCode,
2072
+ retryable: decision.retryable === true,
2073
+ counts: decision.counted,
2074
+ receipt: decision.receipt,
2075
+ }))
2076
+ if (!completion?.advanced) {
2077
+ return finish({ ok: false, sessionId, childId, settled: false, retryable: true,
2078
+ reasonCode: 'ledger-not-advanced', snapshot: snapshotMeta,
2079
+ error: 'the consolidation ledger could not verify the covered snapshot range' })
2080
+ }
2081
+ advanceSleepCursor(sessionId, snapshot.throughSeq, { consolidationSingleOnly: false })
2082
+ // worker 模式:结算成功清超时连击、清「上窗未结算」标记(下一窗增量包不再带核对说明)。
2083
+ if (workerMode) {
2084
+ workerEpochRecord = recordEpochProgress({ sessionId }, { settled: true, progress: false }) || workerEpochRecord
2085
+ setSessionBinding(sessionId, { consolidationPending: null })
2086
+ }
2087
+ // 候选跨窗顺延:本窗没写进库的候选留给下一窗的必写清单;最后一窗也在同一份
2088
+ // brief 里见到它们,不需要为了补写再开一次整窗 fork。核验纯本地,0 Token。
2089
+ const writtenIds = [...(decision.createdIds || []), ...(decision.updatedIds || []), ...(decision.heldIds || [])]
2090
+ const missed = mustCover.filter((candidate) => !candidateCovered(candidate, writtenIds, index))
2091
+ safeLedger(() => setCarryCandidates(sessionId, missed))
2092
+ // 摘要要覆盖 created/updated/held 全部落库 id(设计 §4.2),不只 created——
2093
+ // 否则续窗 worker 看不到已 update/held 的条目,可能重复尝试。ids 仅供摘要,不参与判同。
2094
+ safeLedger(() => recordOperation({ sessionId, key: opKey, outcome: decision.status, ids: writtenIds }))
2095
+ // 私有自动关联(§5.6 兜底):只在整理真的对账并推进边界之后跑,纯算法,
2096
+ // 0 token。worker 若已调用 memu_private_link_suggest,这一遍是幂等的(已有的
2097
+ // relation/person 边会跳过)。link 只是图元数据:失败只记 warn,绝不能让一次
2098
+ // 已经成功的整理变成失败;timeout / unsettled / ledger-not-advanced 三条路径
2099
+ // 走不到这里,所以它们不会触发自动关联。
2100
+ const linkIds = [...(decision.createdIds || []), ...(decision.updatedIds || [])]
2101
+ if (linkIds.length) {
2102
+ try {
2103
+ await autoLinkPrivateMemories({ libraryId: binding.libraryId, sessionId, ids: linkIds })
2104
+ } catch (error) {
2105
+ // autoLinkPrivateMemories 自己已捕获操作性失败;这里只兜"意料之外"的抛错。
2106
+ try { warn('private auto-link after consolidation skipped: ' + String(error?.message || error)) } catch {}
2107
+ }
2108
+ }
2109
+ }
2110
+ // A timeout is not success: the fork may still be mid-write. It has to come
2111
+ // back with a message, not just `timedOut` — the settings button renders
2112
+ // `result.error` and an empty string there is indistinguishable from a click
2113
+ // that did nothing at all (observed: two clicks, no feedback, no memories).
2114
+ if (outcome === 'timeout') {
2115
+ if (workerMode) {
2116
+ // 持久模式(§4.4):超时 = 废弃本回合的结算,不废弃 worker。已写入的条目保留
2117
+ // (本来如此);游标不进(failJob 照旧);区间回 pending;下一窗增量包开头带
2118
+ // 「上窗未结算」核对说明(consolidationPending 标记)。连续 2 次超时升级退役
2119
+ // (防反复卡死吃窗口),退役允许交接——worker 上下文没坏,只是慢。
2120
+ workerEpochRecord = recordEpochProgress({ sessionId }, { timeout: true, progress: false }) || workerEpochRecord
2121
+ setSessionBinding(sessionId, { consolidationPending: { snapshotHash: snapshot.hash, jobId, at: new Date().toISOString() } })
2122
+ if ((Number(workerEpochRecord?.timeouts) || 0) >= WORKER_TIMEOUT_LIMIT) {
2123
+ try { await retireWorker(ctx, childId, 'timeout-x2', { handoff: true }) } catch {}
2124
+ }
2125
+ } else {
2126
+ // Stop the writer before releasing the range, not after. Waiting matters here
2127
+ // because a tool call already in flight can still land a memory on disk, and the
2128
+ // range going back to pending is what lets the next pass redo this window.
2129
+ await stopWorker()
2130
+ }
2131
+ safeLedger(() => failJob({
2132
+ sessionId, jobId, reasonCode: 'timeout',
2133
+ error: workerMode
2134
+ ? 'timed out before a receipt; the turn was abandoned and the range is pending again (a tool call already in flight may have written; the worker is kept for the next window)'
2135
+ : 'timed out before a receipt; the worker was stopped first, but a tool call already in flight may have written',
2136
+ }))
2137
+ return finish({
2138
+ ok: false,
2139
+ sessionId,
2140
+ childId,
2141
+ settled: false,
2142
+ timedOut: true,
2143
+ reasonCode: 'timeout',
2144
+ // The next pass must not assume this window left nothing behind: the range is
2145
+ // pending again and some writes may already have landed.
2146
+ partialWritesPossible: true,
2147
+ error: workerMode
2148
+ ? 'consolidation timed out after ' + Math.round(budgetMs / 1000) + 's over ' + window.events.length + ' events; the turn was abandoned and the range was released (memories written before the timeout are kept, the worker is kept). Retry, or consolidate a shorter conversation.'
2149
+ : 'consolidation timed out after ' + Math.round(budgetMs / 1000) + 's over ' + window.events.length + ' events; the fork was stopped before the range was released (memories written before the timeout are kept). Retry, or consolidate a shorter conversation.',
2150
+ })
2151
+ }
2152
+ return finish({
2153
+ ok: outcome === 'done',
2154
+ sessionId,
2155
+ childId,
2156
+ settled: outcome === 'done',
2157
+ timedOut: false,
2158
+ status: decision?.status || null,
2159
+ outcome: decision?.outcome || null,
2160
+ reasonCode: decision?.reasonCode || null,
2161
+ counts: decision?.counted || null,
2162
+ createdIds: decision?.createdIds || [],
2163
+ updatedIds: decision?.updatedIds || [],
2164
+ heldIds: decision?.heldIds || [],
2165
+ receipt: decision?.receipt
2166
+ ? { status: decision.receipt.status, outcome: decision.receipt.outcome, reasonCode: decision.receipt.reasonCode }
2167
+ : null,
2168
+ credential: completion?.checked ? { checked: completion.checked, pending: completion.pending } : null,
2169
+ snapshot: snapshotMeta,
2170
+ scanned: window.events.length,
2171
+ fresh: freshCount,
2172
+ remaining: window.remaining,
2173
+ window: { fromSeq: window.fromSeq, throughSeq: window.throughSeq },
2174
+ wrote,
2175
+ })
2176
+ } catch (error) {
2177
+ // worker 模式:异常 = 退役条件 5(无交接);fork 模式的销毁留给 finally。
2178
+ if (workerMode && childId && handle) { try { await retireWorker(ctx, childId, 'failure', { handoff: false }) } catch {} }
2179
+ if (jobId) safeLedger(() => failJob({ sessionId, jobId, reasonCode: 'exception', error: String(error?.message || error) }))
2180
+ return finish({ ok: false, sessionId, settled: false, reasonCode: 'exception', error: String(error?.message || error) })
2181
+ } finally {
2182
+ inFlight.delete(sessionId)
2183
+ if (workerMode) {
2184
+ // 持久 worker(§15.2 改动点 6):每窗 finally 只清 inFlight 与本轮局部资源——
2185
+ // per-window 重验监听随窗摘除;worker 本体、工具面与子绑定留给 epoch
2186
+ // (retireWorker 与插件停用负责销毁)。'fork' 路径的清理原样保留。
2187
+ try { offSession?.() } catch {}
2188
+ } else {
2189
+ try { await stopWorker() } catch {}
2190
+ try { workerTools?.dispose?.() } catch {}
2191
+ try { workerRestriction?.dispose?.() } catch {}
2192
+ try { if (childId) deleteSessionBinding(childId) } catch {}
2193
+ }
2194
+ }
2195
+ }
2196
+ export function isConsolidating(sessionId) {
2197
+ return inFlight.has(sessionId)
2198
+ }