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.
- package/AGENTS.md +108 -110
- package/CHANGELOG.md +169 -868
- package/LICENSE +21 -21
- package/README.md +368 -374
- package/README.zh.md +354 -360
- package/assets/icon.svg +7 -7
- package/cordis.patch.yml +8 -8
- package/docs/active-memory-ab.md +279 -385
- package/docs/binding-lifecycle.md +99 -99
- package/docs/client-conventions.md +75 -75
- package/docs/contributing.md +217 -217
- package/docs/emotion-model-spec.md +247 -281
- package/docs/env-and-commands.md +149 -152
- package/docs/host-adaptation.md +339 -360
- package/docs/host-api.md +131 -137
- package/docs/host-versions.md +117 -120
- package/docs/mcp-porting.md +146 -146
- package/docs/memory-semantics.md +271 -259
- package/docs/pending-work.md +44 -51
- package/docs/troubleshooting.md +909 -854
- package/lib/active-memory.js +160 -165
- package/lib/activity-log.js +207 -207
- package/lib/auto-link/apply.js +248 -249
- package/lib/auto-link/candidates.js +163 -163
- package/lib/auto-link/decide.js +300 -300
- package/lib/auto-link/normalize.js +99 -99
- package/lib/auto-link/policy.js +42 -42
- package/lib/auto-link/suppression.js +101 -101
- package/lib/auto-link/terminology.js +311 -311
- package/lib/backup.js +1254 -1254
- package/lib/binding-diagnostics.js +634 -634
- package/lib/budget.js +118 -118
- package/lib/client.js +9820 -9751
- package/lib/commitment.js +178 -138
- package/lib/consolidation-ledger.js +434 -438
- package/lib/consolidation-receipt.js +386 -387
- package/lib/consolidation-snapshot.js +420 -405
- package/lib/consolidation-worker.js +240 -241
- package/lib/context.js +33 -33
- package/lib/curator-evidence.js +131 -131
- package/lib/curator-policy.js +198 -202
- package/lib/curator.js +1813 -1811
- package/lib/cycle.js +524 -513
- package/lib/diagnostics.js +524 -524
- package/lib/embedding-catalog.js +1051 -1055
- package/lib/embedding-download.js +637 -607
- package/lib/embedding-runtime.js +946 -946
- package/lib/engine.js +1103 -1103
- package/lib/entity-repair.js +285 -285
- package/lib/environment-check.js +394 -394
- package/lib/fork-model.js +312 -312
- package/lib/freshness.js +128 -121
- package/lib/global-graph.js +389 -389
- package/lib/graph.js +1193 -1193
- package/lib/host-surface.js +30 -30
- package/lib/inbound.js +284 -281
- package/lib/index.js +506 -511
- package/lib/inject.js +2639 -2619
- package/lib/lexicon-scope.js +143 -143
- package/lib/lexicon.js +1183 -1192
- package/lib/lifecycle-audit.js +37 -0
- package/lib/local-embedding-entry.js +145 -145
- package/lib/local-embedding-manager.js +306 -306
- package/lib/local-embedding-protocol.js +210 -210
- package/lib/local-embedding-worker.js +682 -682
- package/lib/local-vector-service.js +506 -453
- package/lib/maintenance-ledger.js +138 -0
- package/lib/maintenance-review.js +103 -0
- package/lib/maintenance-runner.js +267 -0
- package/lib/managed-runtime.js +118 -118
- package/lib/media.js +607 -513
- package/lib/memory.js +5035 -4941
- package/lib/memu-config.js +213 -213
- package/lib/memu.js +565 -565
- package/lib/migrate.js +200 -200
- package/lib/mood.js +300 -300
- package/lib/paths.js +453 -457
- package/lib/port-surface.js +82 -82
- package/lib/preset-mount.js +79 -0
- package/lib/preset-scope.js +126 -126
- package/lib/private-links.js +567 -567
- package/lib/private.js +2198 -2209
- package/lib/prompts/global-curator.md +135 -135
- package/lib/prompts/image-caption.md +1 -1
- package/lib/prompts/private-consolidation.coding.md +39 -39
- package/lib/prompts/private-consolidation.md +32 -32
- package/lib/prompts/private-consolidation.mixed.md +37 -37
- package/lib/prompts/private-consolidation.rp.md +47 -47
- package/lib/prompts/private-policy.coding.md +35 -35
- package/lib/prompts/private-policy.md +36 -36
- package/lib/prompts/private-policy.mixed.md +29 -29
- package/lib/prompts/private-policy.rp.md +43 -43
- package/lib/prompts/system-guide.coding.md +20 -20
- package/lib/prompts/system-guide.md +25 -25
- package/lib/prompts/system-guide.mixed.md +22 -22
- package/lib/prompts/system-guide.rp.md +23 -23
- package/lib/prompts.js +331 -331
- package/lib/recall-cache.js +212 -212
- package/lib/remote-summary.js +123 -123
- package/lib/rpc.js +2531 -2532
- package/lib/salient-wake.js +438 -438
- package/lib/snippet.js +125 -125
- package/lib/state.js +1948 -1928
- package/lib/stats.js +236 -236
- package/lib/temporal.js +345 -348
- package/lib/text-retrieval.js +992 -1001
- package/lib/text-similarity.js +305 -305
- package/lib/tokenizer-v2.js +271 -271
- package/lib/tools.js +1098 -1091
- package/lib/turn-log.js +545 -545
- package/lib/vector-migration.js +928 -930
- package/lib/vector-profile.js +1353 -1359
- package/lib/visibility.js +59 -59
- package/lib/webui/graph-LICENSE.txt +1 -1
- package/lib/webui/graph-view.bundle.js +2 -2
- package/lib/webui/graph-view.js +1171 -1175
- package/lib/webui/mark.svg +7 -7
- package/lib/webui/standalone.css +1178 -1178
- package/lib/webui/standalone.js +238 -238
- package/lib/webui.js +136 -136
- package/lib/worker-pool.js +1015 -979
- package/package.json +153 -153
- package/requirements.lock +34 -34
- package/scripts/acceptance-local.mjs +946 -946
- package/scripts/active-memory-ab-live.mjs +653 -655
- package/scripts/active-memory-ab.mjs +1302 -1302
- package/scripts/audit-memory-lifecycle.mjs +55 -0
- package/scripts/bench-recall.mjs +142 -142
- package/scripts/build-graph.mjs +44 -45
- package/scripts/chain-matrix.mjs +541 -541
- package/scripts/check-all.mjs +68 -74
- package/scripts/check-doc-drift.mjs +547 -547
- package/scripts/check-graph-browser.mjs +261 -261
- package/scripts/check-i18n.mjs +81 -83
- package/scripts/check-idle-compositing.mjs +61 -61
- package/scripts/check-seed-compat.mjs +115 -118
- package/scripts/check-text-format.mjs +55 -0
- package/scripts/curator-pair-calibrate.mjs +259 -259
- package/scripts/diagnose-bindings.mjs +176 -176
- package/scripts/drive-session.mjs +863 -864
- package/scripts/engine-smoke.mjs +69 -69
- package/scripts/entity-dedupe.mjs +110 -110
- package/scripts/lexicon-calibrate.mjs +230 -230
- package/scripts/lexicon-dedupe.mjs +318 -318
- package/scripts/local-runtime-install.mjs +142 -142
- package/scripts/local-runtime-verify.mjs +56 -56
- package/scripts/local-vector-verify.mjs +93 -93
- package/scripts/make-readme-shots.mjs +59 -59
- package/scripts/migrate-visibility.mjs +94 -94
- package/scripts/mock-llm.mjs +938 -903
- package/scripts/preview.mjs +58 -58
- package/scripts/prune-sessions.mjs +31 -34
- package/scripts/prune-turnlogs.mjs +29 -30
- package/scripts/prune-vectors.mjs +24 -24
- package/scripts/rebuild-auto-links.mjs +252 -252
- package/scripts/recall-bench.mjs +820 -820
- package/scripts/repetition-ab-scenarios.mjs +93 -93
- package/scripts/repetition-detector-snapshot.mjs +314 -314
- package/scripts/repetition-eval-live.mjs +360 -360
- package/scripts/repetition-eval.mjs +702 -702
- package/scripts/replay.mjs +705 -575
- package/scripts/setup.mjs +46 -46
- package/scripts/simulate-injection.mjs +299 -301
- package/tests/absorb-review.test.mjs +354 -354
- package/tests/activation.test.mjs +89 -89
- package/tests/active-memory-ab.test.mjs +745 -745
- package/tests/active-memory.test.mjs +129 -129
- package/tests/activity-log.test.mjs +126 -126
- package/tests/activity-wiring.test.mjs +155 -155
- package/tests/appendix-b.test.mjs +217 -217
- package/tests/appendix-b2.test.mjs +166 -166
- package/tests/audit-batch3.test.mjs +247 -247
- package/tests/audit-regression.test.mjs +275 -275
- package/tests/audit-safety.test.mjs +227 -227
- package/tests/auto-link-candidates.test.mjs +245 -245
- package/tests/auto-link-decide.test.mjs +512 -512
- package/tests/auto-link-migration.test.mjs +133 -133
- package/tests/backend-compensation.test.mjs +272 -272
- package/tests/backup.test.mjs +793 -793
- package/tests/binding-diagnostics.test.mjs +720 -720
- package/tests/browser.test.mjs +476 -476
- package/tests/client-export.test.mjs +521 -521
- package/tests/client-render.test.mjs +2008 -1728
- package/tests/coalesce.test.mjs +113 -113
- package/tests/commitment.test.mjs +243 -144
- package/tests/config.test.mjs +159 -159
- package/tests/consolidation-credential.test.mjs +330 -330
- package/tests/consolidation-feed.test.mjs +122 -122
- package/tests/consolidation-fork.test.mjs +1586 -1539
- package/tests/consolidation-ledger.test.mjs +389 -389
- package/tests/consolidation-snapshot.test.mjs +567 -505
- package/tests/consolidation-value.test.mjs +89 -89
- package/tests/context-scope.test.mjs +40 -40
- package/tests/cross-library-recall.test.mjs +269 -269
- package/tests/cue.test.mjs +58 -58
- package/tests/curator-absorb.test.mjs +444 -444
- package/tests/curator-calibrate.test.mjs +173 -173
- package/tests/curator-clusters.test.mjs +306 -306
- package/tests/curator-commit.test.mjs +325 -325
- package/tests/curator-contract.test.mjs +191 -191
- package/tests/curator-evidence.test.mjs +102 -102
- package/tests/curator-link.test.mjs +317 -317
- package/tests/curator-pairing.test.mjs +339 -339
- package/tests/curator-probe.test.mjs +490 -490
- package/tests/curator-review-mode.test.mjs +315 -315
- package/tests/curator.test.mjs +152 -152
- package/tests/cycle.test.mjs +567 -568
- package/tests/diagnostics.test.mjs +278 -278
- package/tests/disclosure.test.mjs +249 -249
- package/tests/doc-drift.test.mjs +342 -342
- package/tests/drive-session.test.mjs +152 -152
- package/tests/dynamic-rrf.test.mjs +182 -182
- package/tests/dynamic-threshold.test.mjs +52 -52
- package/tests/embedding-catalog.test.mjs +374 -374
- package/tests/embedding-download.test.mjs +529 -486
- package/tests/embedding-runtime.test.mjs +449 -449
- package/tests/emotion-chain.test.mjs +84 -84
- package/tests/emotion-contract.test.mjs +445 -445
- package/tests/engine.test.mjs +108 -108
- package/tests/entity-merge.test.mjs +278 -278
- package/tests/environment-check.test.mjs +187 -187
- package/tests/fact-version.test.mjs +146 -146
- package/tests/fixtures/active-memory-ab/README.md +56 -56
- package/tests/fixtures/active-memory-ab/cases/01-clean-dense-turn.json +351 -351
- package/tests/fixtures/active-memory-ab/cases/02-clean-thin-turn.json +122 -122
- package/tests/fixtures/active-memory-ab/cases/03-clean-starved-small.json +125 -125
- package/tests/fixtures/active-memory-ab/cases/04-clean-large-thin.json +137 -137
- package/tests/fixtures/active-memory-ab/cases/05-clean-half-step.json +166 -166
- package/tests/fixtures/active-memory-ab/cases/06-clean-duplicate-reread.json +197 -197
- package/tests/fixtures/active-memory-ab/cases/07-clean-recent-recall.json +125 -125
- package/tests/fixtures/active-memory-ab/cases/08-global-relevant.json +111 -111
- package/tests/fixtures/active-memory-ab/cases/09-global-irrelevant-conflict.json +158 -158
- package/tests/fixtures/active-memory-ab/cases/10-no-human-turn.json +97 -97
- package/tests/fixtures/active-memory-ab/cases/11-clean-scale-100.json +137 -137
- package/tests/fixtures/active-memory-ab/cases/12-clean-scale-1000.json +137 -137
- package/tests/fixtures/active-memory-ab/cases/13-clean-scale-5000.json +137 -137
- package/tests/fixtures/active-memory-ab/cases/14-clean-scale-20000.json +137 -137
- package/tests/fixtures/active-memory-ab/lead-ai-reviewed-reference.json +191 -191
- package/tests/fixtures/active-memory-ab/manifest.json +199 -199
- package/tests/fixtures/curator-pairs/labeled.v1.jsonl +90 -90
- package/tests/fixtures/lexicon-stub-hooks.mjs +15 -15
- package/tests/fixtures/lexicon-stub.mjs +284 -284
- package/tests/fixtures/mock-llm/reply.txt +1 -1
- package/tests/fixtures/recall-bench/01-paraphrase.json +183 -183
- package/tests/fixtures/recall-bench/02-exact.json +152 -152
- package/tests/fixtures/recall-bench/03-negation.json +172 -172
- package/tests/fixtures/recall-bench/04-no-answer.json +161 -161
- package/tests/fixtures/recall-bench/05-conflict.json +193 -193
- package/tests/fixtures/recall-bench/06-boundary.json +272 -272
- package/tests/fixtures/recall-bench/07-secret.json +190 -190
- package/tests/fixtures/recall-bench/08-coding.json +163 -163
- package/tests/fixtures/recall-bench-gold-candidates/01-paraphrase.json +193 -193
- package/tests/fixtures/recall-bench-gold-candidates/02-exact.json +197 -197
- package/tests/fixtures/recall-bench-gold-candidates/03-negation.json +244 -244
- package/tests/fixtures/recall-bench-gold-candidates/04-no-answer.json +189 -189
- package/tests/fixtures/recall-bench-gold-candidates/05-conflict.json +245 -245
- package/tests/fixtures/recall-bench-gold-candidates/06-boundary.json +279 -279
- package/tests/fixtures/recall-bench-gold-candidates/07-secret.json +224 -224
- package/tests/fixtures/recall-bench-gold-candidates/08-coding.json +218 -218
- package/tests/fixtures/repetition-eval/01-zh-rp.json +92 -92
- package/tests/fixtures/repetition-eval/02-en.json +96 -96
- package/tests/fixtures/repetition-eval/03-code.json +90 -90
- package/tests/fixtures/repetition-eval/04-names.json +115 -115
- package/tests/fixtures/repetition-eval/05-user-quote.json +95 -95
- package/tests/fixtures/repetition-eval/06-agreement.json +85 -85
- package/tests/fixtures/tokenizer-cases.mjs +27 -27
- package/tests/fork-model.test.mjs +345 -345
- package/tests/freshness.test.mjs +140 -140
- package/tests/global-graph.test.mjs +106 -106
- package/tests/global-lifecycle.test.mjs +149 -149
- package/tests/graph-cascade.test.mjs +363 -363
- package/tests/graph-view.test.mjs +414 -414
- package/tests/graph.test.mjs +371 -371
- package/tests/help-page.test.mjs +416 -416
- package/tests/hook-order.test.mjs +72 -72
- package/tests/humanlike.test.mjs +232 -232
- package/tests/hybrid-recall.test.mjs +610 -610
- package/tests/inbound.test.mjs +441 -441
- package/tests/inject-conflict.test.mjs +173 -173
- package/tests/inject-guide.test.mjs +513 -513
- package/tests/inject.test.mjs +384 -384
- package/tests/injection-budget-settings.test.mjs +35 -35
- package/tests/injection-budget.test.mjs +165 -165
- package/tests/injection-chain.test.mjs +442 -442
- package/tests/injection-intent-budget.test.mjs +92 -92
- package/tests/injection-rollback.test.mjs +428 -428
- package/tests/issue2-chain.test.mjs +169 -169
- package/tests/lexical-bm25.test.mjs +171 -171
- package/tests/lexicon-calibrate.test.mjs +48 -48
- package/tests/lexicon-dedupe.test.mjs +171 -171
- package/tests/lexicon-frequency.test.mjs +195 -195
- package/tests/lexicon-inject.test.mjs +459 -459
- package/tests/lexicon-perf.test.mjs +464 -464
- package/tests/lexicon-scope.test.mjs +256 -256
- package/tests/lexicon-ui.test.mjs +667 -667
- package/tests/lexicon.test.mjs +922 -922
- package/tests/lifecycle-audit.test.mjs +56 -0
- package/tests/loader-register.mjs +3 -3
- package/tests/loader.mjs +17 -17
- package/tests/local-embedding-entry.test.mjs +95 -95
- package/tests/local-embedding-env.test.mjs +51 -51
- package/tests/local-embedding-manager.test.mjs +494 -494
- package/tests/local-embedding-protocol.test.mjs +121 -121
- package/tests/local-embedding-worker.test.mjs +440 -440
- package/tests/local-vector-service.test.mjs +41 -0
- package/tests/maintenance-status.test.mjs +77 -0
- package/tests/maintenance.test.mjs +438 -0
- package/tests/managed-memory.test.mjs +1234 -1234
- package/tests/managed-runtime.test.mjs +72 -72
- package/tests/media-injection.test.mjs +225 -0
- package/tests/media.test.mjs +135 -135
- package/tests/memory-chain.test.mjs +169 -169
- package/tests/memory-fields.test.mjs +134 -134
- package/tests/memu-resident-route.test.mjs +130 -130
- package/tests/memu-resident.test.mjs +33 -33
- package/tests/migration-payload.test.mjs +40 -42
- package/tests/mock-llm.test.mjs +263 -225
- package/tests/mood.test.mjs +109 -109
- package/tests/multiprocess.test.mjs +29 -29
- package/tests/negation-polarity.test.mjs +135 -135
- package/tests/new-session-gate.test.mjs +617 -617
- package/tests/open-loop-date.test.mjs +416 -416
- package/tests/ops-hardening.test.mjs +209 -209
- package/tests/package-shipping.test.mjs +88 -88
- package/tests/pending-injection.test.mjs +107 -107
- package/tests/port-surface.test.mjs +138 -138
- package/tests/preset-mount.test.mjs +124 -0
- package/tests/preset-scope.test.mjs +212 -212
- package/tests/private-links.test.mjs +493 -493
- package/tests/prompt-semantics.test.mjs +51 -51
- package/tests/prompts.test.mjs +315 -315
- package/tests/query-decompose.test.mjs +62 -62
- package/tests/react-snapshot.test.mjs +24 -24
- package/tests/recall-bench.test.mjs +317 -317
- package/tests/recall-cache.test.mjs +292 -292
- package/tests/recall-corpus-eligibility.test.mjs +51 -51
- package/tests/recall-dedup.test.mjs +446 -446
- package/tests/recall-intent.test.mjs +172 -172
- package/tests/regression-sweep.test.mjs +311 -311
- package/tests/reminder-fairness.test.mjs +55 -0
- package/tests/remote.test.mjs +140 -140
- package/tests/rename.test.mjs +30 -30
- package/tests/repetition-detector-snapshot.test.mjs +231 -231
- package/tests/repetition-eval-live.test.mjs +177 -177
- package/tests/repetition-eval.test.mjs +373 -373
- package/tests/salience-domain.test.mjs +173 -173
- package/tests/salient-date.test.mjs +142 -142
- package/tests/salient-wake.test.mjs +389 -389
- package/tests/settings-beat.test.mjs +222 -222
- package/tests/settings-coverage.test.mjs +97 -97
- package/tests/settings-plumbing.test.mjs +79 -79
- package/tests/short-term.test.mjs +182 -166
- package/tests/sidebar-beat.test.mjs +213 -213
- package/tests/sidebar-refresh.test.mjs +123 -123
- package/tests/sidebar.test.mjs +102 -74
- package/tests/simulate-injection.test.mjs +76 -76
- package/tests/slot-similarity.test.mjs +153 -153
- package/tests/snippet.test.mjs +79 -79
- package/tests/source-kind.test.mjs +52 -52
- package/tests/speaker-provenance.test.mjs +120 -120
- package/tests/stale-maintenance.test.mjs +206 -131
- package/tests/state-gc.test.mjs +34 -34
- package/tests/state.test.mjs +155 -155
- package/tests/stats.test.mjs +112 -112
- package/tests/storage.test.mjs +125 -125
- package/tests/stubs/child-process-spy.mjs +14 -14
- package/tests/stubs/dsh-llm-pi-ai.js +13 -13
- package/tests/stubs/dsh-llm.js +5 -5
- package/tests/stubs/dsh-schedule.js +140 -140
- package/tests/stubs/dsh-session-query.js +26 -26
- package/tests/stubs/dsh-session.js +7 -7
- package/tests/stubs/dsh-tools.js +101 -101
- package/tests/temporal-repair.test.mjs +78 -0
- package/tests/temporal.test.mjs +124 -124
- package/tests/text-format.test.mjs +24 -0
- package/tests/tokenizer-v2.test.mjs +142 -142
- package/tests/tool-schema.test.mjs +126 -126
- package/tests/tools.test.mjs +810 -810
- package/tests/turn-log.test.mjs +487 -487
- package/tests/ui-defaults.test.mjs +57 -57
- package/tests/update-fields.test.mjs +138 -138
- package/tests/vector-gc.test.mjs +37 -37
- package/tests/vector-migration.test.mjs +810 -810
- package/tests/vector-profile.test.mjs +449 -449
- package/tests/visibility-migration.test.mjs +152 -152
- package/tests/webui-auth.test.mjs +963 -963
- package/tests/webui.test.mjs +421 -421
- package/tests/windows-env.test.mjs +89 -89
- package/tests/worker-lifecycle.test.mjs +1521 -1429
package/lib/text-retrieval.js
CHANGED
|
@@ -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
|
-
*
|
|
103
|
-
* (CJK unigram+bigram+trigram 三层 + 实体保护,Set 插入序数组);关 → V1
|
|
104
|
-
* 原路径。签名与语义兼容,返回去重 token 数组(插入序)。
|
|
105
|
-
*
|
|
106
|
-
*
|
|
107
|
-
*
|
|
108
|
-
*
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
const
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
const
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
for (const term of
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
docs,
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
*
|
|
170
|
-
*
|
|
171
|
-
*
|
|
172
|
-
*
|
|
173
|
-
*
|
|
174
|
-
*
|
|
175
|
-
*
|
|
176
|
-
*
|
|
177
|
-
*
|
|
178
|
-
*
|
|
179
|
-
*
|
|
180
|
-
*
|
|
181
|
-
*
|
|
182
|
-
*
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
*
|
|
235
|
-
*
|
|
236
|
-
*
|
|
237
|
-
*
|
|
238
|
-
*
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
* §4.
|
|
290
|
-
*
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
if (
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
//
|
|
326
|
-
|
|
327
|
-
//
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
//
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
//
|
|
336
|
-
//
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
const
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
*
|
|
425
|
-
*
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
return
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
*
|
|
496
|
-
*
|
|
497
|
-
*
|
|
498
|
-
*
|
|
499
|
-
*
|
|
500
|
-
*
|
|
501
|
-
*
|
|
502
|
-
*
|
|
503
|
-
*
|
|
504
|
-
*
|
|
505
|
-
*
|
|
506
|
-
*
|
|
507
|
-
*
|
|
508
|
-
|
|
509
|
-
|
|
510
|
-
|
|
511
|
-
|
|
512
|
-
|
|
513
|
-
|
|
514
|
-
|
|
515
|
-
const
|
|
516
|
-
const
|
|
517
|
-
|
|
518
|
-
const
|
|
519
|
-
|
|
520
|
-
|
|
521
|
-
const
|
|
522
|
-
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
const
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
|
|
547
|
-
|
|
548
|
-
|
|
549
|
-
|
|
550
|
-
|
|
551
|
-
|
|
552
|
-
|
|
553
|
-
|
|
554
|
-
|
|
555
|
-
|
|
556
|
-
|
|
557
|
-
|
|
558
|
-
|
|
559
|
-
|
|
560
|
-
|
|
561
|
-
}
|
|
562
|
-
|
|
563
|
-
|
|
564
|
-
|
|
565
|
-
const
|
|
566
|
-
|
|
567
|
-
|
|
568
|
-
|
|
569
|
-
|
|
570
|
-
const
|
|
571
|
-
|
|
572
|
-
|
|
573
|
-
|
|
574
|
-
|
|
575
|
-
const
|
|
576
|
-
|
|
577
|
-
|
|
578
|
-
|
|
579
|
-
|
|
580
|
-
|
|
581
|
-
|
|
582
|
-
|
|
583
|
-
|
|
584
|
-
|
|
585
|
-
|
|
586
|
-
|
|
587
|
-
|
|
588
|
-
|
|
589
|
-
|
|
590
|
-
|
|
591
|
-
|
|
592
|
-
|
|
593
|
-
|
|
594
|
-
|
|
595
|
-
|
|
596
|
-
|
|
597
|
-
|
|
598
|
-
|
|
599
|
-
|
|
600
|
-
|
|
601
|
-
|
|
602
|
-
|
|
603
|
-
|
|
604
|
-
|
|
605
|
-
|
|
606
|
-
|
|
607
|
-
|
|
608
|
-
|
|
609
|
-
|
|
610
|
-
|
|
611
|
-
|
|
612
|
-
|
|
613
|
-
|
|
614
|
-
|
|
615
|
-
|
|
616
|
-
|
|
617
|
-
|
|
618
|
-
|
|
619
|
-
|
|
620
|
-
|
|
621
|
-
|
|
622
|
-
|
|
623
|
-
|
|
624
|
-
|
|
625
|
-
|
|
626
|
-
|
|
627
|
-
|
|
628
|
-
|
|
629
|
-
|
|
630
|
-
|
|
631
|
-
const
|
|
632
|
-
const
|
|
633
|
-
|
|
634
|
-
|
|
635
|
-
|
|
636
|
-
|
|
637
|
-
|
|
638
|
-
|
|
639
|
-
|
|
640
|
-
|
|
641
|
-
|
|
642
|
-
|
|
643
|
-
|
|
644
|
-
|
|
645
|
-
|
|
646
|
-
|
|
647
|
-
}
|
|
648
|
-
|
|
649
|
-
|
|
650
|
-
|
|
651
|
-
|
|
652
|
-
|
|
653
|
-
|
|
654
|
-
|
|
655
|
-
|
|
656
|
-
|
|
657
|
-
|
|
658
|
-
|
|
659
|
-
|
|
660
|
-
|
|
661
|
-
|
|
662
|
-
|
|
663
|
-
.
|
|
664
|
-
|
|
665
|
-
|
|
666
|
-
|
|
667
|
-
|
|
668
|
-
|
|
669
|
-
|
|
670
|
-
|
|
671
|
-
|
|
672
|
-
|
|
673
|
-
|
|
674
|
-
|
|
675
|
-
|
|
676
|
-
|
|
677
|
-
|
|
678
|
-
|
|
679
|
-
|
|
680
|
-
|
|
681
|
-
|
|
682
|
-
|
|
683
|
-
|
|
684
|
-
|
|
685
|
-
|
|
686
|
-
|
|
687
|
-
|
|
688
|
-
|
|
689
|
-
*
|
|
690
|
-
*
|
|
691
|
-
*
|
|
692
|
-
*
|
|
693
|
-
*
|
|
694
|
-
*
|
|
695
|
-
*
|
|
696
|
-
*
|
|
697
|
-
|
|
698
|
-
|
|
699
|
-
|
|
700
|
-
|
|
701
|
-
|
|
702
|
-
|
|
703
|
-
|
|
704
|
-
|
|
705
|
-
|
|
706
|
-
|
|
707
|
-
|
|
708
|
-
|
|
709
|
-
|
|
710
|
-
const
|
|
711
|
-
const
|
|
712
|
-
|
|
713
|
-
const
|
|
714
|
-
|
|
715
|
-
|
|
716
|
-
.
|
|
717
|
-
.
|
|
718
|
-
|
|
719
|
-
|
|
720
|
-
|
|
721
|
-
|
|
722
|
-
const
|
|
723
|
-
|
|
724
|
-
|
|
725
|
-
|
|
726
|
-
|
|
727
|
-
|
|
728
|
-
|
|
729
|
-
|
|
730
|
-
|
|
731
|
-
|
|
732
|
-
|
|
733
|
-
|
|
734
|
-
|
|
735
|
-
|
|
736
|
-
|
|
737
|
-
|
|
738
|
-
|
|
739
|
-
|
|
740
|
-
|
|
741
|
-
|
|
742
|
-
|
|
743
|
-
|
|
744
|
-
|
|
745
|
-
|
|
746
|
-
|
|
747
|
-
|
|
748
|
-
|
|
749
|
-
|
|
750
|
-
|
|
751
|
-
|
|
752
|
-
|
|
753
|
-
|
|
754
|
-
|
|
755
|
-
|
|
756
|
-
|
|
757
|
-
|
|
758
|
-
|
|
759
|
-
//
|
|
760
|
-
|
|
761
|
-
|
|
762
|
-
|
|
763
|
-
|
|
764
|
-
|
|
765
|
-
|
|
766
|
-
|
|
767
|
-
|
|
768
|
-
|
|
769
|
-
|
|
770
|
-
|
|
771
|
-
|
|
772
|
-
|
|
773
|
-
|
|
774
|
-
|
|
775
|
-
|
|
776
|
-
|
|
777
|
-
|
|
778
|
-
|
|
779
|
-
|
|
780
|
-
|
|
781
|
-
|
|
782
|
-
|
|
783
|
-
|
|
784
|
-
|
|
785
|
-
|
|
786
|
-
|
|
787
|
-
|
|
788
|
-
|
|
789
|
-
|
|
790
|
-
|
|
791
|
-
|
|
792
|
-
|
|
793
|
-
|
|
794
|
-
|
|
795
|
-
|
|
796
|
-
|
|
797
|
-
|
|
798
|
-
|
|
799
|
-
|
|
800
|
-
|
|
801
|
-
|
|
802
|
-
|
|
803
|
-
|
|
804
|
-
|
|
805
|
-
|
|
806
|
-
|
|
807
|
-
|
|
808
|
-
|
|
809
|
-
|
|
810
|
-
|
|
811
|
-
|
|
812
|
-
const
|
|
813
|
-
key
|
|
814
|
-
|
|
815
|
-
|
|
816
|
-
|
|
817
|
-
|
|
818
|
-
|
|
819
|
-
|
|
820
|
-
|
|
821
|
-
|
|
822
|
-
|
|
823
|
-
|
|
824
|
-
|
|
825
|
-
|
|
826
|
-
|
|
827
|
-
|
|
828
|
-
|
|
829
|
-
|
|
830
|
-
|
|
831
|
-
|
|
832
|
-
|
|
833
|
-
|
|
834
|
-
|
|
835
|
-
|
|
836
|
-
|
|
837
|
-
|
|
838
|
-
|
|
839
|
-
|
|
840
|
-
|
|
841
|
-
if (
|
|
842
|
-
|
|
843
|
-
|
|
844
|
-
|
|
845
|
-
|
|
846
|
-
|
|
847
|
-
|
|
848
|
-
|
|
849
|
-
|
|
850
|
-
|
|
851
|
-
|
|
852
|
-
|
|
853
|
-
|
|
854
|
-
|
|
855
|
-
|
|
856
|
-
|
|
857
|
-
|
|
858
|
-
|
|
859
|
-
|
|
860
|
-
|
|
861
|
-
|
|
862
|
-
|
|
863
|
-
|
|
864
|
-
|
|
865
|
-
|
|
866
|
-
|
|
867
|
-
|
|
868
|
-
|
|
869
|
-
|
|
870
|
-
|
|
871
|
-
|
|
872
|
-
|
|
873
|
-
|
|
874
|
-
|
|
875
|
-
|
|
876
|
-
|
|
877
|
-
|
|
878
|
-
|
|
879
|
-
|
|
880
|
-
|
|
881
|
-
|
|
882
|
-
|
|
883
|
-
|
|
884
|
-
|
|
885
|
-
|
|
886
|
-
|
|
887
|
-
|
|
888
|
-
|
|
889
|
-
|
|
890
|
-
|
|
891
|
-
|
|
892
|
-
|
|
893
|
-
|
|
894
|
-
|
|
895
|
-
|
|
896
|
-
|
|
897
|
-
|
|
898
|
-
|
|
899
|
-
|
|
900
|
-
|
|
901
|
-
|
|
902
|
-
|
|
903
|
-
|
|
904
|
-
|
|
905
|
-
|
|
906
|
-
|
|
907
|
-
|
|
908
|
-
|
|
909
|
-
|
|
910
|
-
|
|
911
|
-
|
|
912
|
-
|
|
913
|
-
|
|
914
|
-
|
|
915
|
-
|
|
916
|
-
|
|
917
|
-
|
|
918
|
-
|
|
919
|
-
|
|
920
|
-
|
|
921
|
-
|
|
922
|
-
|
|
923
|
-
|
|
924
|
-
|
|
925
|
-
|
|
926
|
-
|
|
927
|
-
|
|
928
|
-
|
|
929
|
-
|
|
930
|
-
|
|
931
|
-
|
|
932
|
-
|
|
933
|
-
//
|
|
934
|
-
|
|
935
|
-
|
|
936
|
-
|
|
937
|
-
|
|
938
|
-
|
|
939
|
-
|
|
940
|
-
|
|
941
|
-
|
|
942
|
-
|
|
943
|
-
|
|
944
|
-
const
|
|
945
|
-
|
|
946
|
-
|
|
947
|
-
|
|
948
|
-
|
|
949
|
-
|
|
950
|
-
|
|
951
|
-
|
|
952
|
-
|
|
953
|
-
|
|
954
|
-
|
|
955
|
-
|
|
956
|
-
|
|
957
|
-
|
|
958
|
-
|
|
959
|
-
|
|
960
|
-
|
|
961
|
-
|
|
962
|
-
|
|
963
|
-
|
|
964
|
-
|
|
965
|
-
|
|
966
|
-
|
|
967
|
-
|
|
968
|
-
const
|
|
969
|
-
|
|
970
|
-
|
|
971
|
-
|
|
972
|
-
|
|
973
|
-
|
|
974
|
-
|
|
975
|
-
|
|
976
|
-
|
|
977
|
-
|
|
978
|
-
|
|
979
|
-
|
|
980
|
-
|
|
981
|
-
}
|
|
982
|
-
|
|
983
|
-
|
|
984
|
-
|
|
985
|
-
|
|
986
|
-
|
|
987
|
-
|
|
988
|
-
|
|
989
|
-
|
|
990
|
-
|
|
991
|
-
|
|
992
|
-
|
|
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
|
+
}
|