dsh-memu-memory 1.4.2 → 1.4.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (389) hide show
  1. package/AGENTS.md +108 -110
  2. package/CHANGELOG.md +169 -868
  3. package/LICENSE +21 -21
  4. package/README.md +368 -374
  5. package/README.zh.md +354 -360
  6. package/assets/icon.svg +7 -7
  7. package/cordis.patch.yml +8 -8
  8. package/docs/active-memory-ab.md +279 -385
  9. package/docs/binding-lifecycle.md +99 -99
  10. package/docs/client-conventions.md +75 -75
  11. package/docs/contributing.md +217 -217
  12. package/docs/emotion-model-spec.md +247 -281
  13. package/docs/env-and-commands.md +149 -152
  14. package/docs/host-adaptation.md +339 -360
  15. package/docs/host-api.md +131 -137
  16. package/docs/host-versions.md +117 -120
  17. package/docs/mcp-porting.md +146 -146
  18. package/docs/memory-semantics.md +271 -259
  19. package/docs/pending-work.md +44 -51
  20. package/docs/troubleshooting.md +909 -854
  21. package/lib/active-memory.js +160 -165
  22. package/lib/activity-log.js +207 -207
  23. package/lib/auto-link/apply.js +248 -249
  24. package/lib/auto-link/candidates.js +163 -163
  25. package/lib/auto-link/decide.js +300 -300
  26. package/lib/auto-link/normalize.js +99 -99
  27. package/lib/auto-link/policy.js +42 -42
  28. package/lib/auto-link/suppression.js +101 -101
  29. package/lib/auto-link/terminology.js +311 -311
  30. package/lib/backup.js +1254 -1254
  31. package/lib/binding-diagnostics.js +634 -634
  32. package/lib/budget.js +118 -118
  33. package/lib/client.js +9820 -9751
  34. package/lib/commitment.js +178 -138
  35. package/lib/consolidation-ledger.js +434 -438
  36. package/lib/consolidation-receipt.js +386 -387
  37. package/lib/consolidation-snapshot.js +420 -405
  38. package/lib/consolidation-worker.js +240 -241
  39. package/lib/context.js +33 -33
  40. package/lib/curator-evidence.js +131 -131
  41. package/lib/curator-policy.js +198 -202
  42. package/lib/curator.js +1813 -1811
  43. package/lib/cycle.js +524 -513
  44. package/lib/diagnostics.js +524 -524
  45. package/lib/embedding-catalog.js +1051 -1055
  46. package/lib/embedding-download.js +637 -607
  47. package/lib/embedding-runtime.js +946 -946
  48. package/lib/engine.js +1103 -1103
  49. package/lib/entity-repair.js +285 -285
  50. package/lib/environment-check.js +394 -394
  51. package/lib/fork-model.js +312 -312
  52. package/lib/freshness.js +128 -121
  53. package/lib/global-graph.js +389 -389
  54. package/lib/graph.js +1193 -1193
  55. package/lib/host-surface.js +30 -30
  56. package/lib/inbound.js +284 -281
  57. package/lib/index.js +506 -511
  58. package/lib/inject.js +2639 -2619
  59. package/lib/lexicon-scope.js +143 -143
  60. package/lib/lexicon.js +1183 -1192
  61. package/lib/lifecycle-audit.js +37 -0
  62. package/lib/local-embedding-entry.js +145 -145
  63. package/lib/local-embedding-manager.js +306 -306
  64. package/lib/local-embedding-protocol.js +210 -210
  65. package/lib/local-embedding-worker.js +682 -682
  66. package/lib/local-vector-service.js +506 -453
  67. package/lib/maintenance-ledger.js +138 -0
  68. package/lib/maintenance-review.js +103 -0
  69. package/lib/maintenance-runner.js +267 -0
  70. package/lib/managed-runtime.js +118 -118
  71. package/lib/media.js +607 -513
  72. package/lib/memory.js +5035 -4941
  73. package/lib/memu-config.js +213 -213
  74. package/lib/memu.js +565 -565
  75. package/lib/migrate.js +200 -200
  76. package/lib/mood.js +300 -300
  77. package/lib/paths.js +453 -457
  78. package/lib/port-surface.js +82 -82
  79. package/lib/preset-mount.js +79 -0
  80. package/lib/preset-scope.js +126 -126
  81. package/lib/private-links.js +567 -567
  82. package/lib/private.js +2198 -2209
  83. package/lib/prompts/global-curator.md +135 -135
  84. package/lib/prompts/image-caption.md +1 -1
  85. package/lib/prompts/private-consolidation.coding.md +39 -39
  86. package/lib/prompts/private-consolidation.md +32 -32
  87. package/lib/prompts/private-consolidation.mixed.md +37 -37
  88. package/lib/prompts/private-consolidation.rp.md +47 -47
  89. package/lib/prompts/private-policy.coding.md +35 -35
  90. package/lib/prompts/private-policy.md +36 -36
  91. package/lib/prompts/private-policy.mixed.md +29 -29
  92. package/lib/prompts/private-policy.rp.md +43 -43
  93. package/lib/prompts/system-guide.coding.md +20 -20
  94. package/lib/prompts/system-guide.md +25 -25
  95. package/lib/prompts/system-guide.mixed.md +22 -22
  96. package/lib/prompts/system-guide.rp.md +23 -23
  97. package/lib/prompts.js +331 -331
  98. package/lib/recall-cache.js +212 -212
  99. package/lib/remote-summary.js +123 -123
  100. package/lib/rpc.js +2531 -2532
  101. package/lib/salient-wake.js +438 -438
  102. package/lib/snippet.js +125 -125
  103. package/lib/state.js +1948 -1928
  104. package/lib/stats.js +236 -236
  105. package/lib/temporal.js +345 -348
  106. package/lib/text-retrieval.js +992 -1001
  107. package/lib/text-similarity.js +305 -305
  108. package/lib/tokenizer-v2.js +271 -271
  109. package/lib/tools.js +1098 -1091
  110. package/lib/turn-log.js +545 -545
  111. package/lib/vector-migration.js +928 -930
  112. package/lib/vector-profile.js +1353 -1359
  113. package/lib/visibility.js +59 -59
  114. package/lib/webui/graph-LICENSE.txt +1 -1
  115. package/lib/webui/graph-view.bundle.js +2 -2
  116. package/lib/webui/graph-view.js +1171 -1175
  117. package/lib/webui/mark.svg +7 -7
  118. package/lib/webui/standalone.css +1178 -1178
  119. package/lib/webui/standalone.js +238 -238
  120. package/lib/webui.js +136 -136
  121. package/lib/worker-pool.js +1015 -979
  122. package/package.json +153 -153
  123. package/requirements.lock +34 -34
  124. package/scripts/acceptance-local.mjs +946 -946
  125. package/scripts/active-memory-ab-live.mjs +653 -655
  126. package/scripts/active-memory-ab.mjs +1302 -1302
  127. package/scripts/audit-memory-lifecycle.mjs +55 -0
  128. package/scripts/bench-recall.mjs +142 -142
  129. package/scripts/build-graph.mjs +44 -45
  130. package/scripts/chain-matrix.mjs +541 -541
  131. package/scripts/check-all.mjs +68 -74
  132. package/scripts/check-doc-drift.mjs +547 -547
  133. package/scripts/check-graph-browser.mjs +261 -261
  134. package/scripts/check-i18n.mjs +81 -83
  135. package/scripts/check-idle-compositing.mjs +61 -61
  136. package/scripts/check-seed-compat.mjs +115 -118
  137. package/scripts/check-text-format.mjs +55 -0
  138. package/scripts/curator-pair-calibrate.mjs +259 -259
  139. package/scripts/diagnose-bindings.mjs +176 -176
  140. package/scripts/drive-session.mjs +863 -864
  141. package/scripts/engine-smoke.mjs +69 -69
  142. package/scripts/entity-dedupe.mjs +110 -110
  143. package/scripts/lexicon-calibrate.mjs +230 -230
  144. package/scripts/lexicon-dedupe.mjs +318 -318
  145. package/scripts/local-runtime-install.mjs +142 -142
  146. package/scripts/local-runtime-verify.mjs +56 -56
  147. package/scripts/local-vector-verify.mjs +93 -93
  148. package/scripts/make-readme-shots.mjs +59 -59
  149. package/scripts/migrate-visibility.mjs +94 -94
  150. package/scripts/mock-llm.mjs +938 -903
  151. package/scripts/preview.mjs +58 -58
  152. package/scripts/prune-sessions.mjs +31 -34
  153. package/scripts/prune-turnlogs.mjs +29 -30
  154. package/scripts/prune-vectors.mjs +24 -24
  155. package/scripts/rebuild-auto-links.mjs +252 -252
  156. package/scripts/recall-bench.mjs +820 -820
  157. package/scripts/repetition-ab-scenarios.mjs +93 -93
  158. package/scripts/repetition-detector-snapshot.mjs +314 -314
  159. package/scripts/repetition-eval-live.mjs +360 -360
  160. package/scripts/repetition-eval.mjs +702 -702
  161. package/scripts/replay.mjs +705 -575
  162. package/scripts/setup.mjs +46 -46
  163. package/scripts/simulate-injection.mjs +299 -301
  164. package/tests/absorb-review.test.mjs +354 -354
  165. package/tests/activation.test.mjs +89 -89
  166. package/tests/active-memory-ab.test.mjs +745 -745
  167. package/tests/active-memory.test.mjs +129 -129
  168. package/tests/activity-log.test.mjs +126 -126
  169. package/tests/activity-wiring.test.mjs +155 -155
  170. package/tests/appendix-b.test.mjs +217 -217
  171. package/tests/appendix-b2.test.mjs +166 -166
  172. package/tests/audit-batch3.test.mjs +247 -247
  173. package/tests/audit-regression.test.mjs +275 -275
  174. package/tests/audit-safety.test.mjs +227 -227
  175. package/tests/auto-link-candidates.test.mjs +245 -245
  176. package/tests/auto-link-decide.test.mjs +512 -512
  177. package/tests/auto-link-migration.test.mjs +133 -133
  178. package/tests/backend-compensation.test.mjs +272 -272
  179. package/tests/backup.test.mjs +793 -793
  180. package/tests/binding-diagnostics.test.mjs +720 -720
  181. package/tests/browser.test.mjs +476 -476
  182. package/tests/client-export.test.mjs +521 -521
  183. package/tests/client-render.test.mjs +2008 -1728
  184. package/tests/coalesce.test.mjs +113 -113
  185. package/tests/commitment.test.mjs +243 -144
  186. package/tests/config.test.mjs +159 -159
  187. package/tests/consolidation-credential.test.mjs +330 -330
  188. package/tests/consolidation-feed.test.mjs +122 -122
  189. package/tests/consolidation-fork.test.mjs +1586 -1539
  190. package/tests/consolidation-ledger.test.mjs +389 -389
  191. package/tests/consolidation-snapshot.test.mjs +567 -505
  192. package/tests/consolidation-value.test.mjs +89 -89
  193. package/tests/context-scope.test.mjs +40 -40
  194. package/tests/cross-library-recall.test.mjs +269 -269
  195. package/tests/cue.test.mjs +58 -58
  196. package/tests/curator-absorb.test.mjs +444 -444
  197. package/tests/curator-calibrate.test.mjs +173 -173
  198. package/tests/curator-clusters.test.mjs +306 -306
  199. package/tests/curator-commit.test.mjs +325 -325
  200. package/tests/curator-contract.test.mjs +191 -191
  201. package/tests/curator-evidence.test.mjs +102 -102
  202. package/tests/curator-link.test.mjs +317 -317
  203. package/tests/curator-pairing.test.mjs +339 -339
  204. package/tests/curator-probe.test.mjs +490 -490
  205. package/tests/curator-review-mode.test.mjs +315 -315
  206. package/tests/curator.test.mjs +152 -152
  207. package/tests/cycle.test.mjs +567 -568
  208. package/tests/diagnostics.test.mjs +278 -278
  209. package/tests/disclosure.test.mjs +249 -249
  210. package/tests/doc-drift.test.mjs +342 -342
  211. package/tests/drive-session.test.mjs +152 -152
  212. package/tests/dynamic-rrf.test.mjs +182 -182
  213. package/tests/dynamic-threshold.test.mjs +52 -52
  214. package/tests/embedding-catalog.test.mjs +374 -374
  215. package/tests/embedding-download.test.mjs +529 -486
  216. package/tests/embedding-runtime.test.mjs +449 -449
  217. package/tests/emotion-chain.test.mjs +84 -84
  218. package/tests/emotion-contract.test.mjs +445 -445
  219. package/tests/engine.test.mjs +108 -108
  220. package/tests/entity-merge.test.mjs +278 -278
  221. package/tests/environment-check.test.mjs +187 -187
  222. package/tests/fact-version.test.mjs +146 -146
  223. package/tests/fixtures/active-memory-ab/README.md +56 -56
  224. package/tests/fixtures/active-memory-ab/cases/01-clean-dense-turn.json +351 -351
  225. package/tests/fixtures/active-memory-ab/cases/02-clean-thin-turn.json +122 -122
  226. package/tests/fixtures/active-memory-ab/cases/03-clean-starved-small.json +125 -125
  227. package/tests/fixtures/active-memory-ab/cases/04-clean-large-thin.json +137 -137
  228. package/tests/fixtures/active-memory-ab/cases/05-clean-half-step.json +166 -166
  229. package/tests/fixtures/active-memory-ab/cases/06-clean-duplicate-reread.json +197 -197
  230. package/tests/fixtures/active-memory-ab/cases/07-clean-recent-recall.json +125 -125
  231. package/tests/fixtures/active-memory-ab/cases/08-global-relevant.json +111 -111
  232. package/tests/fixtures/active-memory-ab/cases/09-global-irrelevant-conflict.json +158 -158
  233. package/tests/fixtures/active-memory-ab/cases/10-no-human-turn.json +97 -97
  234. package/tests/fixtures/active-memory-ab/cases/11-clean-scale-100.json +137 -137
  235. package/tests/fixtures/active-memory-ab/cases/12-clean-scale-1000.json +137 -137
  236. package/tests/fixtures/active-memory-ab/cases/13-clean-scale-5000.json +137 -137
  237. package/tests/fixtures/active-memory-ab/cases/14-clean-scale-20000.json +137 -137
  238. package/tests/fixtures/active-memory-ab/lead-ai-reviewed-reference.json +191 -191
  239. package/tests/fixtures/active-memory-ab/manifest.json +199 -199
  240. package/tests/fixtures/curator-pairs/labeled.v1.jsonl +90 -90
  241. package/tests/fixtures/lexicon-stub-hooks.mjs +15 -15
  242. package/tests/fixtures/lexicon-stub.mjs +284 -284
  243. package/tests/fixtures/mock-llm/reply.txt +1 -1
  244. package/tests/fixtures/recall-bench/01-paraphrase.json +183 -183
  245. package/tests/fixtures/recall-bench/02-exact.json +152 -152
  246. package/tests/fixtures/recall-bench/03-negation.json +172 -172
  247. package/tests/fixtures/recall-bench/04-no-answer.json +161 -161
  248. package/tests/fixtures/recall-bench/05-conflict.json +193 -193
  249. package/tests/fixtures/recall-bench/06-boundary.json +272 -272
  250. package/tests/fixtures/recall-bench/07-secret.json +190 -190
  251. package/tests/fixtures/recall-bench/08-coding.json +163 -163
  252. package/tests/fixtures/recall-bench-gold-candidates/01-paraphrase.json +193 -193
  253. package/tests/fixtures/recall-bench-gold-candidates/02-exact.json +197 -197
  254. package/tests/fixtures/recall-bench-gold-candidates/03-negation.json +244 -244
  255. package/tests/fixtures/recall-bench-gold-candidates/04-no-answer.json +189 -189
  256. package/tests/fixtures/recall-bench-gold-candidates/05-conflict.json +245 -245
  257. package/tests/fixtures/recall-bench-gold-candidates/06-boundary.json +279 -279
  258. package/tests/fixtures/recall-bench-gold-candidates/07-secret.json +224 -224
  259. package/tests/fixtures/recall-bench-gold-candidates/08-coding.json +218 -218
  260. package/tests/fixtures/repetition-eval/01-zh-rp.json +92 -92
  261. package/tests/fixtures/repetition-eval/02-en.json +96 -96
  262. package/tests/fixtures/repetition-eval/03-code.json +90 -90
  263. package/tests/fixtures/repetition-eval/04-names.json +115 -115
  264. package/tests/fixtures/repetition-eval/05-user-quote.json +95 -95
  265. package/tests/fixtures/repetition-eval/06-agreement.json +85 -85
  266. package/tests/fixtures/tokenizer-cases.mjs +27 -27
  267. package/tests/fork-model.test.mjs +345 -345
  268. package/tests/freshness.test.mjs +140 -140
  269. package/tests/global-graph.test.mjs +106 -106
  270. package/tests/global-lifecycle.test.mjs +149 -149
  271. package/tests/graph-cascade.test.mjs +363 -363
  272. package/tests/graph-view.test.mjs +414 -414
  273. package/tests/graph.test.mjs +371 -371
  274. package/tests/help-page.test.mjs +416 -416
  275. package/tests/hook-order.test.mjs +72 -72
  276. package/tests/humanlike.test.mjs +232 -232
  277. package/tests/hybrid-recall.test.mjs +610 -610
  278. package/tests/inbound.test.mjs +441 -441
  279. package/tests/inject-conflict.test.mjs +173 -173
  280. package/tests/inject-guide.test.mjs +513 -513
  281. package/tests/inject.test.mjs +384 -384
  282. package/tests/injection-budget-settings.test.mjs +35 -35
  283. package/tests/injection-budget.test.mjs +165 -165
  284. package/tests/injection-chain.test.mjs +442 -442
  285. package/tests/injection-intent-budget.test.mjs +92 -92
  286. package/tests/injection-rollback.test.mjs +428 -428
  287. package/tests/issue2-chain.test.mjs +169 -169
  288. package/tests/lexical-bm25.test.mjs +171 -171
  289. package/tests/lexicon-calibrate.test.mjs +48 -48
  290. package/tests/lexicon-dedupe.test.mjs +171 -171
  291. package/tests/lexicon-frequency.test.mjs +195 -195
  292. package/tests/lexicon-inject.test.mjs +459 -459
  293. package/tests/lexicon-perf.test.mjs +464 -464
  294. package/tests/lexicon-scope.test.mjs +256 -256
  295. package/tests/lexicon-ui.test.mjs +667 -667
  296. package/tests/lexicon.test.mjs +922 -922
  297. package/tests/lifecycle-audit.test.mjs +56 -0
  298. package/tests/loader-register.mjs +3 -3
  299. package/tests/loader.mjs +17 -17
  300. package/tests/local-embedding-entry.test.mjs +95 -95
  301. package/tests/local-embedding-env.test.mjs +51 -51
  302. package/tests/local-embedding-manager.test.mjs +494 -494
  303. package/tests/local-embedding-protocol.test.mjs +121 -121
  304. package/tests/local-embedding-worker.test.mjs +440 -440
  305. package/tests/local-vector-service.test.mjs +41 -0
  306. package/tests/maintenance-status.test.mjs +77 -0
  307. package/tests/maintenance.test.mjs +438 -0
  308. package/tests/managed-memory.test.mjs +1234 -1234
  309. package/tests/managed-runtime.test.mjs +72 -72
  310. package/tests/media-injection.test.mjs +225 -0
  311. package/tests/media.test.mjs +135 -135
  312. package/tests/memory-chain.test.mjs +169 -169
  313. package/tests/memory-fields.test.mjs +134 -134
  314. package/tests/memu-resident-route.test.mjs +130 -130
  315. package/tests/memu-resident.test.mjs +33 -33
  316. package/tests/migration-payload.test.mjs +40 -42
  317. package/tests/mock-llm.test.mjs +263 -225
  318. package/tests/mood.test.mjs +109 -109
  319. package/tests/multiprocess.test.mjs +29 -29
  320. package/tests/negation-polarity.test.mjs +135 -135
  321. package/tests/new-session-gate.test.mjs +617 -617
  322. package/tests/open-loop-date.test.mjs +416 -416
  323. package/tests/ops-hardening.test.mjs +209 -209
  324. package/tests/package-shipping.test.mjs +88 -88
  325. package/tests/pending-injection.test.mjs +107 -107
  326. package/tests/port-surface.test.mjs +138 -138
  327. package/tests/preset-mount.test.mjs +124 -0
  328. package/tests/preset-scope.test.mjs +212 -212
  329. package/tests/private-links.test.mjs +493 -493
  330. package/tests/prompt-semantics.test.mjs +51 -51
  331. package/tests/prompts.test.mjs +315 -315
  332. package/tests/query-decompose.test.mjs +62 -62
  333. package/tests/react-snapshot.test.mjs +24 -24
  334. package/tests/recall-bench.test.mjs +317 -317
  335. package/tests/recall-cache.test.mjs +292 -292
  336. package/tests/recall-corpus-eligibility.test.mjs +51 -51
  337. package/tests/recall-dedup.test.mjs +446 -446
  338. package/tests/recall-intent.test.mjs +172 -172
  339. package/tests/regression-sweep.test.mjs +311 -311
  340. package/tests/reminder-fairness.test.mjs +55 -0
  341. package/tests/remote.test.mjs +140 -140
  342. package/tests/rename.test.mjs +30 -30
  343. package/tests/repetition-detector-snapshot.test.mjs +231 -231
  344. package/tests/repetition-eval-live.test.mjs +177 -177
  345. package/tests/repetition-eval.test.mjs +373 -373
  346. package/tests/salience-domain.test.mjs +173 -173
  347. package/tests/salient-date.test.mjs +142 -142
  348. package/tests/salient-wake.test.mjs +389 -389
  349. package/tests/settings-beat.test.mjs +222 -222
  350. package/tests/settings-coverage.test.mjs +97 -97
  351. package/tests/settings-plumbing.test.mjs +79 -79
  352. package/tests/short-term.test.mjs +182 -166
  353. package/tests/sidebar-beat.test.mjs +213 -213
  354. package/tests/sidebar-refresh.test.mjs +123 -123
  355. package/tests/sidebar.test.mjs +102 -74
  356. package/tests/simulate-injection.test.mjs +76 -76
  357. package/tests/slot-similarity.test.mjs +153 -153
  358. package/tests/snippet.test.mjs +79 -79
  359. package/tests/source-kind.test.mjs +52 -52
  360. package/tests/speaker-provenance.test.mjs +120 -120
  361. package/tests/stale-maintenance.test.mjs +206 -131
  362. package/tests/state-gc.test.mjs +34 -34
  363. package/tests/state.test.mjs +155 -155
  364. package/tests/stats.test.mjs +112 -112
  365. package/tests/storage.test.mjs +125 -125
  366. package/tests/stubs/child-process-spy.mjs +14 -14
  367. package/tests/stubs/dsh-llm-pi-ai.js +13 -13
  368. package/tests/stubs/dsh-llm.js +5 -5
  369. package/tests/stubs/dsh-schedule.js +140 -140
  370. package/tests/stubs/dsh-session-query.js +26 -26
  371. package/tests/stubs/dsh-session.js +7 -7
  372. package/tests/stubs/dsh-tools.js +101 -101
  373. package/tests/temporal-repair.test.mjs +78 -0
  374. package/tests/temporal.test.mjs +124 -124
  375. package/tests/text-format.test.mjs +24 -0
  376. package/tests/tokenizer-v2.test.mjs +142 -142
  377. package/tests/tool-schema.test.mjs +126 -126
  378. package/tests/tools.test.mjs +810 -810
  379. package/tests/turn-log.test.mjs +487 -487
  380. package/tests/ui-defaults.test.mjs +57 -57
  381. package/tests/update-fields.test.mjs +138 -138
  382. package/tests/vector-gc.test.mjs +37 -37
  383. package/tests/vector-migration.test.mjs +810 -810
  384. package/tests/vector-profile.test.mjs +449 -449
  385. package/tests/visibility-migration.test.mjs +152 -152
  386. package/tests/webui-auth.test.mjs +963 -963
  387. package/tests/webui.test.mjs +421 -421
  388. package/tests/windows-env.test.mjs +89 -89
  389. package/tests/worker-lifecycle.test.mjs +1521 -1429
package/lib/curator.js CHANGED
@@ -1,1811 +1,1813 @@
1
- import { createHash } from 'node:crypto'
2
- import {
3
- globalDbPath, loadGlobalIndex, updateGlobalIndex, newMemoryId, getSettings, effectiveVectorRoute,
4
- } from './state.js'
5
- import { commit, forget } from './memu.js'
6
- import { loadPrompt } from './prompts.js'
7
- import { retryStoreWrite, redactSecrets, warn, isSafeId } from './paths.js'
8
- import { record } from './activity-log.js'
9
- import { activeEntryStamp, assertVectorWriteAllowed, hasActiveVectorGeneration, readVectorState, withVectorWrite } from './vector-profile.js'
10
- import { upsertLexiconTerm } from './lexicon.js'
11
- import { clean, bigrams, dice, similarTexts, DUP_REJECT_DICE, TOPIC_DICE } from './text-similarity.js'
12
- import { estTokens } from './budget.js'
13
- // —— 包 F1(spec §4.1-§4.9/§6.6):候选检索、证据落地、全局 link ——
14
- import {
15
- buildCandidateClusters,
16
- buildCorpus,
17
- bm25,
18
- globalConflictCheck,
19
- pairFeatures,
20
- pairScore,
21
- rankPairCandidates,
22
- tokenize,
23
- } from './text-retrieval.js'
24
- import { buildEvidenceCorpus, groundEvidence } from './curator-evidence.js'
25
- import { applyGlobalLinks, validateGlobalLink, appendAudit } from './global-graph.js'
26
- import {
27
- ABSORB_ABSTRACTIVE_COVERAGE,
28
- ABSORB_AUTO_SOURCE_COVERAGE,
29
- ABSORB_AUTO_UNION_COVERAGE,
30
- ABSORB_MAX_CHARS,
31
- ABSORB_MAX_SOURCES,
32
- ABSORB_MIN_LENGTH_RATIO,
33
- ABSORB_REVIEW_SOURCE_COVERAGE,
34
- ABSORB_REVIEW_UNION_COVERAGE,
35
- CLUSTER_MIN_PAIR,
36
- CURATOR_CLUSTER_TOKENS,
37
- CURATOR_INDEX_MAX_ENTRIES,
38
- CURATOR_INDEX_TOKENS,
39
- CURATOR_MAX_LINK_ABSORB,
40
- EVIDENCE_MAX,
41
- PAIR_ABSORB_MIN,
42
- PAIR_DUPLICATE_MIN,
43
- PAIR_LINK_MIN,
44
- PAIR_SCAN_LIMIT,
45
- } from './curator-policy.js'
46
-
47
- const MAX_SESSIONS = 10
48
- const MAX_TOTAL_CHARS = 90_000
49
- const MAX_SESSION_CHARS = 14_000
50
- // C2:转录同时受字符预算与 token 预算约束。字符预算保留原有行为;token 预算
51
- // 按 estTokens 累计,超过 30k 就停——中文转录的字符数≈token 数,只靠 90k 字符
52
- // 在上限时仍会送出约 90k token。
53
- const MAX_TRANSCRIPT_TOKENS = 30_000
54
- // C3:curator 输出上限收紧到 24 条(提示词同口径)。超出的条目在提交前丢弃并记日志。
55
- const MAX_CURATOR_MEMORIES = 24
56
- const jobs = new Map()
57
-
58
- function managedVectorIntent() {
59
- if (effectiveVectorRoute() !== 'managed-local') return false
60
- try {
61
- const state = readVectorState({ tolerateMissing: true }).state
62
- return Boolean(state && (state.active || state.requested || state.pending))
63
- } catch {
64
- return true
65
- }
66
- }
67
-
68
- // 与 memory.js 同一条口径:受管路由还没有代际时,引擎这一步按词法处理(索引照写),
69
- // 否则 MemU 会以 "managed local vector profile is not active" 拒绝整次提炼。
70
- function engineRoute() {
71
- const route = effectiveVectorRoute()
72
- return route === 'managed-local' && !hasActiveVectorGeneration() ? 'lexical' : route
73
- }
74
-
75
- async function withManagedCuratorWrite(action) {
76
- if (!managedVectorIntent()) return action()
77
- // Same rule as the private write path: requested-but-never-migrated has no
78
- // generation to stay consistent with, so the global index + engine still get
79
- // the memories. Failing here would throw away a whole curation run.
80
- if (!hasActiveVectorGeneration()) {
81
- warn('managed vector write degraded to index+engine: no active vector generation; run the profile switch to enable vectors')
82
- record({ kind: 'vector', level: 'warn', scope: 'global', message: '向量未激活,全局提炼已降级为索引+引擎', detail: { reason: 'no active vector generation' } })
83
- return action()
84
- }
85
- return withVectorWrite(async () => { assertVectorWriteAllowed(); return action() })
86
- }
87
-
88
- function textOf(blocks) {
89
- if (!Array.isArray(blocks)) return ''
90
- return blocks
91
- .filter((b) => b?.type === 'text' && typeof b.text === 'string')
92
- .map((b) => b.text)
93
- .join('')
94
- .trim()
95
- }
96
-
97
- function truncate(text, max) {
98
- const s = String(text || '')
99
- return s.length > max ? `${s.slice(0, max)}…` : s
100
- }
101
-
102
- function argsText(value) {
103
- if (value == null) return ''
104
- return typeof value === 'string' ? value : JSON.stringify(value)
105
- }
106
-
107
- function toolCallKey(name, args) {
108
- return `${name || '?'}\u0000${argsText(args)}`
109
- }
110
-
111
- function blockCallId(block) {
112
- return typeof block?.id === 'string' && block.id ? block.id : null
113
- }
114
-
115
- function eventCallId(event) {
116
- return typeof event?.data?.callId === 'string' && event.data.callId ? event.data.callId : null
117
- }
118
-
119
- /**
120
- * 转录压缩。C2:assistant/message 的 tool-call 块与独立 tool/call 事件是同一
121
- * 次调用的双写,以 tool/call 事件为准——块只在没有对应事件时保留(先按 callId
122
- * 配对;两侧都没有 id 时按 name+arguments 计数配对,支持重复调用)。字符预算
123
- * 保留原行为,另加可选 token 预算(累计 estTokens 超预算即停)。
124
- * 工具行额度可按域覆盖:编码域的修改重点在命令/错误签名/参数里,300/400 只够开头。
125
- */
126
- export const CONDENSE_TOOL_RESULT_CHARS = 400
127
- export const CONDENSE_TOOL_CALL_CHARS = 300
128
- const CONDENSE_TOOL_RESULT_CHARS_CODING = 1_400
129
- const CONDENSE_TOOL_CALL_CHARS_CODING = 700
130
-
131
- export function condenseLimitsFor(domain) {
132
- return String(domain) === 'coding'
133
- ? { toolResultChars: CONDENSE_TOOL_RESULT_CHARS_CODING, toolCallChars: CONDENSE_TOOL_CALL_CHARS_CODING }
134
- : { toolResultChars: CONDENSE_TOOL_RESULT_CHARS, toolCallChars: CONDENSE_TOOL_CALL_CHARS }
135
- }
136
-
137
- export function condenseEvents(events, maxChars = MAX_SESSION_CHARS, { maxTokens = Infinity, toolResultChars = CONDENSE_TOOL_RESULT_CHARS, toolCallChars = CONDENSE_TOOL_CALL_CHARS } = {}) {
138
- // 事件侧先收一遍:callId 集合 + (name, arguments) 计数,供块侧配对。
139
- const eventCallIds = new Set()
140
- const eventSignatures = new Map()
141
- for (const event of events || []) {
142
- if (event?.type !== 'tool/call') continue
143
- const id = eventCallId(event)
144
- if (id) eventCallIds.add(id)
145
- const key = toolCallKey(event.data?.name, event.data?.arguments)
146
- eventSignatures.set(key, (eventSignatures.get(key) || 0) + 1)
147
- }
148
- const claimedSignatures = new Map()
149
- const lines = []
150
- for (const event of events || []) {
151
- try {
152
- const type = event?.type
153
- if (type === 'user/message') {
154
- if (event.data?.source?.kind !== 'user') continue
155
- const text = textOf(event.data?.content)
156
- if (text) lines.push(`User: ${text}`)
157
- continue
158
- }
159
- if (type === 'assistant/message') {
160
- const blocks = event.data?.message?.content || []
161
- const texts = textOf(blocks)
162
- if (texts) lines.push(`Assistant: ${texts}`)
163
- for (const b of blocks) {
164
- if (b?.type !== 'tool-call') continue
165
- const id = blockCallId(b)
166
- if (id && eventCallIds.has(id)) continue
167
- // 无 id 或 id 未配对:用 name+arguments 计数配对,事件侧有几个就吸收几个块。
168
- const key = toolCallKey(b.name, b.arguments)
169
- const available = (eventSignatures.get(key) || 0) - (claimedSignatures.get(key) || 0)
170
- if (available > 0) {
171
- claimedSignatures.set(key, (claimedSignatures.get(key) || 0) + 1)
172
- continue
173
- }
174
- lines.push(`Tool call: ${b.name}${b.arguments ? ` ${truncate(argsText(b.arguments), toolCallChars)}` : ''}`)
175
- }
176
- continue
177
- }
178
- if (type === 'tool/result') {
179
- const text = textOf(event.data?.message?.content)
180
- if (text) lines.push(`Tool result${event.data?.message?.isError ? ' (error)' : ''}: ${truncate(text, toolResultChars)}`)
181
- continue
182
- }
183
- if (type === 'tool/call') {
184
- lines.push(`Tool call: ${event.data?.name || '?'} ${truncate(argsText(event.data?.arguments), toolCallChars)}`)
185
- }
186
- } catch {}
187
- }
188
- let kept = lines
189
- let tokenTruncated = false
190
- if (Number.isFinite(maxTokens) && maxTokens > 0) {
191
- kept = []
192
- let used = 0
193
- for (const line of lines) {
194
- const cost = estTokens(line) + (kept.length > 0 ? 1 : 0)
195
- // 永远保留第一行(与 budget.packToBudget 同口径),之后累计超预算即停。
196
- if (kept.length > 0 && used + cost > maxTokens) { tokenTruncated = true; break }
197
- kept.push(line)
198
- used += cost
199
- }
200
- }
201
- let joined = redactSecrets(kept.join('\n'))
202
- if (tokenTruncated) {
203
- joined += `\n...[truncated ${lines.length - kept.length} lines over token budget ${maxTokens}]...`
204
- }
205
- if (joined.length > maxChars) {
206
- const head = joined.slice(0, Math.floor(maxChars * 0.6))
207
- const tail = joined.slice(-Math.floor(maxChars * 0.35))
208
- joined = `${head}\n...[truncated ${joined.length - maxChars} chars]...\n${tail}`
209
- }
210
- return joined
211
- }
212
-
213
- // —— §4.5 curator 上下文打包(包 F1)——
214
- // 旧 compactGlobalIndex 是"插入顺序前 200 条 ×600 字"的平铺,第 201 条后永远不可见、
215
- // 无预算。这里改为:BM25(会话文本) top80 → 追加最近 30 / universal 10 / pending 10,
216
- // 去重后按 BM25 desc → updatedAt desc → id 排序,estTokens 累计超预算即停(丢低分,
217
- // 不截断 JSON)。同输入同输出,不依赖对象插入顺序。
218
- function renderIndexEntry(id, entry, contentCap) {
219
- const links = Array.isArray(entry?.links) ? entry.links : []
220
- const item = {
221
- id,
222
- track: entry?.track || 'memory',
223
- domain: entry?.domain || 'unknown',
224
- applies_to: Array.isArray(entry?.appliesTo) ? entry.appliesTo.slice(0, 20) : [],
225
- title: entry?.title || '',
226
- content: truncate(entry?.content || '', contentCap),
227
- confidence: entry?.confidence ?? null,
228
- status: entry?.status || 'active',
229
- updatedAt: entry?.updatedAt || null,
230
- linkCount: links.length,
231
- linkedTo: links.slice(0, 5).map((l) => ({ to: l?.to || null, kind: l?.kind || null })),
232
- }
233
- if (Array.isArray(entry?.absorbedFrom) && entry.absorbedFrom.length) item.absorbedFrom = entry.absorbedFrom
234
- return item
235
- }
236
-
237
- export function packCuratorIndexContext({ index, sessionText, tokenBudget = CURATOR_INDEX_TOKENS, maxEntries = CURATOR_INDEX_MAX_ENTRIES } = {}) {
238
- const pool = []
239
- for (const [id, entry] of Object.entries(index?.entries || {})) {
240
- if (!entry || entry.status === 'archived') continue
241
- if (entry.reviewKind) continue // 本版没有 link 伪条目;防御性过滤
242
- pool.push({ id, entry, updatedAt: String(entry.updatedAt || ''), score: 0 })
243
- }
244
- if (pool.length) {
245
- const corpus = buildCorpus(pool.map((p) => ({ ...p.entry, id: p.id })))
246
- const query = tokenize(sessionText || '')
247
- for (const p of pool) {
248
- const doc = corpus.docs.get(p.id)
249
- p.score = doc ? bm25(query, doc, corpus) : 0
250
- }
251
- }
252
- const byScore = [...pool].sort((a, b) => b.score - a.score || b.updatedAt.localeCompare(a.updatedAt) || (a.id < b.id ? -1 : 1))
253
- const byRecent = [...pool].sort((a, b) => b.updatedAt.localeCompare(a.updatedAt) || (a.id < b.id ? -1 : 1))
254
- const selected = new Map()
255
- const take = (list) => { for (const p of list) if (!selected.has(p.id)) selected.set(p.id, p) }
256
- take(byScore.slice(0, 80)) // BM25 top 80
257
- take(byRecent.slice(0, 30)) // 最近 30
258
- take(byRecent.filter((p) => (p.entry?.domain || '') === 'universal').slice(0, 10)) // universal 10
259
- take(pool.filter((p) => (p.entry?.status || '') === 'pending_review' && (p.entry?.track || 'memory') === 'memory')
260
- .sort((a, b) => b.updatedAt.localeCompare(a.updatedAt) || (a.id < b.id ? -1 : 1)).slice(0, 10)) // pending_review 记忆 10
261
-
262
- const ordered = [...selected.values()].sort((a, b) => b.score - a.score || b.updatedAt.localeCompare(a.updatedAt) || (a.id < b.id ? -1 : 1))
263
- const entries = []
264
- let tokens = 0
265
- for (let i = 0; i < ordered.length && entries.length < maxEntries; i++) {
266
- const item = renderIndexEntry(ordered[i].id, ordered[i].entry, i < 20 ? 900 : 600)
267
- const cost = estTokens(JSON.stringify(item))
268
- if (entries.length > 0 && tokens + cost > tokenBudget) break
269
- entries.push(item)
270
- tokens += cost
271
- }
272
- return { entries, tokens, omitted: Math.max(0, ordered.length - entries.length), includedIds: entries.map((e) => e.id) }
273
- }
274
-
275
- // candidate_clusters 的 prompt 打包(§4.5):预算 2000 tokens,簇内正文截 300 字,
276
- // pair_scores 保留 2 位;簇已按 avg_score 降序,超预算丢低分簇。
277
- export function packCuratorClusterContext(clusterResult, { tokenBudget = CURATOR_CLUSTER_TOKENS } = {}) {
278
- const clusters = []
279
- let tokens = 0
280
- for (const cluster of clusterResult?.clusters || []) {
281
- const rendered = {
282
- cluster_id: cluster.cluster_id,
283
- suggested_op: cluster.suggested_op,
284
- medoid_id: cluster.medoid_id,
285
- avg_score: cluster.avg_score,
286
- pair_scores: cluster.pair_scores,
287
- members: (cluster.members || []).map((m) => ({
288
- id: m.id, title: m.title || '', track: m.track || 'memory',
289
- domain: m.domain || 'unknown', updatedAt: m.updatedAt || null,
290
- content: truncate(m.content || '', 300),
291
- })),
292
- }
293
- const cost = estTokens(JSON.stringify(rendered))
294
- if (clusters.length > 0 && tokens + cost > tokenBudget) break
295
- clusters.push(rendered)
296
- tokens += cost
297
- }
298
- const total = clusterResult?.clusters?.length || 0
299
- return {
300
- clusters,
301
- tokens,
302
- omitted: Math.max(0, total - clusters.length),
303
- truncated: (clusterResult?.truncated === true) || (total - clusters.length) > 0,
304
- }
305
- }
306
-
307
- async function readSession(sessionQuery, id) {
308
- if (typeof sessionQuery.readSession === 'function') {
309
- const snapshot = await sessionQuery.readSession(id)
310
- return {
311
- events: snapshot?.events || [],
312
- header: snapshot?.session || null,
313
- inheritedEventCount: snapshot?.inheritedEventCount ?? null,
314
- }
315
- }
316
- if (typeof sessionQuery.observeSession === 'function') {
317
- const observation = await sessionQuery.observeSession(id, { projectionMode: 'none' })
318
- try {
319
- return {
320
- events: observation?.events || [],
321
- header: observation?.header || null,
322
- inheritedEventCount: observation?.inheritedEventCount ?? null,
323
- }
324
- } finally {
325
- try { observation?.[Symbol.dispose]?.() } catch {}
326
- }
327
- }
328
- throw new Error('sessionQuery has neither readSession nor observeSession')
329
- }
330
-
331
- async function readSessionMeta(sessionQuery, ids) {
332
- const out = new Map()
333
- try {
334
- const records = await sessionQuery.listSessions()
335
- for (const record of records || []) {
336
- // `SessionRecord` carries only header + liveness; the title arrives from
337
- // readTitleSnapshots below, so keep the record and a mutable title slot.
338
- out.set(record.header?.id, { ...record, title: record.header?.title || '' })
339
- }
340
- } catch {}
341
- try {
342
- if (typeof sessionQuery.readTitleSnapshots === 'function') {
343
- // One result per requested id: `{ sessionId, status, value: { session, title? } }`.
344
- const titles = await sessionQuery.readTitleSnapshots(ids)
345
- for (const r of titles || []) {
346
- if (r?.status !== 'fulfilled' || !r.sessionId || !out.has(r.sessionId)) continue
347
- const title = r.value?.title?.title || r.value?.session?.title
348
- if (title) out.get(r.sessionId).title = title
349
- }
350
- }
351
- } catch {}
352
- return out
353
- }
354
-
355
- function parseJsonObject(text) {
356
- const raw = String(text || '').trim()
357
- try { return JSON.parse(raw) } catch {}
358
- const start = raw.indexOf('{')
359
- const end = raw.lastIndexOf('}')
360
- if (start >= 0 && end > start) {
361
- try { return JSON.parse(raw.slice(start, end + 1)) } catch {}
362
- }
363
- return null
364
- }
365
-
366
- function validDomain(domain) {
367
- const d = String(domain || '').trim()
368
- return d === 'universal' || d === 'coding' || d === 'rp' || d === 'tooling' || d === 'personal' || d === 'general' || d.startsWith('project:')
369
- }
370
-
371
- function agentOptionsFor(model) {
372
- const value = String(model || '').trim()
373
- if (!value) return undefined
374
- const slash = value.indexOf('/')
375
- if (slash <= 0 || slash === value.length - 1) return undefined
376
- return { provider: value.slice(0, slash), model: value.slice(slash + 1) }
377
- }
378
-
379
- export function listCurationJobs() {
380
- return [...jobs.values()].map((j) => ({
381
- id: j.id, status: j.status, step: j.step, createdAt: j.createdAt, endedAt: j.endedAt,
382
- error: j.error || null, result: j.result || null,
383
- }))
384
- }
385
-
386
- export function getCurationJob(id) {
387
- const job = jobs.get(id)
388
- if (!job) return null
389
- return {
390
- id: job.id,
391
- status: job.status,
392
- step: job.step,
393
- logs: job.logs.slice(-80),
394
- createdAt: job.createdAt,
395
- endedAt: job.endedAt || null,
396
- error: job.error || null,
397
- result: job.result || null,
398
- }
399
- }
400
-
401
- export function cancelCurationJob(id) {
402
- const job = jobs.get(id)
403
- if (!job) return false
404
- try { job.abort.abort(new Error('cancelled by user')) } catch {}
405
- return true
406
- }
407
-
408
- // 孤儿窗口补偿(这是补偿设计,不是事务):curator 是 commit-before-index —— 批量提交
409
- // 成功而全局索引写失败时,引擎库里会留下索引不认识的孤儿行。这里对刚提交的每个 name
410
- // 逐个 forget,尽力撤销;这是尽力而为,不是回滚保证:删不掉的必须可见。补偿结果(包括
411
- // 哪些补上了、哪些没补上)逐条记录进活动日志 kind:'curate',绝不吞掉。
412
- async function compensateCuratorCommit(originalError, { files, route }) {
413
- const db = globalDbPath()
414
- const compensated = []
415
- const failed = []
416
- for (const file of files) {
417
- try {
418
- const result = await forget({ db, name: file.name })
419
- if (!result || typeof result !== 'object' || result.ok === false || result.error || result.parseWarning
420
- || !Number.isSafeInteger(result.deleted) || result.deleted < 0) {
421
- throw new Error('backend compensation delete was not acknowledged')
422
- }
423
- compensated.push(file.name)
424
- } catch (compensationError) {
425
- failed.push({ name: file.name, error: String(compensationError?.message || compensationError) })
426
- }
427
- }
428
- if (failed.length) {
429
- record({
430
- kind: 'curate', scope: 'global', ok: false, level: 'error',
431
- message: `全局提炼索引写失败后的补偿不完整:${compensated.length}/${files.length} 条已从向量库撤销,${failed.length} 条撤销失败(引擎库残留孤儿行,需手动清理)`,
432
- detail: { route, compensated, failed: failed.slice(0, 20), originalError: String(originalError?.message || originalError) },
433
- refs: files.map((file) => file.name).slice(0, 20),
434
- })
435
- } else {
436
- record({
437
- kind: 'curate', scope: 'global', ok: true, level: 'warn',
438
- message: `全局提炼索引写失败,已从向量库回滚刚提交的 ${compensated.length} 条记忆(补偿成功;索引未变,重跑提炼即可)`,
439
- detail: { route, compensated, failed: [], originalError: String(originalError?.message || originalError) },
440
- refs: files.map((file) => file.name).slice(0, 20),
441
- })
442
- }
443
- }
444
-
445
- // 词典 op 识别(§2.1):op 显式标 'lexicon',或任何带 libraryId / term+kind 的提案。
446
- // 全局 curator 的输出里出现这些字段只能说明模型越权,拒绝而不是猜它的意图。
447
- function isLexiconOp(memory) {
448
- if (!memory || typeof memory !== 'object') return false
449
- if (memory.op === 'lexicon') return true
450
- if (typeof memory.libraryId === 'string' && memory.libraryId.trim()) return true
451
- return typeof memory.term === 'string' && memory.term.trim() && ['slang', 'meme', 'trigger', 'term'].includes(memory.kind)
452
- }
453
-
454
- /**
455
- * 私有整理链路的词典写入(§2.1-§2.2):validated ops 白名单校验 + 落库。
456
- *
457
- * 锁顺序(刻意注释,谁改谁读):本函数先拿 curator 侧的 managed 写闸
458
- * (withManagedCuratorWrite —— 受管向量代际一致性),**在其内部**再让
459
- * upsertLexiconTerm 拿词典自己的 withFileLock。两把锁的嵌套只有一个方向:
460
- * curator(vector) → lexicon(file);lexicon.js 从不回头拿向量锁,所以无死锁环。
461
- * 词典写从不跨 await 持锁——withFileLock 的 action 是同步的。
462
- *
463
- * 校验规则(§2.1 curator 行 + 契约):
464
- * * 只接受 { op:'lexicon', action:'upsert', ... };action 其它值(尤其 delete)
465
- * 一律拒绝——删除是用户/管理操作,模型没有删除路径。
466
- * * 必须 evidence(quote 或 id 至少其一非空),无证据直接拒绝;
467
- * "同一转录同词 ≥2 次才建议"是提示词层的事,代码层只验证据存在。
468
- * * libraryId 必须显式给出且过 isSafeId;op 里带了别的 libraryId 视为越权拒绝。
469
- * * needs_review === true → status:'pending',否则 'active'。
470
- * * sensitive trigger 由 lexicon.js 的 LEXICON_SENSITIVE_FORBIDDEN 兜底(curator
471
- * 来源理论上不该提,但来源字段在模型手里,存储层必须自己设防)。
472
- */
473
- export async function commitPrivateLexiconOps(ops, { libraryId, job } = {}) {
474
- const list = Array.isArray(ops) ? ops : [ops]
475
- const committed = []
476
- const rejected = []
477
- const skipped = []
478
- if (!isSafeId(libraryId)) {
479
- for (const raw of list) rejected.push({ term: raw?.term || null, code: 'LEXICON_INVALID_LIBRARY_ID', reason: 'lexicon ops need a valid private library id' })
480
- return { committed, rejected, skipped }
481
- }
482
- const run = async () => {
483
- for (const raw of list) {
484
- const op = raw && typeof raw === 'object' ? raw : null
485
- if (!op || op.op !== 'lexicon') {
486
- skipped.push({ term: op?.term || null, reason: 'not a lexicon op (op must be "lexicon")' })
487
- continue
488
- }
489
- if (op.action !== 'upsert') {
490
- rejected.push({ term: op.term || null, code: 'LEXICON_ACTION_FORBIDDEN', reason: `lexicon action "${op.action}" is not allowed for consolidation; only upsert, never delete` })
491
- continue
492
- }
493
- const evidence = Array.isArray(op.evidence)
494
- ? op.evidence.filter(item => item && typeof item === 'object' && ((typeof item.quote === 'string' && item.quote.trim()) || (typeof item.id === 'string' && item.id.trim())))
495
- : []
496
- if (!evidence.length) {
497
- rejected.push({ term: op.term || null, code: 'LEXICON_EVIDENCE_REQUIRED', reason: 'lexicon upserts need evidence from the transcript' })
498
- continue
499
- }
500
- if (typeof op.libraryId === 'string' && op.libraryId && op.libraryId !== libraryId) {
501
- rejected.push({ term: op.term || null, code: 'LEXICON_LIBRARY_MISMATCH', reason: `lexicon op targets library ${op.libraryId}, but this consolidation is bound to ${libraryId}` })
502
- continue
503
- }
504
- // 敏感触发词不允许模型猜(§0.2/§2.1):curator 也是模型,整理链路一律不给
505
- // sensitive trigger(trigger 缺省就是 sensitive,除非显式降为 normal)。
506
- if (op.kind === 'trigger' && op.sensitivity !== 'normal') {
507
- rejected.push({ term: op.term || null, code: 'LEXICON_SENSITIVE_FORBIDDEN', reason: 'consolidation cannot create sensitive triggers; sensitive vocabulary needs an explicit user write' })
508
- continue
509
- }
510
- try {
511
- const result = await upsertLexiconTerm({
512
- libraryId,
513
- term: op.term,
514
- kind: op.kind,
515
- meaning: op.meaning,
516
- usage: op.usage,
517
- aliases: op.aliases,
518
- examples: op.examples,
519
- context: op.context,
520
- knownBy: op.knownBy,
521
- visibility: op.visibility,
522
- sensitivity: op.sensitivity,
523
- confidence: op.confidence,
524
- evidence,
525
- source: 'curator',
526
- status: op.needs_review === true ? 'pending' : 'active',
527
- })
528
- committed.push({
529
- termId: result.term.termId,
530
- term: result.term.term,
531
- status: result.term.status,
532
- created: result.created === true,
533
- notOwned: result.notOwned === true,
534
- pendingRevision: result.pendingRevision === true,
535
- })
536
- } catch (error) {
537
- rejected.push({ term: op.term || null, code: error?.code || 'LEXICON_OP_FAILED', reason: String(error?.message || error) })
538
- }
539
- }
540
- return { committed, rejected, skipped }
541
- }
542
- if (job) job.step = 'committing lexicon ops'
543
- // 先过 curator 侧 managed 写闸,再进词典自己的文件锁(顺序见函数头注释)。
544
- return withManagedCuratorWrite(run)
545
- }
546
-
547
- /**
548
- * 审核决策(spec §4.10):硬门 + 风险分。
549
- *
550
- * 硬门恒 pending,不因审核模式放宽:conflict(模型自己承认两段会话打架)、
551
- * 证据为空(可回放性是底线)、merge/supersede/absorb 的 target 不存在。
552
- * 非法 target 在这里返回 skip——调用方必须跳过该提案并且**不得**用同一份内容
553
- * 继续 create(旧代码缺 continue,会把失败的合并悄悄变成一条重复记忆,§0.2)。
554
- *
555
- * 风险分只拦"会改写既有内容"的操作:merge/supersede/absorb 在 auto 下风险
556
- * ≥0.70 才 pending;create 默认通过,needs_review/低置信只记进 risk 供审计与
557
- * 复核排序。review-all 把全部内容操作都送进复核。风险分上限 2。
558
- *
559
- * @returns {{ review: boolean, risk: number, reasons: string[], hard?: boolean } |
560
- * { skip: true, reason: string }}
561
- */
562
- export function reviewDecision({ m, op, evidence, targetId, index, mode }) {
563
- // 硬门(恒 pending;不因 mode 放宽)
564
- if (op === 'conflict') return { review: true, hard: true, risk: 2, reasons: ['conflict'] }
565
- if (!evidence.length) return { review: true, hard: true, risk: 2, reasons: ['missing evidence'] }
566
- if (op === 'merge' || op === 'supersede' || op === 'absorb') {
567
- if (!targetId || !index.entries[targetId]) {
568
- return { skip: true, reason: `target not found: ${targetId || '(empty)'}` }
569
- }
570
- }
571
- // 风险分
572
- let risk = 0
573
- const reasons = []
574
- if (m?.needs_review === true) { risk += 0.70; reasons.push('needs_review') }
575
- if (Number(m?.confidence) < 0.50) { risk += 0.70; reasons.push('confidence<0.50') }
576
- else if (Number(m?.confidence) < 0.60) { risk += 0.20; reasons.push('confidence<0.60') }
577
- if (op === 'merge' || op === 'supersede') { risk += 0.20; reasons.push(op) }
578
- if (op === 'absorb' && (m?.source_ids?.length || 0) > 3) { risk += 0.20; reasons.push('absorb>3 sources') }
579
- if (m?.review_reason) { risk += 0.20; reasons.push('review_reason') }
580
- if (evidence.length === 1) { risk += 0.10; reasons.push('single evidence') }
581
-
582
- const rewrite = op === 'merge' || op === 'supersede' || op === 'absorb'
583
- const review = mode === 'review-all' || (mode === 'auto' && rewrite && risk >= 0.70)
584
- return { review, risk: Math.min(2, Number(risk.toFixed(2))), reasons }
585
- }
586
-
587
- // —— §4.8 去重门/冲突门(包 F1)——
588
- // 门语料只含 active + pending_review:archived/superseded 不是"已存在的事实",
589
- // 不该拦 create,也不该成为 best。LLM 只裁决;提交层用同一把 pair 尺子复核。
590
- // buildCorpus 的约定是条目自带 id/title/content(track/domain/appliesTo 等
591
- // 随条目一起落在 doc.entry 上),所以这里直接展开索引条目再补 id。
592
- function buildGateCorpus(index) {
593
- const rows = []
594
- for (const [id, entry] of Object.entries(index?.entries || {})) {
595
- if (!entry || (entry.status !== 'active' && entry.status !== 'pending_review')) continue
596
- rows.push({ ...entry, id })
597
- }
598
- return buildCorpus(rows)
599
- }
600
-
601
- const OPS_ALLOWLIST = ['create', 'merge', 'supersede', 'noop', 'conflict', 'link', 'absorb']
602
- const SCORE_EPSILON = 1e-9
603
-
604
- /**
605
- * 规划阶段(spec §7.2 planCuratorOps):把模型输出拆成 writes / pendings / links /
606
- * skipped 四类计划;全部语义复核在此完成,提交阶段只做事务。逐条流程:
607
- * lexicon op → skipped;unknown op → skipped(绝不降级 create);noop → 静默跳过;
608
- * link → validateGlobalLink 预检(快照索引 + 证据落地),事务内再复核并发面;
609
- * absorb → skipped 'absorb lands in a later pass'(F2 的 commitCuratorPlans 负责,
610
- * 它直接从原始输出里取 absorb ops,不受这里的 skip 影响);
611
- * create/merge/supersede/conflict → 证据落地(§4.6)→ reviewDecision(§4.10)→
612
- * §4.8 候选门(rankPairCandidates top1):
613
- * create ≥0.90 同 track/domain → skip 'duplicate of <id>'(pending 同域 →
614
- * 'duplicate of pending <id>'),warn 日志;
615
- * create conflict(pairDecision 或 globalConflictCheck 预筛,absorb 带不重复查)→
616
- * pending 'conflict detected';
617
- * create 0.82-0.90 → duplicateOf+relatedTo;0.55-0.82 → relatedTo;
618
- * merge/supersede best 是另一条且高 ≥0.05 → pending 'closest target differs';
619
- * conflict 恒 pending,target 缺失时用 best。
620
- */
621
- export function planCuratorOps(memories, { index, mode, corpus, sessionCorpus = null, now }) {
622
- const writes = []
623
- const pendings = []
624
- const links = []
625
- const skipped = []
626
- const entries = index?.entries || {}
627
- for (const m of memories) {
628
- // 词典 op 是私有整理的专属面(§2.1):全局 curator 只写全局记忆。带 libraryId /
629
- // lexicon 标记的条目在这里一律拒绝——不进向量提交、不进全局索引,只在 skipped 里
630
- // 留下可读的原因。私有写入走 commitPrivateLexiconOps。
631
- if (isLexiconOp(m)) {
632
- skipped.push({ title: m?.term || m?.title, reason: 'lexicon op rejected: the global curator only writes global memory; lexicon ops belong to the private consolidation chain' })
633
- continue
634
- }
635
- // 未知 op 一律拒绝(§4.8):allowlist 之外的 op 不得静默降级成 create——
636
- // 模型写错 op 名时,降级会凭空写条目。'noop' 是模型的"无可奉告",直接跳过。
637
- const op = OPS_ALLOWLIST.includes(m?.op) ? m.op : null
638
- if (op === 'noop') continue
639
- if (!op) {
640
- skipped.push({ title: m?.title, reason: `unknown op: ${m?.op ?? '(missing)'}` })
641
- continue
642
- }
643
- // —— link 分支(§4.9,包 F1):预检通过才进 links 计划;落库在提交事务里,
644
- // 与普通 updates 同一次 updateGlobalIndex;不进 files、不触发向量提交。
645
- if (op === 'link') {
646
- const verdict = validateGlobalLink({
647
- index,
648
- fromId: m?.from_id,
649
- toId: m?.to_id,
650
- kind: m?.kind,
651
- note: m?.note,
652
- confidence: m?.confidence,
653
- evidence: Array.isArray(m?.evidence) ? m.evidence : [],
654
- sessionCorpus,
655
- })
656
- if (!verdict.ok) {
657
- skipped.push({ title: m?.note || m?.to_id || m?.title, reason: `link rejected: ${verdict.reason}` })
658
- continue
659
- }
660
- links.push({ fromId: verdict.fromId, toId: verdict.toId, kind: verdict.kind, symmetric: verdict.symmetric, link: verdict.link })
661
- continue
662
- }
663
- // absorb 提交属于 F2 的 commitCuratorPlans(从原始 output 自取 absorb ops);
664
- // 这里显式跳过——planCuratorOps 不把 absorb 当成 create 走内容提交。
665
- // 注意:absorb 已接线(commitCuratorOutput 里调用 commitCuratorPlans),
666
- // 这个 skip 只是内容半边的路由,不是"未实现"。
667
- if (op === 'absorb') {
668
- skipped.push({ title: m?.title, reason: 'absorb handled by commitCuratorPlans' })
669
- continue
670
- }
671
-
672
- // 证据落地(§4.6):quote 必须能回放到本次策划的会话转录;无 corpus(测试/直呼)
673
- // 时只做形状校验,status='unverified'。有效证据为空是硬门(reviewDecision)。
674
- const grounded = groundEvidence(Array.isArray(m?.evidence) ? m.evidence : [], sessionCorpus)
675
- const evidence = grounded.valid.slice(0, EVIDENCE_MAX)
676
- .map((item) => ({ sessionId: item.sessionId, quote: truncate(item.quote, 500) }))
677
- const domain = String(m?.domain || '').trim()
678
- if (!validDomain(domain)) {
679
- skipped.push({ title: m?.title, reason: `invalid domain: ${domain}` })
680
- continue
681
- }
682
- const track = m?.track === 'skill' ? 'skill' : 'memory'
683
- const title = String(m?.title || '').trim()
684
- const content = String(m?.content || '').trim()
685
- if (!title || !content) {
686
- skipped.push({ title, reason: 'missing title or content' })
687
- continue
688
- }
689
- const targetId = String(m?.target_id || '').trim()
690
- const decision = reviewDecision({ m, op, evidence, targetId, index, mode })
691
- if (decision.skip) {
692
- // 非法 merge/supersede target 到此为止(§0.2 修复):skipped + continue,
693
- // 绝不带着同一份内容继续 create。
694
- skipped.push({ title, reason: decision.reason })
695
- continue
696
- }
697
-
698
- // —— §4.8 候选复核门:每次规划用同一语料、同一把尺子。——
699
- const proposal = {
700
- id: '__curator_proposal__',
701
- title, content, track, domain,
702
- appliesTo: Array.isArray(m?.applies_to) ? m.applies_to : [],
703
- }
704
- const candidates = corpus && corpus.size ? rankPairCandidates({ corpus, proposal, limit: PAIR_SCAN_LIMIT }) : []
705
- const best = candidates[0] || null
706
- let review = decision.review
707
- // reviewReason 优先级:硬门 > 候选门(conflict detected / closest target differs)
708
- // > 模型 review_reason > 'risk threshold'。
709
- let reviewReason = decision.hard
710
- ? decision.reasons[0]
711
- : (String(m?.review_reason || '').trim() || 'risk threshold')
712
- let conflictingWith = targetId || null
713
- const tags = {}
714
- if (op === 'create' && best) {
715
- if (best.score >= PAIR_DUPLICATE_MIN
716
- && (best.entry?.track || 'memory') === track
717
- && (best.entry?.domain || 'unknown') === domain) {
718
- const isPending = best.entry?.status === 'pending_review'
719
- warn(`curator: create skipped, ${isPending ? 'duplicate of pending' : 'duplicate of'} ${best.id} (pair score ${best.score.toFixed(2)})`)
720
- skipped.push({ title, reason: isPending ? `duplicate of pending ${best.id}` : `duplicate of ${best.id}` })
721
- continue
722
- }
723
- // 冲突检测:pairDecision 的 conflict(同标题正文迥异),或 §4.8 预筛
724
- // (negation/value/same_title)。duplicate/absorb 带(≥0.82)不重复查——
725
- // 同标题高相似是同一事实的改写,不是冲突(§4.8 豁免条款的推广)。
726
- const conflictHit = best.decision === 'conflict' || (best.score < PAIR_ABSORB_MIN
727
- && globalConflictCheck(proposal, best.entry, best.features))
728
- if (conflictHit) {
729
- review = true
730
- reviewReason = 'conflict detected'
731
- conflictingWith = best.id
732
- } else if (best.score >= PAIR_ABSORB_MIN) {
733
- tags.duplicateOf = best.id
734
- tags.relatedTo = best.id
735
- } else if (best.score >= PAIR_LINK_MIN) {
736
- tags.relatedTo = best.id
737
- }
738
- }
739
- if ((op === 'merge' || op === 'supersede') && best) {
740
- // best 是另一条且分数比模型 target 高 ≥0.05 → 最近目标存疑,转人审。
741
- const targetEntry = entries[targetId]
742
- const targetScore = targetEntry ? pairScore(pairFeatures(proposal, targetEntry)) : 0
743
- if (best.id !== targetId && best.score >= targetScore + 0.05 - SCORE_EPSILON) {
744
- review = true
745
- reviewReason = 'closest target differs'
746
- conflictingWith = targetId
747
- }
748
- }
749
- if (op === 'conflict' && !targetId && best) conflictingWith = best.id
750
-
751
- const previous = (op === 'merge' || op === 'supersede') && targetId && entries[targetId] ? entries[targetId] : null
752
- // A reviewed (held) entry must never occupy the target's id: rejecting the
753
- // review would archive the only copy and the original active memory would
754
- // be gone. Held entries always get their own id; only a clean merge writes
755
- // in place.
756
- const id = newMemoryId('gmem')
757
- const entry = {
758
- track,
759
- domain,
760
- appliesTo: Array.isArray(m?.applies_to) ? m.applies_to.slice(0, 20) : [],
761
- title: truncate(title, 180),
762
- content: redactSecrets(content),
763
- confidence: Number.isFinite(Number(m?.confidence)) ? Math.max(0, Math.min(1, Number(m.confidence))) : 0.6,
764
- evidence: evidence.map((e) => ({
765
- sessionId: String(e?.sessionId || ''),
766
- quote: truncate(e?.quote || '', 500),
767
- })),
768
- status: 'active',
769
- supersedes: op === 'supersede' ? targetId || null : previous?.supersedes || null,
770
- // 风险分写到所有条目(active 也写,§4.10):它是审计/复核排序的统一口径,
771
- // 不是 pending 的专属属性。旧条目没有这两个字段时按缺省读取,不需要迁移。
772
- reviewRisk: decision.risk,
773
- reviewRiskReasons: decision.reasons,
774
- // 证据是否通过 grounding(§3.1):unverified(直呼/测试)时为 false。
775
- evidenceVerified: grounded.status === 'grounded',
776
- createdAt: previous?.createdAt || now,
777
- updatedAt: now,
778
- }
779
- if (tags.duplicateOf) entry.duplicateOf = tags.duplicateOf
780
- if (tags.relatedTo) entry.relatedTo = tags.relatedTo
781
- if (review) {
782
- // Held in the index only: never committed to MemU, so a contested claim
783
- // cannot be recalled as shared memory until someone decides.
784
- entry.status = 'pending_review'
785
- entry.reviewReason = reviewReason
786
- entry.conflictingWith = conflictingWith
787
- pendings.push({ id, entry })
788
- continue
789
- }
790
- writes.push({
791
- id, entry, op, targetId, previous,
792
- file: { name: id, track, description: truncate(title, 180), content },
793
- })
794
- }
795
- return { writes, pendings, links, skipped }
796
- }
797
-
798
- // Exported for the audit regression suite: merging the commit decision logic
799
- // into startGlobalCuration would require standing up subagents to test it.
800
- export async function commitCuratorOutput(output, { job, sessionCorpus = null } = {}) {
801
- const returned = Array.isArray(output?.memories) ? output.memories : []
802
- // C3:提示词已把上限压到 24;模型仍超量时在提交前截断(超出部分直接丢弃),并
803
- // 留一条可观测日志——静默截断会让「为什么少了几条」永远查不到。
804
- const memories = returned.slice(0, MAX_CURATOR_MEMORIES)
805
- if (returned.length > MAX_CURATOR_MEMORIES) {
806
- warn(`curator: output truncated to ${MAX_CURATOR_MEMORIES} memories (${returned.length} returned)`)
807
- record({
808
- kind: 'curate', scope: 'global', ok: true, level: 'warn',
809
- message: `全局提炼输出超过上限,已截断 ${returned.length} → ${MAX_CURATOR_MEMORIES} 条`,
810
- detail: { op: 'output-truncated', returned: returned.length, kept: memories.length, limit: MAX_CURATOR_MEMORIES },
811
- })
812
- }
813
- if (memories.length === 0) {
814
- return { files: [], created: 0, merged: 0, superseded: 0, pending: 0, linked: 0, skipped: [], reviewRisk: { max: 0, flagged: 0, reasons: {} } }
815
- }
816
- const index = loadGlobalIndex()
817
- // 模式只在循环外读一次(§4.10):一次策划运行用同一个口径,中途改设置不影响本批。
818
- const mode = getSettings().curatorReviewMode || 'auto'
819
- const gateCorpus = buildGateCorpus(index)
820
- const plan = planCuratorOps(memories, { index, mode, corpus: gateCorpus, sessionCorpus, now: new Date().toISOString() })
821
- const contentResult = await commitPlannedOps(plan, { job })
822
- // absorb 半边(F2):planCuratorOps 对 absorb 显式 skip(避免在内容提交里被误当成
823
- // create),absorb ops 由 commitCuratorPlans 从原始 output 自取并直接提交;这里传
824
- // 截断后的 memories,保证 24 条上限对 absorb 同样生效。
825
- const absorbResult = await commitCuratorPlans({ ...(output || {}), memories }, { job })
826
- return {
827
- ...contentResult,
828
- absorbed: absorbResult.absorbed,
829
- pending: contentResult.pending + absorbResult.pending,
830
- held: absorbResult.held,
831
- demoted: absorbResult.demoted,
832
- skipped: [...contentResult.skipped, ...absorbResult.skipped],
833
- }
834
- }
835
-
836
- /**
837
- * 提交阶段(spec §7.2 commitCuratorPlans 的内容操作半边;absorb 半边是 F2 的
838
- * 同名函数,直接吃原始 output)。单次 updateGlobalIndex 事务内按序应用:
839
- * pendings(索引 only)→ writes(held clone 检查 / merge 兜底 / supersede)→
840
- * links(applyGlobalLinks,只有 link 时也要走一次索引事务,§4.9)。
841
- * link 不进 files、不触发向量提交;两档审核模式都自动应用(C2)。
842
- */
843
- async function commitPlannedOps({ writes, pendings, links, skipped }, { job }) {
844
- const files = writes.map((w) => w.file)
845
- const now = new Date().toISOString()
846
-
847
- // 风险统计(§4.10):本批所有写入条目(active + pending)的审计口径——最高分、
848
- // 达到复核阈值(≥0.70)的条目数、每类原因出现的次数。
849
- const written = [...writes.map((w) => w.entry), ...pendings.map((p) => p.entry)]
850
- const riskReasons = {}
851
- for (const entry of written) {
852
- for (const reason of entry.reviewRiskReasons || []) riskReasons[reason] = (riskReasons[reason] || 0) + 1
853
- }
854
- const reviewRiskSummary = {
855
- max: written.length ? Math.max(...written.map((entry) => Number(entry.reviewRisk) || 0)) : 0,
856
- flagged: written.filter((entry) => (Number(entry.reviewRisk) || 0) >= 0.70).length,
857
- reasons: riskReasons,
858
- }
859
-
860
- // 单事务:pendings + writes + links 一次落索引。返回本事务实际落地的 link 列表,
861
- // 供活动日志逐条记录(retry 重跑时以成功那次的返回为准)。
862
- const applyPlan = (fresh) => {
863
- for (const { id, entry } of pendings) fresh.entries[id] = entry
864
- for (const { id, entry, op, targetId, previous } of writes) {
865
- if (previous && JSON.stringify(fresh.entries[targetId]) !== JSON.stringify(previous)) {
866
- const heldId = newMemoryId('gmem')
867
- // 提交成功的只有 `id` 这一行,held 克隆从未进过向量库——它绝不能继承
868
- // "提交成功即落戳"的 entry.vector:向量库里的行名是 `id` 而不是 heldId,
869
- // 带戳会让 membership 把一条不存在的行计进来,而真实存在的 `id` 行反而
870
- // 无处归属(它根本不会按这个克隆写进索引)。
871
- const held = { ...entry, status: 'pending_review', conflictingWith: targetId, reviewReason: 'target changed while curator was running' }
872
- delete held.vector
873
- fresh.entries[heldId] = held
874
- continue
875
- }
876
- if (op === 'merge' && previous) {
877
- entry.content = entry.content || previous.content
878
- entry.title = entry.title || previous.title
879
- entry.evidence = [...(previous.evidence || []), ...(entry.evidence || [])].slice(-40)
880
- }
881
- fresh.entries[id] = entry
882
- if ((op === 'supersede' || op === 'merge') && targetId && fresh.entries[targetId]) {
883
- fresh.entries[targetId].status = 'superseded'
884
- fresh.entries[targetId].supersededBy = id
885
- fresh.entries[targetId].validTo = now
886
- fresh.entries[targetId].updatedAt = now
887
- }
888
- }
889
- return applyGlobalLinks(fresh.entries, links, { now })
890
- }
891
-
892
- if (files.length === 0) {
893
- let linkResult = { applied: [], skipped: [] }
894
- if (pendings.length || links.length) {
895
- // 只有 pending/link 时同样要走一次索引事务(§4.9:只有 link 也要调一次
896
- // updateGlobalIndex);withManagedCuratorWrite 闸门照过,保持锁纪律一致。
897
- await withManagedCuratorWrite(() => retryStoreWrite(() => updateGlobalIndex((fresh) => {
898
- linkResult = applyPlan(fresh)
899
- })))
900
- }
901
- for (const applied of linkResult.applied) {
902
- record({ kind: 'curate', scope: 'global', ok: true, message: `全局关联已落地:${applied.fromId} -(${applied.kind})-> ${applied.toId}`, detail: { op: 'link', from: applied.fromId, to: applied.toId, kind: applied.kind, linkId: applied.linkId } })
903
- }
904
- return {
905
- files: [], created: 0, merged: 0, superseded: 0, pending: pendings.length,
906
- linked: linkResult.applied.length, skipped, reviewRisk: reviewRiskSummary,
907
- }
908
- }
909
-
910
- job.step = `committing ${files.length} global memories`
911
- let linkResult = { applied: [], skipped: [] }
912
- await withManagedCuratorWrite(async () => {
913
- // Managed agent mode still commits the exact same files to the active local
914
- // vector database; only pending_review entries remain index-only.
915
- const route = engineRoute()
916
- let committedToBackend = false
917
- try {
918
- if (route !== 'lexical') {
919
- await commit({
920
- payload: { recall_files: files, resource: [], user: {} },
921
- route, db: globalDbPath(),
922
- })
923
- committedToBackend = true
924
- // 整理写入与单条写入同口径:提交成功就在条目上落"已入向量库"戳,否则这批
925
- // 全局记忆在向量计数(membership 的戳腿)里永远缺失。pending 不提交,不戳。
926
- const vector = activeEntryStamp(route)
927
- if (vector) for (const write of writes) write.entry.vector = vector
928
- }
929
-
930
- if (job?.abort?.signal?.aborted) throw new Error('cancelled by user')
931
- await retryStoreWrite(() => updateGlobalIndex((fresh) => {
932
- linkResult = applyPlan(fresh)
933
- }))
934
- } catch (error) {
935
- // 提交成功之后(abort 检查 / 索引写)的任何失败都会留下孤儿行:尽力撤销。
936
- if (committedToBackend) await compensateCuratorCommit(error, { files, route })
937
- throw error
938
- }
939
- })
940
- for (const applied of linkResult.applied) {
941
- record({ kind: 'curate', scope: 'global', ok: true, message: `全局关联已落地:${applied.fromId} -(${applied.kind})-> ${applied.toId}`, detail: { op: 'link', from: applied.fromId, to: applied.toId, kind: applied.kind, linkId: applied.linkId } })
942
- }
943
- const summary = {
944
- files,
945
- created: writes.filter((w) => w.op === 'create').length,
946
- merged: writes.filter((w) => w.op === 'merge').length,
947
- superseded: writes.filter((w) => w.op === 'supersede').length,
948
- pending: pendings.length,
949
- linked: linkResult.applied.length,
950
- skipped,
951
- reviewRisk: reviewRiskSummary,
952
- }
953
- record({
954
- kind: 'curate',
955
- scope: 'global',
956
- ok: true,
957
- message: `全局提炼:新增 ${summary.created} / 合并 ${summary.merged} / 待复核 ${summary.pending}`
958
- + (summary.linked ? ` / 关联 ${summary.linked}` : '')
959
- + (summary.skipped.length ? ` / 跳过 ${summary.skipped.length}` : ''),
960
- detail: { ...summary, skipped: summary.skipped.slice(0, 20) },
961
- refs: files.map((file) => file.name).slice(0, 20),
962
- })
963
- return summary
964
- }
965
-
966
- // ============================================================================
967
- // 包 F2(spec §4.7/§4.11/§6.7):absorb 合并稿、提交事务、复核与撤销。
968
- // ============================================================================
969
-
970
- // —— absorb 常量(spec §4.12)——单点定义在 lib/curator-policy.js(文件头部 import)。
971
- // 句级去重的 charDice 阈值只属于合并稿这一处,留在本地。
972
- const ABSORB_SENTENCE_DICE = 0.9
973
-
974
- // —— F1 接口(spec §4.1):tokenize/buildCorpus 已由 lib/text-retrieval.js 落地
975
- //(文件头部 import)。buildCorpus 返回的是 BM25 语料(df/size),这里按 F1 的
976
- // idfOf 同一公式折算成合并稿 MMR 用的 idf 表。
977
- function tokensOf(text) {
978
- return new Set(tokenize(text))
979
- }
980
-
981
- function idfMapFromCorpus(corpus) {
982
- const idf = new Map()
983
- if (!corpus?.df) return idf
984
- for (const [term, df] of corpus.df) {
985
- idf.set(term, Math.log(1 + (corpus.size - df + 0.5) / (df + 0.5)))
986
- }
987
- return idf
988
- }
989
-
990
- // idf 语料取自当前全局索引的 active 条目(与候选簇同一口径)。
991
- function absorbIdf(index) {
992
- const docs = Object.entries(index?.entries || {})
993
- .filter(([, entry]) => entry && entry.status === 'active')
994
- .map(([id, entry]) => ({ id, title: entry.title || '', content: entry.content || '' }))
995
- return idfMapFromCorpus(buildCorpus(docs))
996
- }
997
-
998
- // —— absorb 合并稿(spec §4.7)——
999
- const SENTENCE_RE = /[^。!?!?;;\n]+[。!?!?;;]?/gu
1000
-
1001
- function splitSentences(text) {
1002
- const out = []
1003
- for (const raw of String(text || '').match(SENTENCE_RE) || []) {
1004
- const sentence = raw.trim()
1005
- if (sentence) out.push(sentence)
1006
- }
1007
- return out
1008
- }
1009
-
1010
- // token 覆盖率:source 的词元有多大比例出现在 content 里。
1011
- function tokenCoverage(sourceTokens, contentTokens) {
1012
- if (!sourceTokens || sourceTokens.size === 0) return 1
1013
- let hit = 0
1014
- for (const token of sourceTokens) if (contentTokens.has(token)) hit += 1
1015
- return hit / sourceTokens.size
1016
- }
1017
-
1018
- // char 覆盖率:union 的字符 bigram 有多大比例出现在 proposed 里。
1019
- function charCoverage(unionText, proposedText) {
1020
- const unionGrams = bigrams(unionText)
1021
- if (unionGrams.size === 0) return 1
1022
- const proposedGrams = bigrams(proposedText)
1023
- let hit = 0
1024
- for (const gram of unionGrams) if (proposedGrams.has(gram)) hit += 1
1025
- return hit / unionGrams.size
1026
- }
1027
-
1028
- function sentenceInfo(sentence, idf, coveredTokens = null) {
1029
- let sum = 0
1030
- for (const token of tokensOf(sentence)) {
1031
- if (coveredTokens && coveredTokens.has(token)) continue
1032
- sum += Number(idf?.get?.(token) ?? 1)
1033
- }
1034
- return sum
1035
- }
1036
-
1037
- /**
1038
- * 吸收合并稿(spec §4.7)。输入 target、sources、模型的 proposed 稿;
1039
- * 输出 { content, mode, coverage, sourceCoverage, unionCoverage, truncated, omitted }。
1040
- * 句级去重(charDice ≥0.90 或互含丢弃)→ union(target 在前)→ proposed 覆盖
1041
- * ≥0.75 且不超长时用 proposed(abstractive),否则 extractive(放得下直接拼接,
1042
- * 放不下做句子级 MMR:info − 0.7·redundancy·maxInfo 贪心,被丢关键句记 truncated)。
1043
- * idf 由调用方通过 buildCorpus 提供(F1);缺省按 1 计(spec 已兼容 idf=null)。
1044
- */
1045
- export function composeAbsorbContent({ target, sources = [], proposed = '', maxChars = ABSORB_MAX_CHARS, idf = null } = {}) {
1046
- const result = { content: '', mode: 'extractive', coverage: 0, sourceCoverage: 1, unionCoverage: 1, truncated: false, omitted: [] }
1047
- // 1-3. 句子切分 + 句级去重;target 在前,构成 union。origin 记录每个句子的出处
1048
- //(-1 = target,其余 = sources 下标),供关键句判定使用。
1049
- const union = []
1050
- const origins = []
1051
- const keptKeys = []
1052
- const pushSentence = (raw, origin) => {
1053
- const sentence = String(raw || '').trim()
1054
- const key = clean(sentence)
1055
- if (!key) return
1056
- for (const kept of keptKeys) {
1057
- if (kept === key || kept.includes(key) || key.includes(kept) || dice(bigrams(key), bigrams(kept)) >= ABSORB_SENTENCE_DICE) return
1058
- }
1059
- keptKeys.push(key)
1060
- union.push(sentence)
1061
- origins.push(origin)
1062
- }
1063
- const sourceList = Array.isArray(sources) ? sources : []
1064
- for (const sentence of splitSentences(target?.content)) pushSentence(sentence, -1)
1065
- sourceList.forEach((source, index) => {
1066
- for (const sentence of splitSentences(source?.content)) pushSentence(sentence, index)
1067
- })
1068
- if (!union.length) return result
1069
- const unionText = union.join('')
1070
- const proposedText = String(proposed || '').trim()
1071
-
1072
- // 4. proposed 覆盖足够且不超长 → abstractive。
1073
- if (proposedText) {
1074
- result.coverage = Math.max(charCoverage(unionText, proposedText), tokenCoverage(tokensOf(unionText), tokensOf(proposedText)))
1075
- if (result.coverage >= ABSORB_ABSTRACTIVE_COVERAGE && proposedText.length <= maxChars) {
1076
- result.content = proposedText
1077
- result.mode = 'abstractive'
1078
- }
1079
- }
1080
-
1081
- // 5. extractive:总长放得下直接拼接;否则句子级 MMR 贪心到 maxChars。
1082
- if (result.mode === 'extractive') {
1083
- const infos = union.map((sentence) => sentenceInfo(sentence, idf))
1084
- const maxInfo = infos.reduce((acc, value) => Math.max(acc, value), 0)
1085
- const picked = []
1086
- const covered = new Set()
1087
- let length = 0
1088
- const remaining = new Set(union.map((_, index) => index))
1089
- while (remaining.size > 0) {
1090
- let bestIndex = -1
1091
- let bestScore = -Infinity
1092
- for (const index of remaining) {
1093
- let redundancy = 0
1094
- for (const chosen of picked) redundancy = Math.max(redundancy, dice(bigrams(union[index]), bigrams(union[chosen])))
1095
- const score = sentenceInfo(union[index], idf, covered) - 0.7 * redundancy * maxInfo
1096
- if (score > bestScore) { bestScore = score; bestIndex = index }
1097
- }
1098
- remaining.delete(bestIndex)
1099
- if (length + union[bestIndex].length > maxChars) continue
1100
- picked.push(bestIndex)
1101
- length += union[bestIndex].length
1102
- for (const token of tokensOf(union[bestIndex])) covered.add(token)
1103
- }
1104
- if (!picked.length && union.length) picked.push(0)
1105
- // 关键句:target 全部句子 + 每条 source 的 info 前 3 句;被 MMR 丢掉即 truncated。
1106
- const byOrigin = new Map()
1107
- union.forEach((_, index) => {
1108
- if (!byOrigin.has(origins[index])) byOrigin.set(origins[index], [])
1109
- byOrigin.get(origins[index]).push(index)
1110
- })
1111
- const keyIndices = new Set(byOrigin.get(-1) || [])
1112
- for (const [origin, indices] of byOrigin) {
1113
- if (origin === -1) continue
1114
- for (const index of [...indices].sort((a, b) => infos[b] - infos[a]).slice(0, 3)) keyIndices.add(index)
1115
- }
1116
- const missingKeys = [...keyIndices].filter((index) => !picked.includes(index)).sort((a, b) => a - b)
1117
- if (missingKeys.length) {
1118
- result.truncated = true
1119
- result.omitted = missingKeys.slice(0, 10).map((index) => union[index])
1120
- }
1121
- result.content = picked.sort((a, b) => a - b).map((index) => union[index]).join('')
1122
- }
1123
-
1124
- // 6. 覆盖率:sourceCoverage = 每条 source 的 token 覆盖率取最小;unionCoverage = 全部
1125
- // source 词元并集的覆盖率。coverage 是 proposed 对 union 的覆盖(§4.7.4)。
1126
- const contentTokens = tokensOf(result.content)
1127
- const presentSources = sourceList.filter((source) => String(source?.content || '').trim())
1128
- if (presentSources.length) {
1129
- result.sourceCoverage = Math.min(...presentSources.map((source) => tokenCoverage(tokensOf(String(source.content || '')), contentTokens)))
1130
- const unionSourceTokens = new Set()
1131
- for (const source of presentSources) {
1132
- for (const token of tokensOf(String(source.content || ''))) unionSourceTokens.add(token)
1133
- }
1134
- result.unionCoverage = tokenCoverage(unionSourceTokens, contentTokens)
1135
- }
1136
- return result
1137
- }
1138
-
1139
- // absorbOpId(spec §3.1):sha1('absorb|' + sortedIds + '|' + clean(content)).slice(0,16)。
1140
- // 内容用脱敏后的合并稿,保证从已存条目重算能得到同一个 opId(幂等门靠它对账)。
1141
- function absorbOpIdOf(sortedIds, content) {
1142
- return createHash('sha1').update('absorb|' + [...sortedIds].sort().join(',') + '|' + clean(content)).digest('hex').slice(0, 16)
1143
- }
1144
-
1145
- function appliesToSubset(sourceApplies, targetApplies) {
1146
- const target = Array.isArray(targetApplies) ? targetApplies.filter(Boolean) : []
1147
- if (target.length === 0) return true // target 不限 ⇒ 更宽,任何 source 都算子集
1148
- const source = Array.isArray(sourceApplies) ? sourceApplies.filter(Boolean) : []
1149
- return source.every((item) => target.includes(item) || target.includes('all'))
1150
- }
1151
-
1152
- const round4 = (value) => Math.round(Number(value) * 10000) / 10000
1153
-
1154
- /**
1155
- * absorb 的索引单事务(spec §4.11 auto absorb 步骤 3b-3f)。在 updateGlobalIndex 的
1156
- * 同步 mutator 里运行;expectedUpdatedAt 任一不匹配时不做任何修改并返回
1157
- * { landed:false, changed }(调用方决定 held clone 还是抛 'review changed')。
1158
- * 匹配时:merged 入索引(含出边并入 + absorbSnapshot)、target superseded +
1159
- * absorbedInto、sources archived + absorbedBy、簇外入边改指 mergedId。
1160
- */
1161
- export function applyAbsorbIndexTransaction(fresh, { mergedId, merged, targetId, sourceIds = [], expectedUpdatedAt = {}, now }) {
1162
- const entries = fresh.entries
1163
- const memberIds = [targetId, ...sourceIds].filter(Boolean)
1164
- const changed = []
1165
- for (const memberId of memberIds) {
1166
- const current = entries[memberId]
1167
- const expected = expectedUpdatedAt[memberId]
1168
- if (!current || current.status !== 'active' || (expected !== undefined && current.updatedAt !== expected)) {
1169
- changed.push(memberId || '(missing id)')
1170
- }
1171
- }
1172
- if (changed.length) return { landed: false, changed }
1173
-
1174
- const target = entries[targetId]
1175
- const sourceRefs = sourceIds.map((id) => ({ id, entry: entries[id] }))
1176
- const clusterIds = new Set(memberIds)
1177
- const linksOf = (entry) => (Array.isArray(entry?.links) ? entry.links : [])
1178
-
1179
- // 吸收前状态快照(§4.11 f):rewired 存簇外条目的完整 links,撤销整体恢复。
1180
- const rewired = []
1181
- for (const [otherId, other] of Object.entries(entries)) {
1182
- if (clusterIds.has(otherId) || otherId === mergedId) continue
1183
- if (linksOf(other).some((link) => clusterIds.has(link?.to))) {
1184
- rewired.push({ id: otherId, links: structuredClone(linksOf(other)) })
1185
- }
1186
- }
1187
- // 出边并入 merged:target/sources 自己的 links 按 (to,kind) 去重、cap 20;
1188
- // 指向簇内的边在吸收后是悬挂边,改指 mergedId,自环直接丢。
1189
- const outbound = []
1190
- const seenPairs = new Set()
1191
- for (const member of [target, ...sourceRefs.map((ref) => ref.entry)]) {
1192
- for (const link of linksOf(member)) {
1193
- if (!link || !link.to) continue
1194
- const key = `${link.to}|${link.kind || 'related'}`
1195
- if (seenPairs.has(key)) continue
1196
- seenPairs.add(key)
1197
- outbound.push(structuredClone(link))
1198
- }
1199
- }
1200
- const mergedLinks = outbound
1201
- .map((link) => (clusterIds.has(link.to) ? { ...link, to: mergedId } : link))
1202
- .filter((link) => link.to !== mergedId)
1203
- .slice(0, CURATOR_MAX_LINK_ABSORB)
1204
-
1205
- const mergedEntry = {
1206
- ...merged,
1207
- links: mergedLinks,
1208
- updatedAt: now,
1209
- absorbSnapshot: {
1210
- target: { id: targetId, status: target.status, links: structuredClone(linksOf(target)), updatedAt: target.updatedAt },
1211
- sources: sourceRefs.map(({ id, entry }) => ({ id, status: entry.status, links: structuredClone(linksOf(entry)), updatedAt: entry.updatedAt })),
1212
- rewired,
1213
- mergedLinks: structuredClone(mergedLinks),
1214
- at: now,
1215
- },
1216
- }
1217
-
1218
- entries[mergedId] = mergedEntry
1219
- target.status = 'superseded'
1220
- target.supersededBy = mergedId
1221
- target.absorbedInto = mergedId
1222
- target.validTo = now
1223
- target.updatedAt = now
1224
- const audit = { op: 'absorb', at: now, mergedId, targetId, sourceIds: [...sourceIds] }
1225
- appendAudit(mergedEntry, audit)
1226
- appendAudit(target, audit)
1227
- for (const { entry } of sourceRefs) {
1228
- entry.status = 'archived'
1229
- entry.absorbedBy = mergedId
1230
- entry.absorbedAt = now
1231
- entry.validTo = now
1232
- entry.updatedAt = now
1233
- appendAudit(entry, audit)
1234
- }
1235
- for (const { id } of rewired) {
1236
- entries[id].links = entries[id].links.map((link) => (clusterIds.has(link?.to) ? { ...link, to: mergedId } : link))
1237
- }
1238
- return { landed: true, at: now }
1239
- }
1240
-
1241
- /**
1242
- * absorb 计划提交(spec §6.7 + §4.7 + §4.10 + §4.11)。输入 curator 输出,只处理
1243
- * op === 'absorb' 的条目;每条走完 协议校验 → 降级(domain/appliesTo)→ medoid →
1244
- * 合并稿 → 覆盖率分段 → 重复门 → 风险门,auto 直接落 §4.11 事务,其余生成
1245
- * §3.3 pendingAbsorb 提案(只进索引,不进向量库)。
1246
- * 并发变化:不落 active,held pending clone,已提交向量行锁外 best-effort forget。
1247
- */
1248
- export async function commitCuratorPlans(output, { job } = {}) {
1249
- const memories = Array.isArray(output?.memories) ? output.memories : []
1250
- const plans = memories.filter((m) => m && m.op === 'absorb')
1251
- const result = { absorbed: 0, pending: 0, held: 0, skipped: [], demoted: [] }
1252
- if (!plans.length) return result
1253
- const index = loadGlobalIndex()
1254
- // 模式只在循环外读一次(§4.10)。
1255
- const mode = getSettings().curatorReviewMode || 'auto'
1256
- const now = new Date().toISOString()
1257
- const confOf = (value) => (Number.isFinite(Number(value)) ? Number(value) : 0.6)
1258
- const pendingEntries = []
1259
- const autoCommits = []
1260
- const heldNames = []
1261
-
1262
- for (const plan of plans) {
1263
- const label = String(plan?.title || plan?.target_id || '(absorb)')
1264
- // —— 协议校验(§6.7):target active;source 1–5;target 不在 source_ids。——
1265
- const targetId = String(plan?.target_id || '').trim()
1266
- const target = targetId ? index.entries[targetId] : null
1267
- if (!target || target.status !== 'active') {
1268
- result.skipped.push({ title: label, reason: `absorb target not found or not active: ${targetId || '(empty)'}` })
1269
- continue
1270
- }
1271
- const requestedSources = [...new Set((Array.isArray(plan?.source_ids) ? plan.source_ids : [])
1272
- .map((id) => String(id || '').trim()).filter(Boolean))]
1273
- if (requestedSources.length < 1 || requestedSources.length > ABSORB_MAX_SOURCES) {
1274
- result.skipped.push({ title: label, reason: `absorb needs 1-${ABSORB_MAX_SOURCES} distinct source ids, got ${requestedSources.length}` })
1275
- continue
1276
- }
1277
- if (requestedSources.includes(targetId)) {
1278
- result.skipped.push({ title: label, reason: 'absorb target must not appear in source_ids' })
1279
- continue
1280
- }
1281
- // —— 降级(§4.7.11):source 的 appliesTo 必须是 target 子集;最终只允许同 domain。
1282
- // 不满足的 source 不 absorb,降级 link(link 落地由 F1 的 commitCuratorOutput link 分支做)。
1283
- const sourceRefs = []
1284
- for (const sourceId of requestedSources) {
1285
- const source = index.entries[sourceId]
1286
- if (!source || source.status !== 'active') {
1287
- result.demoted.push({ targetId, sourceId, reason: 'source not found or not active' })
1288
- continue
1289
- }
1290
- if ((source.track || 'memory') !== (target.track || 'memory')) {
1291
- result.demoted.push({ targetId, sourceId, reason: 'track differs' })
1292
- continue
1293
- }
1294
- if ((source.domain || 'unknown') !== (target.domain || 'unknown')) {
1295
- result.demoted.push({ targetId, sourceId, reason: 'domain differs; absorb is same-domain only (link candidate)' })
1296
- continue
1297
- }
1298
- if (!appliesToSubset(source.appliesTo, target.appliesTo)) {
1299
- result.demoted.push({ targetId, sourceId, reason: 'source appliesTo is not a subset of target; demoted to link candidate' })
1300
- continue
1301
- }
1302
- sourceRefs.push({ id: sourceId, entry: source })
1303
- }
1304
- if (!sourceRefs.length) {
1305
- result.skipped.push({ title: label, reason: 'no eligible source left after domain/appliesTo demotion' })
1306
- continue
1307
- }
1308
- const sources = sourceRefs.map((ref) => ({ ...ref.entry, id: ref.id }))
1309
-
1310
- // —— medoid/representative(C4):算 medoid,模型 target 只作 provenance,
1311
- // medoid 平均相似度 <0.55 整簇跳过。——
1312
- const members = [{ id: targetId, entry: target }, ...sourceRefs.map((ref) => ({ id: ref.id, entry: ref.entry }))]
1313
- const memberText = new Map(members.map((member) => [member.id, `${member.entry.title || ''} ${member.entry.content || ''}`]))
1314
- let medoid = null
1315
- for (const member of members) {
1316
- let sum = 0
1317
- for (const other of members) {
1318
- if (other.id === member.id) continue
1319
- sum += similarTexts(memberText.get(member.id), memberText.get(other.id))
1320
- }
1321
- const avg = sum / Math.max(1, members.length - 1)
1322
- if (!medoid || avg > medoid.avg) medoid = { id: member.id, avg }
1323
- }
1324
- if (!medoid || medoid.avg < CLUSTER_MIN_PAIR) {
1325
- result.skipped.push({ title: label, reason: `medoid average similarity ${medoid ? medoid.avg.toFixed(2) : 'n/a'} is below the pair floor` })
1326
- continue
1327
- }
1328
- const representativeId = medoid.id
1329
-
1330
- // —— evidence(§4.6/§4.7.8):plan 证据(带 sourceId)优先,簇内既有证据并集,
1331
- // 去重 ≤20;每条 source 至少一条 plan 证据覆盖,否则只进复核。——
1332
- const planEvidence = (Array.isArray(plan?.evidence) ? plan.evidence : [])
1333
- .filter((item) => typeof item?.session_id === 'string' && item.session_id && typeof item?.quote === 'string' && item.quote.trim())
1334
- .map((item) => ({
1335
- sessionId: item.session_id,
1336
- quote: truncate(item.quote, 500),
1337
- sourceId: typeof item?.source_id === 'string' && item.source_id.trim() ? item.source_id.trim() : null,
1338
- }))
1339
- .slice(0, 20)
1340
- const clusterEvidence = []
1341
- const seenEvidence = new Set()
1342
- for (const item of [...planEvidence, ...members.flatMap((member) => (Array.isArray(member.entry.evidence) ? member.entry.evidence : [])
1343
- .map((e) => ({ sessionId: e?.sessionId, quote: e?.quote, sourceId: member.id })))] ) {
1344
- if (clusterEvidence.length >= 20) break
1345
- const sessionId = typeof item?.sessionId === 'string' ? item.sessionId : null
1346
- const quote = typeof item?.quote === 'string' ? item.quote : ''
1347
- if (!sessionId || !quote.trim()) continue
1348
- const key = `${sessionId}|${clean(quote)}|${item.sourceId || ''}`
1349
- if (seenEvidence.has(key)) continue
1350
- seenEvidence.add(key)
1351
- clusterEvidence.push({ sessionId, quote: truncate(quote, 500), sourceId: item.sourceId || null })
1352
- }
1353
- const uncoveredSources = sourceRefs.filter((ref) => !planEvidence.some((item) => item.sourceId === ref.id))
1354
-
1355
- // —— 合并稿 + 覆盖率分段(§4.7.6)。——
1356
- const idf = absorbIdf(index)
1357
- const composed = composeAbsorbContent({ target, sources, proposed: plan?.content, maxChars: ABSORB_MAX_CHARS, idf })
1358
- const mergedContent = redactSecrets(composed.content)
1359
- if (!mergedContent.trim()) {
1360
- result.skipped.push({ title: label, reason: 'absorb produced an empty merged draft' })
1361
- continue
1362
- }
1363
- if (composed.sourceCoverage < ABSORB_REVIEW_SOURCE_COVERAGE || composed.unionCoverage < ABSORB_REVIEW_UNION_COVERAGE) {
1364
- result.skipped.push({ title: label, reason: `absorb coverage below floor (source ${composed.sourceCoverage.toFixed(2)} / union ${composed.unionCoverage.toFixed(2)})` })
1365
- continue
1366
- }
1367
- const longestSource = Math.max(0, ...sourceRefs.map((ref) => String(ref.entry.content || '').length))
1368
- const belowLengthFloor = mergedContent.length < ABSORB_MIN_LENGTH_RATIO * longestSource
1369
-
1370
- // —— 幂等门(§6.7):同 opId 的提案/合并稿已存在 → skip。——
1371
- const memberIdsSorted = [targetId, ...sourceRefs.map((ref) => ref.id)].sort()
1372
- const opId = absorbOpIdOf(memberIdsSorted, mergedContent)
1373
- if (Object.values(index.entries).some((e) => e?.absorbOpId === opId || e?.pendingAbsorb?.opId === opId)) {
1374
- result.skipped.push({ title: label, reason: `duplicate absorb opId ${opId}; already proposed or absorbed` })
1375
- continue
1376
- }
1377
-
1378
- // —— title(§4.7.7)与重复门(§6.7):与簇外 active 条目 similarTexts ≥0.90 →
1379
- // pending 'absorb duplicate of <id>';0.55–0.90 → 新条目打 duplicateOf。——
1380
- const titleCandidate = String(target.title || '').trim()
1381
- || String(plan?.title || '').trim()
1382
- || String(index.entries[representativeId]?.title || '').trim()
1383
- const title = truncate(titleCandidate || label, 180)
1384
- let absorbDuplicate = null
1385
- for (const [otherId, other] of Object.entries(index.entries || {})) {
1386
- if (memberIdsSorted.includes(otherId)) continue
1387
- if (other?.status !== 'active') continue
1388
- const similarity = similarTexts(`${title} ${mergedContent}`, `${other.title || ''} ${other.content || ''}`)
1389
- if (similarity > (absorbDuplicate?.similarity ?? 0)) absorbDuplicate = { id: otherId, similarity }
1390
- }
1391
-
1392
- // —— 风险分(§4.10):写到所有条目(active 也写)。——
1393
- const decision = reviewDecision({ m: plan, op: 'absorb', evidence: planEvidence, targetId, index, mode })
1394
-
1395
- let reviewReason = null
1396
- if (composed.sourceCoverage < ABSORB_AUTO_SOURCE_COVERAGE || composed.unionCoverage < ABSORB_AUTO_UNION_COVERAGE
1397
- || belowLengthFloor || (composed.truncated && composed.omitted.length)) {
1398
- reviewReason = 'absorb coverage'
1399
- } else if (absorbDuplicate && absorbDuplicate.similarity >= DUP_REJECT_DICE) {
1400
- reviewReason = `absorb duplicate of ${absorbDuplicate.id}`
1401
- } else if (uncoveredSources.length || !planEvidence.length) {
1402
- reviewReason = decision.hard ? decision.reasons[0] : 'evidence not grounded'
1403
- } else if (decision.review) {
1404
- reviewReason = decision.hard ? decision.reasons[0] : (String(plan?.review_reason || '').trim() || 'risk threshold')
1405
- }
1406
-
1407
- const confidence = Math.min(0.95, Math.max(confOf(target.confidence), ...sourceRefs.map((ref) => confOf(ref.entry.confidence)), confOf(plan?.confidence)))
1408
- const clusterCreatedAt = members.map((member) => member.entry.createdAt).filter(Boolean).sort()[0] || now
1409
- const expectedUpdatedAt = {
1410
- [targetId]: target.updatedAt,
1411
- ...Object.fromEntries(sourceRefs.map((ref) => [ref.id, ref.entry.updatedAt])),
1412
- }
1413
- const reviewRiskReasons = reviewReason === 'absorb coverage' ? [...decision.reasons, 'absorb coverage'] : decision.reasons
1414
- const entryBase = {
1415
- track: target.track || 'memory',
1416
- domain: target.domain || 'general',
1417
- appliesTo: Array.isArray(target.appliesTo) ? structuredClone(target.appliesTo).slice(0, 20) : [],
1418
- title,
1419
- content: mergedContent,
1420
- confidence,
1421
- evidence: clusterEvidence,
1422
- status: 'active',
1423
- absorbedFrom: memberIdsSorted,
1424
- absorbedAt: now,
1425
- absorbOpId: opId,
1426
- representativeId,
1427
- mergeMode: composed.mode,
1428
- mergeCoverage: round4(composed.coverage),
1429
- sourceCoverage: round4(composed.sourceCoverage),
1430
- unionCoverage: round4(composed.unionCoverage),
1431
- reviewRisk: decision.risk,
1432
- reviewRiskReasons,
1433
- createdAt: clusterCreatedAt,
1434
- updatedAt: now,
1435
- }
1436
- if (absorbDuplicate && absorbDuplicate.similarity >= TOPIC_DICE && absorbDuplicate.similarity < DUP_REJECT_DICE) {
1437
- entryBase.duplicateOf = absorbDuplicate.id
1438
- }
1439
-
1440
- if (reviewReason) {
1441
- // pending absorb(§3.3):只进索引,绝不进向量库;accept 时才提交提案 id 本身。
1442
- pendingEntries.push({
1443
- id: newMemoryId('gmem'),
1444
- entry: {
1445
- ...entryBase,
1446
- status: 'pending_review',
1447
- reviewReason,
1448
- conflictingWith: targetId,
1449
- pendingAbsorb: { targetId, sourceIds: sourceRefs.map((ref) => ref.id), opId, representativeId, expectedUpdatedAt },
1450
- source: 'curator',
1451
- },
1452
- })
1453
- result.pending += 1
1454
- continue
1455
- }
1456
- autoCommits.push({
1457
- mergedId: newMemoryId('gmem'),
1458
- entry: entryBase,
1459
- targetId,
1460
- sourceIds: sourceRefs.map((ref) => ref.id),
1461
- expectedUpdatedAt,
1462
- })
1463
- }
1464
-
1465
- if (pendingEntries.length) {
1466
- if (job) job.step = `writing ${pendingEntries.length} pending absorb proposals`
1467
- await withManagedCuratorWrite(() => retryStoreWrite(() => updateGlobalIndex((fresh) => {
1468
- for (const { id, entry } of pendingEntries) fresh.entries[id] = entry
1469
- })))
1470
- }
1471
-
1472
- if (autoCommits.length) {
1473
- if (job) job.step = `committing ${autoCommits.length} absorb merges`
1474
- await withManagedCuratorWrite(async () => {
1475
- const route = engineRoute()
1476
- const committedNames = []
1477
- try {
1478
- // 先向量后索引(§4.11 auto absorb 步骤 2→3):索引失败时能补偿已提交行。
1479
- if (route !== 'lexical') {
1480
- await commit({
1481
- payload: {
1482
- recall_files: autoCommits.map(({ mergedId, entry }) => ({ name: mergedId, track: entry.track, description: entry.title, content: entry.content })),
1483
- resource: [],
1484
- user: {},
1485
- },
1486
- route,
1487
- db: globalDbPath(),
1488
- })
1489
- for (const c of autoCommits) committedNames.push(c.mergedId)
1490
- const vector = activeEntryStamp(route)
1491
- if (vector) for (const c of autoCommits) c.entry.vector = vector
1492
- }
1493
- await retryStoreWrite(() => updateGlobalIndex((fresh) => {
1494
- for (const c of autoCommits) {
1495
- const outcome = applyAbsorbIndexTransaction(fresh, {
1496
- mergedId: c.mergedId, merged: c.entry, targetId: c.targetId,
1497
- sourceIds: c.sourceIds, expectedUpdatedAt: c.expectedUpdatedAt, now,
1498
- })
1499
- if (!outcome.landed) {
1500
- // 并发变化(§4.11 步骤 5):不落 active,生成 held pending clone;
1501
- // expectedUpdatedAt 刷新为当前值,人审时再做快照校验。
1502
- const heldId = newMemoryId('gmem')
1503
- const refreshed = {}
1504
- for (const memberId of [c.targetId, ...c.sourceIds]) {
1505
- refreshed[memberId] = fresh.entries[memberId]?.updatedAt || c.expectedUpdatedAt[memberId]
1506
- }
1507
- const held = {
1508
- ...c.entry,
1509
- status: 'pending_review',
1510
- reviewReason: 'cluster changed while curator was running',
1511
- conflictingWith: c.targetId,
1512
- pendingAbsorb: { targetId: c.targetId, sourceIds: c.sourceIds, opId: c.entry.absorbOpId, representativeId: c.entry.representativeId, expectedUpdatedAt: refreshed },
1513
- updatedAt: now,
1514
- }
1515
- // 已提交向量库的是 mergedId 这一行;held 克隆从未进过向量库,
1516
- // 绝不能继承"提交成功即落戳"的 entry.vector(同 curator-commit 的坑)。
1517
- delete held.vector
1518
- fresh.entries[heldId] = held
1519
- heldNames.push(c.mergedId)
1520
- result.held += 1
1521
- continue
1522
- }
1523
- result.absorbed += 1
1524
- }
1525
- }))
1526
- } catch (error) {
1527
- if (committedNames.length) await compensateCuratorCommit(error, { files: committedNames.map((name) => ({ name })), route })
1528
- throw error
1529
- }
1530
- // held clone 的已提交行 best-effort forget(锁外 await,修 D11);只在向量路由
1531
- // 真的提交过行时才需要。删不掉必须可见。
1532
- if (route !== 'lexical') {
1533
- for (const name of heldNames) {
1534
- try {
1535
- await forget({ db: globalDbPath(), name })
1536
- } catch (forgetError) {
1537
- record({
1538
- kind: 'curate', scope: 'global', ok: false, level: 'error',
1539
- message: `集合吸收并发保护:held clone 已生成,但向量行 ${name} 撤销失败(引擎库残留孤儿行,需手动清理)`,
1540
- detail: { op: 'absorb', heldForgetFailed: true, name, error: String(forgetError?.message || forgetError) },
1541
- refs: [name],
1542
- })
1543
- }
1544
- }
1545
- }
1546
- })
1547
- }
1548
-
1549
- if (result.absorbed || result.pending || result.held || result.skipped.length || result.demoted.length) {
1550
- record({
1551
- kind: 'curate',
1552
- scope: 'global',
1553
- ok: true,
1554
- message: `集合吸收:合并 ${result.absorbed} / 待复核 ${result.pending}`
1555
- + (result.held ? ` / 并发暂扣 ${result.held}` : '')
1556
- + (result.skipped.length ? ` / 跳过 ${result.skipped.length}` : '')
1557
- + (result.demoted.length ? ` / 降级 link ${result.demoted.length}` : ''),
1558
- detail: { op: 'absorb', ...result, skipped: result.skipped.slice(0, 20), demoted: result.demoted.slice(0, 20) },
1559
- refs: autoCommits.map((c) => c.mergedId).slice(0, 20),
1560
- })
1561
- }
1562
- return result
1563
- }
1564
-
1565
- /**
1566
- * 撤销集合吸收(spec §4.11 undo-absorb)。merged 必须 active 且带 absorbSnapshot;
1567
- * 同一事务恢复 target/sources/rewired,merged 归档(保留正文)。吸收后又被人工改过
1568
- * (updatedAt > absorbedAt)的成员拒绝整体撤销并返回可读错误——部分恢复比不恢复更
1569
- * 难对账。不删除、不写向量。
1570
- */
1571
- export async function undoGlobalAbsorb({ id } = {}) {
1572
- const mergedId = String(id || '').trim()
1573
- if (!mergedId) throw new Error('undo-absorb needs the merged entry id')
1574
- const index = loadGlobalIndex()
1575
- const merged = index.entries[mergedId]
1576
- if (!merged || merged.status !== 'active' || !merged.absorbSnapshot) {
1577
- throw new Error('undo-absorb needs an active merged entry with an absorb snapshot')
1578
- }
1579
- const snapshot = merged.absorbSnapshot
1580
- const memberRefs = [snapshot.target, ...(Array.isArray(snapshot.sources) ? snapshot.sources : [])].filter(Boolean)
1581
- const changedMembers = []
1582
- for (const member of memberRefs) {
1583
- const current = index.entries[member.id]
1584
- if (!current) continue
1585
- const absorbedAt = Date.parse(current.absorbedAt || '') || Date.parse(snapshot.at || '') || 0
1586
- if ((Date.parse(current.updatedAt || '') || 0) > absorbedAt) changedMembers.push(member.id)
1587
- }
1588
- if (changedMembers.length) {
1589
- throw new Error(`absorb undo refused: ${changedMembers.join(', ')} changed after absorption; restore them manually or resolve each edit first`)
1590
- }
1591
- await retryStoreWrite(() => updateGlobalIndex((fresh) => {
1592
- if (JSON.stringify(fresh.entries[mergedId]) !== JSON.stringify(merged)) throw new Error('absorb entry changed; reload and retry')
1593
- const at = new Date().toISOString()
1594
- const targetSnap = snapshot.target
1595
- const currentTarget = targetSnap?.id ? fresh.entries[targetSnap.id] : null
1596
- if (currentTarget && currentTarget.status === 'superseded' && currentTarget.supersededBy === mergedId) {
1597
- currentTarget.status = targetSnap.status || 'active'
1598
- if (Array.isArray(targetSnap.links)) currentTarget.links = structuredClone(targetSnap.links)
1599
- delete currentTarget.supersededBy
1600
- delete currentTarget.absorbedInto
1601
- delete currentTarget.validTo
1602
- currentTarget.updatedAt = at
1603
- }
1604
- for (const sourceSnap of Array.isArray(snapshot.sources) ? snapshot.sources : []) {
1605
- const current = fresh.entries[sourceSnap.id]
1606
- if (!current || current.status !== 'archived' || current.absorbedBy !== mergedId) continue
1607
- current.status = sourceSnap.status || 'active'
1608
- if (Array.isArray(sourceSnap.links)) current.links = structuredClone(sourceSnap.links)
1609
- delete current.absorbedBy
1610
- delete current.absorbedAt
1611
- delete current.validTo
1612
- current.updatedAt = at
1613
- }
1614
- for (const rewiredSnap of Array.isArray(snapshot.rewired) ? snapshot.rewired : []) {
1615
- const current = fresh.entries[rewiredSnap.id]
1616
- if (current && Array.isArray(rewiredSnap.links)) current.links = structuredClone(rewiredSnap.links)
1617
- }
1618
- const stored = fresh.entries[mergedId]
1619
- stored.status = 'archived'
1620
- stored.absorbUndoneAt = at
1621
- stored.updatedAt = at
1622
- const audit = { op: 'undo-absorb', at, mergedId }
1623
- appendAudit(currentTarget, audit)
1624
- for (const sourceSnap of Array.isArray(snapshot.sources) ? snapshot.sources : []) {
1625
- appendAudit(fresh.entries[sourceSnap.id], audit)
1626
- }
1627
- appendAudit(stored, audit)
1628
- }))
1629
- // 活动日志 CURATOR_ABSORB_UNDO(§4.11 撤销 4):以 detail.op 标记,kind 仍是 curate。
1630
- record({
1631
- kind: 'curate',
1632
- scope: 'global',
1633
- ok: true,
1634
- message: `撤销集合吸收 ${mergedId}:target 与来源记忆已恢复,merged 已归档`,
1635
- detail: { op: 'undo-absorb', id: mergedId, snapshotAt: snapshot.at || null },
1636
- refs: [mergedId],
1637
- })
1638
- return { id: mergedId, status: 'archived', undone: true }
1639
- }
1640
-
1641
- // —— 宿主契约兼容(docs/host-adaptation.md §3.4:形状变化用能力探测,不按版本号分支)——
1642
- // 0.2.2-rc.2 随 SubagentActivationSpec 扁平化(parent/cwd/prompt/agentOptions 平铺到
1643
- // 顶层,无 request 外层)同批在 SubagentService 上新增了树内省方法 rootOf/namesOf/
1644
- // resolveName/waitForTreeWork(0.2.1-rc.5 与 0.2.2-rc.1 上四者均不存在)。用标记方法
1645
- // 探测形态:真实宿主上一次命中,无多余字段、无异常噪音。
1646
- export function activationUsesFlatSpec(subagents) {
1647
- return typeof subagents?.rootOf === 'function' || typeof subagents?.namesOf === 'function'
1648
- }
1649
-
1650
- export function startGlobalCuration(ctx, { sessionIds, parentSessionId, model } = {}) {
1651
- const ids = [...new Set((Array.isArray(sessionIds) ? sessionIds : []).filter((s) => typeof s === 'string' && s.trim()))]
1652
- const jobId = `curate-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`
1653
- const abort = new AbortController()
1654
- const job = {
1655
- id: jobId,
1656
- status: 'running',
1657
- step: 'queued',
1658
- logs: [],
1659
- createdAt: new Date().toISOString(),
1660
- endedAt: null,
1661
- error: null,
1662
- result: null,
1663
- abort,
1664
- }
1665
- jobs.set(jobId, job)
1666
- const log = (line) => {
1667
- job.logs.push(`[${new Date().toISOString()}] ${line}`)
1668
- if (job.logs.length > 200) job.logs.splice(0, job.logs.length - 200)
1669
- }
1670
-
1671
- void (async () => {
1672
- try {
1673
- if (ids.length === 0) throw new Error('select at least one conversation')
1674
- if (ids.length > MAX_SESSIONS) throw new Error(`at most ${MAX_SESSIONS} conversations per curation`)
1675
- const sessionQuery = ctx.get?.('sessionQuery')
1676
- if (!sessionQuery) throw new Error('sessionQuery is unavailable')
1677
- const agents = ctx.get?.('agents')
1678
- const parent = agents?.get?.(parentSessionId)
1679
- if (!parent) throw new Error('the current conversation is not live; open a live conversation and retry')
1680
- const subagents = ctx.get?.('subagents')
1681
- if (!subagents?.startActivation) throw new Error('subagents service is unavailable')
1682
-
1683
- job.step = 'reading sessions'
1684
- log(`reading ${ids.length} session(s)`)
1685
- const meta = await readSessionMeta(sessionQuery, ids)
1686
- const sessions = []
1687
- let total = 0
1688
- let transcriptTokens = 0
1689
- for (const id of ids) {
1690
- if (abort.signal.aborted) throw new Error('cancelled by user')
1691
- const snapshot = await readSession(sessionQuery, id)
1692
- const record = meta.get(id)
1693
- const header = snapshot.header || record?.header || {}
1694
- const remaining = Math.max(2000, Math.min(MAX_SESSION_CHARS, MAX_TOTAL_CHARS - total))
1695
- // C2:token 预算跨会话累计(30k),与字符预算同时生效;先停谁算谁。
1696
- const tokenRemaining = Math.max(500, MAX_TRANSCRIPT_TOKENS - transcriptTokens)
1697
- const transcript = condenseEvents(snapshot.events, remaining, { maxTokens: tokenRemaining })
1698
- total += transcript.length
1699
- transcriptTokens += estTokens(transcript)
1700
- sessions.push({
1701
- id,
1702
- title: record?.title || record?.displayTitle || header.title || '',
1703
- createdAt: header.createdAt || null,
1704
- cwd: header.cwd || '',
1705
- agentPreset: header.agentPreset || '',
1706
- live: record?.live === true,
1707
- transcript,
1708
- })
1709
- if (total >= MAX_TOTAL_CHARS || transcriptTokens >= MAX_TRANSCRIPT_TOKENS) break
1710
- }
1711
-
1712
- // —— §4.5/§6.6(包 F1):相关性打包索引(4000 tokens)+ 候选簇(2000 tokens),
1713
- // 取代旧 compactGlobalIndex 的"插入顺序前 200 条"平铺。sessionCorpus 同步构建,
1714
- // 提交层证据落地(§4.6)用同一份转录做回放校验。
1715
- const globalIndex = loadGlobalIndex()
1716
- const sessionText = sessions.map((s) => s.transcript).join('\n')
1717
- const packedIndex = packCuratorIndexContext({ index: globalIndex, sessionText })
1718
- const packedClusters = packCuratorClusterContext(buildCandidateClusters(globalIndex))
1719
- const input = JSON.stringify({
1720
- sessions,
1721
- existing_global_index: packedIndex.entries,
1722
- index_truncated: packedIndex.omitted > 0,
1723
- candidate_clusters: packedClusters.clusters,
1724
- clusters_truncated: packedClusters.truncated,
1725
- })
1726
- const prompt = loadPrompt('global-curator', { input }).text
1727
- job.step = 'curator running'
1728
- log('starting non-main curator subagent')
1729
- const curatorModel = model || getSettings().curatorModel
1730
- const agentOptions = agentOptionsFor(curatorModel)
1731
- const task = {
1732
- parent,
1733
- cwd: parent.session?.header?.cwd,
1734
- prompt: [{ type: 'text', text: prompt }],
1735
- ...(agentOptions ? { agentOptions } : {}),
1736
- }
1737
- const base = {
1738
- provider: 'spawn',
1739
- label: 'dsh-memu-memory global curator',
1740
- delivery: 'caller',
1741
- signal: abort.signal,
1742
- }
1743
- const flat = activationUsesFlatSpec(subagents)
1744
- let activation
1745
- try {
1746
- activation = await subagents.startActivation(flat ? { ...base, ...task } : { ...base, request: task })
1747
- } catch (error) {
1748
- // 零副作用兜底:两代宿主都在产生任何副作用(建子会话、落盘)之前读取形态
1749
- // 不符的字段并抛 TypeError——旧契约 src/index.ts 读 spec.request.maxDepth
1750
- //(0.2.1-rc.5:274 / 0.2.2-rc.1:276),0.2.2-rc.2+:275 读 spec.parent.id。遇到
1751
- // 极简 mock(只提供 startActivation,无从探测)或未来宿主移除标记方法时,catch
1752
- // 后换另一种形态重试一次是安全的。仅 TypeError 且未被取消时重试,且只重试一次。
1753
- if (!(error instanceof TypeError) || abort.signal.aborted) throw error
1754
- log(`activation shape mismatch (${flat ? 'flat' : 'nested'} rejected by TypeError); retrying with ${flat ? 'nested' : 'flat'} shape`)
1755
- activation = await subagents.startActivation(flat ? { ...base, request: task } : { ...base, ...task })
1756
- }
1757
- let result
1758
- try {
1759
- result = await activation.result
1760
- } finally {
1761
- try { await activation.dispose() } catch {}
1762
- }
1763
- if (result?.stopReason !== 'completed') {
1764
- throw new Error(`curator stopped: ${result?.stopReason || 'unknown'}`)
1765
- }
1766
- const text = textOf(result.output)
1767
- const output = parseJsonObject(text)
1768
- if (!output || !Array.isArray(output.memories)) {
1769
- throw new Error(`curator did not return valid JSON: ${truncate(text, 800)}`)
1770
- }
1771
- job.step = 'committing'
1772
- // 生产调用必须传会话语料(§4.6.6):证据 quote 要能在本次策划的转录里回放,
1773
- // 否则一律 pending。transcripts 已在 condenseEvents 里脱敏。
1774
- const committed = await commitCuratorOutput(output, {
1775
- job,
1776
- sessionCorpus: buildEvidenceCorpus(sessions.map((s) => ({ id: s.id, transcript: s.transcript }))),
1777
- })
1778
- job.status = 'completed'
1779
- job.endedAt = new Date().toISOString()
1780
- job.result = {
1781
- sessions: output.sessions || [],
1782
- domainSummary: output.domain_summary || {},
1783
- created: committed.created,
1784
- merged: committed.merged,
1785
- superseded: committed.superseded,
1786
- linked: committed.linked || 0,
1787
- skipped: committed.skipped,
1788
- }
1789
- log(`done: ${committed.created} created, ${committed.merged} merged, ${committed.superseded} superseded, ${committed.linked || 0} linked`)
1790
- } catch (error) {
1791
- const aborted = abort.signal.aborted || /cancelled by user/.test(String(error?.message || ''))
1792
- job.status = aborted ? 'cancelled' : 'error'
1793
- job.error = String(error?.message || error)
1794
- job.endedAt = new Date().toISOString()
1795
- log(`${job.status}: ${job.error}`)
1796
- // 失败落活动日志:此前只写内存 job.error,宿主重启后失败原因无从追溯
1797
- //(issue #3 附带观察)。取消不记——那不是故障。
1798
- if (!aborted) {
1799
- record({
1800
- kind: 'curate', scope: 'global', ok: false, level: 'error',
1801
- message: '全局提炼失败:' + job.error,
1802
- detail: { jobId, model: model || getSettings().curatorModel, sessions: ids.length, step: job.step || null },
1803
- })
1804
- }
1805
- }
1806
- })()
1807
-
1808
- return getCurationJob(jobId)
1809
- }
1810
-
1811
- export { readSession as readSessionSnapshot }
1
+ import { createHash } from 'node:crypto'
2
+ import {
3
+ globalDbPath, loadGlobalIndex, updateGlobalIndex, newMemoryId, getSettings, effectiveVectorRoute,
4
+ } from './state.js'
5
+ import { commit, forget } from './memu.js'
6
+ import { loadPrompt } from './prompts.js'
7
+ import { retryStoreWrite, redactSecrets, warn, isSafeId } from './paths.js'
8
+ import { record } from './activity-log.js'
9
+ import { activeEntryStamp, assertVectorWriteAllowed, hasActiveVectorGeneration, readVectorState, withVectorWrite } from './vector-profile.js'
10
+ import { upsertLexiconTerm } from './lexicon.js'
11
+ import { clean, bigrams, dice, similarTexts, DUP_REJECT_DICE, TOPIC_DICE } from './text-similarity.js'
12
+ import { estTokens } from './budget.js'
13
+ import { effectiveAgentPreset } from './consolidation-snapshot.js'
14
+ // —— 候选检索、证据落地与全局关联 ——
15
+ import {
16
+ buildCandidateClusters,
17
+ buildCorpus,
18
+ bm25,
19
+ globalConflictCheck,
20
+ pairFeatures,
21
+ pairScore,
22
+ rankPairCandidates,
23
+ tokenize,
24
+ } from './text-retrieval.js'
25
+ import { buildEvidenceCorpus, groundEvidence } from './curator-evidence.js'
26
+ import { applyGlobalLinks, validateGlobalLink, appendAudit } from './global-graph.js'
27
+ import {
28
+ ABSORB_ABSTRACTIVE_COVERAGE,
29
+ ABSORB_AUTO_SOURCE_COVERAGE,
30
+ ABSORB_AUTO_UNION_COVERAGE,
31
+ ABSORB_MAX_CHARS,
32
+ ABSORB_MAX_SOURCES,
33
+ ABSORB_MIN_LENGTH_RATIO,
34
+ ABSORB_REVIEW_SOURCE_COVERAGE,
35
+ ABSORB_REVIEW_UNION_COVERAGE,
36
+ CLUSTER_MIN_PAIR,
37
+ CURATOR_CLUSTER_TOKENS,
38
+ CURATOR_INDEX_MAX_ENTRIES,
39
+ CURATOR_INDEX_TOKENS,
40
+ CURATOR_MAX_LINK_ABSORB,
41
+ EVIDENCE_MAX,
42
+ PAIR_ABSORB_MIN,
43
+ PAIR_DUPLICATE_MIN,
44
+ PAIR_LINK_MIN,
45
+ PAIR_SCAN_LIMIT,
46
+ } from './curator-policy.js'
47
+
48
+ const MAX_SESSIONS = 10
49
+ const MAX_TOTAL_CHARS = 90_000
50
+ const MAX_SESSION_CHARS = 14_000
51
+ // 转录同时受字符预算与 token 预算约束。字符预算保留原有行为;token 预算
52
+ // 按 estTokens 累计,超过 30k 就停——中文转录的字符数≈token 数,只靠 90k 字符
53
+ // 在上限时仍会送出约 90k token。
54
+ const MAX_TRANSCRIPT_TOKENS = 30_000
55
+ // curator 输出上限为 24 条,与提示词一致;超出的条目在提交前丢弃并记日志。
56
+ const MAX_CURATOR_MEMORIES = 24
57
+ const jobs = new Map()
58
+
59
+ function managedVectorIntent() {
60
+ if (effectiveVectorRoute() !== 'managed-local') return false
61
+ try {
62
+ const state = readVectorState({ tolerateMissing: true }).state
63
+ return Boolean(state && (state.active || state.requested || state.pending))
64
+ } catch {
65
+ return true
66
+ }
67
+ }
68
+
69
+ // 与 memory.js 同一条口径:受管路由还没有代际时,引擎这一步按词法处理(索引照写),
70
+ // 否则 MemU 会以 "managed local vector profile is not active" 拒绝整次提炼。
71
+ function engineRoute() {
72
+ const route = effectiveVectorRoute()
73
+ return route === 'managed-local' && !hasActiveVectorGeneration() ? 'lexical' : route
74
+ }
75
+
76
+ async function withManagedCuratorWrite(action) {
77
+ if (!managedVectorIntent()) return action()
78
+ // Same rule as the private write path: requested-but-never-migrated has no
79
+ // generation to stay consistent with, so the global index + engine still get
80
+ // the memories. Failing here would throw away a whole curation run.
81
+ if (!hasActiveVectorGeneration()) {
82
+ warn('managed vector write degraded to index+engine: no active vector generation; run the profile switch to enable vectors')
83
+ record({ kind: 'vector', level: 'warn', scope: 'global', message: '向量未激活,全局提炼已降级为索引+引擎', detail: { reason: 'no active vector generation' } })
84
+ return action()
85
+ }
86
+ return withVectorWrite(async () => { assertVectorWriteAllowed(); return action() })
87
+ }
88
+
89
+ function textOf(blocks) {
90
+ if (!Array.isArray(blocks)) return ''
91
+ return blocks
92
+ .filter((b) => b?.type === 'text' && typeof b.text === 'string')
93
+ .map((b) => b.text)
94
+ .join('')
95
+ .trim()
96
+ }
97
+
98
+ function truncate(text, max) {
99
+ const s = String(text || '')
100
+ return s.length > max ? `${s.slice(0, max)}…` : s
101
+ }
102
+
103
+ function argsText(value) {
104
+ if (value == null) return ''
105
+ return typeof value === 'string' ? value : JSON.stringify(value)
106
+ }
107
+
108
+ function toolCallKey(name, args) {
109
+ return `${name || '?'}\u0000${argsText(args)}`
110
+ }
111
+
112
+ function blockCallId(block) {
113
+ return typeof block?.id === 'string' && block.id ? block.id : null
114
+ }
115
+
116
+ function eventCallId(event) {
117
+ return typeof event?.data?.callId === 'string' && event.data.callId ? event.data.callId : null
118
+ }
119
+
120
+ /**
121
+ * 转录压缩:assistant/message 的 tool-call 块与独立 tool/call 事件是同一
122
+ * 次调用的双写,以 tool/call 事件为准——块只在没有对应事件时保留(先按 callId
123
+ * 配对;两侧都没有 id 时按 name+arguments 计数配对,支持重复调用)。字符预算
124
+ * 保留原行为,另加可选 token 预算(累计 estTokens 超预算即停)。
125
+ * 工具行额度可按域覆盖:编码域的修改重点在命令/错误签名/参数里,300/400 只够开头。
126
+ */
127
+ export const CONDENSE_TOOL_RESULT_CHARS = 400
128
+ export const CONDENSE_TOOL_CALL_CHARS = 300
129
+ const CONDENSE_TOOL_RESULT_CHARS_CODING = 1_400
130
+ const CONDENSE_TOOL_CALL_CHARS_CODING = 700
131
+
132
+ export function condenseLimitsFor(domain) {
133
+ return String(domain) === 'coding'
134
+ ? { toolResultChars: CONDENSE_TOOL_RESULT_CHARS_CODING, toolCallChars: CONDENSE_TOOL_CALL_CHARS_CODING }
135
+ : { toolResultChars: CONDENSE_TOOL_RESULT_CHARS, toolCallChars: CONDENSE_TOOL_CALL_CHARS }
136
+ }
137
+
138
+ export function condenseEvents(events, maxChars = MAX_SESSION_CHARS, { maxTokens = Infinity, toolResultChars = CONDENSE_TOOL_RESULT_CHARS, toolCallChars = CONDENSE_TOOL_CALL_CHARS } = {}) {
139
+ // 事件侧先收一遍:callId 集合 + (name, arguments) 计数,供块侧配对。
140
+ const eventCallIds = new Set()
141
+ const eventSignatures = new Map()
142
+ for (const event of events || []) {
143
+ if (event?.type !== 'tool/call') continue
144
+ const id = eventCallId(event)
145
+ if (id) eventCallIds.add(id)
146
+ const key = toolCallKey(event.data?.name, event.data?.arguments)
147
+ eventSignatures.set(key, (eventSignatures.get(key) || 0) + 1)
148
+ }
149
+ const claimedSignatures = new Map()
150
+ const lines = []
151
+ for (const event of events || []) {
152
+ try {
153
+ const type = event?.type
154
+ if (type === 'user/message') {
155
+ if (event.data?.source?.kind !== 'user') continue
156
+ const text = textOf(event.data?.content)
157
+ if (text) lines.push(`User: ${text}`)
158
+ continue
159
+ }
160
+ if (type === 'assistant/message') {
161
+ const blocks = event.data?.message?.content || []
162
+ const texts = textOf(blocks)
163
+ if (texts) lines.push(`Assistant: ${texts}`)
164
+ for (const b of blocks) {
165
+ if (b?.type !== 'tool-call') continue
166
+ const id = blockCallId(b)
167
+ if (id && eventCallIds.has(id)) continue
168
+ // 无 id 或 id 未配对:用 name+arguments 计数配对,事件侧有几个就吸收几个块。
169
+ const key = toolCallKey(b.name, b.arguments)
170
+ const available = (eventSignatures.get(key) || 0) - (claimedSignatures.get(key) || 0)
171
+ if (available > 0) {
172
+ claimedSignatures.set(key, (claimedSignatures.get(key) || 0) + 1)
173
+ continue
174
+ }
175
+ lines.push(`Tool call: ${b.name}${b.arguments ? ` ${truncate(argsText(b.arguments), toolCallChars)}` : ''}`)
176
+ }
177
+ continue
178
+ }
179
+ if (type === 'tool/result') {
180
+ const text = textOf(event.data?.message?.content)
181
+ if (text) lines.push(`Tool result${event.data?.message?.isError ? ' (error)' : ''}: ${truncate(text, toolResultChars)}`)
182
+ continue
183
+ }
184
+ if (type === 'tool/call') {
185
+ lines.push(`Tool call: ${event.data?.name || '?'} ${truncate(argsText(event.data?.arguments), toolCallChars)}`)
186
+ }
187
+ } catch {}
188
+ }
189
+ let kept = lines
190
+ let tokenTruncated = false
191
+ if (Number.isFinite(maxTokens) && maxTokens > 0) {
192
+ kept = []
193
+ let used = 0
194
+ for (const line of lines) {
195
+ const cost = estTokens(line) + (kept.length > 0 ? 1 : 0)
196
+ // 永远保留第一行(与 budget.packToBudget 同口径),之后累计超预算即停。
197
+ if (kept.length > 0 && used + cost > maxTokens) { tokenTruncated = true; break }
198
+ kept.push(line)
199
+ used += cost
200
+ }
201
+ }
202
+ let joined = redactSecrets(kept.join('\n'))
203
+ if (tokenTruncated) {
204
+ joined += `\n...[truncated ${lines.length - kept.length} lines over token budget ${maxTokens}]...`
205
+ }
206
+ if (joined.length > maxChars) {
207
+ const head = joined.slice(0, Math.floor(maxChars * 0.6))
208
+ const tail = joined.slice(-Math.floor(maxChars * 0.35))
209
+ joined = `${head}\n...[truncated ${joined.length - maxChars} chars]...\n${tail}`
210
+ }
211
+ return joined
212
+ }
213
+
214
+ // —— curator 上下文打包 ——
215
+ // 旧 compactGlobalIndex 是"插入顺序前 200 条 ×600 字"的平铺,第 201 条后永远不可见、
216
+ // 无预算。这里改为:BM25(会话文本) top80 → 追加最近 30 / universal 10 / pending 10,
217
+ // 去重后按 BM25 desc → updatedAt desc → id 排序,estTokens 累计超预算即停(丢低分,
218
+ // 不截断 JSON)。同输入同输出,不依赖对象插入顺序。
219
+ function renderIndexEntry(id, entry, contentCap) {
220
+ const links = Array.isArray(entry?.links) ? entry.links : []
221
+ const item = {
222
+ id,
223
+ track: entry?.track || 'memory',
224
+ domain: entry?.domain || 'unknown',
225
+ applies_to: Array.isArray(entry?.appliesTo) ? entry.appliesTo.slice(0, 20) : [],
226
+ title: entry?.title || '',
227
+ content: truncate(entry?.content || '', contentCap),
228
+ confidence: entry?.confidence ?? null,
229
+ status: entry?.status || 'active',
230
+ updatedAt: entry?.updatedAt || null,
231
+ linkCount: links.length,
232
+ linkedTo: links.slice(0, 5).map((l) => ({ to: l?.to || null, kind: l?.kind || null })),
233
+ }
234
+ if (Array.isArray(entry?.absorbedFrom) && entry.absorbedFrom.length) item.absorbedFrom = entry.absorbedFrom
235
+ return item
236
+ }
237
+
238
+ export function packCuratorIndexContext({ index, sessionText, tokenBudget = CURATOR_INDEX_TOKENS, maxEntries = CURATOR_INDEX_MAX_ENTRIES } = {}) {
239
+ const pool = []
240
+ for (const [id, entry] of Object.entries(index?.entries || {})) {
241
+ if (!entry || entry.status === 'archived') continue
242
+ if (entry.reviewKind) continue // 本版没有 link 伪条目;防御性过滤
243
+ pool.push({ id, entry, updatedAt: String(entry.updatedAt || ''), score: 0 })
244
+ }
245
+ if (pool.length) {
246
+ const corpus = buildCorpus(pool.map((p) => ({ ...p.entry, id: p.id })))
247
+ const query = tokenize(sessionText || '')
248
+ for (const p of pool) {
249
+ const doc = corpus.docs.get(p.id)
250
+ p.score = doc ? bm25(query, doc, corpus) : 0
251
+ }
252
+ }
253
+ const byScore = [...pool].sort((a, b) => b.score - a.score || b.updatedAt.localeCompare(a.updatedAt) || (a.id < b.id ? -1 : 1))
254
+ const byRecent = [...pool].sort((a, b) => b.updatedAt.localeCompare(a.updatedAt) || (a.id < b.id ? -1 : 1))
255
+ const selected = new Map()
256
+ const take = (list) => { for (const p of list) if (!selected.has(p.id)) selected.set(p.id, p) }
257
+ take(byScore.slice(0, 80)) // BM25 top 80
258
+ take(byRecent.slice(0, 30)) // 最近 30
259
+ take(byRecent.filter((p) => (p.entry?.domain || '') === 'universal').slice(0, 10)) // universal 10
260
+ take(pool.filter((p) => (p.entry?.status || '') === 'pending_review' && (p.entry?.track || 'memory') === 'memory')
261
+ .sort((a, b) => b.updatedAt.localeCompare(a.updatedAt) || (a.id < b.id ? -1 : 1)).slice(0, 10)) // pending_review 记忆 10
262
+
263
+ const ordered = [...selected.values()].sort((a, b) => b.score - a.score || b.updatedAt.localeCompare(a.updatedAt) || (a.id < b.id ? -1 : 1))
264
+ const entries = []
265
+ let tokens = 0
266
+ for (let i = 0; i < ordered.length && entries.length < maxEntries; i++) {
267
+ const item = renderIndexEntry(ordered[i].id, ordered[i].entry, i < 20 ? 900 : 600)
268
+ const cost = estTokens(JSON.stringify(item))
269
+ if (entries.length > 0 && tokens + cost > tokenBudget) break
270
+ entries.push(item)
271
+ tokens += cost
272
+ }
273
+ return { entries, tokens, omitted: Math.max(0, ordered.length - entries.length), includedIds: entries.map((e) => e.id) }
274
+ }
275
+
276
+ // candidate_clusters 的 prompt 打包(§4.5):预算 2000 tokens,簇内正文截 300 字,
277
+ // pair_scores 保留 2 位;簇已按 avg_score 降序,超预算丢低分簇。
278
+ export function packCuratorClusterContext(clusterResult, { tokenBudget = CURATOR_CLUSTER_TOKENS } = {}) {
279
+ const clusters = []
280
+ let tokens = 0
281
+ for (const cluster of clusterResult?.clusters || []) {
282
+ const rendered = {
283
+ cluster_id: cluster.cluster_id,
284
+ suggested_op: cluster.suggested_op,
285
+ medoid_id: cluster.medoid_id,
286
+ avg_score: cluster.avg_score,
287
+ pair_scores: cluster.pair_scores,
288
+ members: (cluster.members || []).map((m) => ({
289
+ id: m.id, title: m.title || '', track: m.track || 'memory',
290
+ domain: m.domain || 'unknown', updatedAt: m.updatedAt || null,
291
+ content: truncate(m.content || '', 300),
292
+ })),
293
+ }
294
+ const cost = estTokens(JSON.stringify(rendered))
295
+ if (clusters.length > 0 && tokens + cost > tokenBudget) break
296
+ clusters.push(rendered)
297
+ tokens += cost
298
+ }
299
+ const total = clusterResult?.clusters?.length || 0
300
+ return {
301
+ clusters,
302
+ tokens,
303
+ omitted: Math.max(0, total - clusters.length),
304
+ truncated: (clusterResult?.truncated === true) || (total - clusters.length) > 0,
305
+ }
306
+ }
307
+
308
+ async function readSession(sessionQuery, id) {
309
+ if (typeof sessionQuery.readSession === 'function') {
310
+ const snapshot = await sessionQuery.readSession(id)
311
+ return {
312
+ events: snapshot?.events || [],
313
+ header: snapshot?.session || null,
314
+ inheritedEventCount: snapshot?.inheritedEventCount ?? null,
315
+ }
316
+ }
317
+ if (typeof sessionQuery.observeSession === 'function') {
318
+ const observation = await sessionQuery.observeSession(id, { projectionMode: 'none' })
319
+ try {
320
+ return {
321
+ events: observation?.events || [],
322
+ header: observation?.header || null,
323
+ inheritedEventCount: observation?.inheritedEventCount ?? null,
324
+ }
325
+ } finally {
326
+ try { observation?.[Symbol.dispose]?.() } catch {}
327
+ }
328
+ }
329
+ throw new Error('sessionQuery has neither readSession nor observeSession')
330
+ }
331
+
332
+ async function readSessionMeta(sessionQuery, ids) {
333
+ const out = new Map()
334
+ try {
335
+ const records = await sessionQuery.listSessions()
336
+ for (const record of records || []) {
337
+ // `SessionRecord` carries only header + liveness; the title arrives from
338
+ // readTitleSnapshots below, so keep the record and a mutable title slot.
339
+ out.set(record.header?.id, { ...record, title: record.header?.title || '' })
340
+ }
341
+ } catch {}
342
+ try {
343
+ if (typeof sessionQuery.readTitleSnapshots === 'function') {
344
+ // One result per requested id: `{ sessionId, status, value: { session, title? } }`.
345
+ const titles = await sessionQuery.readTitleSnapshots(ids)
346
+ for (const r of titles || []) {
347
+ if (r?.status !== 'fulfilled' || !r.sessionId || !out.has(r.sessionId)) continue
348
+ const title = r.value?.title?.title || r.value?.session?.title
349
+ if (title) out.get(r.sessionId).title = title
350
+ }
351
+ }
352
+ } catch {}
353
+ return out
354
+ }
355
+
356
+ function parseJsonObject(text) {
357
+ const raw = String(text || '').trim()
358
+ try { return JSON.parse(raw) } catch {}
359
+ const start = raw.indexOf('{')
360
+ const end = raw.lastIndexOf('}')
361
+ if (start >= 0 && end > start) {
362
+ try { return JSON.parse(raw.slice(start, end + 1)) } catch {}
363
+ }
364
+ return null
365
+ }
366
+
367
+ function validDomain(domain) {
368
+ const d = String(domain || '').trim()
369
+ return d === 'universal' || d === 'coding' || d === 'rp' || d === 'tooling' || d === 'personal' || d === 'general' || d.startsWith('project:')
370
+ }
371
+
372
+ function agentOptionsFor(model) {
373
+ const value = String(model || '').trim()
374
+ if (!value) return undefined
375
+ const slash = value.indexOf('/')
376
+ if (slash <= 0 || slash === value.length - 1) return undefined
377
+ return { provider: value.slice(0, slash), model: value.slice(slash + 1) }
378
+ }
379
+
380
+ export function listCurationJobs() {
381
+ return [...jobs.values()].map((j) => ({
382
+ id: j.id, status: j.status, step: j.step, createdAt: j.createdAt, endedAt: j.endedAt,
383
+ error: j.error || null, result: j.result || null,
384
+ }))
385
+ }
386
+
387
+ export function getCurationJob(id) {
388
+ const job = jobs.get(id)
389
+ if (!job) return null
390
+ return {
391
+ id: job.id,
392
+ status: job.status,
393
+ step: job.step,
394
+ logs: job.logs.slice(-80),
395
+ createdAt: job.createdAt,
396
+ endedAt: job.endedAt || null,
397
+ error: job.error || null,
398
+ result: job.result || null,
399
+ }
400
+ }
401
+
402
+ export function cancelCurationJob(id) {
403
+ const job = jobs.get(id)
404
+ if (!job) return false
405
+ try { job.abort.abort(new Error('cancelled by user')) } catch {}
406
+ return true
407
+ }
408
+
409
+ // 孤儿窗口补偿(这是补偿设计,不是事务):curator 是 commit-before-index —— 批量提交
410
+ // 成功而全局索引写失败时,引擎库里会留下索引不认识的孤儿行。这里对刚提交的每个 name
411
+ // 逐个 forget,尽力撤销;这是尽力而为,不是回滚保证:删不掉的必须可见。补偿结果(包括
412
+ // 哪些补上了、哪些没补上)逐条记录进活动日志 kind:'curate',绝不吞掉。
413
+ async function compensateCuratorCommit(originalError, { files, route }) {
414
+ const db = globalDbPath()
415
+ const compensated = []
416
+ const failed = []
417
+ for (const file of files) {
418
+ try {
419
+ const result = await forget({ db, name: file.name })
420
+ if (!result || typeof result !== 'object' || result.ok === false || result.error || result.parseWarning
421
+ || !Number.isSafeInteger(result.deleted) || result.deleted < 0) {
422
+ throw new Error('backend compensation delete was not acknowledged')
423
+ }
424
+ compensated.push(file.name)
425
+ } catch (compensationError) {
426
+ failed.push({ name: file.name, error: String(compensationError?.message || compensationError) })
427
+ }
428
+ }
429
+ if (failed.length) {
430
+ record({
431
+ kind: 'curate', scope: 'global', ok: false, level: 'error',
432
+ message: `全局提炼索引写失败后的补偿不完整:${compensated.length}/${files.length} 条已从向量库撤销,${failed.length} 条撤销失败(引擎库残留孤儿行,需手动清理)`,
433
+ detail: { route, compensated, failed: failed.slice(0, 20), originalError: String(originalError?.message || originalError) },
434
+ refs: files.map((file) => file.name).slice(0, 20),
435
+ })
436
+ } else {
437
+ record({
438
+ kind: 'curate', scope: 'global', ok: true, level: 'warn',
439
+ message: `全局提炼索引写失败,已从向量库回滚刚提交的 ${compensated.length} 条记忆(补偿成功;索引未变,重跑提炼即可)`,
440
+ detail: { route, compensated, failed: [], originalError: String(originalError?.message || originalError) },
441
+ refs: files.map((file) => file.name).slice(0, 20),
442
+ })
443
+ }
444
+ }
445
+
446
+ // 词典 op 识别(§2.1):op 显式标 'lexicon',或任何带 libraryId / term+kind 的提案。
447
+ // 全局 curator 的输出里出现这些字段只能说明模型越权,拒绝而不是猜它的意图。
448
+ function isLexiconOp(memory) {
449
+ if (!memory || typeof memory !== 'object') return false
450
+ if (memory.op === 'lexicon') return true
451
+ if (typeof memory.libraryId === 'string' && memory.libraryId.trim()) return true
452
+ return typeof memory.term === 'string' && memory.term.trim() && ['slang', 'meme', 'trigger', 'term'].includes(memory.kind)
453
+ }
454
+
455
+ /**
456
+ * 私有整理链路的词典写入(§2.1-§2.2):validated ops 白名单校验 + 落库。
457
+ *
458
+ * 锁顺序(刻意注释,谁改谁读):本函数先拿 curator 侧的 managed 写闸
459
+ * (withManagedCuratorWrite —— 受管向量代际一致性),**在其内部**再让
460
+ * upsertLexiconTerm 拿词典自己的 withFileLock。两把锁的嵌套只有一个方向:
461
+ * curator(vector) → lexicon(file);lexicon.js 从不回头拿向量锁,所以无死锁环。
462
+ * 词典写从不跨 await 持锁——withFileLock 的 action 是同步的。
463
+ *
464
+ * 校验规则(§2.1 curator 行 + 契约):
465
+ * * 只接受 { op:'lexicon', action:'upsert', ... };action 其它值(尤其 delete)
466
+ * 一律拒绝——删除是用户/管理操作,模型没有删除路径。
467
+ * * 必须 evidence(quote 或 id 至少其一非空),无证据直接拒绝;
468
+ * "同一转录同词 ≥2 次才建议"是提示词层的事,代码层只验证据存在。
469
+ * * libraryId 必须显式给出且过 isSafeId;op 里带了别的 libraryId 视为越权拒绝。
470
+ * * needs_review === true → status:'pending',否则 'active'。
471
+ * * sensitive trigger 由 lexicon.js 的 LEXICON_SENSITIVE_FORBIDDEN 兜底(curator
472
+ * 来源理论上不该提,但来源字段在模型手里,存储层必须自己设防)。
473
+ */
474
+ export async function commitPrivateLexiconOps(ops, { libraryId, job } = {}) {
475
+ const list = Array.isArray(ops) ? ops : [ops]
476
+ const committed = []
477
+ const rejected = []
478
+ const skipped = []
479
+ if (!isSafeId(libraryId)) {
480
+ for (const raw of list) rejected.push({ term: raw?.term || null, code: 'LEXICON_INVALID_LIBRARY_ID', reason: 'lexicon ops need a valid private library id' })
481
+ return { committed, rejected, skipped }
482
+ }
483
+ const run = async () => {
484
+ for (const raw of list) {
485
+ const op = raw && typeof raw === 'object' ? raw : null
486
+ if (!op || op.op !== 'lexicon') {
487
+ skipped.push({ term: op?.term || null, reason: 'not a lexicon op (op must be "lexicon")' })
488
+ continue
489
+ }
490
+ if (op.action !== 'upsert') {
491
+ rejected.push({ term: op.term || null, code: 'LEXICON_ACTION_FORBIDDEN', reason: `lexicon action "${op.action}" is not allowed for consolidation; only upsert, never delete` })
492
+ continue
493
+ }
494
+ const evidence = Array.isArray(op.evidence)
495
+ ? op.evidence.filter(item => item && typeof item === 'object' && ((typeof item.quote === 'string' && item.quote.trim()) || (typeof item.id === 'string' && item.id.trim())))
496
+ : []
497
+ if (!evidence.length) {
498
+ rejected.push({ term: op.term || null, code: 'LEXICON_EVIDENCE_REQUIRED', reason: 'lexicon upserts need evidence from the transcript' })
499
+ continue
500
+ }
501
+ if (typeof op.libraryId === 'string' && op.libraryId && op.libraryId !== libraryId) {
502
+ rejected.push({ term: op.term || null, code: 'LEXICON_LIBRARY_MISMATCH', reason: `lexicon op targets library ${op.libraryId}, but this consolidation is bound to ${libraryId}` })
503
+ continue
504
+ }
505
+ // 敏感触发词不允许模型猜(§0.2/§2.1):curator 也是模型,整理链路一律不给
506
+ // sensitive trigger(trigger 缺省就是 sensitive,除非显式降为 normal)。
507
+ if (op.kind === 'trigger' && op.sensitivity !== 'normal') {
508
+ rejected.push({ term: op.term || null, code: 'LEXICON_SENSITIVE_FORBIDDEN', reason: 'consolidation cannot create sensitive triggers; sensitive vocabulary needs an explicit user write' })
509
+ continue
510
+ }
511
+ try {
512
+ const result = await upsertLexiconTerm({
513
+ libraryId,
514
+ term: op.term,
515
+ kind: op.kind,
516
+ meaning: op.meaning,
517
+ usage: op.usage,
518
+ aliases: op.aliases,
519
+ examples: op.examples,
520
+ context: op.context,
521
+ knownBy: op.knownBy,
522
+ visibility: op.visibility,
523
+ sensitivity: op.sensitivity,
524
+ confidence: op.confidence,
525
+ evidence,
526
+ source: 'curator',
527
+ status: op.needs_review === true ? 'pending' : 'active',
528
+ })
529
+ committed.push({
530
+ termId: result.term.termId,
531
+ term: result.term.term,
532
+ status: result.term.status,
533
+ created: result.created === true,
534
+ notOwned: result.notOwned === true,
535
+ pendingRevision: result.pendingRevision === true,
536
+ })
537
+ } catch (error) {
538
+ rejected.push({ term: op.term || null, code: error?.code || 'LEXICON_OP_FAILED', reason: String(error?.message || error) })
539
+ }
540
+ }
541
+ return { committed, rejected, skipped }
542
+ }
543
+ if (job) job.step = 'committing lexicon ops'
544
+ // 先过 curator 侧 managed 写闸,再进词典自己的文件锁(顺序见函数头注释)。
545
+ return withManagedCuratorWrite(run)
546
+ }
547
+
548
+ /**
549
+ * 审核决策(spec §4.10):硬门 + 风险分。
550
+ *
551
+ * 硬门恒 pending,不因审核模式放宽:conflict(模型自己承认两段会话打架)、
552
+ * 证据为空(可回放性是底线)、merge/supersede/absorb 的 target 不存在。
553
+ * 非法 target 在这里返回 skip——调用方必须跳过该提案并且**不得**用同一份内容
554
+ * 继续 create(旧代码缺 continue,会把失败的合并悄悄变成一条重复记忆,§0.2)。
555
+ *
556
+ * 风险分只拦"会改写既有内容"的操作:merge/supersede/absorb 在 auto 下风险
557
+ * ≥0.70 才 pending;create 默认通过,needs_review/低置信只记进 risk 供审计与
558
+ * 复核排序。review-all 把全部内容操作都送进复核。风险分上限 2。
559
+ *
560
+ * @returns {{ review: boolean, risk: number, reasons: string[], hard?: boolean } |
561
+ * { skip: true, reason: string }}
562
+ */
563
+ export function reviewDecision({ m, op, evidence, targetId, index, mode }) {
564
+ // 硬门(恒 pending;不因 mode 放宽)
565
+ if (op === 'conflict') return { review: true, hard: true, risk: 2, reasons: ['conflict'] }
566
+ if (!evidence.length) return { review: true, hard: true, risk: 2, reasons: ['missing evidence'] }
567
+ if (op === 'merge' || op === 'supersede' || op === 'absorb') {
568
+ if (!targetId || !index.entries[targetId]) {
569
+ return { skip: true, reason: `target not found: ${targetId || '(empty)'}` }
570
+ }
571
+ }
572
+ // 风险分
573
+ let risk = 0
574
+ const reasons = []
575
+ if (m?.needs_review === true) { risk += 0.70; reasons.push('needs_review') }
576
+ if (Number(m?.confidence) < 0.50) { risk += 0.70; reasons.push('confidence<0.50') }
577
+ else if (Number(m?.confidence) < 0.60) { risk += 0.20; reasons.push('confidence<0.60') }
578
+ if (op === 'merge' || op === 'supersede') { risk += 0.20; reasons.push(op) }
579
+ if (op === 'absorb' && (m?.source_ids?.length || 0) > 3) { risk += 0.20; reasons.push('absorb>3 sources') }
580
+ if (m?.review_reason) { risk += 0.20; reasons.push('review_reason') }
581
+ if (evidence.length === 1) { risk += 0.10; reasons.push('single evidence') }
582
+
583
+ const rewrite = op === 'merge' || op === 'supersede' || op === 'absorb'
584
+ const review = mode === 'review-all' || (mode === 'auto' && rewrite && risk >= 0.70)
585
+ return { review, risk: Math.min(2, Number(risk.toFixed(2))), reasons }
586
+ }
587
+
588
+ // —— 去重门与冲突门 ——
589
+ // 门语料只含 active + pending_review:archived/superseded 不是"已存在的事实",
590
+ // 不该拦 create,也不该成为 best。LLM 只裁决;提交层用同一把 pair 尺子复核。
591
+ // buildCorpus 的约定是条目自带 id/title/content(track/domain/appliesTo 等
592
+ // 随条目一起落在 doc.entry 上),所以这里直接展开索引条目再补 id。
593
+ function buildGateCorpus(index) {
594
+ const rows = []
595
+ for (const [id, entry] of Object.entries(index?.entries || {})) {
596
+ if (!entry || (entry.status !== 'active' && entry.status !== 'pending_review')) continue
597
+ rows.push({ ...entry, id })
598
+ }
599
+ return buildCorpus(rows)
600
+ }
601
+
602
+ const OPS_ALLOWLIST = ['create', 'merge', 'supersede', 'noop', 'conflict', 'link', 'absorb']
603
+ const SCORE_EPSILON = 1e-9
604
+
605
+ /**
606
+ * 规划阶段(spec §7.2 planCuratorOps):把模型输出拆成 writes / pendings / links /
607
+ * skipped 四类计划;全部语义复核在此完成,提交阶段只做事务。逐条流程:
608
+ * lexicon op → skipped;unknown op → skipped(绝不降级 create);noop → 静默跳过;
609
+ * link → validateGlobalLink 预检(快照索引 + 证据落地),事务内再复核并发面;
610
+ * absorb → skipped 'absorb lands in a later pass'(F2 的 commitCuratorPlans 负责,
611
+ * 它直接从原始输出里取 absorb ops,不受这里的 skip 影响);
612
+ * create/merge/supersede/conflict → 证据落地(§4.6)→ reviewDecision(§4.10)→
613
+ * §4.8 候选门(rankPairCandidates top1):
614
+ * create ≥0.90 同 track/domain → skip 'duplicate of <id>'(pending 同域 →
615
+ * 'duplicate of pending <id>'),warn 日志;
616
+ * create conflict(pairDecision 或 globalConflictCheck 预筛,absorb 带不重复查)→
617
+ * pending 'conflict detected';
618
+ * create 0.82-0.90 → duplicateOf+relatedTo;0.55-0.82 → relatedTo;
619
+ * merge/supersede best 是另一条且高 ≥0.05 → pending 'closest target differs';
620
+ * conflict 恒 pending,target 缺失时用 best。
621
+ */
622
+ export function planCuratorOps(memories, { index, mode, corpus, sessionCorpus = null, now }) {
623
+ const writes = []
624
+ const pendings = []
625
+ const links = []
626
+ const skipped = []
627
+ const entries = index?.entries || {}
628
+ for (const m of memories) {
629
+ // 词典 op 是私有整理的专属面(§2.1):全局 curator 只写全局记忆。带 libraryId /
630
+ // lexicon 标记的条目在这里一律拒绝——不进向量提交、不进全局索引,只在 skipped 里
631
+ // 留下可读的原因。私有写入走 commitPrivateLexiconOps。
632
+ if (isLexiconOp(m)) {
633
+ skipped.push({ title: m?.term || m?.title, reason: 'lexicon op rejected: the global curator only writes global memory; lexicon ops belong to the private consolidation chain' })
634
+ continue
635
+ }
636
+ // 未知 op 一律拒绝(§4.8):allowlist 之外的 op 不得静默降级成 create——
637
+ // 模型写错 op 名时,降级会凭空写条目。'noop' 是模型的"无可奉告",直接跳过。
638
+ const op = OPS_ALLOWLIST.includes(m?.op) ? m.op : null
639
+ if (op === 'noop') continue
640
+ if (!op) {
641
+ skipped.push({ title: m?.title, reason: `unknown op: ${m?.op ?? '(missing)'}` })
642
+ continue
643
+ }
644
+ // link 分支预检通过才进入 links 计划;落库在提交事务中,
645
+ // 与普通 updates 同一次 updateGlobalIndex;不进 files、不触发向量提交。
646
+ if (op === 'link') {
647
+ const verdict = validateGlobalLink({
648
+ index,
649
+ fromId: m?.from_id,
650
+ toId: m?.to_id,
651
+ kind: m?.kind,
652
+ note: m?.note,
653
+ confidence: m?.confidence,
654
+ evidence: Array.isArray(m?.evidence) ? m.evidence : [],
655
+ sessionCorpus,
656
+ })
657
+ if (!verdict.ok) {
658
+ skipped.push({ title: m?.note || m?.to_id || m?.title, reason: `link rejected: ${verdict.reason}` })
659
+ continue
660
+ }
661
+ links.push({ fromId: verdict.fromId, toId: verdict.toId, kind: verdict.kind, symmetric: verdict.symmetric, link: verdict.link })
662
+ continue
663
+ }
664
+ // absorb 提交属于 F2 的 commitCuratorPlans(从原始 output 自取 absorb ops);
665
+ // 这里显式跳过——planCuratorOps 不把 absorb 当成 create 走内容提交。
666
+ // 注意:absorb 已接线(commitCuratorOutput 里调用 commitCuratorPlans),
667
+ // 这个 skip 只是内容半边的路由,不是"未实现"。
668
+ if (op === 'absorb') {
669
+ skipped.push({ title: m?.title, reason: 'absorb handled by commitCuratorPlans' })
670
+ continue
671
+ }
672
+
673
+ // 证据落地(§4.6):quote 必须能回放到本次策划的会话转录;无 corpus(测试/直呼)
674
+ // 时只做形状校验,status='unverified'。有效证据为空是硬门(reviewDecision)。
675
+ const grounded = groundEvidence(Array.isArray(m?.evidence) ? m.evidence : [], sessionCorpus)
676
+ const evidence = grounded.valid.slice(0, EVIDENCE_MAX)
677
+ .map((item) => ({ sessionId: item.sessionId, quote: truncate(item.quote, 500) }))
678
+ const domain = String(m?.domain || '').trim()
679
+ if (!validDomain(domain)) {
680
+ skipped.push({ title: m?.title, reason: `invalid domain: ${domain}` })
681
+ continue
682
+ }
683
+ const track = m?.track === 'skill' ? 'skill' : 'memory'
684
+ const title = String(m?.title || '').trim()
685
+ const content = String(m?.content || '').trim()
686
+ if (!title || !content) {
687
+ skipped.push({ title, reason: 'missing title or content' })
688
+ continue
689
+ }
690
+ const targetId = String(m?.target_id || '').trim()
691
+ const decision = reviewDecision({ m, op, evidence, targetId, index, mode })
692
+ if (decision.skip) {
693
+ // 非法 merge/supersede target 到此为止(§0.2 修复):skipped + continue,
694
+ // 绝不带着同一份内容继续 create。
695
+ skipped.push({ title, reason: decision.reason })
696
+ continue
697
+ }
698
+
699
+ // —— §4.8 候选复核门:每次规划用同一语料、同一把尺子。——
700
+ const proposal = {
701
+ id: '__curator_proposal__',
702
+ title, content, track, domain,
703
+ appliesTo: Array.isArray(m?.applies_to) ? m.applies_to : [],
704
+ }
705
+ const candidates = corpus && corpus.size ? rankPairCandidates({ corpus, proposal, limit: PAIR_SCAN_LIMIT }) : []
706
+ const best = candidates[0] || null
707
+ let review = decision.review
708
+ // reviewReason 优先级:硬门 > 候选门(conflict detected / closest target differs)
709
+ // > 模型 review_reason > 'risk threshold'。
710
+ let reviewReason = decision.hard
711
+ ? decision.reasons[0]
712
+ : (String(m?.review_reason || '').trim() || 'risk threshold')
713
+ let conflictingWith = targetId || null
714
+ const tags = {}
715
+ if (op === 'create' && best) {
716
+ if (best.score >= PAIR_DUPLICATE_MIN
717
+ && (best.entry?.track || 'memory') === track
718
+ && (best.entry?.domain || 'unknown') === domain) {
719
+ const isPending = best.entry?.status === 'pending_review'
720
+ warn(`curator: create skipped, ${isPending ? 'duplicate of pending' : 'duplicate of'} ${best.id} (pair score ${best.score.toFixed(2)})`)
721
+ skipped.push({ title, reason: isPending ? `duplicate of pending ${best.id}` : `duplicate of ${best.id}` })
722
+ continue
723
+ }
724
+ // 冲突检测:pairDecision 的 conflict(同标题正文迥异),或 §4.8 预筛
725
+ // (negation/value/same_title)。duplicate/absorb 带(≥0.82)不重复查——
726
+ // 同标题高相似是同一事实的改写,不是冲突(§4.8 豁免条款的推广)。
727
+ const conflictHit = best.decision === 'conflict' || (best.score < PAIR_ABSORB_MIN
728
+ && globalConflictCheck(proposal, best.entry, best.features))
729
+ if (conflictHit) {
730
+ review = true
731
+ reviewReason = 'conflict detected'
732
+ conflictingWith = best.id
733
+ } else if (best.score >= PAIR_ABSORB_MIN) {
734
+ tags.duplicateOf = best.id
735
+ tags.relatedTo = best.id
736
+ } else if (best.score >= PAIR_LINK_MIN) {
737
+ tags.relatedTo = best.id
738
+ }
739
+ }
740
+ if ((op === 'merge' || op === 'supersede') && best) {
741
+ // best 是另一条且分数比模型 target 高 ≥0.05 → 最近目标存疑,转人审。
742
+ const targetEntry = entries[targetId]
743
+ const targetScore = targetEntry ? pairScore(pairFeatures(proposal, targetEntry)) : 0
744
+ if (best.id !== targetId && best.score >= targetScore + 0.05 - SCORE_EPSILON) {
745
+ review = true
746
+ reviewReason = 'closest target differs'
747
+ conflictingWith = targetId
748
+ }
749
+ }
750
+ if (op === 'conflict' && !targetId && best) conflictingWith = best.id
751
+
752
+ const previous = (op === 'merge' || op === 'supersede') && targetId && entries[targetId] ? entries[targetId] : null
753
+ // A reviewed (held) entry must never occupy the target's id: rejecting the
754
+ // review would archive the only copy and the original active memory would
755
+ // be gone. Held entries always get their own id; only a clean merge writes
756
+ // in place.
757
+ const id = newMemoryId('gmem')
758
+ const entry = {
759
+ track,
760
+ domain,
761
+ appliesTo: Array.isArray(m?.applies_to) ? m.applies_to.slice(0, 20) : [],
762
+ title: truncate(title, 180),
763
+ content: redactSecrets(content),
764
+ confidence: Number.isFinite(Number(m?.confidence)) ? Math.max(0, Math.min(1, Number(m.confidence))) : 0.6,
765
+ evidence: evidence.map((e) => ({
766
+ sessionId: String(e?.sessionId || ''),
767
+ quote: truncate(e?.quote || '', 500),
768
+ })),
769
+ status: 'active',
770
+ supersedes: op === 'supersede' ? targetId || null : previous?.supersedes || null,
771
+ // 风险分写到所有条目(active 也写,§4.10):它是审计/复核排序的统一口径,
772
+ // 不是 pending 的专属属性。旧条目没有这两个字段时按缺省读取,不需要迁移。
773
+ reviewRisk: decision.risk,
774
+ reviewRiskReasons: decision.reasons,
775
+ // 证据是否通过 grounding(§3.1):unverified(直呼/测试)时为 false。
776
+ evidenceVerified: grounded.status === 'grounded',
777
+ createdAt: previous?.createdAt || now,
778
+ updatedAt: now,
779
+ }
780
+ if (tags.duplicateOf) entry.duplicateOf = tags.duplicateOf
781
+ if (tags.relatedTo) entry.relatedTo = tags.relatedTo
782
+ if (review) {
783
+ // Held in the index only: never committed to MemU, so a contested claim
784
+ // cannot be recalled as shared memory until someone decides.
785
+ entry.status = 'pending_review'
786
+ entry.reviewReason = reviewReason
787
+ entry.conflictingWith = conflictingWith
788
+ pendings.push({ id, entry })
789
+ continue
790
+ }
791
+ writes.push({
792
+ id, entry, op, targetId, previous,
793
+ file: { name: id, track, description: truncate(title, 180), content },
794
+ })
795
+ }
796
+ return { writes, pendings, links, skipped }
797
+ }
798
+
799
+ // Exported for the audit regression suite: merging the commit decision logic
800
+ // into startGlobalCuration would require standing up subagents to test it.
801
+ export async function commitCuratorOutput(output, { job, sessionCorpus = null } = {}) {
802
+ const returned = Array.isArray(output?.memories) ? output.memories : []
803
+ // 模型输出超过提示词规定的 24 条时,在提交前截断超出部分,并
804
+ // 留一条可观测日志——静默截断会让「为什么少了几条」永远查不到。
805
+ const memories = returned.slice(0, MAX_CURATOR_MEMORIES)
806
+ if (returned.length > MAX_CURATOR_MEMORIES) {
807
+ warn(`curator: output truncated to ${MAX_CURATOR_MEMORIES} memories (${returned.length} returned)`)
808
+ record({
809
+ kind: 'curate', scope: 'global', ok: true, level: 'warn',
810
+ message: `全局提炼输出超过上限,已截断 ${returned.length} → ${MAX_CURATOR_MEMORIES} 条`,
811
+ detail: { op: 'output-truncated', returned: returned.length, kept: memories.length, limit: MAX_CURATOR_MEMORIES },
812
+ })
813
+ }
814
+ if (memories.length === 0) {
815
+ return { files: [], created: 0, merged: 0, superseded: 0, pending: 0, linked: 0, skipped: [], reviewRisk: { max: 0, flagged: 0, reasons: {} } }
816
+ }
817
+ const index = loadGlobalIndex()
818
+ // 模式只在循环外读一次(§4.10):一次策划运行用同一个口径,中途改设置不影响本批。
819
+ const mode = getSettings().curatorReviewMode || 'auto'
820
+ const gateCorpus = buildGateCorpus(index)
821
+ const plan = planCuratorOps(memories, { index, mode, corpus: gateCorpus, sessionCorpus, now: new Date().toISOString() })
822
+ const contentResult = await commitPlannedOps(plan, { job })
823
+ // absorb 半边(F2):planCuratorOps 对 absorb 显式 skip(避免在内容提交里被误当成
824
+ // create),absorb ops 由 commitCuratorPlans 从原始 output 自取并直接提交;这里传
825
+ // 截断后的 memories,保证 24 条上限对 absorb 同样生效。
826
+ const absorbResult = await commitCuratorPlans({ ...(output || {}), memories }, { job })
827
+ return {
828
+ ...contentResult,
829
+ absorbed: absorbResult.absorbed,
830
+ pending: contentResult.pending + absorbResult.pending,
831
+ held: absorbResult.held,
832
+ demoted: absorbResult.demoted,
833
+ skipped: [...contentResult.skipped, ...absorbResult.skipped],
834
+ }
835
+ }
836
+
837
+ /**
838
+ * 提交阶段(spec §7.2 commitCuratorPlans 的内容操作半边;absorb 半边是 F2 的
839
+ * 同名函数,直接吃原始 output)。单次 updateGlobalIndex 事务内按序应用:
840
+ * pendings(索引 only)→ writes(held clone 检查 / merge 兜底 / supersede)→
841
+ * links(applyGlobalLinks,只有 link 时也要走一次索引事务,§4.9)。
842
+ * link 不进 files、不触发向量提交;两档审核模式都自动应用(C2)。
843
+ */
844
+ async function commitPlannedOps({ writes, pendings, links, skipped }, { job }) {
845
+ const files = writes.map((w) => w.file)
846
+ const now = new Date().toISOString()
847
+
848
+ // 风险统计(§4.10):本批所有写入条目(active + pending)的审计口径——最高分、
849
+ // 达到复核阈值(≥0.70)的条目数、每类原因出现的次数。
850
+ const written = [...writes.map((w) => w.entry), ...pendings.map((p) => p.entry)]
851
+ const riskReasons = {}
852
+ for (const entry of written) {
853
+ for (const reason of entry.reviewRiskReasons || []) riskReasons[reason] = (riskReasons[reason] || 0) + 1
854
+ }
855
+ const reviewRiskSummary = {
856
+ max: written.length ? Math.max(...written.map((entry) => Number(entry.reviewRisk) || 0)) : 0,
857
+ flagged: written.filter((entry) => (Number(entry.reviewRisk) || 0) >= 0.70).length,
858
+ reasons: riskReasons,
859
+ }
860
+
861
+ // 单事务:pendings + writes + links 一次落索引。返回本事务实际落地的 link 列表,
862
+ // 供活动日志逐条记录(retry 重跑时以成功那次的返回为准)。
863
+ const applyPlan = (fresh) => {
864
+ for (const { id, entry } of pendings) fresh.entries[id] = entry
865
+ for (const { id, entry, op, targetId, previous } of writes) {
866
+ if (previous && JSON.stringify(fresh.entries[targetId]) !== JSON.stringify(previous)) {
867
+ const heldId = newMemoryId('gmem')
868
+ // 提交成功的只有 `id` 这一行,held 克隆从未进过向量库——它绝不能继承
869
+ // "提交成功即落戳"的 entry.vector:向量库里的行名是 `id` 而不是 heldId,
870
+ // 带戳会让 membership 把一条不存在的行计进来,而真实存在的 `id` 行反而
871
+ // 无处归属(它根本不会按这个克隆写进索引)。
872
+ const held = { ...entry, status: 'pending_review', conflictingWith: targetId, reviewReason: 'target changed while curator was running' }
873
+ delete held.vector
874
+ fresh.entries[heldId] = held
875
+ continue
876
+ }
877
+ if (op === 'merge' && previous) {
878
+ entry.content = entry.content || previous.content
879
+ entry.title = entry.title || previous.title
880
+ entry.evidence = [...(previous.evidence || []), ...(entry.evidence || [])].slice(-40)
881
+ }
882
+ fresh.entries[id] = entry
883
+ if ((op === 'supersede' || op === 'merge') && targetId && fresh.entries[targetId]) {
884
+ fresh.entries[targetId].status = 'superseded'
885
+ fresh.entries[targetId].supersededBy = id
886
+ fresh.entries[targetId].validTo = now
887
+ fresh.entries[targetId].updatedAt = now
888
+ }
889
+ }
890
+ return applyGlobalLinks(fresh.entries, links, { now })
891
+ }
892
+
893
+ if (files.length === 0) {
894
+ let linkResult = { applied: [], skipped: [] }
895
+ if (pendings.length || links.length) {
896
+ // 只有 pending/link 时同样要走一次索引事务(§4.9:只有 link 也要调一次
897
+ // updateGlobalIndex);withManagedCuratorWrite 闸门照过,保持锁纪律一致。
898
+ await withManagedCuratorWrite(() => retryStoreWrite(() => updateGlobalIndex((fresh) => {
899
+ linkResult = applyPlan(fresh)
900
+ })))
901
+ }
902
+ for (const applied of linkResult.applied) {
903
+ record({ kind: 'curate', scope: 'global', ok: true, message: `全局关联已落地:${applied.fromId} -(${applied.kind})-> ${applied.toId}`, detail: { op: 'link', from: applied.fromId, to: applied.toId, kind: applied.kind, linkId: applied.linkId } })
904
+ }
905
+ return {
906
+ files: [], created: 0, merged: 0, superseded: 0, pending: pendings.length,
907
+ linked: linkResult.applied.length, skipped, reviewRisk: reviewRiskSummary,
908
+ }
909
+ }
910
+
911
+ job.step = `committing ${files.length} global memories`
912
+ let linkResult = { applied: [], skipped: [] }
913
+ await withManagedCuratorWrite(async () => {
914
+ // Managed agent mode still commits the exact same files to the active local
915
+ // vector database; only pending_review entries remain index-only.
916
+ const route = engineRoute()
917
+ let committedToBackend = false
918
+ try {
919
+ if (route !== 'lexical') {
920
+ await commit({
921
+ payload: { recall_files: files, resource: [], user: {} },
922
+ route, db: globalDbPath(),
923
+ })
924
+ committedToBackend = true
925
+ // 整理写入与单条写入同口径:提交成功就在条目上落"已入向量库"戳,否则这批
926
+ // 全局记忆在向量计数(membership 的戳腿)里永远缺失。pending 不提交,不戳。
927
+ const vector = activeEntryStamp(route)
928
+ if (vector) for (const write of writes) write.entry.vector = vector
929
+ }
930
+
931
+ if (job?.abort?.signal?.aborted) throw new Error('cancelled by user')
932
+ await retryStoreWrite(() => updateGlobalIndex((fresh) => {
933
+ linkResult = applyPlan(fresh)
934
+ }))
935
+ } catch (error) {
936
+ // 提交成功之后(abort 检查 / 索引写)的任何失败都会留下孤儿行:尽力撤销。
937
+ if (committedToBackend) await compensateCuratorCommit(error, { files, route })
938
+ throw error
939
+ }
940
+ })
941
+ for (const applied of linkResult.applied) {
942
+ record({ kind: 'curate', scope: 'global', ok: true, message: `全局关联已落地:${applied.fromId} -(${applied.kind})-> ${applied.toId}`, detail: { op: 'link', from: applied.fromId, to: applied.toId, kind: applied.kind, linkId: applied.linkId } })
943
+ }
944
+ const summary = {
945
+ files,
946
+ created: writes.filter((w) => w.op === 'create').length,
947
+ merged: writes.filter((w) => w.op === 'merge').length,
948
+ superseded: writes.filter((w) => w.op === 'supersede').length,
949
+ pending: pendings.length,
950
+ linked: linkResult.applied.length,
951
+ skipped,
952
+ reviewRisk: reviewRiskSummary,
953
+ }
954
+ record({
955
+ kind: 'curate',
956
+ scope: 'global',
957
+ ok: true,
958
+ message: `全局提炼:新增 ${summary.created} / 合并 ${summary.merged} / 待复核 ${summary.pending}`
959
+ + (summary.linked ? ` / 关联 ${summary.linked}` : '')
960
+ + (summary.skipped.length ? ` / 跳过 ${summary.skipped.length}` : ''),
961
+ detail: { ...summary, skipped: summary.skipped.slice(0, 20) },
962
+ refs: files.map((file) => file.name).slice(0, 20),
963
+ })
964
+ return summary
965
+ }
966
+
967
+ // ============================================================================
968
+ // absorb 合并稿、提交事务、复核与撤销。
969
+ // ============================================================================
970
+
971
+ // —— absorb 常量(spec §4.12)——单点定义在 lib/curator-policy.js(文件头部 import)。
972
+ // 句级去重的 charDice 阈值只属于合并稿这一处,留在本地。
973
+ const ABSORB_SENTENCE_DICE = 0.9
974
+
975
+ // —— F1 接口(spec §4.1):tokenize/buildCorpus 已由 lib/text-retrieval.js 落地
976
+ //(文件头部 import)。buildCorpus 返回的是 BM25 语料(df/size),这里按 F1 的
977
+ // idfOf 同一公式折算成合并稿 MMR 用的 idf 表。
978
+ function tokensOf(text) {
979
+ return new Set(tokenize(text))
980
+ }
981
+
982
+ function idfMapFromCorpus(corpus) {
983
+ const idf = new Map()
984
+ if (!corpus?.df) return idf
985
+ for (const [term, df] of corpus.df) {
986
+ idf.set(term, Math.log(1 + (corpus.size - df + 0.5) / (df + 0.5)))
987
+ }
988
+ return idf
989
+ }
990
+
991
+ // idf 语料取自当前全局索引的 active 条目(与候选簇同一口径)。
992
+ function absorbIdf(index) {
993
+ const docs = Object.entries(index?.entries || {})
994
+ .filter(([, entry]) => entry && entry.status === 'active')
995
+ .map(([id, entry]) => ({ id, title: entry.title || '', content: entry.content || '' }))
996
+ return idfMapFromCorpus(buildCorpus(docs))
997
+ }
998
+
999
+ // —— absorb 合并稿(spec §4.7)——
1000
+ const SENTENCE_RE = /[^。!?!?;;\n]+[。!?!?;;]?/gu
1001
+
1002
+ function splitSentences(text) {
1003
+ const out = []
1004
+ for (const raw of String(text || '').match(SENTENCE_RE) || []) {
1005
+ const sentence = raw.trim()
1006
+ if (sentence) out.push(sentence)
1007
+ }
1008
+ return out
1009
+ }
1010
+
1011
+ // token 覆盖率:source 的词元有多大比例出现在 content 里。
1012
+ function tokenCoverage(sourceTokens, contentTokens) {
1013
+ if (!sourceTokens || sourceTokens.size === 0) return 1
1014
+ let hit = 0
1015
+ for (const token of sourceTokens) if (contentTokens.has(token)) hit += 1
1016
+ return hit / sourceTokens.size
1017
+ }
1018
+
1019
+ // char 覆盖率:union 的字符 bigram 有多大比例出现在 proposed 里。
1020
+ function charCoverage(unionText, proposedText) {
1021
+ const unionGrams = bigrams(unionText)
1022
+ if (unionGrams.size === 0) return 1
1023
+ const proposedGrams = bigrams(proposedText)
1024
+ let hit = 0
1025
+ for (const gram of unionGrams) if (proposedGrams.has(gram)) hit += 1
1026
+ return hit / unionGrams.size
1027
+ }
1028
+
1029
+ function sentenceInfo(sentence, idf, coveredTokens = null) {
1030
+ let sum = 0
1031
+ for (const token of tokensOf(sentence)) {
1032
+ if (coveredTokens && coveredTokens.has(token)) continue
1033
+ sum += Number(idf?.get?.(token) ?? 1)
1034
+ }
1035
+ return sum
1036
+ }
1037
+
1038
+ /**
1039
+ * 吸收合并稿(spec §4.7)。输入 target、sources、模型的 proposed 稿;
1040
+ * 输出 { content, mode, coverage, sourceCoverage, unionCoverage, truncated, omitted }。
1041
+ * 句级去重(charDice ≥0.90 或互含丢弃)→ union(target 在前)→ proposed 覆盖
1042
+ * ≥0.75 且不超长时用 proposed(abstractive),否则 extractive(放得下直接拼接,
1043
+ * 放不下做句子级 MMR:info − 0.7·redundancy·maxInfo 贪心,被丢关键句记 truncated)。
1044
+ * idf 由调用方通过 buildCorpus 提供(F1);缺省按 1 计(spec 已兼容 idf=null)。
1045
+ */
1046
+ export function composeAbsorbContent({ target, sources = [], proposed = '', maxChars = ABSORB_MAX_CHARS, idf = null } = {}) {
1047
+ const result = { content: '', mode: 'extractive', coverage: 0, sourceCoverage: 1, unionCoverage: 1, truncated: false, omitted: [] }
1048
+ // 1-3. 句子切分 + 句级去重;target 在前,构成 union。origin 记录每个句子的出处
1049
+ //(-1 = target,其余 = sources 下标),供关键句判定使用。
1050
+ const union = []
1051
+ const origins = []
1052
+ const keptKeys = []
1053
+ const pushSentence = (raw, origin) => {
1054
+ const sentence = String(raw || '').trim()
1055
+ const key = clean(sentence)
1056
+ if (!key) return
1057
+ for (const kept of keptKeys) {
1058
+ if (kept === key || kept.includes(key) || key.includes(kept) || dice(bigrams(key), bigrams(kept)) >= ABSORB_SENTENCE_DICE) return
1059
+ }
1060
+ keptKeys.push(key)
1061
+ union.push(sentence)
1062
+ origins.push(origin)
1063
+ }
1064
+ const sourceList = Array.isArray(sources) ? sources : []
1065
+ for (const sentence of splitSentences(target?.content)) pushSentence(sentence, -1)
1066
+ sourceList.forEach((source, index) => {
1067
+ for (const sentence of splitSentences(source?.content)) pushSentence(sentence, index)
1068
+ })
1069
+ if (!union.length) return result
1070
+ const unionText = union.join('')
1071
+ const proposedText = String(proposed || '').trim()
1072
+
1073
+ // 4. proposed 覆盖足够且不超长 → abstractive。
1074
+ if (proposedText) {
1075
+ result.coverage = Math.max(charCoverage(unionText, proposedText), tokenCoverage(tokensOf(unionText), tokensOf(proposedText)))
1076
+ if (result.coverage >= ABSORB_ABSTRACTIVE_COVERAGE && proposedText.length <= maxChars) {
1077
+ result.content = proposedText
1078
+ result.mode = 'abstractive'
1079
+ }
1080
+ }
1081
+
1082
+ // 5. extractive:总长放得下直接拼接;否则句子级 MMR 贪心到 maxChars。
1083
+ if (result.mode === 'extractive') {
1084
+ const infos = union.map((sentence) => sentenceInfo(sentence, idf))
1085
+ const maxInfo = infos.reduce((acc, value) => Math.max(acc, value), 0)
1086
+ const picked = []
1087
+ const covered = new Set()
1088
+ let length = 0
1089
+ const remaining = new Set(union.map((_, index) => index))
1090
+ while (remaining.size > 0) {
1091
+ let bestIndex = -1
1092
+ let bestScore = -Infinity
1093
+ for (const index of remaining) {
1094
+ let redundancy = 0
1095
+ for (const chosen of picked) redundancy = Math.max(redundancy, dice(bigrams(union[index]), bigrams(union[chosen])))
1096
+ const score = sentenceInfo(union[index], idf, covered) - 0.7 * redundancy * maxInfo
1097
+ if (score > bestScore) { bestScore = score; bestIndex = index }
1098
+ }
1099
+ remaining.delete(bestIndex)
1100
+ if (length + union[bestIndex].length > maxChars) continue
1101
+ picked.push(bestIndex)
1102
+ length += union[bestIndex].length
1103
+ for (const token of tokensOf(union[bestIndex])) covered.add(token)
1104
+ }
1105
+ if (!picked.length && union.length) picked.push(0)
1106
+ // 关键句:target 全部句子 + 每条 source 的 info 前 3 句;被 MMR 丢掉即 truncated。
1107
+ const byOrigin = new Map()
1108
+ union.forEach((_, index) => {
1109
+ if (!byOrigin.has(origins[index])) byOrigin.set(origins[index], [])
1110
+ byOrigin.get(origins[index]).push(index)
1111
+ })
1112
+ const keyIndices = new Set(byOrigin.get(-1) || [])
1113
+ for (const [origin, indices] of byOrigin) {
1114
+ if (origin === -1) continue
1115
+ for (const index of [...indices].sort((a, b) => infos[b] - infos[a]).slice(0, 3)) keyIndices.add(index)
1116
+ }
1117
+ const missingKeys = [...keyIndices].filter((index) => !picked.includes(index)).sort((a, b) => a - b)
1118
+ if (missingKeys.length) {
1119
+ result.truncated = true
1120
+ result.omitted = missingKeys.slice(0, 10).map((index) => union[index])
1121
+ }
1122
+ result.content = picked.sort((a, b) => a - b).map((index) => union[index]).join('')
1123
+ }
1124
+
1125
+ // 6. 覆盖率:sourceCoverage = 每条 source 的 token 覆盖率取最小;unionCoverage = 全部
1126
+ // source 词元并集的覆盖率。coverage 是 proposed 对 union 的覆盖(§4.7.4)。
1127
+ const contentTokens = tokensOf(result.content)
1128
+ const presentSources = sourceList.filter((source) => String(source?.content || '').trim())
1129
+ if (presentSources.length) {
1130
+ result.sourceCoverage = Math.min(...presentSources.map((source) => tokenCoverage(tokensOf(String(source.content || '')), contentTokens)))
1131
+ const unionSourceTokens = new Set()
1132
+ for (const source of presentSources) {
1133
+ for (const token of tokensOf(String(source.content || ''))) unionSourceTokens.add(token)
1134
+ }
1135
+ result.unionCoverage = tokenCoverage(unionSourceTokens, contentTokens)
1136
+ }
1137
+ return result
1138
+ }
1139
+
1140
+ // absorbOpId(spec §3.1):sha1('absorb|' + sortedIds + '|' + clean(content)).slice(0,16)。
1141
+ // 内容用脱敏后的合并稿,保证从已存条目重算能得到同一个 opId(幂等门靠它对账)。
1142
+ function absorbOpIdOf(sortedIds, content) {
1143
+ return createHash('sha1').update('absorb|' + [...sortedIds].sort().join(',') + '|' + clean(content)).digest('hex').slice(0, 16)
1144
+ }
1145
+
1146
+ function appliesToSubset(sourceApplies, targetApplies) {
1147
+ const target = Array.isArray(targetApplies) ? targetApplies.filter(Boolean) : []
1148
+ if (target.length === 0) return true // target 不限 ⇒ 更宽,任何 source 都算子集
1149
+ const source = Array.isArray(sourceApplies) ? sourceApplies.filter(Boolean) : []
1150
+ return source.every((item) => target.includes(item) || target.includes('all'))
1151
+ }
1152
+
1153
+ const round4 = (value) => Math.round(Number(value) * 10000) / 10000
1154
+
1155
+ /**
1156
+ * absorb 的索引单事务(spec §4.11 auto absorb 步骤 3b-3f)。在 updateGlobalIndex 的
1157
+ * 同步 mutator 里运行;expectedUpdatedAt 任一不匹配时不做任何修改并返回
1158
+ * { landed:false, changed }(调用方决定 held clone 还是抛 'review changed')。
1159
+ * 匹配时:merged 入索引(含出边并入 + absorbSnapshot)、target superseded +
1160
+ * absorbedInto、sources archived + absorbedBy、簇外入边改指 mergedId。
1161
+ */
1162
+ export function applyAbsorbIndexTransaction(fresh, { mergedId, merged, targetId, sourceIds = [], expectedUpdatedAt = {}, now }) {
1163
+ const entries = fresh.entries
1164
+ const memberIds = [targetId, ...sourceIds].filter(Boolean)
1165
+ const changed = []
1166
+ for (const memberId of memberIds) {
1167
+ const current = entries[memberId]
1168
+ const expected = expectedUpdatedAt[memberId]
1169
+ if (!current || current.status !== 'active' || (expected !== undefined && current.updatedAt !== expected)) {
1170
+ changed.push(memberId || '(missing id)')
1171
+ }
1172
+ }
1173
+ if (changed.length) return { landed: false, changed }
1174
+
1175
+ const target = entries[targetId]
1176
+ const sourceRefs = sourceIds.map((id) => ({ id, entry: entries[id] }))
1177
+ const clusterIds = new Set(memberIds)
1178
+ const linksOf = (entry) => (Array.isArray(entry?.links) ? entry.links : [])
1179
+
1180
+ // 吸收前状态快照(§4.11 f):rewired 存簇外条目的完整 links,撤销整体恢复。
1181
+ const rewired = []
1182
+ for (const [otherId, other] of Object.entries(entries)) {
1183
+ if (clusterIds.has(otherId) || otherId === mergedId) continue
1184
+ if (linksOf(other).some((link) => clusterIds.has(link?.to))) {
1185
+ rewired.push({ id: otherId, links: structuredClone(linksOf(other)) })
1186
+ }
1187
+ }
1188
+ // 出边并入 merged:target/sources 自己的 links 按 (to,kind) 去重、cap 20;
1189
+ // 指向簇内的边在吸收后是悬挂边,改指 mergedId,自环直接丢。
1190
+ const outbound = []
1191
+ const seenPairs = new Set()
1192
+ for (const member of [target, ...sourceRefs.map((ref) => ref.entry)]) {
1193
+ for (const link of linksOf(member)) {
1194
+ if (!link || !link.to) continue
1195
+ const key = `${link.to}|${link.kind || 'related'}`
1196
+ if (seenPairs.has(key)) continue
1197
+ seenPairs.add(key)
1198
+ outbound.push(structuredClone(link))
1199
+ }
1200
+ }
1201
+ const mergedLinks = outbound
1202
+ .map((link) => (clusterIds.has(link.to) ? { ...link, to: mergedId } : link))
1203
+ .filter((link) => link.to !== mergedId)
1204
+ .slice(0, CURATOR_MAX_LINK_ABSORB)
1205
+
1206
+ const mergedEntry = {
1207
+ ...merged,
1208
+ links: mergedLinks,
1209
+ updatedAt: now,
1210
+ absorbSnapshot: {
1211
+ target: { id: targetId, status: target.status, links: structuredClone(linksOf(target)), updatedAt: target.updatedAt },
1212
+ sources: sourceRefs.map(({ id, entry }) => ({ id, status: entry.status, links: structuredClone(linksOf(entry)), updatedAt: entry.updatedAt })),
1213
+ rewired,
1214
+ mergedLinks: structuredClone(mergedLinks),
1215
+ at: now,
1216
+ },
1217
+ }
1218
+
1219
+ entries[mergedId] = mergedEntry
1220
+ target.status = 'superseded'
1221
+ target.supersededBy = mergedId
1222
+ target.absorbedInto = mergedId
1223
+ target.validTo = now
1224
+ target.updatedAt = now
1225
+ const audit = { op: 'absorb', at: now, mergedId, targetId, sourceIds: [...sourceIds] }
1226
+ appendAudit(mergedEntry, audit)
1227
+ appendAudit(target, audit)
1228
+ for (const { entry } of sourceRefs) {
1229
+ entry.status = 'archived'
1230
+ entry.absorbedBy = mergedId
1231
+ entry.absorbedAt = now
1232
+ entry.validTo = now
1233
+ entry.updatedAt = now
1234
+ appendAudit(entry, audit)
1235
+ }
1236
+ for (const { id } of rewired) {
1237
+ entries[id].links = entries[id].links.map((link) => (clusterIds.has(link?.to) ? { ...link, to: mergedId } : link))
1238
+ }
1239
+ return { landed: true, at: now }
1240
+ }
1241
+
1242
+ /**
1243
+ * absorb 计划提交(spec §6.7 + §4.7 + §4.10 + §4.11)。输入 curator 输出,只处理
1244
+ * op === 'absorb' 的条目;每条走完 协议校验 → 降级(domain/appliesTo)→ medoid →
1245
+ * 合并稿 → 覆盖率分段 → 重复门 → 风险门,auto 直接落 §4.11 事务,其余生成
1246
+ * §3.3 pendingAbsorb 提案(只进索引,不进向量库)。
1247
+ * 并发变化:不落 active,held pending clone,已提交向量行锁外 best-effort forget。
1248
+ */
1249
+ export async function commitCuratorPlans(output, { job } = {}) {
1250
+ const memories = Array.isArray(output?.memories) ? output.memories : []
1251
+ const plans = memories.filter((m) => m && m.op === 'absorb')
1252
+ const result = { absorbed: 0, pending: 0, held: 0, skipped: [], demoted: [] }
1253
+ if (!plans.length) return result
1254
+ const index = loadGlobalIndex()
1255
+ // 模式只在循环外读一次(§4.10)。
1256
+ const mode = getSettings().curatorReviewMode || 'auto'
1257
+ const now = new Date().toISOString()
1258
+ const confOf = (value) => (Number.isFinite(Number(value)) ? Number(value) : 0.6)
1259
+ const pendingEntries = []
1260
+ const autoCommits = []
1261
+ const heldNames = []
1262
+
1263
+ for (const plan of plans) {
1264
+ const label = String(plan?.title || plan?.target_id || '(absorb)')
1265
+ // —— 协议校验(§6.7):target active;source 1–5;target 不在 source_ids。——
1266
+ const targetId = String(plan?.target_id || '').trim()
1267
+ const target = targetId ? index.entries[targetId] : null
1268
+ if (!target || target.status !== 'active') {
1269
+ result.skipped.push({ title: label, reason: `absorb target not found or not active: ${targetId || '(empty)'}` })
1270
+ continue
1271
+ }
1272
+ const requestedSources = [...new Set((Array.isArray(plan?.source_ids) ? plan.source_ids : [])
1273
+ .map((id) => String(id || '').trim()).filter(Boolean))]
1274
+ if (requestedSources.length < 1 || requestedSources.length > ABSORB_MAX_SOURCES) {
1275
+ result.skipped.push({ title: label, reason: `absorb needs 1-${ABSORB_MAX_SOURCES} distinct source ids, got ${requestedSources.length}` })
1276
+ continue
1277
+ }
1278
+ if (requestedSources.includes(targetId)) {
1279
+ result.skipped.push({ title: label, reason: 'absorb target must not appear in source_ids' })
1280
+ continue
1281
+ }
1282
+ // —— 降级(§4.7.11):source 的 appliesTo 必须是 target 子集;最终只允许同 domain。
1283
+ // 不满足的 source 不 absorb,降级 link(link 落地由 F1 的 commitCuratorOutput link 分支做)。
1284
+ const sourceRefs = []
1285
+ for (const sourceId of requestedSources) {
1286
+ const source = index.entries[sourceId]
1287
+ if (!source || source.status !== 'active') {
1288
+ result.demoted.push({ targetId, sourceId, reason: 'source not found or not active' })
1289
+ continue
1290
+ }
1291
+ if ((source.track || 'memory') !== (target.track || 'memory')) {
1292
+ result.demoted.push({ targetId, sourceId, reason: 'track differs' })
1293
+ continue
1294
+ }
1295
+ if ((source.domain || 'unknown') !== (target.domain || 'unknown')) {
1296
+ result.demoted.push({ targetId, sourceId, reason: 'domain differs; absorb is same-domain only (link candidate)' })
1297
+ continue
1298
+ }
1299
+ if (!appliesToSubset(source.appliesTo, target.appliesTo)) {
1300
+ result.demoted.push({ targetId, sourceId, reason: 'source appliesTo is not a subset of target; demoted to link candidate' })
1301
+ continue
1302
+ }
1303
+ sourceRefs.push({ id: sourceId, entry: source })
1304
+ }
1305
+ if (!sourceRefs.length) {
1306
+ result.skipped.push({ title: label, reason: 'no eligible source left after domain/appliesTo demotion' })
1307
+ continue
1308
+ }
1309
+ const sources = sourceRefs.map((ref) => ({ ...ref.entry, id: ref.id }))
1310
+
1311
+ // —— medoid/representative(C4):算 medoid,模型 target 只作 provenance,
1312
+ // medoid 平均相似度 <0.55 整簇跳过。——
1313
+ const members = [{ id: targetId, entry: target }, ...sourceRefs.map((ref) => ({ id: ref.id, entry: ref.entry }))]
1314
+ const memberText = new Map(members.map((member) => [member.id, `${member.entry.title || ''} ${member.entry.content || ''}`]))
1315
+ let medoid = null
1316
+ for (const member of members) {
1317
+ let sum = 0
1318
+ for (const other of members) {
1319
+ if (other.id === member.id) continue
1320
+ sum += similarTexts(memberText.get(member.id), memberText.get(other.id))
1321
+ }
1322
+ const avg = sum / Math.max(1, members.length - 1)
1323
+ if (!medoid || avg > medoid.avg) medoid = { id: member.id, avg }
1324
+ }
1325
+ if (!medoid || medoid.avg < CLUSTER_MIN_PAIR) {
1326
+ result.skipped.push({ title: label, reason: `medoid average similarity ${medoid ? medoid.avg.toFixed(2) : 'n/a'} is below the pair floor` })
1327
+ continue
1328
+ }
1329
+ const representativeId = medoid.id
1330
+
1331
+ // —— evidence(§4.6/§4.7.8):plan 证据(带 sourceId)优先,簇内既有证据并集,
1332
+ // 去重 ≤20;每条 source 至少一条 plan 证据覆盖,否则只进复核。——
1333
+ const planEvidence = (Array.isArray(plan?.evidence) ? plan.evidence : [])
1334
+ .filter((item) => typeof item?.session_id === 'string' && item.session_id && typeof item?.quote === 'string' && item.quote.trim())
1335
+ .map((item) => ({
1336
+ sessionId: item.session_id,
1337
+ quote: truncate(item.quote, 500),
1338
+ sourceId: typeof item?.source_id === 'string' && item.source_id.trim() ? item.source_id.trim() : null,
1339
+ }))
1340
+ .slice(0, 20)
1341
+ const clusterEvidence = []
1342
+ const seenEvidence = new Set()
1343
+ for (const item of [...planEvidence, ...members.flatMap((member) => (Array.isArray(member.entry.evidence) ? member.entry.evidence : [])
1344
+ .map((e) => ({ sessionId: e?.sessionId, quote: e?.quote, sourceId: member.id })))] ) {
1345
+ if (clusterEvidence.length >= 20) break
1346
+ const sessionId = typeof item?.sessionId === 'string' ? item.sessionId : null
1347
+ const quote = typeof item?.quote === 'string' ? item.quote : ''
1348
+ if (!sessionId || !quote.trim()) continue
1349
+ const key = `${sessionId}|${clean(quote)}|${item.sourceId || ''}`
1350
+ if (seenEvidence.has(key)) continue
1351
+ seenEvidence.add(key)
1352
+ clusterEvidence.push({ sessionId, quote: truncate(quote, 500), sourceId: item.sourceId || null })
1353
+ }
1354
+ const uncoveredSources = sourceRefs.filter((ref) => !planEvidence.some((item) => item.sourceId === ref.id))
1355
+
1356
+ // —— 合并稿 + 覆盖率分段(§4.7.6)。——
1357
+ const idf = absorbIdf(index)
1358
+ const composed = composeAbsorbContent({ target, sources, proposed: plan?.content, maxChars: ABSORB_MAX_CHARS, idf })
1359
+ const mergedContent = redactSecrets(composed.content)
1360
+ if (!mergedContent.trim()) {
1361
+ result.skipped.push({ title: label, reason: 'absorb produced an empty merged draft' })
1362
+ continue
1363
+ }
1364
+ if (composed.sourceCoverage < ABSORB_REVIEW_SOURCE_COVERAGE || composed.unionCoverage < ABSORB_REVIEW_UNION_COVERAGE) {
1365
+ result.skipped.push({ title: label, reason: `absorb coverage below floor (source ${composed.sourceCoverage.toFixed(2)} / union ${composed.unionCoverage.toFixed(2)})` })
1366
+ continue
1367
+ }
1368
+ const longestSource = Math.max(0, ...sourceRefs.map((ref) => String(ref.entry.content || '').length))
1369
+ const belowLengthFloor = mergedContent.length < ABSORB_MIN_LENGTH_RATIO * longestSource
1370
+
1371
+ // —— 幂等门(§6.7):同 opId 的提案/合并稿已存在 → skip。——
1372
+ const memberIdsSorted = [targetId, ...sourceRefs.map((ref) => ref.id)].sort()
1373
+ const opId = absorbOpIdOf(memberIdsSorted, mergedContent)
1374
+ if (Object.values(index.entries).some((e) => e?.absorbOpId === opId || e?.pendingAbsorb?.opId === opId)) {
1375
+ result.skipped.push({ title: label, reason: `duplicate absorb opId ${opId}; already proposed or absorbed` })
1376
+ continue
1377
+ }
1378
+
1379
+ // —— title(§4.7.7)与重复门(§6.7):与簇外 active 条目 similarTexts ≥0.90 →
1380
+ // pending 'absorb duplicate of <id>';0.55–0.90 → 新条目打 duplicateOf。——
1381
+ const titleCandidate = String(target.title || '').trim()
1382
+ || String(plan?.title || '').trim()
1383
+ || String(index.entries[representativeId]?.title || '').trim()
1384
+ const title = truncate(titleCandidate || label, 180)
1385
+ let absorbDuplicate = null
1386
+ for (const [otherId, other] of Object.entries(index.entries || {})) {
1387
+ if (memberIdsSorted.includes(otherId)) continue
1388
+ if (other?.status !== 'active') continue
1389
+ const similarity = similarTexts(`${title} ${mergedContent}`, `${other.title || ''} ${other.content || ''}`)
1390
+ if (similarity > (absorbDuplicate?.similarity ?? 0)) absorbDuplicate = { id: otherId, similarity }
1391
+ }
1392
+
1393
+ // —— 风险分(§4.10):写到所有条目(active 也写)。——
1394
+ const decision = reviewDecision({ m: plan, op: 'absorb', evidence: planEvidence, targetId, index, mode })
1395
+
1396
+ let reviewReason = null
1397
+ if (composed.sourceCoverage < ABSORB_AUTO_SOURCE_COVERAGE || composed.unionCoverage < ABSORB_AUTO_UNION_COVERAGE
1398
+ || belowLengthFloor || (composed.truncated && composed.omitted.length)) {
1399
+ reviewReason = 'absorb coverage'
1400
+ } else if (absorbDuplicate && absorbDuplicate.similarity >= DUP_REJECT_DICE) {
1401
+ reviewReason = `absorb duplicate of ${absorbDuplicate.id}`
1402
+ } else if (uncoveredSources.length || !planEvidence.length) {
1403
+ reviewReason = decision.hard ? decision.reasons[0] : 'evidence not grounded'
1404
+ } else if (decision.review) {
1405
+ reviewReason = decision.hard ? decision.reasons[0] : (String(plan?.review_reason || '').trim() || 'risk threshold')
1406
+ }
1407
+
1408
+ const confidence = Math.min(0.95, Math.max(confOf(target.confidence), ...sourceRefs.map((ref) => confOf(ref.entry.confidence)), confOf(plan?.confidence)))
1409
+ const clusterCreatedAt = members.map((member) => member.entry.createdAt).filter(Boolean).sort()[0] || now
1410
+ const expectedUpdatedAt = {
1411
+ [targetId]: target.updatedAt,
1412
+ ...Object.fromEntries(sourceRefs.map((ref) => [ref.id, ref.entry.updatedAt])),
1413
+ }
1414
+ const reviewRiskReasons = reviewReason === 'absorb coverage' ? [...decision.reasons, 'absorb coverage'] : decision.reasons
1415
+ const entryBase = {
1416
+ track: target.track || 'memory',
1417
+ domain: target.domain || 'general',
1418
+ appliesTo: Array.isArray(target.appliesTo) ? structuredClone(target.appliesTo).slice(0, 20) : [],
1419
+ title,
1420
+ content: mergedContent,
1421
+ confidence,
1422
+ evidence: clusterEvidence,
1423
+ status: 'active',
1424
+ absorbedFrom: memberIdsSorted,
1425
+ absorbedAt: now,
1426
+ absorbOpId: opId,
1427
+ representativeId,
1428
+ mergeMode: composed.mode,
1429
+ mergeCoverage: round4(composed.coverage),
1430
+ sourceCoverage: round4(composed.sourceCoverage),
1431
+ unionCoverage: round4(composed.unionCoverage),
1432
+ reviewRisk: decision.risk,
1433
+ reviewRiskReasons,
1434
+ createdAt: clusterCreatedAt,
1435
+ updatedAt: now,
1436
+ }
1437
+ if (absorbDuplicate && absorbDuplicate.similarity >= TOPIC_DICE && absorbDuplicate.similarity < DUP_REJECT_DICE) {
1438
+ entryBase.duplicateOf = absorbDuplicate.id
1439
+ }
1440
+
1441
+ if (reviewReason) {
1442
+ // pending absorb(§3.3):只进索引,绝不进向量库;accept 时才提交提案 id 本身。
1443
+ pendingEntries.push({
1444
+ id: newMemoryId('gmem'),
1445
+ entry: {
1446
+ ...entryBase,
1447
+ status: 'pending_review',
1448
+ reviewReason,
1449
+ conflictingWith: targetId,
1450
+ pendingAbsorb: { targetId, sourceIds: sourceRefs.map((ref) => ref.id), opId, representativeId, expectedUpdatedAt },
1451
+ source: 'curator',
1452
+ },
1453
+ })
1454
+ result.pending += 1
1455
+ continue
1456
+ }
1457
+ autoCommits.push({
1458
+ mergedId: newMemoryId('gmem'),
1459
+ entry: entryBase,
1460
+ targetId,
1461
+ sourceIds: sourceRefs.map((ref) => ref.id),
1462
+ expectedUpdatedAt,
1463
+ })
1464
+ }
1465
+
1466
+ if (pendingEntries.length) {
1467
+ if (job) job.step = `writing ${pendingEntries.length} pending absorb proposals`
1468
+ await withManagedCuratorWrite(() => retryStoreWrite(() => updateGlobalIndex((fresh) => {
1469
+ for (const { id, entry } of pendingEntries) fresh.entries[id] = entry
1470
+ })))
1471
+ }
1472
+
1473
+ if (autoCommits.length) {
1474
+ if (job) job.step = `committing ${autoCommits.length} absorb merges`
1475
+ await withManagedCuratorWrite(async () => {
1476
+ const route = engineRoute()
1477
+ const committedNames = []
1478
+ try {
1479
+ // 先向量后索引(§4.11 auto absorb 步骤 2→3):索引失败时能补偿已提交行。
1480
+ if (route !== 'lexical') {
1481
+ await commit({
1482
+ payload: {
1483
+ recall_files: autoCommits.map(({ mergedId, entry }) => ({ name: mergedId, track: entry.track, description: entry.title, content: entry.content })),
1484
+ resource: [],
1485
+ user: {},
1486
+ },
1487
+ route,
1488
+ db: globalDbPath(),
1489
+ })
1490
+ for (const c of autoCommits) committedNames.push(c.mergedId)
1491
+ const vector = activeEntryStamp(route)
1492
+ if (vector) for (const c of autoCommits) c.entry.vector = vector
1493
+ }
1494
+ await retryStoreWrite(() => updateGlobalIndex((fresh) => {
1495
+ for (const c of autoCommits) {
1496
+ const outcome = applyAbsorbIndexTransaction(fresh, {
1497
+ mergedId: c.mergedId, merged: c.entry, targetId: c.targetId,
1498
+ sourceIds: c.sourceIds, expectedUpdatedAt: c.expectedUpdatedAt, now,
1499
+ })
1500
+ if (!outcome.landed) {
1501
+ // 并发变化(§4.11 步骤 5):不落 active,生成 held pending clone;
1502
+ // expectedUpdatedAt 刷新为当前值,人审时再做快照校验。
1503
+ const heldId = newMemoryId('gmem')
1504
+ const refreshed = {}
1505
+ for (const memberId of [c.targetId, ...c.sourceIds]) {
1506
+ refreshed[memberId] = fresh.entries[memberId]?.updatedAt || c.expectedUpdatedAt[memberId]
1507
+ }
1508
+ const held = {
1509
+ ...c.entry,
1510
+ status: 'pending_review',
1511
+ reviewReason: 'cluster changed while curator was running',
1512
+ conflictingWith: c.targetId,
1513
+ pendingAbsorb: { targetId: c.targetId, sourceIds: c.sourceIds, opId: c.entry.absorbOpId, representativeId: c.entry.representativeId, expectedUpdatedAt: refreshed },
1514
+ updatedAt: now,
1515
+ }
1516
+ // 已提交向量库的是 mergedId 这一行;held 克隆从未进过向量库,
1517
+ // entry.vector 必须由当前向量写入结果生成,不能继承旧条目的戳。
1518
+ delete held.vector
1519
+ fresh.entries[heldId] = held
1520
+ heldNames.push(c.mergedId)
1521
+ result.held += 1
1522
+ continue
1523
+ }
1524
+ result.absorbed += 1
1525
+ }
1526
+ }))
1527
+ } catch (error) {
1528
+ if (committedNames.length) await compensateCuratorCommit(error, { files: committedNames.map((name) => ({ name })), route })
1529
+ throw error
1530
+ }
1531
+ // held clone 的已提交行 best-effort forget(锁外 await,修 D11);只在向量路由
1532
+ // 真的提交过行时才需要。删不掉必须可见。
1533
+ if (route !== 'lexical') {
1534
+ for (const name of heldNames) {
1535
+ try {
1536
+ await forget({ db: globalDbPath(), name })
1537
+ } catch (forgetError) {
1538
+ record({
1539
+ kind: 'curate', scope: 'global', ok: false, level: 'error',
1540
+ message: `集合吸收并发保护:held clone 已生成,但向量行 ${name} 撤销失败(引擎库残留孤儿行,需手动清理)`,
1541
+ detail: { op: 'absorb', heldForgetFailed: true, name, error: String(forgetError?.message || forgetError) },
1542
+ refs: [name],
1543
+ })
1544
+ }
1545
+ }
1546
+ }
1547
+ })
1548
+ }
1549
+
1550
+ if (result.absorbed || result.pending || result.held || result.skipped.length || result.demoted.length) {
1551
+ record({
1552
+ kind: 'curate',
1553
+ scope: 'global',
1554
+ ok: true,
1555
+ message: `集合吸收:合并 ${result.absorbed} / 待复核 ${result.pending}`
1556
+ + (result.held ? ` / 并发暂扣 ${result.held}` : '')
1557
+ + (result.skipped.length ? ` / 跳过 ${result.skipped.length}` : '')
1558
+ + (result.demoted.length ? ` / 降级 link ${result.demoted.length}` : ''),
1559
+ detail: { op: 'absorb', ...result, skipped: result.skipped.slice(0, 20), demoted: result.demoted.slice(0, 20) },
1560
+ refs: autoCommits.map((c) => c.mergedId).slice(0, 20),
1561
+ })
1562
+ }
1563
+ return result
1564
+ }
1565
+
1566
+ /**
1567
+ * 撤销集合吸收(spec §4.11 undo-absorb)。merged 必须 active 且带 absorbSnapshot;
1568
+ * 同一事务恢复 target/sources/rewired,merged 归档(保留正文)。吸收后又被人工改过
1569
+ * (updatedAt > absorbedAt)的成员拒绝整体撤销并返回可读错误——部分恢复比不恢复更
1570
+ * 难对账。不删除、不写向量。
1571
+ */
1572
+ export async function undoGlobalAbsorb({ id } = {}) {
1573
+ const mergedId = String(id || '').trim()
1574
+ if (!mergedId) throw new Error('undo-absorb needs the merged entry id')
1575
+ const index = loadGlobalIndex()
1576
+ const merged = index.entries[mergedId]
1577
+ if (!merged || merged.status !== 'active' || !merged.absorbSnapshot) {
1578
+ throw new Error('undo-absorb needs an active merged entry with an absorb snapshot')
1579
+ }
1580
+ const snapshot = merged.absorbSnapshot
1581
+ const memberRefs = [snapshot.target, ...(Array.isArray(snapshot.sources) ? snapshot.sources : [])].filter(Boolean)
1582
+ const changedMembers = []
1583
+ for (const member of memberRefs) {
1584
+ const current = index.entries[member.id]
1585
+ if (!current) continue
1586
+ const absorbedAt = Date.parse(current.absorbedAt || '') || Date.parse(snapshot.at || '') || 0
1587
+ if ((Date.parse(current.updatedAt || '') || 0) > absorbedAt) changedMembers.push(member.id)
1588
+ }
1589
+ if (changedMembers.length) {
1590
+ throw new Error(`absorb undo refused: ${changedMembers.join(', ')} changed after absorption; restore them manually or resolve each edit first`)
1591
+ }
1592
+ await retryStoreWrite(() => updateGlobalIndex((fresh) => {
1593
+ if (JSON.stringify(fresh.entries[mergedId]) !== JSON.stringify(merged)) throw new Error('absorb entry changed; reload and retry')
1594
+ const at = new Date().toISOString()
1595
+ const targetSnap = snapshot.target
1596
+ const currentTarget = targetSnap?.id ? fresh.entries[targetSnap.id] : null
1597
+ if (currentTarget && currentTarget.status === 'superseded' && currentTarget.supersededBy === mergedId) {
1598
+ currentTarget.status = targetSnap.status || 'active'
1599
+ if (Array.isArray(targetSnap.links)) currentTarget.links = structuredClone(targetSnap.links)
1600
+ delete currentTarget.supersededBy
1601
+ delete currentTarget.absorbedInto
1602
+ delete currentTarget.validTo
1603
+ currentTarget.updatedAt = at
1604
+ }
1605
+ for (const sourceSnap of Array.isArray(snapshot.sources) ? snapshot.sources : []) {
1606
+ const current = fresh.entries[sourceSnap.id]
1607
+ if (!current || current.status !== 'archived' || current.absorbedBy !== mergedId) continue
1608
+ current.status = sourceSnap.status || 'active'
1609
+ if (Array.isArray(sourceSnap.links)) current.links = structuredClone(sourceSnap.links)
1610
+ delete current.absorbedBy
1611
+ delete current.absorbedAt
1612
+ delete current.validTo
1613
+ current.updatedAt = at
1614
+ }
1615
+ for (const rewiredSnap of Array.isArray(snapshot.rewired) ? snapshot.rewired : []) {
1616
+ const current = fresh.entries[rewiredSnap.id]
1617
+ if (current && Array.isArray(rewiredSnap.links)) current.links = structuredClone(rewiredSnap.links)
1618
+ }
1619
+ const stored = fresh.entries[mergedId]
1620
+ stored.status = 'archived'
1621
+ stored.absorbUndoneAt = at
1622
+ stored.updatedAt = at
1623
+ const audit = { op: 'undo-absorb', at, mergedId }
1624
+ appendAudit(currentTarget, audit)
1625
+ for (const sourceSnap of Array.isArray(snapshot.sources) ? snapshot.sources : []) {
1626
+ appendAudit(fresh.entries[sourceSnap.id], audit)
1627
+ }
1628
+ appendAudit(stored, audit)
1629
+ }))
1630
+ // 活动日志 CURATOR_ABSORB_UNDO(§4.11 撤销 4):以 detail.op 标记,kind 仍是 curate。
1631
+ record({
1632
+ kind: 'curate',
1633
+ scope: 'global',
1634
+ ok: true,
1635
+ message: `撤销集合吸收 ${mergedId}:target 与来源记忆已恢复,merged 已归档`,
1636
+ detail: { op: 'undo-absorb', id: mergedId, snapshotAt: snapshot.at || null },
1637
+ refs: [mergedId],
1638
+ })
1639
+ return { id: mergedId, status: 'archived', undone: true }
1640
+ }
1641
+
1642
+ // —— 宿主契约兼容(docs/host-adaptation.md §3.4:形状变化用能力探测,不按版本号分支)——
1643
+ // 0.2.2-rc.2 随 SubagentActivationSpec 扁平化(parent/cwd/prompt/agentOptions 平铺到
1644
+ // 顶层,无 request 外层)同批在 SubagentService 上新增了树内省方法 rootOf/namesOf/
1645
+ // resolveName/waitForTreeWork(0.2.1-rc.5 与 0.2.2-rc.1 上四者均不存在)。用标记方法
1646
+ // 探测形态,避免向宿主提交不匹配的激活字段。
1647
+ export function activationUsesFlatSpec(subagents) {
1648
+ return typeof subagents?.rootOf === 'function' || typeof subagents?.namesOf === 'function'
1649
+ }
1650
+
1651
+ export function startGlobalCuration(ctx, { sessionIds, parentSessionId, model } = {}) {
1652
+ const ids = [...new Set((Array.isArray(sessionIds) ? sessionIds : []).filter((s) => typeof s === 'string' && s.trim()))]
1653
+ const jobId = `curate-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`
1654
+ const abort = new AbortController()
1655
+ const job = {
1656
+ id: jobId,
1657
+ status: 'running',
1658
+ step: 'queued',
1659
+ logs: [],
1660
+ createdAt: new Date().toISOString(),
1661
+ endedAt: null,
1662
+ error: null,
1663
+ result: null,
1664
+ abort,
1665
+ }
1666
+ jobs.set(jobId, job)
1667
+ const log = (line) => {
1668
+ job.logs.push(`[${new Date().toISOString()}] ${line}`)
1669
+ if (job.logs.length > 200) job.logs.splice(0, job.logs.length - 200)
1670
+ }
1671
+
1672
+ void (async () => {
1673
+ try {
1674
+ if (ids.length === 0) throw new Error('select at least one conversation')
1675
+ if (ids.length > MAX_SESSIONS) throw new Error(`at most ${MAX_SESSIONS} conversations per curation`)
1676
+ const sessionQuery = ctx.get?.('sessionQuery')
1677
+ if (!sessionQuery) throw new Error('sessionQuery is unavailable')
1678
+ const agents = ctx.get?.('agents')
1679
+ const parent = agents?.get?.(parentSessionId)
1680
+ if (!parent) throw new Error('the current conversation is not live; open a live conversation and retry')
1681
+ const subagents = ctx.get?.('subagents')
1682
+ if (!subagents?.startActivation) throw new Error('subagents service is unavailable')
1683
+
1684
+ job.step = 'reading sessions'
1685
+ log(`reading ${ids.length} session(s)`)
1686
+ const meta = await readSessionMeta(sessionQuery, ids)
1687
+ const sessions = []
1688
+ let total = 0
1689
+ let transcriptTokens = 0
1690
+ for (const id of ids) {
1691
+ if (abort.signal.aborted) throw new Error('cancelled by user')
1692
+ const snapshot = await readSession(sessionQuery, id)
1693
+ const record = meta.get(id)
1694
+ const header = snapshot.header || record?.header || {}
1695
+ const remaining = Math.max(2000, Math.min(MAX_SESSION_CHARS, MAX_TOTAL_CHARS - total))
1696
+ // token 预算跨会话累计(30k),与字符预算同时生效;任一耗尽即停止。
1697
+ const tokenRemaining = Math.max(500, MAX_TRANSCRIPT_TOKENS - transcriptTokens)
1698
+ const transcript = condenseEvents(snapshot.events, remaining, { maxTokens: tokenRemaining })
1699
+ total += transcript.length
1700
+ transcriptTokens += estTokens(transcript)
1701
+ sessions.push({
1702
+ id,
1703
+ title: record?.title || record?.displayTitle || header.title || '',
1704
+ createdAt: header.createdAt || null,
1705
+ cwd: header.cwd || '',
1706
+ // 实际在跑的预设(投影口径),不是 header 的创建事实。
1707
+ agentPreset: effectiveAgentPreset(header, snapshot.events) || '',
1708
+ live: record?.live === true,
1709
+ transcript,
1710
+ })
1711
+ if (total >= MAX_TOTAL_CHARS || transcriptTokens >= MAX_TRANSCRIPT_TOKENS) break
1712
+ }
1713
+
1714
+ // 按相关性打包索引(4000 tokens)与候选簇(2000 tokens),
1715
+ // 取代旧 compactGlobalIndex 的"插入顺序前 200 条"平铺。sessionCorpus 同步构建,
1716
+ // 提交层证据落地(§4.6)用同一份转录做回放校验。
1717
+ const globalIndex = loadGlobalIndex()
1718
+ const sessionText = sessions.map((s) => s.transcript).join('\n')
1719
+ const packedIndex = packCuratorIndexContext({ index: globalIndex, sessionText })
1720
+ const packedClusters = packCuratorClusterContext(buildCandidateClusters(globalIndex))
1721
+ const input = JSON.stringify({
1722
+ sessions,
1723
+ existing_global_index: packedIndex.entries,
1724
+ index_truncated: packedIndex.omitted > 0,
1725
+ candidate_clusters: packedClusters.clusters,
1726
+ clusters_truncated: packedClusters.truncated,
1727
+ })
1728
+ const prompt = loadPrompt('global-curator', { input }).text
1729
+ job.step = 'curator running'
1730
+ log('starting non-main curator subagent')
1731
+ const curatorModel = model || getSettings().curatorModel
1732
+ const agentOptions = agentOptionsFor(curatorModel)
1733
+ const task = {
1734
+ parent,
1735
+ cwd: parent.session?.header?.cwd,
1736
+ prompt: [{ type: 'text', text: prompt }],
1737
+ ...(agentOptions ? { agentOptions } : {}),
1738
+ }
1739
+ const base = {
1740
+ provider: 'spawn',
1741
+ label: 'dsh-memu-memory global curator',
1742
+ delivery: 'caller',
1743
+ signal: abort.signal,
1744
+ }
1745
+ const flat = activationUsesFlatSpec(subagents)
1746
+ let activation
1747
+ try {
1748
+ activation = await subagents.startActivation(flat ? { ...base, ...task } : { ...base, request: task })
1749
+ } catch (error) {
1750
+ // 零副作用兜底:两代宿主都在产生任何副作用(建子会话、落盘)之前读取形态
1751
+ // 不符的字段并抛 TypeError——旧契约 src/index.ts 读 spec.request.maxDepth
1752
+ //(0.2.1-rc.5:274 / 0.2.2-rc.1:276),0.2.2-rc.2+:275 读 spec.parent.id。遇到
1753
+ // 极简 mock(只提供 startActivation,无从探测)或未来宿主移除标记方法时,catch
1754
+ // 后换另一种形态重试一次是安全的。仅 TypeError 且未被取消时重试,且只重试一次。
1755
+ if (!(error instanceof TypeError) || abort.signal.aborted) throw error
1756
+ log(`activation shape mismatch (${flat ? 'flat' : 'nested'} rejected by TypeError); retrying with ${flat ? 'nested' : 'flat'} shape`)
1757
+ activation = await subagents.startActivation(flat ? { ...base, request: task } : { ...base, ...task })
1758
+ }
1759
+ let result
1760
+ try {
1761
+ result = await activation.result
1762
+ } finally {
1763
+ try { await activation.dispose() } catch {}
1764
+ }
1765
+ if (result?.stopReason !== 'completed') {
1766
+ throw new Error(`curator stopped: ${result?.stopReason || 'unknown'}`)
1767
+ }
1768
+ const text = textOf(result.output)
1769
+ const output = parseJsonObject(text)
1770
+ if (!output || !Array.isArray(output.memories)) {
1771
+ throw new Error(`curator did not return valid JSON: ${truncate(text, 800)}`)
1772
+ }
1773
+ job.step = 'committing'
1774
+ // 生产调用必须传会话语料(§4.6.6):证据 quote 要能在本次策划的转录里回放,
1775
+ // 否则一律 pending。transcripts 已在 condenseEvents 里脱敏。
1776
+ const committed = await commitCuratorOutput(output, {
1777
+ job,
1778
+ sessionCorpus: buildEvidenceCorpus(sessions.map((s) => ({ id: s.id, transcript: s.transcript }))),
1779
+ })
1780
+ job.status = 'completed'
1781
+ job.endedAt = new Date().toISOString()
1782
+ job.result = {
1783
+ sessions: output.sessions || [],
1784
+ domainSummary: output.domain_summary || {},
1785
+ created: committed.created,
1786
+ merged: committed.merged,
1787
+ superseded: committed.superseded,
1788
+ linked: committed.linked || 0,
1789
+ skipped: committed.skipped,
1790
+ }
1791
+ log(`done: ${committed.created} created, ${committed.merged} merged, ${committed.superseded} superseded, ${committed.linked || 0} linked`)
1792
+ } catch (error) {
1793
+ const aborted = abort.signal.aborted || /cancelled by user/.test(String(error?.message || ''))
1794
+ job.status = aborted ? 'cancelled' : 'error'
1795
+ job.error = String(error?.message || error)
1796
+ job.endedAt = new Date().toISOString()
1797
+ log(`${job.status}: ${job.error}`)
1798
+ // 失败落活动日志:此前只写内存 job.error,宿主重启后失败原因无从追溯
1799
+ //(issue #3 附带观察)。取消不记——那不是故障。
1800
+ if (!aborted) {
1801
+ record({
1802
+ kind: 'curate', scope: 'global', ok: false, level: 'error',
1803
+ message: '全局提炼失败:' + job.error,
1804
+ detail: { jobId, model: model || getSettings().curatorModel, sessions: ids.length, step: job.step || null },
1805
+ })
1806
+ }
1807
+ }
1808
+ })()
1809
+
1810
+ return getCurationJob(jobId)
1811
+ }
1812
+
1813
+ export { readSession as readSessionSnapshot }