dsh-memu-memory 1.4.2 → 1.4.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (389) hide show
  1. package/AGENTS.md +108 -110
  2. package/CHANGELOG.md +169 -868
  3. package/LICENSE +21 -21
  4. package/README.md +368 -374
  5. package/README.zh.md +354 -360
  6. package/assets/icon.svg +7 -7
  7. package/cordis.patch.yml +8 -8
  8. package/docs/active-memory-ab.md +279 -385
  9. package/docs/binding-lifecycle.md +99 -99
  10. package/docs/client-conventions.md +75 -75
  11. package/docs/contributing.md +217 -217
  12. package/docs/emotion-model-spec.md +247 -281
  13. package/docs/env-and-commands.md +149 -152
  14. package/docs/host-adaptation.md +339 -360
  15. package/docs/host-api.md +131 -137
  16. package/docs/host-versions.md +117 -120
  17. package/docs/mcp-porting.md +146 -146
  18. package/docs/memory-semantics.md +271 -259
  19. package/docs/pending-work.md +44 -51
  20. package/docs/troubleshooting.md +909 -854
  21. package/lib/active-memory.js +160 -165
  22. package/lib/activity-log.js +207 -207
  23. package/lib/auto-link/apply.js +248 -249
  24. package/lib/auto-link/candidates.js +163 -163
  25. package/lib/auto-link/decide.js +300 -300
  26. package/lib/auto-link/normalize.js +99 -99
  27. package/lib/auto-link/policy.js +42 -42
  28. package/lib/auto-link/suppression.js +101 -101
  29. package/lib/auto-link/terminology.js +311 -311
  30. package/lib/backup.js +1254 -1254
  31. package/lib/binding-diagnostics.js +634 -634
  32. package/lib/budget.js +118 -118
  33. package/lib/client.js +9820 -9751
  34. package/lib/commitment.js +178 -138
  35. package/lib/consolidation-ledger.js +434 -438
  36. package/lib/consolidation-receipt.js +386 -387
  37. package/lib/consolidation-snapshot.js +420 -405
  38. package/lib/consolidation-worker.js +240 -241
  39. package/lib/context.js +33 -33
  40. package/lib/curator-evidence.js +131 -131
  41. package/lib/curator-policy.js +198 -202
  42. package/lib/curator.js +1813 -1811
  43. package/lib/cycle.js +524 -513
  44. package/lib/diagnostics.js +524 -524
  45. package/lib/embedding-catalog.js +1051 -1055
  46. package/lib/embedding-download.js +637 -607
  47. package/lib/embedding-runtime.js +946 -946
  48. package/lib/engine.js +1103 -1103
  49. package/lib/entity-repair.js +285 -285
  50. package/lib/environment-check.js +394 -394
  51. package/lib/fork-model.js +312 -312
  52. package/lib/freshness.js +128 -121
  53. package/lib/global-graph.js +389 -389
  54. package/lib/graph.js +1193 -1193
  55. package/lib/host-surface.js +30 -30
  56. package/lib/inbound.js +284 -281
  57. package/lib/index.js +506 -511
  58. package/lib/inject.js +2639 -2619
  59. package/lib/lexicon-scope.js +143 -143
  60. package/lib/lexicon.js +1183 -1192
  61. package/lib/lifecycle-audit.js +37 -0
  62. package/lib/local-embedding-entry.js +145 -145
  63. package/lib/local-embedding-manager.js +306 -306
  64. package/lib/local-embedding-protocol.js +210 -210
  65. package/lib/local-embedding-worker.js +682 -682
  66. package/lib/local-vector-service.js +506 -453
  67. package/lib/maintenance-ledger.js +138 -0
  68. package/lib/maintenance-review.js +103 -0
  69. package/lib/maintenance-runner.js +267 -0
  70. package/lib/managed-runtime.js +118 -118
  71. package/lib/media.js +607 -513
  72. package/lib/memory.js +5035 -4941
  73. package/lib/memu-config.js +213 -213
  74. package/lib/memu.js +565 -565
  75. package/lib/migrate.js +200 -200
  76. package/lib/mood.js +300 -300
  77. package/lib/paths.js +453 -457
  78. package/lib/port-surface.js +82 -82
  79. package/lib/preset-mount.js +79 -0
  80. package/lib/preset-scope.js +126 -126
  81. package/lib/private-links.js +567 -567
  82. package/lib/private.js +2198 -2209
  83. package/lib/prompts/global-curator.md +135 -135
  84. package/lib/prompts/image-caption.md +1 -1
  85. package/lib/prompts/private-consolidation.coding.md +39 -39
  86. package/lib/prompts/private-consolidation.md +32 -32
  87. package/lib/prompts/private-consolidation.mixed.md +37 -37
  88. package/lib/prompts/private-consolidation.rp.md +47 -47
  89. package/lib/prompts/private-policy.coding.md +35 -35
  90. package/lib/prompts/private-policy.md +36 -36
  91. package/lib/prompts/private-policy.mixed.md +29 -29
  92. package/lib/prompts/private-policy.rp.md +43 -43
  93. package/lib/prompts/system-guide.coding.md +20 -20
  94. package/lib/prompts/system-guide.md +25 -25
  95. package/lib/prompts/system-guide.mixed.md +22 -22
  96. package/lib/prompts/system-guide.rp.md +23 -23
  97. package/lib/prompts.js +331 -331
  98. package/lib/recall-cache.js +212 -212
  99. package/lib/remote-summary.js +123 -123
  100. package/lib/rpc.js +2531 -2532
  101. package/lib/salient-wake.js +438 -438
  102. package/lib/snippet.js +125 -125
  103. package/lib/state.js +1948 -1928
  104. package/lib/stats.js +236 -236
  105. package/lib/temporal.js +345 -348
  106. package/lib/text-retrieval.js +992 -1001
  107. package/lib/text-similarity.js +305 -305
  108. package/lib/tokenizer-v2.js +271 -271
  109. package/lib/tools.js +1098 -1091
  110. package/lib/turn-log.js +545 -545
  111. package/lib/vector-migration.js +928 -930
  112. package/lib/vector-profile.js +1353 -1359
  113. package/lib/visibility.js +59 -59
  114. package/lib/webui/graph-LICENSE.txt +1 -1
  115. package/lib/webui/graph-view.bundle.js +2 -2
  116. package/lib/webui/graph-view.js +1171 -1175
  117. package/lib/webui/mark.svg +7 -7
  118. package/lib/webui/standalone.css +1178 -1178
  119. package/lib/webui/standalone.js +238 -238
  120. package/lib/webui.js +136 -136
  121. package/lib/worker-pool.js +1015 -979
  122. package/package.json +153 -153
  123. package/requirements.lock +34 -34
  124. package/scripts/acceptance-local.mjs +946 -946
  125. package/scripts/active-memory-ab-live.mjs +653 -655
  126. package/scripts/active-memory-ab.mjs +1302 -1302
  127. package/scripts/audit-memory-lifecycle.mjs +55 -0
  128. package/scripts/bench-recall.mjs +142 -142
  129. package/scripts/build-graph.mjs +44 -45
  130. package/scripts/chain-matrix.mjs +541 -541
  131. package/scripts/check-all.mjs +68 -74
  132. package/scripts/check-doc-drift.mjs +547 -547
  133. package/scripts/check-graph-browser.mjs +261 -261
  134. package/scripts/check-i18n.mjs +81 -83
  135. package/scripts/check-idle-compositing.mjs +61 -61
  136. package/scripts/check-seed-compat.mjs +115 -118
  137. package/scripts/check-text-format.mjs +55 -0
  138. package/scripts/curator-pair-calibrate.mjs +259 -259
  139. package/scripts/diagnose-bindings.mjs +176 -176
  140. package/scripts/drive-session.mjs +863 -864
  141. package/scripts/engine-smoke.mjs +69 -69
  142. package/scripts/entity-dedupe.mjs +110 -110
  143. package/scripts/lexicon-calibrate.mjs +230 -230
  144. package/scripts/lexicon-dedupe.mjs +318 -318
  145. package/scripts/local-runtime-install.mjs +142 -142
  146. package/scripts/local-runtime-verify.mjs +56 -56
  147. package/scripts/local-vector-verify.mjs +93 -93
  148. package/scripts/make-readme-shots.mjs +59 -59
  149. package/scripts/migrate-visibility.mjs +94 -94
  150. package/scripts/mock-llm.mjs +938 -903
  151. package/scripts/preview.mjs +58 -58
  152. package/scripts/prune-sessions.mjs +31 -34
  153. package/scripts/prune-turnlogs.mjs +29 -30
  154. package/scripts/prune-vectors.mjs +24 -24
  155. package/scripts/rebuild-auto-links.mjs +252 -252
  156. package/scripts/recall-bench.mjs +820 -820
  157. package/scripts/repetition-ab-scenarios.mjs +93 -93
  158. package/scripts/repetition-detector-snapshot.mjs +314 -314
  159. package/scripts/repetition-eval-live.mjs +360 -360
  160. package/scripts/repetition-eval.mjs +702 -702
  161. package/scripts/replay.mjs +705 -575
  162. package/scripts/setup.mjs +46 -46
  163. package/scripts/simulate-injection.mjs +299 -301
  164. package/tests/absorb-review.test.mjs +354 -354
  165. package/tests/activation.test.mjs +89 -89
  166. package/tests/active-memory-ab.test.mjs +745 -745
  167. package/tests/active-memory.test.mjs +129 -129
  168. package/tests/activity-log.test.mjs +126 -126
  169. package/tests/activity-wiring.test.mjs +155 -155
  170. package/tests/appendix-b.test.mjs +217 -217
  171. package/tests/appendix-b2.test.mjs +166 -166
  172. package/tests/audit-batch3.test.mjs +247 -247
  173. package/tests/audit-regression.test.mjs +275 -275
  174. package/tests/audit-safety.test.mjs +227 -227
  175. package/tests/auto-link-candidates.test.mjs +245 -245
  176. package/tests/auto-link-decide.test.mjs +512 -512
  177. package/tests/auto-link-migration.test.mjs +133 -133
  178. package/tests/backend-compensation.test.mjs +272 -272
  179. package/tests/backup.test.mjs +793 -793
  180. package/tests/binding-diagnostics.test.mjs +720 -720
  181. package/tests/browser.test.mjs +476 -476
  182. package/tests/client-export.test.mjs +521 -521
  183. package/tests/client-render.test.mjs +2008 -1728
  184. package/tests/coalesce.test.mjs +113 -113
  185. package/tests/commitment.test.mjs +243 -144
  186. package/tests/config.test.mjs +159 -159
  187. package/tests/consolidation-credential.test.mjs +330 -330
  188. package/tests/consolidation-feed.test.mjs +122 -122
  189. package/tests/consolidation-fork.test.mjs +1586 -1539
  190. package/tests/consolidation-ledger.test.mjs +389 -389
  191. package/tests/consolidation-snapshot.test.mjs +567 -505
  192. package/tests/consolidation-value.test.mjs +89 -89
  193. package/tests/context-scope.test.mjs +40 -40
  194. package/tests/cross-library-recall.test.mjs +269 -269
  195. package/tests/cue.test.mjs +58 -58
  196. package/tests/curator-absorb.test.mjs +444 -444
  197. package/tests/curator-calibrate.test.mjs +173 -173
  198. package/tests/curator-clusters.test.mjs +306 -306
  199. package/tests/curator-commit.test.mjs +325 -325
  200. package/tests/curator-contract.test.mjs +191 -191
  201. package/tests/curator-evidence.test.mjs +102 -102
  202. package/tests/curator-link.test.mjs +317 -317
  203. package/tests/curator-pairing.test.mjs +339 -339
  204. package/tests/curator-probe.test.mjs +490 -490
  205. package/tests/curator-review-mode.test.mjs +315 -315
  206. package/tests/curator.test.mjs +152 -152
  207. package/tests/cycle.test.mjs +567 -568
  208. package/tests/diagnostics.test.mjs +278 -278
  209. package/tests/disclosure.test.mjs +249 -249
  210. package/tests/doc-drift.test.mjs +342 -342
  211. package/tests/drive-session.test.mjs +152 -152
  212. package/tests/dynamic-rrf.test.mjs +182 -182
  213. package/tests/dynamic-threshold.test.mjs +52 -52
  214. package/tests/embedding-catalog.test.mjs +374 -374
  215. package/tests/embedding-download.test.mjs +529 -486
  216. package/tests/embedding-runtime.test.mjs +449 -449
  217. package/tests/emotion-chain.test.mjs +84 -84
  218. package/tests/emotion-contract.test.mjs +445 -445
  219. package/tests/engine.test.mjs +108 -108
  220. package/tests/entity-merge.test.mjs +278 -278
  221. package/tests/environment-check.test.mjs +187 -187
  222. package/tests/fact-version.test.mjs +146 -146
  223. package/tests/fixtures/active-memory-ab/README.md +56 -56
  224. package/tests/fixtures/active-memory-ab/cases/01-clean-dense-turn.json +351 -351
  225. package/tests/fixtures/active-memory-ab/cases/02-clean-thin-turn.json +122 -122
  226. package/tests/fixtures/active-memory-ab/cases/03-clean-starved-small.json +125 -125
  227. package/tests/fixtures/active-memory-ab/cases/04-clean-large-thin.json +137 -137
  228. package/tests/fixtures/active-memory-ab/cases/05-clean-half-step.json +166 -166
  229. package/tests/fixtures/active-memory-ab/cases/06-clean-duplicate-reread.json +197 -197
  230. package/tests/fixtures/active-memory-ab/cases/07-clean-recent-recall.json +125 -125
  231. package/tests/fixtures/active-memory-ab/cases/08-global-relevant.json +111 -111
  232. package/tests/fixtures/active-memory-ab/cases/09-global-irrelevant-conflict.json +158 -158
  233. package/tests/fixtures/active-memory-ab/cases/10-no-human-turn.json +97 -97
  234. package/tests/fixtures/active-memory-ab/cases/11-clean-scale-100.json +137 -137
  235. package/tests/fixtures/active-memory-ab/cases/12-clean-scale-1000.json +137 -137
  236. package/tests/fixtures/active-memory-ab/cases/13-clean-scale-5000.json +137 -137
  237. package/tests/fixtures/active-memory-ab/cases/14-clean-scale-20000.json +137 -137
  238. package/tests/fixtures/active-memory-ab/lead-ai-reviewed-reference.json +191 -191
  239. package/tests/fixtures/active-memory-ab/manifest.json +199 -199
  240. package/tests/fixtures/curator-pairs/labeled.v1.jsonl +90 -90
  241. package/tests/fixtures/lexicon-stub-hooks.mjs +15 -15
  242. package/tests/fixtures/lexicon-stub.mjs +284 -284
  243. package/tests/fixtures/mock-llm/reply.txt +1 -1
  244. package/tests/fixtures/recall-bench/01-paraphrase.json +183 -183
  245. package/tests/fixtures/recall-bench/02-exact.json +152 -152
  246. package/tests/fixtures/recall-bench/03-negation.json +172 -172
  247. package/tests/fixtures/recall-bench/04-no-answer.json +161 -161
  248. package/tests/fixtures/recall-bench/05-conflict.json +193 -193
  249. package/tests/fixtures/recall-bench/06-boundary.json +272 -272
  250. package/tests/fixtures/recall-bench/07-secret.json +190 -190
  251. package/tests/fixtures/recall-bench/08-coding.json +163 -163
  252. package/tests/fixtures/recall-bench-gold-candidates/01-paraphrase.json +193 -193
  253. package/tests/fixtures/recall-bench-gold-candidates/02-exact.json +197 -197
  254. package/tests/fixtures/recall-bench-gold-candidates/03-negation.json +244 -244
  255. package/tests/fixtures/recall-bench-gold-candidates/04-no-answer.json +189 -189
  256. package/tests/fixtures/recall-bench-gold-candidates/05-conflict.json +245 -245
  257. package/tests/fixtures/recall-bench-gold-candidates/06-boundary.json +279 -279
  258. package/tests/fixtures/recall-bench-gold-candidates/07-secret.json +224 -224
  259. package/tests/fixtures/recall-bench-gold-candidates/08-coding.json +218 -218
  260. package/tests/fixtures/repetition-eval/01-zh-rp.json +92 -92
  261. package/tests/fixtures/repetition-eval/02-en.json +96 -96
  262. package/tests/fixtures/repetition-eval/03-code.json +90 -90
  263. package/tests/fixtures/repetition-eval/04-names.json +115 -115
  264. package/tests/fixtures/repetition-eval/05-user-quote.json +95 -95
  265. package/tests/fixtures/repetition-eval/06-agreement.json +85 -85
  266. package/tests/fixtures/tokenizer-cases.mjs +27 -27
  267. package/tests/fork-model.test.mjs +345 -345
  268. package/tests/freshness.test.mjs +140 -140
  269. package/tests/global-graph.test.mjs +106 -106
  270. package/tests/global-lifecycle.test.mjs +149 -149
  271. package/tests/graph-cascade.test.mjs +363 -363
  272. package/tests/graph-view.test.mjs +414 -414
  273. package/tests/graph.test.mjs +371 -371
  274. package/tests/help-page.test.mjs +416 -416
  275. package/tests/hook-order.test.mjs +72 -72
  276. package/tests/humanlike.test.mjs +232 -232
  277. package/tests/hybrid-recall.test.mjs +610 -610
  278. package/tests/inbound.test.mjs +441 -441
  279. package/tests/inject-conflict.test.mjs +173 -173
  280. package/tests/inject-guide.test.mjs +513 -513
  281. package/tests/inject.test.mjs +384 -384
  282. package/tests/injection-budget-settings.test.mjs +35 -35
  283. package/tests/injection-budget.test.mjs +165 -165
  284. package/tests/injection-chain.test.mjs +442 -442
  285. package/tests/injection-intent-budget.test.mjs +92 -92
  286. package/tests/injection-rollback.test.mjs +428 -428
  287. package/tests/issue2-chain.test.mjs +169 -169
  288. package/tests/lexical-bm25.test.mjs +171 -171
  289. package/tests/lexicon-calibrate.test.mjs +48 -48
  290. package/tests/lexicon-dedupe.test.mjs +171 -171
  291. package/tests/lexicon-frequency.test.mjs +195 -195
  292. package/tests/lexicon-inject.test.mjs +459 -459
  293. package/tests/lexicon-perf.test.mjs +464 -464
  294. package/tests/lexicon-scope.test.mjs +256 -256
  295. package/tests/lexicon-ui.test.mjs +667 -667
  296. package/tests/lexicon.test.mjs +922 -922
  297. package/tests/lifecycle-audit.test.mjs +56 -0
  298. package/tests/loader-register.mjs +3 -3
  299. package/tests/loader.mjs +17 -17
  300. package/tests/local-embedding-entry.test.mjs +95 -95
  301. package/tests/local-embedding-env.test.mjs +51 -51
  302. package/tests/local-embedding-manager.test.mjs +494 -494
  303. package/tests/local-embedding-protocol.test.mjs +121 -121
  304. package/tests/local-embedding-worker.test.mjs +440 -440
  305. package/tests/local-vector-service.test.mjs +41 -0
  306. package/tests/maintenance-status.test.mjs +77 -0
  307. package/tests/maintenance.test.mjs +438 -0
  308. package/tests/managed-memory.test.mjs +1234 -1234
  309. package/tests/managed-runtime.test.mjs +72 -72
  310. package/tests/media-injection.test.mjs +225 -0
  311. package/tests/media.test.mjs +135 -135
  312. package/tests/memory-chain.test.mjs +169 -169
  313. package/tests/memory-fields.test.mjs +134 -134
  314. package/tests/memu-resident-route.test.mjs +130 -130
  315. package/tests/memu-resident.test.mjs +33 -33
  316. package/tests/migration-payload.test.mjs +40 -42
  317. package/tests/mock-llm.test.mjs +263 -225
  318. package/tests/mood.test.mjs +109 -109
  319. package/tests/multiprocess.test.mjs +29 -29
  320. package/tests/negation-polarity.test.mjs +135 -135
  321. package/tests/new-session-gate.test.mjs +617 -617
  322. package/tests/open-loop-date.test.mjs +416 -416
  323. package/tests/ops-hardening.test.mjs +209 -209
  324. package/tests/package-shipping.test.mjs +88 -88
  325. package/tests/pending-injection.test.mjs +107 -107
  326. package/tests/port-surface.test.mjs +138 -138
  327. package/tests/preset-mount.test.mjs +124 -0
  328. package/tests/preset-scope.test.mjs +212 -212
  329. package/tests/private-links.test.mjs +493 -493
  330. package/tests/prompt-semantics.test.mjs +51 -51
  331. package/tests/prompts.test.mjs +315 -315
  332. package/tests/query-decompose.test.mjs +62 -62
  333. package/tests/react-snapshot.test.mjs +24 -24
  334. package/tests/recall-bench.test.mjs +317 -317
  335. package/tests/recall-cache.test.mjs +292 -292
  336. package/tests/recall-corpus-eligibility.test.mjs +51 -51
  337. package/tests/recall-dedup.test.mjs +446 -446
  338. package/tests/recall-intent.test.mjs +172 -172
  339. package/tests/regression-sweep.test.mjs +311 -311
  340. package/tests/reminder-fairness.test.mjs +55 -0
  341. package/tests/remote.test.mjs +140 -140
  342. package/tests/rename.test.mjs +30 -30
  343. package/tests/repetition-detector-snapshot.test.mjs +231 -231
  344. package/tests/repetition-eval-live.test.mjs +177 -177
  345. package/tests/repetition-eval.test.mjs +373 -373
  346. package/tests/salience-domain.test.mjs +173 -173
  347. package/tests/salient-date.test.mjs +142 -142
  348. package/tests/salient-wake.test.mjs +389 -389
  349. package/tests/settings-beat.test.mjs +222 -222
  350. package/tests/settings-coverage.test.mjs +97 -97
  351. package/tests/settings-plumbing.test.mjs +79 -79
  352. package/tests/short-term.test.mjs +182 -166
  353. package/tests/sidebar-beat.test.mjs +213 -213
  354. package/tests/sidebar-refresh.test.mjs +123 -123
  355. package/tests/sidebar.test.mjs +102 -74
  356. package/tests/simulate-injection.test.mjs +76 -76
  357. package/tests/slot-similarity.test.mjs +153 -153
  358. package/tests/snippet.test.mjs +79 -79
  359. package/tests/source-kind.test.mjs +52 -52
  360. package/tests/speaker-provenance.test.mjs +120 -120
  361. package/tests/stale-maintenance.test.mjs +206 -131
  362. package/tests/state-gc.test.mjs +34 -34
  363. package/tests/state.test.mjs +155 -155
  364. package/tests/stats.test.mjs +112 -112
  365. package/tests/storage.test.mjs +125 -125
  366. package/tests/stubs/child-process-spy.mjs +14 -14
  367. package/tests/stubs/dsh-llm-pi-ai.js +13 -13
  368. package/tests/stubs/dsh-llm.js +5 -5
  369. package/tests/stubs/dsh-schedule.js +140 -140
  370. package/tests/stubs/dsh-session-query.js +26 -26
  371. package/tests/stubs/dsh-session.js +7 -7
  372. package/tests/stubs/dsh-tools.js +101 -101
  373. package/tests/temporal-repair.test.mjs +78 -0
  374. package/tests/temporal.test.mjs +124 -124
  375. package/tests/text-format.test.mjs +24 -0
  376. package/tests/tokenizer-v2.test.mjs +142 -142
  377. package/tests/tool-schema.test.mjs +126 -126
  378. package/tests/tools.test.mjs +810 -810
  379. package/tests/turn-log.test.mjs +487 -487
  380. package/tests/ui-defaults.test.mjs +57 -57
  381. package/tests/update-fields.test.mjs +138 -138
  382. package/tests/vector-gc.test.mjs +37 -37
  383. package/tests/vector-migration.test.mjs +810 -810
  384. package/tests/vector-profile.test.mjs +449 -449
  385. package/tests/visibility-migration.test.mjs +152 -152
  386. package/tests/webui-auth.test.mjs +963 -963
  387. package/tests/webui.test.mjs +421 -421
  388. package/tests/windows-env.test.mjs +89 -89
  389. package/tests/worker-lifecycle.test.mjs +1521 -1429
@@ -1,1001 +1,992 @@
1
- // Local candidate retrieval for the global curator (spec §4.1-§4.4, §4.8).
2
- //
3
- // Pipeline position: the LLM only arbitrates; everything here is model-free.
4
- // tokenize + BM25 give the ranking spine, character-Dice/token/entity features
5
- // give the pair score, weighted RRF fuses the three rankings, and the greedy
6
- // all-pairs clique turns edges into candidate clusters. The commit layer
7
- // (curator.js planCuratorOps) reuses rankPairCandidates as the final
8
- // duplicate/conflict gate — one ruler from blocking to commit.
9
- //
10
- // Dependency discipline: this module imports only lib/text-similarity.js (the
11
- // shared similarity ruler), lib/curator-policy.js (the single constant table)
12
- // and lib/tokenizer-v2.js (the V2 tokenizer delegated to by the TOKENIZER_V2
13
- // switch). No state, no IO, no clock — same input, same output, always.
14
-
15
- import {
16
- bigrams,
17
- dice,
18
- jaccard,
19
- lengthGap,
20
- similarityDetail,
21
- similarTexts,
22
- } from './text-similarity.js'
23
- import {
24
- BM25_B,
25
- BM25_DF_MIN_POOL,
26
- BM25_DF_RATIO,
27
- BM25_K1,
28
- BM25_MAX_QUERY_TERMS,
29
- BLOCK_DF_RATIO,
30
- CLUSTER_BLOCK_MIN_SHARED,
31
- CLUSTER_EXACT_PAIR_LIMIT,
32
- CLUSTER_MAX,
33
- CLUSTER_MAX_MEMBERS,
34
- CLUSTER_MAX_PAIRS,
35
- CLUSTER_MIN_PAIR,
36
- CLUSTER_RECENT_LIMIT,
37
- CROSS_DOMAIN_LINK_MIN,
38
- PAIR_ABSORB_MIN,
39
- PAIR_DUPLICATE_MIN,
40
- PAIR_LINK_MIN,
41
- PAIR_SCAN_LIMIT,
42
- PAIR_W_ENTITY,
43
- PAIR_W_LEXICAL,
44
- PAIR_W_TITLE,
45
- PAIR_W_TOKEN,
46
- RRF_DYNAMIC,
47
- RRF_K,
48
- RRF_SLICE_BAND,
49
- RRF_SLICE_BAND_CAP,
50
- RRF_W_BM25,
51
- RRF_W_DICE,
52
- RRF_W_ENTITY,
53
- TOKENIZER_V2,
54
- computeRRFWeights,
55
- } from './curator-policy.js'
56
- import {
57
- tokenStreamV2,
58
- tokenize as tokenizeV2,
59
- } from './tokenizer-v2.js'
60
- import { hasTemporalHint, resolveQueryDates, DEFAULT_TIME_ZONE } from './temporal.js'
61
-
62
- // —— §4.1 分词 ——
63
-
64
- /**
65
- * V1 分词原实现(双角色):TOKENIZER_V2 关时的回退路径;开时是本模块内
66
- * **idf 盲集合运算**(blocking 共享计数、tokenJaccard)的固定口径。
67
- * NFKC + lowercase; latin runs of ≥2 chars keep `._-` joins as one token; CJK
68
- * runs become single chars when isolated, otherwise overlapping bigrams; the
69
- * result is deduplicated (a set — Jaccard/blocking only care about presence).
70
- * Build tf from tokenStream below, never from this.
71
- */
72
- function tokenizeV1(text) {
73
- const s = String(text || '').normalize('NFKC').toLowerCase()
74
- const out = []
75
- for (const m of s.matchAll(/[a-z0-9]+(?:[._-][a-z0-9]+)*/g)) {
76
- if (m[0].length >= 2) out.push(m[0])
77
- }
78
- for (const m of s.matchAll(/[\u3400-\u9fff\uf900-\ufaff]+/g)) {
79
- const run = m[0]
80
- if (run.length === 1) out.push(run)
81
- else for (let i = 0; i < run.length - 1; i++) out.push(run.slice(i, i + 2))
82
- }
83
- return [...new Set(out)]
84
- }
85
-
86
- /** V1 token stream 原实现(无去重)——BM25 tf 的频率来源(回退路径)。 */
87
- function tokenStreamV1(text) {
88
- const s = String(text || '').normalize('NFKC').toLowerCase()
89
- const out = []
90
- for (const m of s.matchAll(/[a-z0-9]+(?:[._-][a-z0-9]+)*/g)) {
91
- if (m[0].length >= 2) out.push(m[0])
92
- }
93
- for (const m of s.matchAll(/[\u3400-\u9fff\uf900-\ufaff]+/g)) {
94
- const run = m[0]
95
- if (run.length === 1) out.push(run)
96
- else for (let i = 0; i < run.length - 1; i++) out.push(run.slice(i, i + 2))
97
- }
98
- return out
99
- }
100
-
101
- /**
102
- * 对外分词入口(双轨制,P0-1):TOKENIZER_V2 开 → 委托 lib/tokenizer-v2.js
103
- * (CJK unigram+bigram+trigram 三层 + 实体保护,Set 插入序数组);关 → V1
104
- * 原路径。签名与语义兼容,返回去重 token 数组(插入序)。
105
- *
106
- * 消费口径分层(P0 基准回归修复):V2 的增量 token **只进 BM25 流**(idf
107
- * 加权通道,unigram 的低 idf 由权重自然压掉,子词命中是纯收益);idf 盲的
108
- * 集合运算——blocking 共享计数、tokenJaccard——固定 tokenizeV1(bigram+latin)。
109
- * unigram 同时喂给集合运算会把高频单字灌进倒排/共享计数(候选池被灌爆、
110
- * 集合重叠被拉平,Recall@10 0.7675→0.6375 的定量根因)。开关关时本入口
111
- * 本来就是 V1,关闭路径字节级不变。
112
- */
113
- export function tokenize(text) {
114
- if (TOKENIZER_V2) return tokenizeV2(text)
115
- return tokenizeV1(text)
116
- }
117
-
118
- /**
119
- * Raw token stream (no dedupe) — the frequency source for BM25's tf.
120
- * 与 tokenize 同一开关:V2 → tokenStreamV2(与 tokenizeV2 同一生成器);V1 →
121
- * tokenStreamV1。
122
- */
123
- function tokenStream(text) {
124
- if (TOKENIZER_V2) return tokenStreamV2(text)
125
- return tokenStreamV1(text)
126
- }
127
-
128
- // —— §4.1 语料与 BM25 ——
129
-
130
- /**
131
- * entries: [{ id, title, content, ...rest }] — every extra field travels on
132
- * doc.entry so callers can reach track/domain/appliesTo/updatedAt without a
133
- * second lookup. Returns { docs, df, inverted, avgdl, size }.
134
- */
135
- export function buildCorpus(entries) {
136
- const docs = new Map()
137
- const df = new Map()
138
- const inverted = new Map()
139
- let totalLen = 0
140
- for (const entry of entries || []) {
141
- const id = entry?.id
142
- if (id == null || docs.has(id)) continue
143
- const stream = tokenStream(`${entry.title || ''} ${entry.content || ''}`)
144
- const tf = new Map()
145
- for (const term of stream) tf.set(term, (tf.get(term) || 0) + 1)
146
- docs.set(id, { id, tokens: new Set(stream), tf, len: stream.length, entry })
147
- totalLen += stream.length
148
- for (const term of tf.keys()) {
149
- df.set(term, (df.get(term) || 0) + 1)
150
- if (!inverted.has(term)) inverted.set(term, new Set())
151
- inverted.get(term).add(id)
152
- }
153
- }
154
- return {
155
- docs,
156
- df,
157
- inverted,
158
- avgdl: docs.size ? totalLen / docs.size : 0,
159
- size: docs.size,
160
- }
161
- }
162
-
163
- function idfOf(corpus, term) {
164
- const df = corpus.df.get(term) || 0
165
- return Math.log(1 + (corpus.size - df + 0.5) / (df + 0.5))
166
- }
167
-
168
- /**
169
- * §4.1 BM25 formula with the query-side frequency gate (A-2)。
170
- *
171
- * 每个 query term 独立判定,df 超过 dfCap 就整条不参与打分,其中
172
- * dfCap = max(BM25_DF_MIN_POOL, ceil(BM25_DF_RATIO × N))。
173
- * 只看占比会在极小语料上把查询词剔光(12 条记忆都含「会议」→ 占比 100% → 召回
174
- * 0 条,实测回归),所以下限取「一次召回至少会看的候选数」;只看绝对数又会把
175
- * 「20000 条里 100 条」这种真正有区分度的词误杀。V2 的 CJK unigram 让「的」「了」
176
- * 在小库和大库上都会撞线。
177
- * 剔除的是整个 term,不是把它的分数清零后继续保留条目:后者只换来一个恒定 0
178
- * 分的候选,候选池照样是全库。
179
- *
180
- * qtf(A-12):query 侧保留重复 term 的频率并乘进分数。qtf=1 时与旧口径逐位
181
- * 相同,所以既有的精确数值断言不受影响;重复查询词只会放大它自己的贡献,不会
182
- * 倒挂 IDF——真正的高频词在闸门处已经被剔除。
183
- *
184
- * Queries wider than BM25_MAX_QUERY_TERMS keep only the 64 highest-IDF terms —
185
- * measured among terms the corpus actually knows (df > 0): an absent term scores
186
- * 0 no matter its nominal IDF, so letting it occupy the quota would only shrink
187
- * the effective query. Ties break by term.
188
- */
189
- export function bm25(queryTokens, doc, corpus, { k1 = BM25_K1, b = BM25_B } = {}) {
190
- if (!queryTokens?.length || !doc || !corpus || corpus.size === 0) return 0
191
- const qtf = new Map()
192
- for (const term of queryTokens) {
193
- if (!corpus.df.has(term)) continue
194
- qtf.set(term, (qtf.get(term) || 0) + 1)
195
- }
196
- if (qtf.size === 0) return 0
197
- const dfCap = Math.max(BM25_DF_MIN_POOL, Math.ceil(BM25_DF_RATIO * corpus.size))
198
- let terms = []
199
- for (const [term, count] of qtf) {
200
- if ((corpus.df.get(term) || 0) > dfCap) continue
201
- terms.push({ term, qtf: count, idf: idfOf(corpus, term) })
202
- }
203
- if (terms.length === 0) return 0
204
- if (terms.length > BM25_MAX_QUERY_TERMS) {
205
- terms = terms
206
- .sort((a, b2) => b2.idf - a.idf || (a.term < b2.term ? -1 : 1))
207
- .slice(0, BM25_MAX_QUERY_TERMS)
208
- }
209
- let score = 0
210
- for (const { term, qtf: count, idf } of terms) {
211
- const tf = doc.tf.get(term) || 0
212
- if (!tf) continue
213
- score += idf * count * (tf * (k1 + 1)) / (tf + k1 * (1 - b + b * doc.len / corpus.avgdl))
214
- }
215
- return score
216
- }
217
-
218
- // —— §4.2 成对特征 ——
219
-
220
- function entitySet(appliesTo) {
221
- const out = new Set()
222
- for (const item of Array.isArray(appliesTo) ? appliesTo : []) {
223
- const v = String(item || '').trim().toLowerCase()
224
- if (v) out.add(v)
225
- }
226
- return out
227
- }
228
-
229
- function normalizedTitle(entry) {
230
- return String(entry?.title || '').trim().toLowerCase()
231
- }
232
-
233
- /**
234
- * §4.2 pair features over two index-shaped entries
235
- * ({ title, content, track, domain, appliesTo }).
236
- * charDice — similarTexts(title+\n+content):length-prune + containment floor
237
- * containment — the probe floor when the length prune fired, else 0
238
- * lexical — max(charDice, containment)
239
- * tokenJaccard — V1 口径 tokenize set Jaccard over title+content(idf 盲集合
240
- * 运算固定 V1;V2 三层只服务 BM25,见 tokenize 的 JSDoc)
241
- * titleDice — bigram Dice over the raw titles
242
- * titleExact — trimmed/lowercase title equality (non-empty)
243
- * entityJaccard — appliesTo set Jaccard; both empty → 0.5 neutral
244
- */
245
- export function pairFeatures(a, b) {
246
- const aText = `${a?.title || ''}\n${a?.content || ''}`
247
- const bText = `${b?.title || ''}\n${b?.content || ''}`
248
- const detail = similarityDetail(aText, bText)
249
- return {
250
- charDice: detail.dice,
251
- containment: detail.containment,
252
- lexical: Math.max(detail.dice, detail.containment),
253
- // idf 盲集合运算固定 V1 口径:unigram 会把跨主题的高频单字重叠拉平
254
- // tokenJaccard 的区分度。开关关时 tokenize 本就返回 V1,两种写法等价。
255
- tokenJaccard: jaccard(new Set(tokenizeV1(aText)), new Set(tokenizeV1(bText))),
256
- titleDice: dice(bigrams(a?.title || ''), bigrams(b?.title || '')),
257
- titleExact: normalizedTitle(a) !== '' && normalizedTitle(a) === normalizedTitle(b),
258
- entityJaccard: entityScore(a?.appliesTo, b?.appliesTo),
259
- lengthGap: detail.lengthGap,
260
- }
261
- }
262
-
263
- function entityScore(aApplies, bApplies) {
264
- const a = entitySet(aApplies)
265
- const b = entitySet(bApplies)
266
- if (a.size === 0 && b.size === 0) return 0.5
267
- return jaccard(a, b)
268
- }
269
-
270
- /**
271
- * §4.2 weighted sum. Accepts a features object (preferred — pairFeatures is
272
- * already computed on hot paths) or the two entries directly.
273
- */
274
- export function pairScore(aOrFeatures, b) {
275
- const f = aOrFeatures && typeof aOrFeatures === 'object' && 'lexical' in aOrFeatures
276
- ? aOrFeatures
277
- : pairFeatures(aOrFeatures, b)
278
- return PAIR_W_LEXICAL * f.lexical
279
- + PAIR_W_TOKEN * f.tokenJaccard
280
- + PAIR_W_TITLE * f.titleDice
281
- + PAIR_W_ENTITY * f.entityJaccard
282
- }
283
-
284
- function isRpCodingClash(aDomain, bDomain) {
285
- return (aDomain === 'rp' && bDomain === 'coding') || (aDomain === 'coding' && bDomain === 'rp')
286
- }
287
-
288
- /**
289
- * §4.2 pairDecision, verbatim bands:
290
- * track differs → none
291
- * domain differs → link only at pairScore ≥0.65(跨域只 link 不 absorb;
292
- * rp↔coding 永不 link——§4.9 的校验层再拦一次)
293
- * titleExact && lexical <0.55 → conflict(同标题正文迥异;lexical 而非裸 charDice,
294
- * 因为 §4.8 明确 containment ≥0.92 是重复/细化不是冲突)
295
- * ≥0.90 duplicate / ≥0.82 absorb / ≥0.55 link / else none
296
- */
297
- export function pairDecision(a, b, features = pairFeatures(a, b)) {
298
- if ((a?.track || 'memory') !== (b?.track || 'memory')) return 'none'
299
- const aDomain = a?.domain || 'unknown'
300
- const bDomain = b?.domain || 'unknown'
301
- const score = pairScore(features)
302
- if (aDomain !== bDomain) {
303
- if (isRpCodingClash(aDomain, bDomain)) return 'none'
304
- return score >= CROSS_DOMAIN_LINK_MIN ? 'link' : 'none'
305
- }
306
- if (features.titleExact && features.lexical < PAIR_LINK_MIN) return 'conflict'
307
- if (score >= PAIR_DUPLICATE_MIN) return 'duplicate'
308
- if (score >= PAIR_ABSORB_MIN) return 'absorb'
309
- if (score >= PAIR_LINK_MIN) return 'link'
310
- return 'none'
311
- }
312
-
313
- // —— §4.8 全局冲突预筛 ——
314
-
315
- // Same pattern as memory.js's NEGATION_RE (not exported there; lib/memory.js is
316
- // outside this package's edit scope). One ruler for "opposite claim". 整文本
317
- // 口径保持原样(P0 前的既有行为,也是无锚点时的回退路径),词典不在此扩。
318
- const NEGATION_RE = /不|没|别|无|never|not|no longer|doesn't|don't/i
319
-
320
- /** True when the text carries a negation marker (memory.js findConflict 口径). */
321
- export function negationPolarity(text) {
322
- return NEGATION_RE.test(String(text || ''))
323
- }
324
-
325
- // —— 子句级否定作用域(P1-2)——
326
- //
327
- // 整文本 negationPolarity 有两类误报:无关子句的否定污染(「截止日期是 5 月
328
- // 1 日,别忘了」整条算否定侧)和双重否定(「不是不喜欢香菜」仍算否定侧)。
329
- // polarityAt 把判定范围缩到锚点所在的子句,用标记计数 mod 2 近似否定作用域,
330
- // 不做句法分析——同输入同输出,无 clock。
331
-
332
- // 子句切分:中西标点一视同仁(连续标点算一次切分)。
333
- const CLAUSE_SPLIT_RE = /[。!?;,、,.!?;:]+/
334
-
335
- // 对比结构:「不是 A 而是 B」的 B、「不用 A 改成/换成 B」的 B 都是肯定侧,
336
- // 前文标记的否定作用到对比词为止。
337
- const CONTRAST_RE = /而不是|而是|改成|换成/g
338
-
339
- // 否定标记词典。CJK 没有词边界(\b 对中文无效),靠最长优先的 alternation
340
- // 保证「不再」「没有」只数一次而不是拆成「不」+「再」;「非常/未来/别的」
341
- // 与否定标记同形但不是否定(高频词),用 lookahead 排除。英文统一用 \b 包住
342
- // (缩写以 't 结尾,\b 仍成立;不 \b 的话 'not' 会命中 another/desktop)。
343
- const NEG_MARKER_RE = /禁止|不得|无法|不能|不再|从不|从未|并不|并非|没有|拒绝|反对|不|没|别(?!的)|无|未(?!来)|勿|莫|非(?!常)|\b(?:not|never|no longer|cannot|without|avoid|refuse|stop|doesn't|don't|won't|can't)\b/gi
344
-
345
- /**
346
- * 一个子句内、锚点所在片段是否为否定侧。对比词把子句切成片段,逐片段判定:
347
- * 片段自带标记计数(奇数 → 否定);「而不是」引出的片段额外继承 1 个否定
348
- * (「而不是队列」的队列仍是否定侧,等价于标记紧邻锚点前不被对比词隔断的
349
- * 场景),「而是/改成/换成」引出的片段从 0 起算。锚点在同片段多次出现只按
350
- * 片段判定一次,锚点落在多个片段时任一片段否定即为否定(保守)。
351
- */
352
- function segmentNegated(clause, needle) {
353
- const segments = []
354
- let last = 0
355
- let inherit = false
356
- for (const m of clause.matchAll(CONTRAST_RE)) {
357
- segments.push({ text: clause.slice(last, m.index), inherit })
358
- inherit = m[0] === '而不是'
359
- last = m.index + m[0].length
360
- }
361
- segments.push({ text: clause.slice(last), inherit })
362
- for (const segment of segments) {
363
- if (!segment.text.includes(needle)) continue
364
- let markers = 0
365
- for (const _ of segment.text.matchAll(NEG_MARKER_RE)) markers += 1
366
- if ((markers + (segment.inherit ? 1 : 0)) % 2 === 1) return true
367
- }
368
- return false
369
- }
370
-
371
- /**
372
- * 子句级否定极性(P1-2):text 里 anchor 所在的每个子句,任一为否定即算否定
373
- * 侧(锚点多次出现取保守口径)。子句切分与标记匹配都在 NFKC + lowercase 之后
374
- * 进行——锚点来自 tokenize(同一规范化),latin 大小写/全角差异不会漏匹配。
375
- * 锚点为空或不在 text 中出现 → false(没有可判定的作用域就不是否定侧)。
376
- */
377
- export function polarityAt(text, anchor) {
378
- const needle = String(anchor || '').normalize('NFKC').toLowerCase()
379
- if (!needle) return false
380
- const s = String(text || '').normalize('NFKC').toLowerCase()
381
- for (const clause of s.split(CLAUSE_SPLIT_RE)) {
382
- if (clause.includes(needle) && segmentNegated(clause, needle)) return true
383
- }
384
- return false
385
- }
386
-
387
- /** 数字、周X/星期X、YYYY-MM-DD、M月D日 —— 抽出来比集合(§4.8 numericSetsDiffer)。 */
388
- export function numericSet(text) {
389
- const s = String(text || '')
390
- const out = new Set()
391
- for (const m of s.matchAll(/\d{4}-\d{1,2}-\d{1,2}/g)) out.add(m[0])
392
- for (const m of s.matchAll(/\d{1,2}月\d{1,2}[日号]/g)) out.add(m[0])
393
- for (const m of s.matchAll(/周[一二三四五六日天]|星期[一二三四五六日天]/g)) out.add(m[0])
394
- for (const m of s.matchAll(/\d+(?:\.\d+)?/g)) out.add(m[0])
395
- return out
396
- }
397
-
398
- export function numericSetsDiffer(a, b) {
399
- const sa = numericSet(a)
400
- const sb = numericSet(b)
401
- if (sa.size === 0 || sb.size === 0) return false
402
- for (const item of sa) if (!sb.has(item)) return true
403
- for (const item of sb) if (!sa.has(item)) return true
404
- return false
405
- }
406
-
407
- /**
408
- * 冲突锚点:双方 body 的共享 token 里最长者(长度相同取字典序最小,完全确定,
409
- * 与遍历序无关)。token 来自当前生效的 tokenize(双轨开关自动生效),只要求
410
- * 子串包含关系(clause.includes(anchor))——锚点本身就是文本的子串,CJK
411
- * unigram/bigram 与 latin 词都覆盖。无共享词返回 ''(调用方回退整文本口径)。
412
- */
413
- export function longestSharedToken(aBody, bBody) {
414
- const bTokens = new Set(tokenize(bBody))
415
- let anchor = ''
416
- for (const token of new Set(tokenize(aBody))) {
417
- if (!bTokens.has(token)) continue
418
- if (token.length > anchor.length || (token.length === anchor.length && token < anchor)) anchor = token
419
- }
420
- return anchor
421
- }
422
-
423
- /**
424
- * §4.8 全局冲突预筛(同 domain/track 前提由调用方保证)。返回 'same_title' |
425
- * 'negation' | 'value' 或 null。containment ≥0.92 或 charDice ≥0.95 一票豁免
426
- * (重复/细化,不是冲突)。预筛只决定“送不送人审”,最终由 LLM + 人审裁决。
427
- *
428
- * negation 分支(P1-2):有共享锚点 → 双方 polarityAt(body, anchor) 不同才算
429
- * 否定冲突(子句级作用域,修掉「无关子句否定污染」与「双重否定」两类误报);
430
- * 无共享锚点 → 回退整文本 negationPolarity 对比(原口径,行为不变)。
431
- */
432
- export function globalConflictCheck(a, b, features = pairFeatures(a, b)) {
433
- if (features.containment >= 0.92 || features.charDice >= 0.95) return null
434
- if (features.titleExact && features.charDice < 0.95) return 'same_title'
435
- const aBody = String(a?.content || '')
436
- const bBody = String(b?.content || '')
437
- if (features.charDice >= 0.55) {
438
- const anchor = longestSharedToken(aBody, bBody)
439
- const differs = anchor
440
- ? polarityAt(aBody, anchor) !== polarityAt(bBody, anchor)
441
- : negationPolarity(aBody) !== negationPolarity(bBody)
442
- if (differs) return 'negation'
443
- }
444
- if (features.titleDice >= 0.8 && features.charDice >= 0.55
445
- && numericSetsDiffer(`${a?.title || ''} ${aBody}`, `${b?.title || ''} ${bBody}`)) return 'value'
446
- return null
447
- }
448
-
449
- // —— §4.3 候选召回 ——
450
-
451
- function trackOf(entry) {
452
- return entry?.track || 'memory'
453
- }
454
-
455
- function updatedDesc(a, b) {
456
- return String(b?.updatedAt || '').localeCompare(String(a?.updatedAt || ''))
457
- }
458
-
459
- function idAsc(a, b) {
460
- return String(a.id).localeCompare(String(b.id))
461
- }
462
-
463
- /**
464
- * 标准竞赛排名(1,2,2,4):并列分数共享同一名次,后续名次跳号。
465
- * metricOf 返回参与并列判定的值(数组按值拼成键)——排序里的 id/键 tiebreak
466
- * 只负责让输出完全确定,不再把同分文档强行排成不同名次。RRF 是按名次加权
467
- * 融合的,给并列者不同名次等于凭空制造分差。
468
- */
469
- function competitionRanks(sorted, metricOf) {
470
- const ranks = new Map()
471
- let previous = null
472
- let rank = 0
473
- sorted.forEach((item, index) => {
474
- const metric = metricOf(item)
475
- const key = Array.isArray(metric) ? metric.join('\u0000') : String(metric)
476
- if (key !== previous) {
477
- rank = index + 1
478
- previous = key
479
- }
480
- ranks.set(item.id ?? item.key, rank)
481
- })
482
- return ranks
483
- }
484
-
485
- /** 两个 token 集的交集大小(不构造第三个集合):blocking 的便宜预筛。 */
486
- function sharedTokenCount(a, b) {
487
- if (!a || !b || a.size === 0 || b.size === 0) return 0
488
- const [small, large] = a.size <= b.size ? [a, b] : [b, a]
489
- let shared = 0
490
- for (const token of small) if (large.has(token)) shared += 1
491
- return shared
492
- }
493
-
494
- /**
495
- * §4.3 rankPairCandidates({ corpus, proposal, limit })。
496
- *
497
- * 1) blocking:同 track;N ≤ exactPairLimit 时精确两两,否则查询 token 中
498
- * df ≤ 30%N 的稀有词、共享 ≥2 token,或 exact title。
499
- * 2) 三路排名 bm25 / charDice / entityJaccard(tiebreak containment)。
500
- * 3) 加权 RRF(k=60)。RRF_DYNAMIC 开 → 权重来自 computeRRFWeights(proposal,
501
- * corpus):普通查询退化为静态 0.5/0.3/0.2,近期查询加第四路 recency
502
- * (候选按 updatedAt 降序排名),coding 域 entity 提权;关 → 恒用静态
503
- * 0.5/(60+rankBm25) + 0.3/(60+rankDice) + 0.2/(60+rankEntity)。
504
- * 4) RRF 代理切分 + 边界带 → pairScore 真尺终选:前 max 名进评分集,与切点
505
- * rrf 之差 ≤ RRF_SLICE_BAND 的候选并入(总量 ≤ max×RRF_SLICE_BAND_CAP),
506
- * 全部算 pairFeatures/pairScore,按 pairScore 降序截取前 max——近重复簇里
507
- * rrf 平刀锋时 len 归一噪声不再决定准入。
508
- * 5) 不足 limit 用同域最近条目补齐(“多看几眼”,不降低门槛)。
509
- *
510
- * 返回 [{ id, entry, score, decision, features, rrf, fallback }],score 降序,
511
- * 平手 rrf 降序 → id 升序——完全确定(动态路径的 recency 排名同样带
512
- * idAsc tiebreak,不引入任何 clock/随机性)。
513
- */
514
- export function rankPairCandidates({ corpus, proposal, limit = PAIR_SCAN_LIMIT }) {
515
- const max = Number(limit) > 0 ? Math.floor(Number(limit)) : PAIR_SCAN_LIMIT
516
- const out = []
517
- if (!corpus || corpus.size === 0 || !proposal) return out
518
- const n = corpus.size
519
- const proposalTrack = trackOf(proposal)
520
- const proposalDomain = proposal?.domain || 'unknown'
521
- const proposalTitle = normalizedTitle(proposal)
522
- const proposalId = proposal?.id ?? null
523
- const queryText = `${proposal.title || ''} ${proposal.content || ''}`
524
- // BM25 查询词用当前生效分词(V2 三层在这里是收益);blocking 是 idf 盲的
525
- // 共享计数,走下面的 V1 口径。
526
- const queryTokens = tokenize(queryText)
527
-
528
- // 1) blocking
529
- const candidates = new Map()
530
- if (n <= CLUSTER_EXACT_PAIR_LIMIT) {
531
- for (const doc of corpus.docs.values()) {
532
- if (proposalId != null && doc.id === proposalId) continue
533
- if (trackOf(doc.entry) !== proposalTrack) continue
534
- candidates.set(doc.id, 0)
535
- }
536
- } else {
537
- const dfCap = Math.ceil(BLOCK_DF_RATIO * n)
538
- const shared = new Map()
539
- // blocking 固定 V1 口径(bigram+latin):V1 token ⊆ V2 token,V2 建的
540
- // corpus.inverted 照样命中,bigram 的 posting/df 也不受 unigram 膨胀影响;
541
- // 若用 V2 查询,高频单字会让无关条目凑满 ≥2 共享词,候选池被灌爆、
542
- // target 被挤出 RRF 前 limit 切片(基准 Recall 池命中 0.985→0.8625 的主因)。
543
- for (const term of tokenizeV1(queryText)) {
544
- const posting = corpus.inverted.get(term)
545
- if (!posting || posting.size === 0 || posting.size > dfCap) continue
546
- for (const id of posting) {
547
- if (proposalId != null && id === proposalId) continue
548
- shared.set(id, (shared.get(id) || 0) + 1)
549
- }
550
- }
551
- for (const [id, count] of shared) {
552
- if (count >= CLUSTER_BLOCK_MIN_SHARED) candidates.set(id, count)
553
- }
554
- if (proposalTitle) {
555
- for (const doc of corpus.docs.values()) {
556
- if (proposalId != null && doc.id === proposalId) continue
557
- if (trackOf(doc.entry) !== proposalTrack) continue
558
- if (normalizedTitle(doc.entry) === proposalTitle) candidates.set(doc.id, Math.max(candidates.get(doc.id) || 0, CLUSTER_BLOCK_MIN_SHARED))
559
- }
560
- }
561
- }
562
- if (candidates.size === 0) return backfill({ corpus, proposal, proposalDomain, proposalId, max, out: [], taken: new Set(), queryTokens })
563
-
564
- // 2) three rankings
565
- const ids = [...candidates.keys()]
566
- const bm25Scores = ids.map((id) => ({ id, s: bm25(queryTokens, corpus.docs.get(id), corpus) }))
567
- bm25Scores.sort((a, b) => b.s - a.s || idAsc(a, b))
568
- const rankBm25 = competitionRanks(bm25Scores, (item) => item.s)
569
-
570
- const probes = ids.map((id) => {
571
- const doc = corpus.docs.get(id)
572
- const detail = similarityDetail(`${proposal.title || ''}\n${proposal.content || ''}`, `${doc.entry?.title || ''}\n${doc.entry?.content || ''}`)
573
- return { id, diceScore: detail.dice, containment: detail.containment, lexical: Math.max(detail.dice, detail.containment) }
574
- })
575
- const diceRankOrder = [...probes].sort((a, b) => b.diceScore - a.diceScore || b.containment - a.containment || idAsc(a, b))
576
- // 并列按 (diceScore, containment) 判定:两个分量都相同才算同分,id 只是
577
- // 输出顺序的确定性 tiebreak。
578
- const rankDice = competitionRanks(diceRankOrder, (item) => [item.diceScore, item.containment])
579
-
580
- const entityOrder = ids.map((id) => {
581
- const doc = corpus.docs.get(id)
582
- return {
583
- id,
584
- entity: entityScore(proposal.appliesTo, doc.entry?.appliesTo),
585
- containment: containmentOf(proposal, doc.entry),
586
- }
587
- }).sort((a, b) => b.entity - a.entity || b.containment - a.containment || idAsc(a, b))
588
- const rankEntity = competitionRanks(entityOrder, (item) => [item.entity, item.containment])
589
-
590
- // 3) weighted RRF。开关关 → 静态三路原式(字节级回退路径);开 → 权重来自
591
- // computeRRFWeights,含 recency 键时加第四路 updatedAt 降序排名。
592
- let rrf
593
- if (!RRF_DYNAMIC) {
594
- rrf = new Map()
595
- for (const id of ids) {
596
- rrf.set(id, RRF_W_BM25 / (RRF_K + rankBm25.get(id))
597
- + RRF_W_DICE / (RRF_K + rankDice.get(id))
598
- + RRF_W_ENTITY / (RRF_K + rankEntity.get(id)))
599
- }
600
- } else {
601
- const weights = computeRRFWeights(proposal, corpus)
602
- const rankRecency = new Map()
603
- if (weights.recency != null) {
604
- // 第四路:updatedAt 字符串降序(updatedDesc + idAsc tiebreak,与 backfill
605
- // 同一确定性口径);rank 为 1 起的稠密序,只覆盖 blocking 后的候选集。
606
- const recencyOrder = ids
607
- .map((id) => ({ id, entry: corpus.docs.get(id).entry }))
608
- .sort((a, b) => updatedDesc(a.entry, b.entry) || idAsc(a, b))
609
- const ranked = competitionRanks(recencyOrder, (item) => String(item.entry?.updatedAt || ''))
610
- for (const [id, rank] of ranked) rankRecency.set(id, rank)
611
- }
612
- rrf = new Map()
613
- for (const id of ids) {
614
- let value = weights.bm25 / (RRF_K + rankBm25.get(id))
615
- + weights.dice / (RRF_K + rankDice.get(id))
616
- + weights.entity / (RRF_K + rankEntity.get(id))
617
- if (weights.recency != null) value += weights.recency / (RRF_K + rankRecency.get(id))
618
- rrf.set(id, value)
619
- }
620
- }
621
- ids.sort((a, b) => rrf.get(b) - rrf.get(a) || idAsc(a, b))
622
-
623
- // 4) features for the scored slice(P0-1 回归修复:准入从 RRF 代理换成
624
- // pairScore 真尺)。pre-cut 用 RRF 代理决定谁进入完整 pairFeatures/pairScore
625
- // 评分;近重复簇里 rrf 平刀锋时(bench 实测缝 3.6e-5),len 归一噪声决定
626
- // 准入,pairScore 更准的候选反而落榜。修法:与切点 rrf 之差 ≤
627
- // RRF_SLICE_BAND 的候选并入评分集(总量 ≤ max×RRF_SLICE_BAND_CAP,防病态
628
- // 全带,超限按 rrf 降序 + idAsc 截断),评分集全部评分后按 pairScore 降序
629
- // 截取前 max——准入决策从代理换真尺,返回数量语义不变(≤max)。开关关/开
630
- // 同轨生效(这是准入结构的改进,不分轨)。
631
- const cutIndex = Math.min(max, ids.length) - 1
632
- const bandFloor = rrf.get(ids[cutIndex]) - RRF_SLICE_BAND
633
- let scoredIds = []
634
- for (const id of ids) {
635
- if (rrf.get(id) < bandFloor) break // ids 已按 (rrf desc, idAsc) 排序,后面只会更低
636
- scoredIds.push(id)
637
- }
638
- const bandCap = max * RRF_SLICE_BAND_CAP
639
- if (scoredIds.length > bandCap) scoredIds = scoredIds.slice(0, bandCap)
640
- const taken = new Set()
641
- for (const id of scoredIds) {
642
- const doc = corpus.docs.get(id)
643
- const features = pairFeatures(proposal, doc.entry)
644
- const score = pairScore(features)
645
- taken.add(id)
646
- out.push({ id, entry: doc.entry, score, decision: pairDecision(proposal, doc.entry, features), features, rrf: rrf.get(id), fallback: false })
647
- }
648
- out.sort((a, b) => b.score - a.score || b.rrf - a.rrf || idAsc(a, b))
649
- // 真尺终选:评分集可能因边界带超过 max,按 pairScore 降序截取前 max
650
- if (out.length > max) out.length = max
651
- // 5) same-domain recent backfill — extra eyes, never a lower bar
652
- return backfill({ corpus, proposal, proposalDomain, proposalId, max, out, taken, queryTokens })
653
- }
654
-
655
- function containmentOf(a, b) {
656
- const detail = similarityDetail(`${a?.title || ''}\n${a?.content || ''}`, `${b?.title || ''}\n${b?.content || ''}`)
657
- return detail.containment
658
- }
659
-
660
- function backfill({ corpus, proposal, proposalDomain, proposalId, max, out, taken, queryTokens }) {
661
- if (out.length >= max) return out
662
- const recent = [...corpus.docs.values()]
663
- .filter((doc) => proposalId == null || doc.id !== proposalId)
664
- .filter((doc) => (doc.entry?.domain || 'unknown') === proposalDomain)
665
- .filter((doc) => !taken.has(doc.id))
666
- .sort((a, b) => updatedDesc(a.entry, b.entry) || idAsc(a, b))
667
- for (const doc of recent) {
668
- if (out.length >= max) break
669
- const features = pairFeatures(proposal, doc.entry)
670
- const score = pairScore(features)
671
- taken.add(doc.id)
672
- out.push({ id: doc.id, entry: doc.entry, score, decision: pairDecision(proposal, doc.entry, features), features, rrf: 0, fallback: true })
673
- }
674
- out.sort((a, b) => b.score - a.score || b.rrf - a.rrf || idAsc(a, b))
675
- return out
676
- }
677
-
678
- // —— §4.4 候选簇 ——
679
-
680
- function pairKey(aId, bId) {
681
- return aId < bId ? `${aId}\u0000${bId}` : `${bId}\u0000${aId}`
682
- }
683
-
684
- function round2(value) {
685
- return Math.round(value * 100) / 100
686
- }
687
-
688
- /**
689
- * §4.4 buildCandidateClusters(index, options)。
690
- *
691
- * 1) active 条目按 updatedAt 降序取最近 recentLimit(2000) 条,按 track 分组。
692
- * 2) 同 track 内:N ≤ exactPairLimit(300) 全对;否则倒排 blocking(df ≤
693
- * 30%N 的 posting、共享 ≥ blockMinShared(2) token,收集总量 ≤
694
- * CLUSTER_MAX_PAIRS 的硬上限)。
695
- * 3) 共享 token 为 0 的对先被预筛,其余算 pairFeatures/pairScore,保留
696
- * ≥ minPairScore(0.55) 的边。
697
- * 4) 边排序用三路 RRF(同 §4.3:bm25 双向和 / charDice / entityJaccard)。
698
- * 5) 贪心成簇:边按 RRF 降序;种子=边两端;新成员必须与簇内**所有**成员
699
- * pairScore ≥ 0.55(全对约束,禁传递闭包);每簇 ≤6;每条目只进一个簇。
700
- * 6) medoid = 成员两两平均分最高者(平手 updatedAt 降序 → id 升序)。
701
- * 7) suggested_op:≥3 成员且 avg ≥0.82 且同 domain → absorb;2+ 成员且
702
- * avg ≥0.55 → link;否则 none。medoid 平均 <0.55 整簇丢弃。
703
- * 8) 按 avg_score 降序最多输出 maxClusters(12) 簇。
704
- *
705
- * 返回 { clusters, truncated, scanned }。
706
- */
707
- export function buildCandidateClusters(index, options = {}) {
708
- const maxClusters = options.maxClusters ?? CLUSTER_MAX
709
- const maxMembers = options.maxMembers ?? CLUSTER_MAX_MEMBERS
710
- const minPair = options.minPairScore ?? CLUSTER_MIN_PAIR
711
- const blockMinShared = options.blockMinShared ?? CLUSTER_BLOCK_MIN_SHARED
712
- const exactPairLimit = options.exactPairLimit ?? CLUSTER_EXACT_PAIR_LIMIT
713
- const recentLimit = options.recentLimit ?? CLUSTER_RECENT_LIMIT
714
-
715
- const active = Object.entries(index?.entries || index || {})
716
- .filter(([, e]) => e && e.status === 'active')
717
- .map(([id, entry]) => ({ id, entry }))
718
- .sort((a, b) => updatedDesc(a.entry, b.entry) || idAsc(a, b))
719
- const truncated = active.length > recentLimit
720
- const pool = active.slice(0, recentLimit)
721
-
722
- const byTrack = new Map()
723
- for (const item of pool) {
724
- const track = trackOf(item.entry)
725
- if (!byTrack.has(track)) byTrack.set(track, [])
726
- byTrack.get(track).push(item)
727
- }
728
-
729
- // edges: { a, b, aId, bId, features, score, rrf }
730
- const edges = []
731
- for (const [track, items] of byTrack) {
732
- const n = items.length
733
- if (n < 2) continue
734
- const tokenSets = new Map()
735
- const streams = new Map()
736
- const inverted = new Map()
737
- for (const item of items) {
738
- // blocking 倒排固定 V1 口径(idf 盲集合运算):unigram 会把高频单字灌大
739
- // 倒排与两两共享计数(N=500 簇延迟 +60% 的根因),对成簇质量无收益。
740
- // 边打分的 BM25 路由(下方 bm25Route/buildCorpus)仍走 V2 流。
741
- const text = `${item.entry?.title || ''} ${item.entry?.content || ''}`
742
- const tokens = tokenizeV1(text)
743
- tokenSets.set(item.id, new Set(tokens))
744
- // BM25 流只算一次:pairList 里同一条目会出现在许多对中,逐对重算
745
- // tokenStream 是另一份 O(N²) 的浪费。
746
- streams.set(item.id, tokenStream(text))
747
- for (const term of tokens) {
748
- if (!inverted.has(term)) inverted.set(term, [])
749
- inverted.get(term).push(item.id)
750
- }
751
- }
752
- const byId = new Map(items.map((item) => [item.id, item]))
753
- const pairSet = new Set()
754
- if (n <= exactPairLimit) {
755
- for (let i = 0; i < n; i++) {
756
- for (let j = i + 1; j < n; j++) pairSet.add(pairKey(items[i].id, items[j].id))
757
- }
758
- } else {
759
- // 倒排层剪枝(A-1):与 rankPairCandidates 同口径的 dfCap。中文常用字
760
- // bigram 的 posting 几乎覆盖全库,不剪枝时每个 posting 都展开成 N²/2 个
761
- // 对——这才是 N=500 要 5.8s 的根因,不是 similarityDetail 本身慢。
762
- // 被跳过的是整条 posting(倒排表层面的剪枝),不涉及候选门槛。
763
- const dfCap = Math.ceil(BLOCK_DF_RATIO * n)
764
- const shared = new Map()
765
- // 硬上限(CLUSTER_MAX_PAIRS)是防御性的:df 剪枝之后仍可能有大量中等
766
- // 频率词留下 O(N²) 的对,超过上限就停止收集**新**对(已收集的计数继续
767
- // 累加)。倒排按条目插入序遍历,截断位置确定 → 输出仍可复现。上限必须在
768
- // 内层检查:单个 posting(≤dfCap 条)自身就可能超过它。
769
- collectPairs: for (const posting of inverted.values()) {
770
- if (posting.length < 2 || posting.length > dfCap) continue
771
- for (let i = 0; i < posting.length; i++) {
772
- for (let j = i + 1; j < posting.length; j++) {
773
- const key = pairKey(posting[i], posting[j])
774
- const count = shared.get(key)
775
- if (count === undefined) {
776
- if (shared.size >= CLUSTER_MAX_PAIRS) break collectPairs
777
- shared.set(key, 1)
778
- } else {
779
- shared.set(key, count + 1)
780
- }
781
- }
782
- }
783
- }
784
- for (const [key, count] of shared) {
785
- if (count >= blockMinShared) pairSet.add(key)
786
- }
787
- }
788
- if (pairSet.size === 0) continue
789
-
790
- const corpus = buildCorpus(items.map((item) => ({ id: item.id, title: item.entry?.title || '', content: item.entry?.content || '', entry: item.entry })))
791
- // 便宜预筛:共享 token 为 0 的对直接跳过,连 similarityDetail(bigram 集
792
- // 构建 + 长度探针)都不进。它只剔除没有任何共享词元(V1 口径)的候选,
793
- // 不降低最终 pairScore 门槛。
794
- const pairList = []
795
- for (const key of pairSet) {
796
- const [aId, bId] = key.split('\u0000')
797
- const aItem = byId.get(aId)
798
- const bItem = byId.get(bId)
799
- if (sharedTokenCount(tokenSets.get(aId), tokenSets.get(bId)) === 0) continue
800
- const features = pairFeatures(aItem.entry, bItem.entry)
801
- const score = pairScore(features)
802
- if (score < minPair) continue
803
- pairList.push({ key, aId, bId, aItem, bItem, features, score })
804
- }
805
- if (pairList.length === 0) continue
806
-
807
- // three route rankings for edge order only。
808
- // 刻意不做动态权重(P0-2 只落在 rankPairCandidates):buildCandidateClusters
809
- // 没有 proposal/查询上下文——它是无监督的全库成簇,三路 RRF 只决定贪心
810
- // 长簇的边访问顺序;引入「查询类型」没有语义落点,静态三路保证簇构建
811
- // 与查询无关、完全可复现。并列分数共享同一名次(A-12)。
812
- const bm25Route = pairList.map((pair) => ({
813
- key: pair.key,
814
- s: bm25(streams.get(pair.aId), corpus.docs.get(pair.bId), corpus)
815
- + bm25(streams.get(pair.bId), corpus.docs.get(pair.aId), corpus),
816
- })).sort((a, b) => b.s - a.s || (a.key < b.key ? -1 : 1))
817
- const rankBm25 = competitionRanks(bm25Route, (item) => item.s)
818
- const diceRoute = [...pairList].sort((a, b) => b.features.charDice - a.features.charDice
819
- || b.features.containment - a.features.containment || (a.key < b.key ? -1 : 1))
820
- const rankDice = competitionRanks(diceRoute, (item) => [item.features.charDice, item.features.containment])
821
- const entityRoute = [...pairList].sort((a, b) => b.features.entityJaccard - a.features.entityJaccard
822
- || b.features.containment - a.features.containment || (a.key < b.key ? -1 : 1))
823
- const rankEntity = competitionRanks(entityRoute, (item) => [item.features.entityJaccard, item.features.containment])
824
- for (const pair of pairList) {
825
- pair.rrf = RRF_W_BM25 / (RRF_K + rankBm25.get(pair.key))
826
- + RRF_W_DICE / (RRF_K + rankDice.get(pair.key))
827
- + RRF_W_ENTITY / (RRF_K + rankEntity.get(pair.key))
828
- }
829
- pairList.sort((a, b) => b.rrf - a.rrf || b.score - a.score || (a.key < b.key ? -1 : 1))
830
- edges.push(...pairList)
831
- }
832
-
833
- // greedy all-pairs clique growth
834
- edges.sort((a, b) => b.rrf - a.rrf || b.score - a.score || (a.key < b.key ? -1 : 1))
835
- const memberOf = new Map()
836
- const clusters = []
837
- for (const edge of edges) {
838
- const clusterA = memberOf.get(edge.aId)
839
- const clusterB = memberOf.get(edge.bId)
840
- if (clusterA && clusterB) continue
841
- if (!clusterA && !clusterB) {
842
- if (clusters.length >= maxClusters) continue
843
- const cluster = { members: [edge.aItem, edge.bItem], scores: new Map([[edge.key, edge.score]]) }
844
- clusters.push(cluster)
845
- memberOf.set(edge.aId, cluster)
846
- memberOf.set(edge.bId, cluster)
847
- continue
848
- }
849
- const cluster = clusterA || clusterB
850
- if (cluster.members.length >= maxMembers) continue
851
- const candidate = clusterA ? edge.bItem : edge.aItem
852
- let ok = true
853
- for (const member of cluster.members) {
854
- const key = pairKey(candidate.id, member.id)
855
- let score = cluster.scores.get(key)
856
- if (score == null) {
857
- score = pairScore(pairFeatures(candidate.entry, member.entry))
858
- cluster.scores.set(key, score)
859
- }
860
- if (score < minPair) { ok = false; break }
861
- }
862
- if (!ok) continue
863
- cluster.members.push(candidate)
864
- memberOf.set(candidate.id, cluster)
865
- }
866
-
867
- // medoid + output
868
- const out = []
869
- for (const cluster of clusters) {
870
- const members = [...cluster.members].sort((a, b) => idAsc(a, b))
871
- const pairScores = {}
872
- let sum = 0
873
- let count = 0
874
- for (let i = 0; i < members.length; i++) {
875
- for (let j = i + 1; j < members.length; j++) {
876
- const key = pairKey(members[i].id, members[j].id)
877
- let score = cluster.scores.get(key)
878
- if (score == null) {
879
- score = pairScore(pairFeatures(members[i].entry, members[j].entry))
880
- cluster.scores.set(key, score)
881
- }
882
- pairScores[`${members[i].id}|${members[j].id}`] = round2(score)
883
- sum += score
884
- count += 1
885
- }
886
- }
887
- const avg = count ? sum / count : 0
888
- let medoid = null
889
- let bestAvg = -1
890
- for (const member of members) {
891
- let mSum = 0
892
- for (const other of members) {
893
- if (other.id === member.id) continue
894
- const key = pairKey(member.id, other.id)
895
- mSum += cluster.scores.get(key) ?? 0
896
- }
897
- const mAvg = members.length > 1 ? mSum / (members.length - 1) : 0
898
- if (mAvg > bestAvg + 1e-9
899
- || (Math.abs(mAvg - bestAvg) <= 1e-9 && medoid
900
- && (updatedDesc(member.entry, medoid.entry) < 0
901
- || (updatedDesc(member.entry, medoid.entry) === 0 && String(member.id).localeCompare(String(medoid.id)) < 0)))) {
902
- bestAvg = mAvg
903
- medoid = member
904
- }
905
- }
906
- // medoid 平均 <0.55 → 整簇不输出(§4.4.9;全对约束下属防御分支)
907
- if (members.length > 1 && bestAvg < minPair) continue
908
- const sameDomain = members.every((m) => (m.entry?.domain || 'unknown') === (members[0].entry?.domain || 'unknown'))
909
- const suggestedOp = members.length >= 3 && avg >= PAIR_ABSORB_MIN && sameDomain
910
- ? 'absorb'
911
- : (members.length >= 2 && avg >= minPair ? 'link' : 'none')
912
- out.push({
913
- cluster_id: '',
914
- members: members.map((m) => ({
915
- id: m.id,
916
- title: m.entry?.title || '',
917
- track: trackOf(m.entry),
918
- domain: m.entry?.domain || 'unknown',
919
- updatedAt: m.entry?.updatedAt || null,
920
- content: m.entry?.content || '',
921
- })),
922
- pair_scores: pairScores,
923
- medoid_id: medoid?.id || members[0]?.id || '',
924
- avg_score: round2(avg),
925
- suggested_op: suggestedOp,
926
- })
927
- }
928
- out.sort((a, b) => b.avg_score - a.avg_score || String(a.medoid_id).localeCompare(String(b.medoid_id)))
929
- for (let i = 0; i < out.length; i++) out[i].cluster_id = `cl-${i + 1}`
930
- return { clusters: out.slice(0, maxClusters), truncated, scanned: pool.length }
931
- }
932
-
933
- // —— S5 查询意图与分解 ——
934
- //
935
- // 召回入口只需要知道“这句话在问哪一类事”,然后决定过滤与取数策略:
936
- // date 时间题:先解析相对日期,按 absolute_date 过滤/排序
937
- // entity 实体题:抽出实体名/别名,按实体索引扩展一跳
938
- // conflict 冲突题:按 fact_key / conflicts_with 成对取
939
- // commitment 约定题:未完成/到期承诺优先
940
- // boundary 边界题:只有用户明确问到时才注入 only_if_asked
941
- // general 普通题
942
- // 纯规则,无外部模型,无网络;识别不出来就是 general,不猜。
943
-
944
- const CONFLICT_RE = /矛盾|冲突|到底|哪一版|哪个版本|哪边|前后说法|说法不一|改口|不一致|不是说|谁对|真的吗|相反|contradict|conflict|which version/i
945
- const COMMITMENT_RE = /答应|承诺|约定|说好|欠|兑现|到期|还没|什么时候还|做到|提醒我|promise|commitment|owe/i
946
- const BOUNDARY_RE = /秘密|保密|别说|别告诉|不要告诉|不能说|不能提|隐私|瞒着|never[-_ ]?say|only if asked|secret/i
947
- const DATE_QUERY_RE = /什么时候|哪天|几号|日期|时间|多久|几点|星期几|上次|之前|后来|最近|when|what time|which day/i
948
-
949
- /**
950
- * @returns {'date'|'entity'|'conflict'|'commitment'|'boundary'|'general'}
951
- */
952
- export function detectQueryIntent(query, { now = new Date(), timeZone = DEFAULT_TIME_ZONE, knownEntities = [] } = {}) {
953
- const text = String(query || '').trim()
954
- if (!text) return 'general'
955
- if (CONFLICT_RE.test(text)) return 'conflict'
956
- if (COMMITMENT_RE.test(text)) return 'commitment'
957
- if (BOUNDARY_RE.test(text)) return 'boundary'
958
- if (hasTemporalHint(text) || DATE_QUERY_RE.test(text) || /\d{4}[-/]\d{1,2}[-/]\d{1,2}/.test(text)) return 'date'
959
- if (extractQueryEntities(text, { knownEntities }).length > 0) return 'entity'
960
- return 'general'
961
- }
962
-
963
- const QUOTED_RE = /["“”「」『』]([^"“”「」『』]{2,30})["“”「」『』]/g
964
- const AT_RE = /@([\w\u4e00-\u9fff-]{2,30})/g
965
-
966
- /** 实体抽取只用“明确标注”的名字:引号、@、已知实体表。宁缺毋滥。 */
967
- export function extractQueryEntities(query, { knownEntities = [] } = {}) {
968
- const text = String(query || '')
969
- const found = []
970
- const add = (value) => {
971
- const name = String(value || '').trim()
972
- if (name.length < 2 || name.length > 30) return
973
- if (!found.includes(name)) found.push(name)
974
- }
975
- for (const match of text.matchAll(QUOTED_RE)) add(match[1])
976
- for (const match of text.matchAll(AT_RE)) add(match[1])
977
- for (const name of Array.isArray(knownEntities) ? knownEntities : []) {
978
- if (typeof name === 'string' && name.trim().length >= 2 && text.includes(name)) add(name)
979
- }
980
- return found.slice(0, 6)
981
- }
982
-
983
- /**
984
- * 把查询拆成召回能直接用的零件。`expanded` 是拼给词法/向量检索的查询,
985
- * `dates`/`entities` 同时供过滤与排序使用。
986
- */
987
- export function decomposeQuery(query, intent = null, { now = new Date(), timeZone = DEFAULT_TIME_ZONE, knownEntities = [] } = {}) {
988
- const text = String(query || '')
989
- const resolvedIntent = intent || detectQueryIntent(text, { now, timeZone, knownEntities })
990
- const dates = resolveQueryDates(text, { now, timeZone })
991
- const entities = extractQueryEntities(text, { knownEntities })
992
- const terms = [...new Set([...dates, ...entities])]
993
- return {
994
- query: text,
995
- intent: resolvedIntent,
996
- dates,
997
- entities,
998
- terms,
999
- expanded: [text, ...terms].filter(Boolean).join(' ').trim(),
1000
- }
1001
- }
1
+ // Local candidate retrieval for the global curator (spec §4.1-§4.4, §4.8).
2
+ //
3
+ // Pipeline position: the LLM only arbitrates; everything here is model-free.
4
+ // tokenize + BM25 give the ranking spine, character-Dice/token/entity features
5
+ // give the pair score, weighted RRF fuses the three rankings, and the greedy
6
+ // all-pairs clique turns edges into candidate clusters. The commit layer
7
+ // (curator.js planCuratorOps) reuses rankPairCandidates as the final
8
+ // duplicate/conflict gate — one ruler from blocking to commit.
9
+ //
10
+ // Dependency discipline: this module imports only lib/text-similarity.js (the
11
+ // shared similarity ruler), lib/curator-policy.js (the single constant table)
12
+ // and lib/tokenizer-v2.js (the V2 tokenizer delegated to by the TOKENIZER_V2
13
+ // switch). No state, no IO, no clock — same input, same output, always.
14
+
15
+ import {
16
+ bigrams,
17
+ dice,
18
+ jaccard,
19
+ lengthGap,
20
+ similarityDetail,
21
+ similarTexts,
22
+ } from './text-similarity.js'
23
+ import {
24
+ BM25_B,
25
+ BM25_DF_MIN_POOL,
26
+ BM25_DF_RATIO,
27
+ BM25_K1,
28
+ BM25_MAX_QUERY_TERMS,
29
+ BLOCK_DF_RATIO,
30
+ CLUSTER_BLOCK_MIN_SHARED,
31
+ CLUSTER_EXACT_PAIR_LIMIT,
32
+ CLUSTER_MAX,
33
+ CLUSTER_MAX_MEMBERS,
34
+ CLUSTER_MAX_PAIRS,
35
+ CLUSTER_MIN_PAIR,
36
+ CLUSTER_RECENT_LIMIT,
37
+ CROSS_DOMAIN_LINK_MIN,
38
+ PAIR_ABSORB_MIN,
39
+ PAIR_DUPLICATE_MIN,
40
+ PAIR_LINK_MIN,
41
+ PAIR_SCAN_LIMIT,
42
+ PAIR_W_ENTITY,
43
+ PAIR_W_LEXICAL,
44
+ PAIR_W_TITLE,
45
+ PAIR_W_TOKEN,
46
+ RRF_DYNAMIC,
47
+ RRF_K,
48
+ RRF_SLICE_BAND,
49
+ RRF_SLICE_BAND_CAP,
50
+ RRF_W_BM25,
51
+ RRF_W_DICE,
52
+ RRF_W_ENTITY,
53
+ TOKENIZER_V2,
54
+ computeRRFWeights,
55
+ } from './curator-policy.js'
56
+ import {
57
+ tokenStreamV2,
58
+ tokenize as tokenizeV2,
59
+ } from './tokenizer-v2.js'
60
+ import { hasTemporalHint, resolveQueryDates, DEFAULT_TIME_ZONE } from './temporal.js'
61
+
62
+ // —— §4.1 分词 ——
63
+
64
+ /**
65
+ * V1 分词原实现(双角色):TOKENIZER_V2 关时的回退路径;开时是本模块内
66
+ * **idf 盲集合运算**(blocking 共享计数、tokenJaccard)的固定口径。
67
+ * NFKC + lowercase; latin runs of ≥2 chars keep `._-` joins as one token; CJK
68
+ * runs become single chars when isolated, otherwise overlapping bigrams; the
69
+ * result is deduplicated (a set — Jaccard/blocking only care about presence).
70
+ * Build tf from tokenStream below, never from this.
71
+ */
72
+ function tokenizeV1(text) {
73
+ const s = String(text || '').normalize('NFKC').toLowerCase()
74
+ const out = []
75
+ for (const m of s.matchAll(/[a-z0-9]+(?:[._-][a-z0-9]+)*/g)) {
76
+ if (m[0].length >= 2) out.push(m[0])
77
+ }
78
+ for (const m of s.matchAll(/[\u3400-\u9fff\uf900-\ufaff]+/g)) {
79
+ const run = m[0]
80
+ if (run.length === 1) out.push(run)
81
+ else for (let i = 0; i < run.length - 1; i++) out.push(run.slice(i, i + 2))
82
+ }
83
+ return [...new Set(out)]
84
+ }
85
+
86
+ /** V1 token stream 原实现(无去重)——BM25 tf 的频率来源(回退路径)。 */
87
+ function tokenStreamV1(text) {
88
+ const s = String(text || '').normalize('NFKC').toLowerCase()
89
+ const out = []
90
+ for (const m of s.matchAll(/[a-z0-9]+(?:[._-][a-z0-9]+)*/g)) {
91
+ if (m[0].length >= 2) out.push(m[0])
92
+ }
93
+ for (const m of s.matchAll(/[\u3400-\u9fff\uf900-\ufaff]+/g)) {
94
+ const run = m[0]
95
+ if (run.length === 1) out.push(run)
96
+ else for (let i = 0; i < run.length - 1; i++) out.push(run.slice(i, i + 2))
97
+ }
98
+ return out
99
+ }
100
+
101
+ /**
102
+ * 对外分词入口(双轨制):TOKENIZER_V2 开 → 委托 lib/tokenizer-v2.js
103
+ * (CJK unigram+bigram+trigram 三层 + 实体保护,Set 插入序数组);关 → V1
104
+ * 原路径。签名与语义兼容,返回去重 token 数组(插入序)。
105
+ *
106
+ * V2 的增量 token 只进入带 idf 权重的 BM25 流;blocking 共享计数与
107
+ * tokenJaccard 固定使用 tokenizeV1(bigram+latin),避免高频单字扩大
108
+ * 候选池并降低集合重叠的区分度。关闭开关时使用 V1。
109
+ */
110
+ export function tokenize(text) {
111
+ if (TOKENIZER_V2) return tokenizeV2(text)
112
+ return tokenizeV1(text)
113
+ }
114
+
115
+ /**
116
+ * Raw token stream (no dedupe) — the frequency source for BM25's tf.
117
+ * 与 tokenize 同一开关:V2 → tokenStreamV2(与 tokenizeV2 同一生成器);V1 →
118
+ * tokenStreamV1。
119
+ */
120
+ function tokenStream(text) {
121
+ if (TOKENIZER_V2) return tokenStreamV2(text)
122
+ return tokenStreamV1(text)
123
+ }
124
+
125
+ // —— §4.1 语料与 BM25 ——
126
+
127
+ /**
128
+ * entries: [{ id, title, content, ...rest }] — every extra field travels on
129
+ * doc.entry so callers can reach track/domain/appliesTo/updatedAt without a
130
+ * second lookup. Returns { docs, df, inverted, avgdl, size }.
131
+ */
132
+ export function buildCorpus(entries) {
133
+ const docs = new Map()
134
+ const df = new Map()
135
+ const inverted = new Map()
136
+ let totalLen = 0
137
+ for (const entry of entries || []) {
138
+ const id = entry?.id
139
+ if (id == null || docs.has(id)) continue
140
+ const stream = tokenStream(`${entry.title || ''} ${entry.content || ''}`)
141
+ const tf = new Map()
142
+ for (const term of stream) tf.set(term, (tf.get(term) || 0) + 1)
143
+ docs.set(id, { id, tokens: new Set(stream), tf, len: stream.length, entry })
144
+ totalLen += stream.length
145
+ for (const term of tf.keys()) {
146
+ df.set(term, (df.get(term) || 0) + 1)
147
+ if (!inverted.has(term)) inverted.set(term, new Set())
148
+ inverted.get(term).add(id)
149
+ }
150
+ }
151
+ return {
152
+ docs,
153
+ df,
154
+ inverted,
155
+ avgdl: docs.size ? totalLen / docs.size : 0,
156
+ size: docs.size,
157
+ }
158
+ }
159
+
160
+ function idfOf(corpus, term) {
161
+ const df = corpus.df.get(term) || 0
162
+ return Math.log(1 + (corpus.size - df + 0.5) / (df + 0.5))
163
+ }
164
+
165
+ /**
166
+ * BM25 formula with the query-side frequency gate.
167
+ *
168
+ * 每个 query term 独立判定,df 超过 dfCap 就整条不参与打分,其中
169
+ * dfCap = max(BM25_DF_MIN_POOL, ceil(BM25_DF_RATIO × N))。
170
+ * 候选池下限保留小语料中的共享词;占比上限限制大语料中缺少区分度的高频词。
171
+ * 两者结合,避免仅按占比清空小库的查询词,或仅按绝对数排除大库中的有效词。
172
+ * 剔除的是整个 term,不是把它的分数清零后继续保留条目:后者只换来一个恒定 0
173
+ * 分的候选,候选池照样是全库。
174
+ *
175
+ * qtf:query 侧保留重复 term 的频率并乘进分数。qtf=1 时与旧口径逐位
176
+ * 相同,所以既有的精确数值断言不受影响;重复查询词只会放大它自己的贡献,不会
177
+ * 倒挂 IDF——真正的高频词在闸门处已经被剔除。
178
+ *
179
+ * Queries wider than BM25_MAX_QUERY_TERMS keep only the 64 highest-IDF terms —
180
+ * measured among terms the corpus actually knows (df > 0): an absent term scores
181
+ * 0 no matter its nominal IDF, so letting it occupy the quota would only shrink
182
+ * the effective query. Ties break by term.
183
+ */
184
+ export function bm25(queryTokens, doc, corpus, { k1 = BM25_K1, b = BM25_B } = {}) {
185
+ if (!queryTokens?.length || !doc || !corpus || corpus.size === 0) return 0
186
+ const qtf = new Map()
187
+ for (const term of queryTokens) {
188
+ if (!corpus.df.has(term)) continue
189
+ qtf.set(term, (qtf.get(term) || 0) + 1)
190
+ }
191
+ if (qtf.size === 0) return 0
192
+ const dfCap = Math.max(BM25_DF_MIN_POOL, Math.ceil(BM25_DF_RATIO * corpus.size))
193
+ let terms = []
194
+ for (const [term, count] of qtf) {
195
+ if ((corpus.df.get(term) || 0) > dfCap) continue
196
+ terms.push({ term, qtf: count, idf: idfOf(corpus, term) })
197
+ }
198
+ if (terms.length === 0) return 0
199
+ if (terms.length > BM25_MAX_QUERY_TERMS) {
200
+ terms = terms
201
+ .sort((a, b2) => b2.idf - a.idf || (a.term < b2.term ? -1 : 1))
202
+ .slice(0, BM25_MAX_QUERY_TERMS)
203
+ }
204
+ let score = 0
205
+ for (const { term, qtf: count, idf } of terms) {
206
+ const tf = doc.tf.get(term) || 0
207
+ if (!tf) continue
208
+ score += idf * count * (tf * (k1 + 1)) / (tf + k1 * (1 - b + b * doc.len / corpus.avgdl))
209
+ }
210
+ return score
211
+ }
212
+
213
+ // —— §4.2 成对特征 ——
214
+
215
+ function entitySet(appliesTo) {
216
+ const out = new Set()
217
+ for (const item of Array.isArray(appliesTo) ? appliesTo : []) {
218
+ const v = String(item || '').trim().toLowerCase()
219
+ if (v) out.add(v)
220
+ }
221
+ return out
222
+ }
223
+
224
+ function normalizedTitle(entry) {
225
+ return String(entry?.title || '').trim().toLowerCase()
226
+ }
227
+
228
+ /**
229
+ * §4.2 pair features over two index-shaped entries
230
+ * ({ title, content, track, domain, appliesTo }).
231
+ * charDice — similarTexts(title+\n+content):length-prune + containment floor
232
+ * containment — the probe floor when the length prune fired, else 0
233
+ * lexical — max(charDice, containment)
234
+ * tokenJaccard — V1 口径 tokenize set Jaccard over title+content(idf 盲集合
235
+ * 运算固定 V1;V2 三层只服务 BM25,见 tokenize 的 JSDoc)
236
+ * titleDice — bigram Dice over the raw titles
237
+ * titleExact — trimmed/lowercase title equality (non-empty)
238
+ * entityJaccard — appliesTo set Jaccard; both empty → 0.5 neutral
239
+ */
240
+ export function pairFeatures(a, b) {
241
+ const aText = `${a?.title || ''}\n${a?.content || ''}`
242
+ const bText = `${b?.title || ''}\n${b?.content || ''}`
243
+ const detail = similarityDetail(aText, bText)
244
+ return {
245
+ charDice: detail.dice,
246
+ containment: detail.containment,
247
+ lexical: Math.max(detail.dice, detail.containment),
248
+ // idf 盲集合运算固定 V1 口径:unigram 会把跨主题的高频单字重叠拉平
249
+ // tokenJaccard 的区分度。开关关时 tokenize 本就返回 V1,两种写法等价。
250
+ tokenJaccard: jaccard(new Set(tokenizeV1(aText)), new Set(tokenizeV1(bText))),
251
+ titleDice: dice(bigrams(a?.title || ''), bigrams(b?.title || '')),
252
+ titleExact: normalizedTitle(a) !== '' && normalizedTitle(a) === normalizedTitle(b),
253
+ entityJaccard: entityScore(a?.appliesTo, b?.appliesTo),
254
+ lengthGap: detail.lengthGap,
255
+ }
256
+ }
257
+
258
+ function entityScore(aApplies, bApplies) {
259
+ const a = entitySet(aApplies)
260
+ const b = entitySet(bApplies)
261
+ if (a.size === 0 && b.size === 0) return 0.5
262
+ return jaccard(a, b)
263
+ }
264
+
265
+ /**
266
+ * §4.2 weighted sum. Accepts a features object (preferred — pairFeatures is
267
+ * already computed on hot paths) or the two entries directly.
268
+ */
269
+ export function pairScore(aOrFeatures, b) {
270
+ const f = aOrFeatures && typeof aOrFeatures === 'object' && 'lexical' in aOrFeatures
271
+ ? aOrFeatures
272
+ : pairFeatures(aOrFeatures, b)
273
+ return PAIR_W_LEXICAL * f.lexical
274
+ + PAIR_W_TOKEN * f.tokenJaccard
275
+ + PAIR_W_TITLE * f.titleDice
276
+ + PAIR_W_ENTITY * f.entityJaccard
277
+ }
278
+
279
+ function isRpCodingClash(aDomain, bDomain) {
280
+ return (aDomain === 'rp' && bDomain === 'coding') || (aDomain === 'coding' && bDomain === 'rp')
281
+ }
282
+
283
+ /**
284
+ * §4.2 pairDecision, verbatim bands:
285
+ * track differs → none
286
+ * domain differs → link only at pairScore ≥0.65(跨域只 link 不 absorb;
287
+ * rp↔coding 永不 link——§4.9 的校验层再拦一次)
288
+ * titleExact && lexical <0.55 → conflict(同标题正文迥异;lexical 而非裸 charDice,
289
+ * 因为 §4.8 明确 containment ≥0.92 是重复/细化不是冲突)
290
+ * ≥0.90 duplicate / ≥0.82 absorb / ≥0.55 link / else none
291
+ */
292
+ export function pairDecision(a, b, features = pairFeatures(a, b)) {
293
+ if ((a?.track || 'memory') !== (b?.track || 'memory')) return 'none'
294
+ const aDomain = a?.domain || 'unknown'
295
+ const bDomain = b?.domain || 'unknown'
296
+ const score = pairScore(features)
297
+ if (aDomain !== bDomain) {
298
+ if (isRpCodingClash(aDomain, bDomain)) return 'none'
299
+ return score >= CROSS_DOMAIN_LINK_MIN ? 'link' : 'none'
300
+ }
301
+ if (features.titleExact && features.lexical < PAIR_LINK_MIN) return 'conflict'
302
+ if (score >= PAIR_DUPLICATE_MIN) return 'duplicate'
303
+ if (score >= PAIR_ABSORB_MIN) return 'absorb'
304
+ if (score >= PAIR_LINK_MIN) return 'link'
305
+ return 'none'
306
+ }
307
+
308
+ // —— §4.8 全局冲突预筛 ——
309
+
310
+ // Same pattern as memory.js's NEGATION_RE (not exported there; lib/memory.js is
311
+ // outside this package's edit scope). One ruler for "opposite claim". 整文本
312
+ // 口径保持原样(P0 前的既有行为,也是无锚点时的回退路径),词典不在此扩。
313
+ const NEGATION_RE = /不|没|别|无|never|not|no longer|doesn't|don't/i
314
+
315
+ /** True when the text carries a negation marker (memory.js findConflict 口径). */
316
+ export function negationPolarity(text) {
317
+ return NEGATION_RE.test(String(text || ''))
318
+ }
319
+
320
+ // —— 子句级否定作用域 ——
321
+ //
322
+ // 整文本 negationPolarity 有两类误报:无关子句的否定污染(「截止日期是 5 月
323
+ // 1 日,别忘了」整条算否定侧)和双重否定(「不是不喜欢香菜」仍算否定侧)。
324
+ // polarityAt 把判定范围缩到锚点所在的子句,用标记计数 mod 2 近似否定作用域,
325
+ // 不做句法分析——同输入同输出,无 clock。
326
+
327
+ // 子句切分:中西标点一视同仁(连续标点算一次切分)。
328
+ const CLAUSE_SPLIT_RE = /[。!?;,、,.!?;:]+/
329
+
330
+ // 对比结构:「不是 A 而是 B」的 B、「不用 A 改成/换成 B」的 B 都是肯定侧,
331
+ // 前文标记的否定作用到对比词为止。
332
+ const CONTRAST_RE = /而不是|而是|改成|换成/g
333
+
334
+ // 否定标记词典。CJK 没有词边界(\b 对中文无效),靠最长优先的 alternation
335
+ // 保证「不再」「没有」只数一次而不是拆成「不」+「再」;「非常/未来/别的」
336
+ // 与否定标记同形但不是否定(高频词),用 lookahead 排除。英文统一用 \b 包住
337
+ // (缩写以 't 结尾,\b 仍成立;不 \b 的话 'not' 会命中 another/desktop)。
338
+ const NEG_MARKER_RE = /禁止|不得|无法|不能|不再|从不|从未|并不|并非|没有|拒绝|反对|不|没|别(?!的)|无|未(?!来)|勿|莫|非(?!常)|\b(?:not|never|no longer|cannot|without|avoid|refuse|stop|doesn't|don't|won't|can't)\b/gi
339
+
340
+ /**
341
+ * 一个子句内、锚点所在片段是否为否定侧。对比词把子句切成片段,逐片段判定:
342
+ * 片段自带标记计数(奇数 → 否定);「而不是」引出的片段额外继承 1 个否定
343
+ * (「而不是队列」的队列仍是否定侧,等价于标记紧邻锚点前不被对比词隔断的
344
+ * 场景),「而是/改成/换成」引出的片段从 0 起算。锚点在同片段多次出现只按
345
+ * 片段判定一次,锚点落在多个片段时任一片段否定即为否定(保守)。
346
+ */
347
+ function segmentNegated(clause, needle) {
348
+ const segments = []
349
+ let last = 0
350
+ let inherit = false
351
+ for (const m of clause.matchAll(CONTRAST_RE)) {
352
+ segments.push({ text: clause.slice(last, m.index), inherit })
353
+ inherit = m[0] === '而不是'
354
+ last = m.index + m[0].length
355
+ }
356
+ segments.push({ text: clause.slice(last), inherit })
357
+ for (const segment of segments) {
358
+ if (!segment.text.includes(needle)) continue
359
+ let markers = 0
360
+ for (const _ of segment.text.matchAll(NEG_MARKER_RE)) markers += 1
361
+ if ((markers + (segment.inherit ? 1 : 0)) % 2 === 1) return true
362
+ }
363
+ return false
364
+ }
365
+
366
+ /**
367
+ * 子句级否定极性:text 里 anchor 所在的每个子句,任一为否定即算否定
368
+ * 侧(锚点多次出现取保守口径)。子句切分与标记匹配都在 NFKC + lowercase 之后
369
+ * 进行——锚点来自 tokenize(同一规范化),latin 大小写/全角差异不会漏匹配。
370
+ * 锚点为空或不在 text 中出现 → false(没有可判定的作用域就不是否定侧)。
371
+ */
372
+ export function polarityAt(text, anchor) {
373
+ const needle = String(anchor || '').normalize('NFKC').toLowerCase()
374
+ if (!needle) return false
375
+ const s = String(text || '').normalize('NFKC').toLowerCase()
376
+ for (const clause of s.split(CLAUSE_SPLIT_RE)) {
377
+ if (clause.includes(needle) && segmentNegated(clause, needle)) return true
378
+ }
379
+ return false
380
+ }
381
+
382
+ /** 数字、周X/星期X、YYYY-MM-DD、M月D日 —— 抽出来比集合(§4.8 numericSetsDiffer)。 */
383
+ export function numericSet(text) {
384
+ const s = String(text || '')
385
+ const out = new Set()
386
+ for (const m of s.matchAll(/\d{4}-\d{1,2}-\d{1,2}/g)) out.add(m[0])
387
+ for (const m of s.matchAll(/\d{1,2}月\d{1,2}[日号]/g)) out.add(m[0])
388
+ for (const m of s.matchAll(/周[一二三四五六日天]|星期[一二三四五六日天]/g)) out.add(m[0])
389
+ for (const m of s.matchAll(/\d+(?:\.\d+)?/g)) out.add(m[0])
390
+ return out
391
+ }
392
+
393
+ export function numericSetsDiffer(a, b) {
394
+ const sa = numericSet(a)
395
+ const sb = numericSet(b)
396
+ if (sa.size === 0 || sb.size === 0) return false
397
+ for (const item of sa) if (!sb.has(item)) return true
398
+ for (const item of sb) if (!sa.has(item)) return true
399
+ return false
400
+ }
401
+
402
+ /**
403
+ * 冲突锚点:双方 body 的共享 token 里最长者(长度相同取字典序最小,完全确定,
404
+ * 与遍历序无关)。token 来自当前生效的 tokenize(双轨开关自动生效),只要求
405
+ * 子串包含关系(clause.includes(anchor))——锚点本身就是文本的子串,CJK
406
+ * unigram/bigram 与 latin 词都覆盖。无共享词返回 ''(调用方回退整文本口径)。
407
+ */
408
+ export function longestSharedToken(aBody, bBody) {
409
+ const bTokens = new Set(tokenize(bBody))
410
+ let anchor = ''
411
+ for (const token of new Set(tokenize(aBody))) {
412
+ if (!bTokens.has(token)) continue
413
+ if (token.length > anchor.length || (token.length === anchor.length && token < anchor)) anchor = token
414
+ }
415
+ return anchor
416
+ }
417
+
418
+ /**
419
+ * §4.8 全局冲突预筛(同 domain/track 前提由调用方保证)。返回 'same_title' |
420
+ * 'negation' | 'value' 或 null。containment ≥0.92 或 charDice ≥0.95 一票豁免
421
+ * (重复/细化,不是冲突)。预筛只决定“送不送人审”,最终由 LLM + 人审裁决。
422
+ *
423
+ * negation 分支:有共享锚点时,双方 polarityAt(body, anchor) 不同才算
424
+ * 否定冲突(子句级作用域,修掉「无关子句否定污染」与「双重否定」两类误报);
425
+ * 无共享锚点 → 回退整文本 negationPolarity 对比(原口径,行为不变)。
426
+ */
427
+ export function globalConflictCheck(a, b, features = pairFeatures(a, b)) {
428
+ if (features.containment >= 0.92 || features.charDice >= 0.95) return null
429
+ if (features.titleExact && features.charDice < 0.95) return 'same_title'
430
+ const aBody = String(a?.content || '')
431
+ const bBody = String(b?.content || '')
432
+ if (features.charDice >= 0.55) {
433
+ const anchor = longestSharedToken(aBody, bBody)
434
+ const differs = anchor
435
+ ? polarityAt(aBody, anchor) !== polarityAt(bBody, anchor)
436
+ : negationPolarity(aBody) !== negationPolarity(bBody)
437
+ if (differs) return 'negation'
438
+ }
439
+ if (features.titleDice >= 0.8 && features.charDice >= 0.55
440
+ && numericSetsDiffer(`${a?.title || ''} ${aBody}`, `${b?.title || ''} ${bBody}`)) return 'value'
441
+ return null
442
+ }
443
+
444
+ // —— §4.3 候选召回 ——
445
+
446
+ function trackOf(entry) {
447
+ return entry?.track || 'memory'
448
+ }
449
+
450
+ function updatedDesc(a, b) {
451
+ return String(b?.updatedAt || '').localeCompare(String(a?.updatedAt || ''))
452
+ }
453
+
454
+ function idAsc(a, b) {
455
+ return String(a.id).localeCompare(String(b.id))
456
+ }
457
+
458
+ /**
459
+ * 标准竞赛排名(1,2,2,4):并列分数共享同一名次,后续名次跳号。
460
+ * metricOf 返回参与并列判定的值(数组按值拼成键)——排序里的 id/键 tiebreak
461
+ * 只负责让输出完全确定,不再把同分文档强行排成不同名次。RRF 是按名次加权
462
+ * 融合的,给并列者不同名次等于凭空制造分差。
463
+ */
464
+ function competitionRanks(sorted, metricOf) {
465
+ const ranks = new Map()
466
+ let previous = null
467
+ let rank = 0
468
+ sorted.forEach((item, index) => {
469
+ const metric = metricOf(item)
470
+ const key = Array.isArray(metric) ? metric.join('\u0000') : String(metric)
471
+ if (key !== previous) {
472
+ rank = index + 1
473
+ previous = key
474
+ }
475
+ ranks.set(item.id ?? item.key, rank)
476
+ })
477
+ return ranks
478
+ }
479
+
480
+ /** 两个 token 集的交集大小(不构造第三个集合):blocking 的便宜预筛。 */
481
+ function sharedTokenCount(a, b) {
482
+ if (!a || !b || a.size === 0 || b.size === 0) return 0
483
+ const [small, large] = a.size <= b.size ? [a, b] : [b, a]
484
+ let shared = 0
485
+ for (const token of small) if (large.has(token)) shared += 1
486
+ return shared
487
+ }
488
+
489
+ /**
490
+ * §4.3 rankPairCandidates({ corpus, proposal, limit })。
491
+ *
492
+ * 1) blocking:同 track;N ≤ exactPairLimit 时精确两两,否则查询 token 中
493
+ * df ≤ 30%N 的稀有词、共享 ≥2 token,或 exact title。
494
+ * 2) 三路排名 bm25 / charDice / entityJaccard(tiebreak containment)。
495
+ * 3) 加权 RRF(k=60)。RRF_DYNAMIC 开 → 权重来自 computeRRFWeights(proposal,
496
+ * corpus):普通查询退化为静态 0.5/0.3/0.2,近期查询加第四路 recency
497
+ * (候选按 updatedAt 降序排名),coding 域 entity 提权;关 → 恒用静态
498
+ * 0.5/(60+rankBm25) + 0.3/(60+rankDice) + 0.2/(60+rankEntity)。
499
+ * 4) RRF 代理切分 + 边界带 → pairScore 真尺终选:前 max 名进评分集,与切点
500
+ * rrf 之差 ≤ RRF_SLICE_BAND 的候选并入(总量 ≤ max×RRF_SLICE_BAND_CAP),
501
+ * 全部算 pairFeatures/pairScore,按 pairScore 降序截取前 max——近重复簇里
502
+ * rrf 平刀锋时 len 归一噪声不再决定准入。
503
+ * 5) 不足 limit 用同域最近条目补齐(“多看几眼”,不降低门槛)。
504
+ *
505
+ * 返回 [{ id, entry, score, decision, features, rrf, fallback }],score 降序,
506
+ * 平手 rrf 降序 → id 升序——完全确定(动态路径的 recency 排名同样带
507
+ * idAsc tiebreak,不引入任何 clock/随机性)。
508
+ */
509
+ export function rankPairCandidates({ corpus, proposal, limit = PAIR_SCAN_LIMIT }) {
510
+ const max = Number(limit) > 0 ? Math.floor(Number(limit)) : PAIR_SCAN_LIMIT
511
+ const out = []
512
+ if (!corpus || corpus.size === 0 || !proposal) return out
513
+ const n = corpus.size
514
+ const proposalTrack = trackOf(proposal)
515
+ const proposalDomain = proposal?.domain || 'unknown'
516
+ const proposalTitle = normalizedTitle(proposal)
517
+ const proposalId = proposal?.id ?? null
518
+ const queryText = `${proposal.title || ''} ${proposal.content || ''}`
519
+ // BM25 查询词用当前生效分词(V2 三层在这里是收益);blocking 是 idf 盲的
520
+ // 共享计数,走下面的 V1 口径。
521
+ const queryTokens = tokenize(queryText)
522
+
523
+ // 1) blocking
524
+ const candidates = new Map()
525
+ if (n <= CLUSTER_EXACT_PAIR_LIMIT) {
526
+ for (const doc of corpus.docs.values()) {
527
+ if (proposalId != null && doc.id === proposalId) continue
528
+ if (trackOf(doc.entry) !== proposalTrack) continue
529
+ candidates.set(doc.id, 0)
530
+ }
531
+ } else {
532
+ const dfCap = Math.ceil(BLOCK_DF_RATIO * n)
533
+ const shared = new Map()
534
+ // blocking 固定 V1 口径(bigram+latin):V1 token ⊆ V2 token,V2 建的
535
+ // corpus.inverted 照样命中,bigram 的 posting/df 也不受 unigram 膨胀影响;
536
+ // 若用 V2 查询,高频单字会让无关条目凑满 ≥2 共享词,候选池被灌爆、
537
+ // target 被挤出 RRF 前 limit 切片(基准 Recall 池命中 0.985→0.8625 的主因)。
538
+ for (const term of tokenizeV1(queryText)) {
539
+ const posting = corpus.inverted.get(term)
540
+ if (!posting || posting.size === 0 || posting.size > dfCap) continue
541
+ for (const id of posting) {
542
+ if (proposalId != null && id === proposalId) continue
543
+ shared.set(id, (shared.get(id) || 0) + 1)
544
+ }
545
+ }
546
+ for (const [id, count] of shared) {
547
+ if (count >= CLUSTER_BLOCK_MIN_SHARED) candidates.set(id, count)
548
+ }
549
+ if (proposalTitle) {
550
+ for (const doc of corpus.docs.values()) {
551
+ if (proposalId != null && doc.id === proposalId) continue
552
+ if (trackOf(doc.entry) !== proposalTrack) continue
553
+ if (normalizedTitle(doc.entry) === proposalTitle) candidates.set(doc.id, Math.max(candidates.get(doc.id) || 0, CLUSTER_BLOCK_MIN_SHARED))
554
+ }
555
+ }
556
+ }
557
+ if (candidates.size === 0) return backfill({ corpus, proposal, proposalDomain, proposalId, max, out: [], taken: new Set(), queryTokens })
558
+
559
+ // 2) three rankings
560
+ const ids = [...candidates.keys()]
561
+ const bm25Scores = ids.map((id) => ({ id, s: bm25(queryTokens, corpus.docs.get(id), corpus) }))
562
+ bm25Scores.sort((a, b) => b.s - a.s || idAsc(a, b))
563
+ const rankBm25 = competitionRanks(bm25Scores, (item) => item.s)
564
+
565
+ const probes = ids.map((id) => {
566
+ const doc = corpus.docs.get(id)
567
+ const detail = similarityDetail(`${proposal.title || ''}\n${proposal.content || ''}`, `${doc.entry?.title || ''}\n${doc.entry?.content || ''}`)
568
+ return { id, diceScore: detail.dice, containment: detail.containment, lexical: Math.max(detail.dice, detail.containment) }
569
+ })
570
+ const diceRankOrder = [...probes].sort((a, b) => b.diceScore - a.diceScore || b.containment - a.containment || idAsc(a, b))
571
+ // 并列按 (diceScore, containment) 判定:两个分量都相同才算同分,id 只是
572
+ // 输出顺序的确定性 tiebreak。
573
+ const rankDice = competitionRanks(diceRankOrder, (item) => [item.diceScore, item.containment])
574
+
575
+ const entityOrder = ids.map((id) => {
576
+ const doc = corpus.docs.get(id)
577
+ return {
578
+ id,
579
+ entity: entityScore(proposal.appliesTo, doc.entry?.appliesTo),
580
+ containment: containmentOf(proposal, doc.entry),
581
+ }
582
+ }).sort((a, b) => b.entity - a.entity || b.containment - a.containment || idAsc(a, b))
583
+ const rankEntity = competitionRanks(entityOrder, (item) => [item.entity, item.containment])
584
+
585
+ // 3) weighted RRF。开关关 → 静态三路原式(字节级回退路径);开 → 权重来自
586
+ // computeRRFWeights,含 recency 键时加第四路 updatedAt 降序排名。
587
+ let rrf
588
+ if (!RRF_DYNAMIC) {
589
+ rrf = new Map()
590
+ for (const id of ids) {
591
+ rrf.set(id, RRF_W_BM25 / (RRF_K + rankBm25.get(id))
592
+ + RRF_W_DICE / (RRF_K + rankDice.get(id))
593
+ + RRF_W_ENTITY / (RRF_K + rankEntity.get(id)))
594
+ }
595
+ } else {
596
+ const weights = computeRRFWeights(proposal, corpus)
597
+ const rankRecency = new Map()
598
+ if (weights.recency != null) {
599
+ // 第四路:updatedAt 字符串降序(updatedDesc + idAsc tiebreak,与 backfill
600
+ // 同一确定性口径);rank 为 1 起的稠密序,只覆盖 blocking 后的候选集。
601
+ const recencyOrder = ids
602
+ .map((id) => ({ id, entry: corpus.docs.get(id).entry }))
603
+ .sort((a, b) => updatedDesc(a.entry, b.entry) || idAsc(a, b))
604
+ const ranked = competitionRanks(recencyOrder, (item) => String(item.entry?.updatedAt || ''))
605
+ for (const [id, rank] of ranked) rankRecency.set(id, rank)
606
+ }
607
+ rrf = new Map()
608
+ for (const id of ids) {
609
+ let value = weights.bm25 / (RRF_K + rankBm25.get(id))
610
+ + weights.dice / (RRF_K + rankDice.get(id))
611
+ + weights.entity / (RRF_K + rankEntity.get(id))
612
+ if (weights.recency != null) value += weights.recency / (RRF_K + rankRecency.get(id))
613
+ rrf.set(id, value)
614
+ }
615
+ }
616
+ ids.sort((a, b) => rrf.get(b) - rrf.get(a) || idAsc(a, b))
617
+
618
+ // 4) 将 RRF 切点附近的候选纳入完整 pairFeatures/pairScore 评分,
619
+ // 降低近重复簇中微小 RRF 差异对准入的影响。带宽为 RRF_SLICE_BAND,
620
+ // 评分总量最多 max×RRF_SLICE_BAND_CAP;超限按 rrf 降序与 idAsc 截断,
621
+ // 最终按 pairScore 取前 max。静态与动态权重均使用同一准入规则。
622
+ const cutIndex = Math.min(max, ids.length) - 1
623
+ const bandFloor = rrf.get(ids[cutIndex]) - RRF_SLICE_BAND
624
+ let scoredIds = []
625
+ for (const id of ids) {
626
+ if (rrf.get(id) < bandFloor) break // ids 已按 (rrf desc, idAsc) 排序,后面只会更低
627
+ scoredIds.push(id)
628
+ }
629
+ const bandCap = max * RRF_SLICE_BAND_CAP
630
+ if (scoredIds.length > bandCap) scoredIds = scoredIds.slice(0, bandCap)
631
+ const taken = new Set()
632
+ for (const id of scoredIds) {
633
+ const doc = corpus.docs.get(id)
634
+ const features = pairFeatures(proposal, doc.entry)
635
+ const score = pairScore(features)
636
+ taken.add(id)
637
+ out.push({ id, entry: doc.entry, score, decision: pairDecision(proposal, doc.entry, features), features, rrf: rrf.get(id), fallback: false })
638
+ }
639
+ out.sort((a, b) => b.score - a.score || b.rrf - a.rrf || idAsc(a, b))
640
+ // 真尺终选:评分集可能因边界带超过 max,按 pairScore 降序截取前 max
641
+ if (out.length > max) out.length = max
642
+ // 5) same-domain recent backfill — extra eyes, never a lower bar
643
+ return backfill({ corpus, proposal, proposalDomain, proposalId, max, out, taken, queryTokens })
644
+ }
645
+
646
+ function containmentOf(a, b) {
647
+ const detail = similarityDetail(`${a?.title || ''}\n${a?.content || ''}`, `${b?.title || ''}\n${b?.content || ''}`)
648
+ return detail.containment
649
+ }
650
+
651
+ function backfill({ corpus, proposal, proposalDomain, proposalId, max, out, taken, queryTokens }) {
652
+ if (out.length >= max) return out
653
+ const recent = [...corpus.docs.values()]
654
+ .filter((doc) => proposalId == null || doc.id !== proposalId)
655
+ .filter((doc) => (doc.entry?.domain || 'unknown') === proposalDomain)
656
+ .filter((doc) => !taken.has(doc.id))
657
+ .sort((a, b) => updatedDesc(a.entry, b.entry) || idAsc(a, b))
658
+ for (const doc of recent) {
659
+ if (out.length >= max) break
660
+ const features = pairFeatures(proposal, doc.entry)
661
+ const score = pairScore(features)
662
+ taken.add(doc.id)
663
+ out.push({ id: doc.id, entry: doc.entry, score, decision: pairDecision(proposal, doc.entry, features), features, rrf: 0, fallback: true })
664
+ }
665
+ out.sort((a, b) => b.score - a.score || b.rrf - a.rrf || idAsc(a, b))
666
+ return out
667
+ }
668
+
669
+ // —— §4.4 候选簇 ——
670
+
671
+ function pairKey(aId, bId) {
672
+ return aId < bId ? `${aId}\u0000${bId}` : `${bId}\u0000${aId}`
673
+ }
674
+
675
+ function round2(value) {
676
+ return Math.round(value * 100) / 100
677
+ }
678
+
679
+ /**
680
+ * §4.4 buildCandidateClusters(index, options)。
681
+ *
682
+ * 1) active 条目按 updatedAt 降序取最近 recentLimit(2000) 条,按 track 分组。
683
+ * 2) 同 track 内:N ≤ exactPairLimit(300) 全对;否则倒排 blocking(df ≤
684
+ * 30%N 的 posting、共享 ≥ blockMinShared(2) token,收集总量 ≤
685
+ * CLUSTER_MAX_PAIRS 的硬上限)。
686
+ * 3) 共享 token 为 0 的对先被预筛,其余算 pairFeatures/pairScore,保留
687
+ * ≥ minPairScore(0.55) 的边。
688
+ * 4) 边排序用三路 RRF(同 §4.3:bm25 双向和 / charDice / entityJaccard)。
689
+ * 5) 贪心成簇:边按 RRF 降序;种子=边两端;新成员必须与簇内**所有**成员
690
+ * pairScore ≥ 0.55(全对约束,禁传递闭包);每簇 ≤6;每条目只进一个簇。
691
+ * 6) medoid = 成员两两平均分最高者(平手 updatedAt 降序 → id 升序)。
692
+ * 7) suggested_op:≥3 成员且 avg ≥0.82 且同 domain → absorb;2+ 成员且
693
+ * avg ≥0.55 → link;否则 none。medoid 平均 <0.55 整簇丢弃。
694
+ * 8) 按 avg_score 降序最多输出 maxClusters(12) 簇。
695
+ *
696
+ * 返回 { clusters, truncated, scanned }。
697
+ */
698
+ export function buildCandidateClusters(index, options = {}) {
699
+ const maxClusters = options.maxClusters ?? CLUSTER_MAX
700
+ const maxMembers = options.maxMembers ?? CLUSTER_MAX_MEMBERS
701
+ const minPair = options.minPairScore ?? CLUSTER_MIN_PAIR
702
+ const blockMinShared = options.blockMinShared ?? CLUSTER_BLOCK_MIN_SHARED
703
+ const exactPairLimit = options.exactPairLimit ?? CLUSTER_EXACT_PAIR_LIMIT
704
+ const recentLimit = options.recentLimit ?? CLUSTER_RECENT_LIMIT
705
+
706
+ const active = Object.entries(index?.entries || index || {})
707
+ .filter(([, e]) => e && e.status === 'active')
708
+ .map(([id, entry]) => ({ id, entry }))
709
+ .sort((a, b) => updatedDesc(a.entry, b.entry) || idAsc(a, b))
710
+ const truncated = active.length > recentLimit
711
+ const pool = active.slice(0, recentLimit)
712
+
713
+ const byTrack = new Map()
714
+ for (const item of pool) {
715
+ const track = trackOf(item.entry)
716
+ if (!byTrack.has(track)) byTrack.set(track, [])
717
+ byTrack.get(track).push(item)
718
+ }
719
+
720
+ // edges: { a, b, aId, bId, features, score, rrf }
721
+ const edges = []
722
+ for (const [track, items] of byTrack) {
723
+ const n = items.length
724
+ if (n < 2) continue
725
+ const tokenSets = new Map()
726
+ const streams = new Map()
727
+ const inverted = new Map()
728
+ for (const item of items) {
729
+ // blocking 倒排固定 V1 口径(idf 盲集合运算):unigram 会把高频单字灌大
730
+ // 倒排与两两共享计数(N=500 簇延迟 +60% 的根因),对成簇质量无收益。
731
+ // 边打分的 BM25 路由(下方 bm25Route/buildCorpus)仍走 V2 流。
732
+ const text = `${item.entry?.title || ''} ${item.entry?.content || ''}`
733
+ const tokens = tokenizeV1(text)
734
+ tokenSets.set(item.id, new Set(tokens))
735
+ // BM25 流只算一次:pairList 里同一条目会出现在许多对中,逐对重算
736
+ // tokenStream 是另一份 O(N²) 的浪费。
737
+ streams.set(item.id, tokenStream(text))
738
+ for (const term of tokens) {
739
+ if (!inverted.has(term)) inverted.set(term, [])
740
+ inverted.get(term).push(item.id)
741
+ }
742
+ }
743
+ const byId = new Map(items.map((item) => [item.id, item]))
744
+ const pairSet = new Set()
745
+ if (n <= exactPairLimit) {
746
+ for (let i = 0; i < n; i++) {
747
+ for (let j = i + 1; j < n; j++) pairSet.add(pairKey(items[i].id, items[j].id))
748
+ }
749
+ } else {
750
+ // 倒排层剪枝(A-1):与 rankPairCandidates 同口径的 dfCap。中文常用字
751
+ // bigram 的 posting 几乎覆盖全库,不剪枝时每个 posting 都展开成 N²/2 个
752
+ // 对——这才是 N=500 要 5.8s 的根因,不是 similarityDetail 本身慢。
753
+ // 被跳过的是整条 posting(倒排表层面的剪枝),不涉及候选门槛。
754
+ const dfCap = Math.ceil(BLOCK_DF_RATIO * n)
755
+ const shared = new Map()
756
+ // 硬上限(CLUSTER_MAX_PAIRS)是防御性的:df 剪枝之后仍可能有大量中等
757
+ // 频率词留下 O(N²) 的对,超过上限就停止收集**新**对(已收集的计数继续
758
+ // 累加)。倒排按条目插入序遍历,截断位置确定 → 输出仍可复现。上限必须在
759
+ // 内层检查:单个 posting(≤dfCap 条)自身就可能超过它。
760
+ collectPairs: for (const posting of inverted.values()) {
761
+ if (posting.length < 2 || posting.length > dfCap) continue
762
+ for (let i = 0; i < posting.length; i++) {
763
+ for (let j = i + 1; j < posting.length; j++) {
764
+ const key = pairKey(posting[i], posting[j])
765
+ const count = shared.get(key)
766
+ if (count === undefined) {
767
+ if (shared.size >= CLUSTER_MAX_PAIRS) break collectPairs
768
+ shared.set(key, 1)
769
+ } else {
770
+ shared.set(key, count + 1)
771
+ }
772
+ }
773
+ }
774
+ }
775
+ for (const [key, count] of shared) {
776
+ if (count >= blockMinShared) pairSet.add(key)
777
+ }
778
+ }
779
+ if (pairSet.size === 0) continue
780
+
781
+ const corpus = buildCorpus(items.map((item) => ({ id: item.id, title: item.entry?.title || '', content: item.entry?.content || '', entry: item.entry })))
782
+ // 便宜预筛:共享 token 为 0 的对直接跳过,连 similarityDetail(bigram 集
783
+ // 构建 + 长度探针)都不进。它只剔除没有任何共享词元(V1 口径)的候选,
784
+ // 不降低最终 pairScore 门槛。
785
+ const pairList = []
786
+ for (const key of pairSet) {
787
+ const [aId, bId] = key.split('\u0000')
788
+ const aItem = byId.get(aId)
789
+ const bItem = byId.get(bId)
790
+ if (sharedTokenCount(tokenSets.get(aId), tokenSets.get(bId)) === 0) continue
791
+ const features = pairFeatures(aItem.entry, bItem.entry)
792
+ const score = pairScore(features)
793
+ if (score < minPair) continue
794
+ pairList.push({ key, aId, bId, aItem, bItem, features, score })
795
+ }
796
+ if (pairList.length === 0) continue
797
+
798
+ // three route rankings for edge order only。
799
+ // 此处使用静态权重;动态权重只用于 rankPairCandidates。buildCandidateClusters
800
+ // 没有 proposal/查询上下文——它是无监督的全库成簇,三路 RRF 只决定贪心
801
+ // 长簇的边访问顺序;引入「查询类型」没有语义落点,静态三路保证簇构建
802
+ // 与查询无关、完全可复现。并列分数共享同一名次(A-12)。
803
+ const bm25Route = pairList.map((pair) => ({
804
+ key: pair.key,
805
+ s: bm25(streams.get(pair.aId), corpus.docs.get(pair.bId), corpus)
806
+ + bm25(streams.get(pair.bId), corpus.docs.get(pair.aId), corpus),
807
+ })).sort((a, b) => b.s - a.s || (a.key < b.key ? -1 : 1))
808
+ const rankBm25 = competitionRanks(bm25Route, (item) => item.s)
809
+ const diceRoute = [...pairList].sort((a, b) => b.features.charDice - a.features.charDice
810
+ || b.features.containment - a.features.containment || (a.key < b.key ? -1 : 1))
811
+ const rankDice = competitionRanks(diceRoute, (item) => [item.features.charDice, item.features.containment])
812
+ const entityRoute = [...pairList].sort((a, b) => b.features.entityJaccard - a.features.entityJaccard
813
+ || b.features.containment - a.features.containment || (a.key < b.key ? -1 : 1))
814
+ const rankEntity = competitionRanks(entityRoute, (item) => [item.features.entityJaccard, item.features.containment])
815
+ for (const pair of pairList) {
816
+ pair.rrf = RRF_W_BM25 / (RRF_K + rankBm25.get(pair.key))
817
+ + RRF_W_DICE / (RRF_K + rankDice.get(pair.key))
818
+ + RRF_W_ENTITY / (RRF_K + rankEntity.get(pair.key))
819
+ }
820
+ pairList.sort((a, b) => b.rrf - a.rrf || b.score - a.score || (a.key < b.key ? -1 : 1))
821
+ edges.push(...pairList)
822
+ }
823
+
824
+ // greedy all-pairs clique growth
825
+ edges.sort((a, b) => b.rrf - a.rrf || b.score - a.score || (a.key < b.key ? -1 : 1))
826
+ const memberOf = new Map()
827
+ const clusters = []
828
+ for (const edge of edges) {
829
+ const clusterA = memberOf.get(edge.aId)
830
+ const clusterB = memberOf.get(edge.bId)
831
+ if (clusterA && clusterB) continue
832
+ if (!clusterA && !clusterB) {
833
+ if (clusters.length >= maxClusters) continue
834
+ const cluster = { members: [edge.aItem, edge.bItem], scores: new Map([[edge.key, edge.score]]) }
835
+ clusters.push(cluster)
836
+ memberOf.set(edge.aId, cluster)
837
+ memberOf.set(edge.bId, cluster)
838
+ continue
839
+ }
840
+ const cluster = clusterA || clusterB
841
+ if (cluster.members.length >= maxMembers) continue
842
+ const candidate = clusterA ? edge.bItem : edge.aItem
843
+ let ok = true
844
+ for (const member of cluster.members) {
845
+ const key = pairKey(candidate.id, member.id)
846
+ let score = cluster.scores.get(key)
847
+ if (score == null) {
848
+ score = pairScore(pairFeatures(candidate.entry, member.entry))
849
+ cluster.scores.set(key, score)
850
+ }
851
+ if (score < minPair) { ok = false; break }
852
+ }
853
+ if (!ok) continue
854
+ cluster.members.push(candidate)
855
+ memberOf.set(candidate.id, cluster)
856
+ }
857
+
858
+ // medoid + output
859
+ const out = []
860
+ for (const cluster of clusters) {
861
+ const members = [...cluster.members].sort((a, b) => idAsc(a, b))
862
+ const pairScores = {}
863
+ let sum = 0
864
+ let count = 0
865
+ for (let i = 0; i < members.length; i++) {
866
+ for (let j = i + 1; j < members.length; j++) {
867
+ const key = pairKey(members[i].id, members[j].id)
868
+ let score = cluster.scores.get(key)
869
+ if (score == null) {
870
+ score = pairScore(pairFeatures(members[i].entry, members[j].entry))
871
+ cluster.scores.set(key, score)
872
+ }
873
+ pairScores[`${members[i].id}|${members[j].id}`] = round2(score)
874
+ sum += score
875
+ count += 1
876
+ }
877
+ }
878
+ const avg = count ? sum / count : 0
879
+ let medoid = null
880
+ let bestAvg = -1
881
+ for (const member of members) {
882
+ let mSum = 0
883
+ for (const other of members) {
884
+ if (other.id === member.id) continue
885
+ const key = pairKey(member.id, other.id)
886
+ mSum += cluster.scores.get(key) ?? 0
887
+ }
888
+ const mAvg = members.length > 1 ? mSum / (members.length - 1) : 0
889
+ if (mAvg > bestAvg + 1e-9
890
+ || (Math.abs(mAvg - bestAvg) <= 1e-9 && medoid
891
+ && (updatedDesc(member.entry, medoid.entry) < 0
892
+ || (updatedDesc(member.entry, medoid.entry) === 0 && String(member.id).localeCompare(String(medoid.id)) < 0)))) {
893
+ bestAvg = mAvg
894
+ medoid = member
895
+ }
896
+ }
897
+ // medoid 平均 <0.55 → 整簇不输出(§4.4.9;全对约束下属防御分支)
898
+ if (members.length > 1 && bestAvg < minPair) continue
899
+ const sameDomain = members.every((m) => (m.entry?.domain || 'unknown') === (members[0].entry?.domain || 'unknown'))
900
+ const suggestedOp = members.length >= 3 && avg >= PAIR_ABSORB_MIN && sameDomain
901
+ ? 'absorb'
902
+ : (members.length >= 2 && avg >= minPair ? 'link' : 'none')
903
+ out.push({
904
+ cluster_id: '',
905
+ members: members.map((m) => ({
906
+ id: m.id,
907
+ title: m.entry?.title || '',
908
+ track: trackOf(m.entry),
909
+ domain: m.entry?.domain || 'unknown',
910
+ updatedAt: m.entry?.updatedAt || null,
911
+ content: m.entry?.content || '',
912
+ })),
913
+ pair_scores: pairScores,
914
+ medoid_id: medoid?.id || members[0]?.id || '',
915
+ avg_score: round2(avg),
916
+ suggested_op: suggestedOp,
917
+ })
918
+ }
919
+ out.sort((a, b) => b.avg_score - a.avg_score || String(a.medoid_id).localeCompare(String(b.medoid_id)))
920
+ for (let i = 0; i < out.length; i++) out[i].cluster_id = `cl-${i + 1}`
921
+ return { clusters: out.slice(0, maxClusters), truncated, scanned: pool.length }
922
+ }
923
+
924
+ // —— S5 查询意图与分解 ——
925
+ //
926
+ // 召回入口只需要知道“这句话在问哪一类事”,然后决定过滤与取数策略:
927
+ // date 时间题:先解析相对日期,按 absolute_date 过滤/排序
928
+ // entity 实体题:抽出实体名/别名,按实体索引扩展一跳
929
+ // conflict 冲突题:按 fact_key / conflicts_with 成对取
930
+ // commitment 约定题:未完成/到期承诺优先
931
+ // boundary 边界题:只有用户明确问到时才注入 only_if_asked
932
+ // general 普通题
933
+ // 纯规则,无外部模型,无网络;识别不出来就是 general,不猜。
934
+
935
+ const CONFLICT_RE = /矛盾|冲突|到底|哪一版|哪个版本|哪边|前后说法|说法不一|改口|不一致|不是说|谁对|真的吗|相反|contradict|conflict|which version/i
936
+ const COMMITMENT_RE = /答应|承诺|约定|说好|欠|兑现|到期|还没|什么时候还|做到|提醒我|promise|commitment|owe/i
937
+ const BOUNDARY_RE = /秘密|保密|别说|别告诉|不要告诉|不能说|不能提|隐私|瞒着|never[-_ ]?say|only if asked|secret/i
938
+ const DATE_QUERY_RE = /什么时候|哪天|几号|日期|时间|多久|几点|星期几|上次|之前|后来|最近|when|what time|which day/i
939
+
940
+ /**
941
+ * @returns {'date'|'entity'|'conflict'|'commitment'|'boundary'|'general'}
942
+ */
943
+ export function detectQueryIntent(query, { now = new Date(), timeZone = DEFAULT_TIME_ZONE, knownEntities = [] } = {}) {
944
+ const text = String(query || '').trim()
945
+ if (!text) return 'general'
946
+ if (CONFLICT_RE.test(text)) return 'conflict'
947
+ if (COMMITMENT_RE.test(text)) return 'commitment'
948
+ if (BOUNDARY_RE.test(text)) return 'boundary'
949
+ if (hasTemporalHint(text) || DATE_QUERY_RE.test(text) || /\d{4}[-/]\d{1,2}[-/]\d{1,2}/.test(text)) return 'date'
950
+ if (extractQueryEntities(text, { knownEntities }).length > 0) return 'entity'
951
+ return 'general'
952
+ }
953
+
954
+ const QUOTED_RE = /["“”「」『』]([^"“”「」『』]{2,30})["“”「」『』]/g
955
+ const AT_RE = /@([\w\u4e00-\u9fff-]{2,30})/g
956
+
957
+ /** 实体抽取只用“明确标注”的名字:引号、@、已知实体表。宁缺毋滥。 */
958
+ export function extractQueryEntities(query, { knownEntities = [] } = {}) {
959
+ const text = String(query || '')
960
+ const found = []
961
+ const add = (value) => {
962
+ const name = String(value || '').trim()
963
+ if (name.length < 2 || name.length > 30) return
964
+ if (!found.includes(name)) found.push(name)
965
+ }
966
+ for (const match of text.matchAll(QUOTED_RE)) add(match[1])
967
+ for (const match of text.matchAll(AT_RE)) add(match[1])
968
+ for (const name of Array.isArray(knownEntities) ? knownEntities : []) {
969
+ if (typeof name === 'string' && name.trim().length >= 2 && text.includes(name)) add(name)
970
+ }
971
+ return found.slice(0, 6)
972
+ }
973
+
974
+ /**
975
+ * 把查询拆成召回能直接用的零件。`expanded` 是拼给词法/向量检索的查询,
976
+ * `dates`/`entities` 同时供过滤与排序使用。
977
+ */
978
+ export function decomposeQuery(query, intent = null, { now = new Date(), timeZone = DEFAULT_TIME_ZONE, knownEntities = [] } = {}) {
979
+ const text = String(query || '')
980
+ const resolvedIntent = intent || detectQueryIntent(text, { now, timeZone, knownEntities })
981
+ const dates = resolveQueryDates(text, { now, timeZone })
982
+ const entities = extractQueryEntities(text, { knownEntities })
983
+ const terms = [...new Set([...dates, ...entities])]
984
+ return {
985
+ query: text,
986
+ intent: resolvedIntent,
987
+ dates,
988
+ entities,
989
+ terms,
990
+ expanded: [text, ...terms].filter(Boolean).join(' ').trim(),
991
+ }
992
+ }