dsh-memu-memory 1.4.1 → 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 -108
- package/CHANGELOG.md +169 -848
- 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 -72
- 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 -0
- package/docs/memory-semantics.md +271 -259
- package/docs/pending-work.md +44 -51
- package/docs/troubleshooting.md +909 -840
- 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 -9648
- 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 -1035
- 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 -4911
- 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 -0
- 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 -2518
- 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 -1066
- 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 -152
- 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 -455
- package/tests/client-export.test.mjs +521 -520
- package/tests/client-render.test.mjs +2008 -1727
- 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 -48
- 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 -415
- 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 -616
- 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 -0
- 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 -23
- 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 -221
- 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 -212
- 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 -414
- package/tests/windows-env.test.mjs +89 -89
- package/tests/worker-lifecycle.test.mjs +1521 -1429
|
@@ -1,311 +1,311 @@
|
|
|
1
|
-
// Nomination layer: local, zero-token term statistics used ONLY to rank a review
|
|
2
|
-
// queue. Nothing here decides that an entity exists or that an edge is written —
|
|
3
|
-
// statistical scores
|
|
4
|
-
|
|
5
|
-
import { AUTOLINK_POLICY_V3 } from './policy.js'
|
|
6
|
-
import { normalizeForIndex } from './normalize.js'
|
|
7
|
-
|
|
8
|
-
const CJK_RUN = /[\u3400-\u9fff\uf900-\ufaff]+/g
|
|
9
|
-
const LATIN_RUN = /[a-z0-9][a-z0-9._-]*/g
|
|
10
|
-
const AV_CAP = 24
|
|
11
|
-
|
|
12
|
-
// Characters that make a CJK string grammatical glue rather than a name.
|
|
13
|
-
const FUNCTION_CHARS = new Set('的了是和与也就都很又还你我他她它们这那哪什么吗呢吧啊呀哦嗯之其而且但却被让给对从向于为及或并着过得地有不想要会可能可以说去来'.split(''))
|
|
14
|
-
// Measure-word templates: 一条/两只/这个/那些… A name never starts with one.
|
|
15
|
-
const MEASURE_PREFIX = /^(一|两|三|几|每|这|那|半)?[条只把张个位次件场顿盘杯碗袋包串支根颗头匹群套双对份页篇段句声口]/
|
|
16
|
-
|
|
17
|
-
const QUOTED_SURFACE = /「([^」\n]+)」|『([^』\n]+)』|《([^》\n]+)》|“([^”\n]+)”|‘([^’\n]+)’|"([^"\n]+)"|'([^'\n]+)'/g
|
|
18
|
-
const INTRO_RE = /(?:名叫|名字(?:是|叫|为)?|称呼(?:是|为)?|自称|叫|\busername\b|\bnickname\b)[ \t]*:?[ \t]*/g
|
|
19
|
-
const SURFACE_RUN = /[\p{L}\p{N}_]+(?:[.-][\p{L}\p{N}_]+)*/gu
|
|
20
|
-
const START_SURFACE = new RegExp('^' + SURFACE_RUN.source, 'u')
|
|
21
|
-
const WHOLE_SURFACE = /^(?:[\u3400-\u9fff\uf900-\ufaff]+|[a-z0-9][a-z0-9._-]*)$/
|
|
22
|
-
|
|
23
|
-
/** Terms whose surface shape cannot be a name on its own (ranking hint only). */
|
|
24
|
-
export function looksGeneric(token) {
|
|
25
|
-
const text = String(token || '')
|
|
26
|
-
if (!text) return true
|
|
27
|
-
if ([...text].some(ch => FUNCTION_CHARS.has(ch))) return true
|
|
28
|
-
if (MEASURE_PREFIX.test(text) && text.length <= 3) return true
|
|
29
|
-
return false
|
|
30
|
-
}
|
|
31
|
-
|
|
32
|
-
function isLatinTerm(term) {
|
|
33
|
-
return /^[a-z0-9]/.test(term) && !/[\u3400-\u9fff\uf900-\ufaff]/.test(term)
|
|
34
|
-
}
|
|
35
|
-
|
|
36
|
-
// Keep weak statistics for the entire corpus, but give strong evidence only to
|
|
37
|
-
// an exact surface. Record CJK fragments even when the parent itself is longer
|
|
38
|
-
// than the statistical n-gram cap.
|
|
39
|
-
function collectSurface(value, evidence, fragments, policy) {
|
|
40
|
-
const surface = value.trim()
|
|
41
|
-
if (WHOLE_SURFACE.test(surface)) evidence.add(surface)
|
|
42
|
-
for (const run of surface.match(CJK_RUN) || []) {
|
|
43
|
-
for (let size = policy.ngramCjkMin; size <= Math.min(policy.ngramCjkMax, run.length); size += 1) {
|
|
44
|
-
for (let i = 0; i + size <= run.length; i += 1) {
|
|
45
|
-
const fragment = run.slice(i, i + size)
|
|
46
|
-
if (fragment !== surface) fragments.add(fragment)
|
|
47
|
-
}
|
|
48
|
-
}
|
|
49
|
-
}
|
|
50
|
-
}
|
|
51
|
-
|
|
52
|
-
function surfaceEvidence(docs, policy) {
|
|
53
|
-
const quoted = new Set()
|
|
54
|
-
const intro = new Set()
|
|
55
|
-
const fragments = new Set()
|
|
56
|
-
const fullRuns = new Set()
|
|
57
|
-
for (const { text } of docs) {
|
|
58
|
-
const source = String(text || '').normalize('NFKC').toLowerCase()
|
|
59
|
-
const quotesByStart = new Map()
|
|
60
|
-
for (const match of source.matchAll(QUOTED_SURFACE)) {
|
|
61
|
-
const value = match.slice(1).find(part => part !== undefined)
|
|
62
|
-
quotesByStart.set(match.index, value)
|
|
63
|
-
collectSurface(value, quoted, fragments, policy)
|
|
64
|
-
}
|
|
65
|
-
for (const match of source.matchAll(INTRO_RE)) {
|
|
66
|
-
const start = match.index + match[0].length
|
|
67
|
-
const value = quotesByStart.get(start) ?? source.slice(start).match(START_SURFACE)?.[0]
|
|
68
|
-
if (value) collectSurface(value, intro, fragments, policy)
|
|
69
|
-
}
|
|
70
|
-
for (const run of source.match(SURFACE_RUN) || []) fullRuns.add(run)
|
|
71
|
-
}
|
|
72
|
-
return { quoted, intro, fragments, fullRuns }
|
|
73
|
-
}
|
|
74
|
-
|
|
75
|
-
function llrFor(term, tf, unigram, ngramTotals) {
|
|
76
|
-
if (term.length < 2) return 0
|
|
77
|
-
const prefix = term.slice(0, -1)
|
|
78
|
-
const suffix = term.slice(1)
|
|
79
|
-
const countOf = (part) => (part.length === 1 ? (unigram.get(part) || 0) : (tf.get(part) || 0))
|
|
80
|
-
const a = tf.get(term) || 0
|
|
81
|
-
const b = Math.max(0, countOf(prefix) - a)
|
|
82
|
-
const c = Math.max(0, countOf(suffix) - a)
|
|
83
|
-
const total = Math.max(1, ngramTotals.get(term.length) || 0)
|
|
84
|
-
const d = Math.max(0, total - a - b - c)
|
|
85
|
-
const rows = [
|
|
86
|
-
[a, b, a + b],
|
|
87
|
-
[c, d, c + d],
|
|
88
|
-
]
|
|
89
|
-
const cols = [a + c, b + d, a + b + c + d]
|
|
90
|
-
let llr = 0
|
|
91
|
-
for (let i = 0; i < 2; i += 1) {
|
|
92
|
-
for (let j = 0; j < 2; j += 1) {
|
|
93
|
-
const observed = rows[i][j]
|
|
94
|
-
if (!observed) continue
|
|
95
|
-
const expected = (rows[i][2] * cols[j]) / Math.max(1, cols[2])
|
|
96
|
-
if (expected > 0) llr += observed * Math.log(observed / expected)
|
|
97
|
-
}
|
|
98
|
-
}
|
|
99
|
-
return 2 * llr
|
|
100
|
-
}
|
|
101
|
-
|
|
102
|
-
function pmiFor(term, tf, unigram, totalChars) {
|
|
103
|
-
if (!totalChars) return 0
|
|
104
|
-
const chars = [...term]
|
|
105
|
-
const termCount = tf.get(term) || 0
|
|
106
|
-
if (!termCount) return 0
|
|
107
|
-
let product = 1
|
|
108
|
-
for (const ch of chars) product *= (unigram.get(ch) || 0) / totalChars
|
|
109
|
-
if (product <= 0) return 0
|
|
110
|
-
return Math.log2((termCount / totalChars) / product)
|
|
111
|
-
}
|
|
112
|
-
|
|
113
|
-
/**
|
|
114
|
-
* Single pass over title+content per document. Returns Map(term -> statistics):
|
|
115
|
-
* tf/df/titleDf, boundary variety, cohesion/freedom, PMI, LLR and the surface
|
|
116
|
-
* shape bits (latin, quoted/intro membership is applied during ranking).
|
|
117
|
-
*/
|
|
118
|
-
export function buildTermStats(entries, policy = AUTOLINK_POLICY_V3) {
|
|
119
|
-
const tf = new Map()
|
|
120
|
-
const df = new Map()
|
|
121
|
-
const titleDf = new Map()
|
|
122
|
-
const unigram = new Map()
|
|
123
|
-
const leftSets = new Map()
|
|
124
|
-
const rightSets = new Map()
|
|
125
|
-
const ngramTotals = new Map()
|
|
126
|
-
let totalChars = 0
|
|
127
|
-
|
|
128
|
-
const bump = (map, key, by = 1) => map.set(key, (map.get(key) || 0) + by)
|
|
129
|
-
const addNeighbour = (map, key, value) => {
|
|
130
|
-
let set = map.get(key)
|
|
131
|
-
if (!set) { set = new Set(); map.set(key, set) }
|
|
132
|
-
if (set.size < AV_CAP) set.add(value)
|
|
133
|
-
}
|
|
134
|
-
|
|
135
|
-
for (const { text, title } of entries) {
|
|
136
|
-
const normalized = String(text || '').normalize('NFKC').toLowerCase()
|
|
137
|
-
const perDoc = new Set()
|
|
138
|
-
for (const match of normalized.matchAll(CJK_RUN)) {
|
|
139
|
-
const run = match[0]
|
|
140
|
-
const start = match.index || 0
|
|
141
|
-
totalChars += [...run].length
|
|
142
|
-
for (const ch of run) bump(unigram, ch)
|
|
143
|
-
for (let size = policy.ngramCjkMin; size <= Math.min(policy.ngramCjkMax, run.length); size += 1) {
|
|
144
|
-
for (let i = 0; i + size <= run.length; i += 1) {
|
|
145
|
-
const term = run.slice(i, i + size)
|
|
146
|
-
bump(tf, term)
|
|
147
|
-
bump(ngramTotals, size)
|
|
148
|
-
perDoc.add(term)
|
|
149
|
-
const offset = Math.max(0, start) + i
|
|
150
|
-
addNeighbour(leftSets, term, offset > 0 ? normalized[offset - 1] : '^')
|
|
151
|
-
addNeighbour(rightSets, term, offset + size < normalized.length ? normalized[offset + size] : '$')
|
|
152
|
-
}
|
|
153
|
-
}
|
|
154
|
-
}
|
|
155
|
-
for (const token of normalized.match(LATIN_RUN) || []) {
|
|
156
|
-
if (token.length < policy.latinMin || token.length > policy.latinMax || /^\d+$/.test(token)) continue
|
|
157
|
-
bump(tf, token)
|
|
158
|
-
bump(ngramTotals, token.length)
|
|
159
|
-
perDoc.add(token)
|
|
160
|
-
}
|
|
161
|
-
for (const term of perDoc) bump(df, term)
|
|
162
|
-
const normalizedTitle = String(title || '').normalize('NFKC').toLowerCase()
|
|
163
|
-
if (normalizedTitle) {
|
|
164
|
-
const titleTerms = new Set()
|
|
165
|
-
for (const run of normalizedTitle.match(CJK_RUN) || []) {
|
|
166
|
-
for (let size = policy.ngramCjkMin; size <= Math.min(policy.ngramCjkMax, run.length); size += 1) {
|
|
167
|
-
for (let i = 0; i + size <= run.length; i += 1) titleTerms.add(run.slice(i, i + size))
|
|
168
|
-
}
|
|
169
|
-
}
|
|
170
|
-
for (const token of normalizedTitle.match(LATIN_RUN) || []) {
|
|
171
|
-
if (token.length >= policy.latinMin && token.length <= policy.latinMax) titleTerms.add(token)
|
|
172
|
-
}
|
|
173
|
-
for (const term of titleTerms) bump(titleDf, term)
|
|
174
|
-
}
|
|
175
|
-
}
|
|
176
|
-
|
|
177
|
-
const stats = new Map()
|
|
178
|
-
for (const [term, count] of tf) {
|
|
179
|
-
if (/^\d+$/.test(term)) continue
|
|
180
|
-
const latin = isLatinTerm(term)
|
|
181
|
-
const leftPart = term.slice(0, -1)
|
|
182
|
-
const rightPart = term.slice(1)
|
|
183
|
-
const base = (part) => (part.length === 1 ? (unigram.get(part) || 1) : (tf.get(part) || 1))
|
|
184
|
-
const cohesion = latin ? 1 : count / Math.max(1, Math.min(base(leftPart), base(rightPart)))
|
|
185
|
-
const avLeft = latin ? Math.min(3, df.get(term) || 1) : (leftSets.get(term)?.size || 0)
|
|
186
|
-
const avRight = latin ? Math.min(3, df.get(term) || 1) : (rightSets.get(term)?.size || 0)
|
|
187
|
-
stats.set(term, {
|
|
188
|
-
term,
|
|
189
|
-
tf: count,
|
|
190
|
-
df: df.get(term) || 0,
|
|
191
|
-
titleDf: titleDf.get(term) || 0,
|
|
192
|
-
cohesion,
|
|
193
|
-
avLeft,
|
|
194
|
-
avRight,
|
|
195
|
-
freedom: Math.min(avLeft, avRight),
|
|
196
|
-
pmi: latin ? 0 : pmiFor(term, tf, unigram, totalChars),
|
|
197
|
-
llr: latin ? 0 : llrFor(term, tf, unigram, ngramTotals),
|
|
198
|
-
latin,
|
|
199
|
-
})
|
|
200
|
-
}
|
|
201
|
-
return stats
|
|
202
|
-
}
|
|
203
|
-
|
|
204
|
-
function scoreOf(stat, { size, quoted, mixed, intro, titleBoost, lexiconTier1, lexiconModel, policy }) {
|
|
205
|
-
const rarity = 1 - Math.min(1, stat.df / Math.max(4, size * 0.25))
|
|
206
|
-
const boundary = Math.min(stat.avLeft, stat.avRight)
|
|
207
|
-
const pmi = Math.max(0, Math.min(12, stat.pmi)) / 12
|
|
208
|
-
const llr = Math.max(0, Math.min(1, Math.log10(1 + stat.llr) / 6))
|
|
209
|
-
const titleFocus = stat.titleDf >= policy.minTitleDf ? Math.min(1, stat.titleDf / 3) : 0
|
|
210
|
-
return boundary * 0.35
|
|
211
|
-
+ Math.min(stat.cohesion, 3) * 0.35
|
|
212
|
-
+ rarity * 0.8
|
|
213
|
-
+ pmi * 0.5
|
|
214
|
-
+ llr * 0.5
|
|
215
|
-
+ titleFocus * 0.6
|
|
216
|
-
+ (quoted ? 2.5 : 0)
|
|
217
|
-
+ (mixed ? 2.0 : 0)
|
|
218
|
-
+ (intro ? 2.0 : 0)
|
|
219
|
-
+ (titleBoost ? 1.2 : 0)
|
|
220
|
-
+ (lexiconTier1 ? 2.5 : 0)
|
|
221
|
-
+ (lexiconModel ? 0.8 : 0)
|
|
222
|
-
}
|
|
223
|
-
|
|
224
|
-
/**
|
|
225
|
-
* Two review tiers. Tier 1 carries surface evidence (quote / identifier /
|
|
226
|
-
* name-intro / user lexicon) and is cheap to confirm; tier 2 is statistical
|
|
227
|
-
* only. Scores order the queue; they never gate an edge write.
|
|
228
|
-
*/
|
|
229
|
-
export function rankCandidates(entries, stats, { policy = AUTOLINK_POLICY_V3, lexiconUser = new Set(), lexiconModel = new Set() } = {}) {
|
|
230
|
-
const docs = entries.map(({ text, title }) => ({ text: `${title || ''}\n${text || ''}` }))
|
|
231
|
-
const { quoted, intro, fragments, fullRuns } = surfaceEvidence(docs, policy)
|
|
232
|
-
const size = Math.max(1, entries.length)
|
|
233
|
-
const tier1 = []
|
|
234
|
-
const tier2 = []
|
|
235
|
-
const rows = []
|
|
236
|
-
for (const stat of stats.values()) {
|
|
237
|
-
const term = stat.term
|
|
238
|
-
if (stat.df < policy.minDf) continue
|
|
239
|
-
if (stat.df > Math.max(policy.minDf, Math.floor(size * policy.maxDfRatio))) continue
|
|
240
|
-
if (looksGeneric(term)) continue
|
|
241
|
-
// Boundary variety
|
|
242
|
-
// name that only ever appears at a title's start/end still belongs in the queue.
|
|
243
|
-
if (/^\d{4}[-/年.]\d{1,2}/.test(term)) continue
|
|
244
|
-
if ((term.match(/\d/g) || []).length >= Math.ceil(term.length / 2)) continue
|
|
245
|
-
const normalized = normalizeForIndex(term)
|
|
246
|
-
const isQuoted = quoted.has(term)
|
|
247
|
-
const isMixed = /[a-z].*\d|\d.*[a-z]/i.test(term)
|
|
248
|
-
const isIntro = intro.has(term)
|
|
249
|
-
const lexiconTier1 = lexiconUser.has(normalized)
|
|
250
|
-
const lexiconModelHit = !lexiconTier1 && lexiconModel.has(normalized)
|
|
251
|
-
if (fragments.has(term) && !isQuoted && !isIntro && !lexiconTier1 && !fullRuns.has(term)) continue
|
|
252
|
-
const titleBoost = stat.titleDf >= policy.minTitleDf
|
|
253
|
-
const row = {
|
|
254
|
-
term,
|
|
255
|
-
score: scoreOf(stat, { size, quoted: isQuoted, mixed: isMixed, intro: isIntro, titleBoost, lexiconTier1, lexiconModel: lexiconModelHit, policy }),
|
|
256
|
-
df: stat.df,
|
|
257
|
-
tf: stat.tf,
|
|
258
|
-
titleDf: stat.titleDf,
|
|
259
|
-
cohesion: Number(stat.cohesion.toFixed(2)),
|
|
260
|
-
avLeft: stat.avLeft,
|
|
261
|
-
avRight: stat.avRight,
|
|
262
|
-
freedom: stat.freedom,
|
|
263
|
-
pmi: Number(stat.pmi.toFixed(2)),
|
|
264
|
-
llr: Number(stat.llr.toFixed(2)),
|
|
265
|
-
quoted: isQuoted,
|
|
266
|
-
mixed: isMixed,
|
|
267
|
-
intro: isIntro,
|
|
268
|
-
lexicon: lexiconTier1 ? 'user' : (lexiconModelHit ? 'model-proposal' : null),
|
|
269
|
-
}
|
|
270
|
-
rows.push({ row, evidenced: isQuoted || isMixed || isIntro || lexiconTier1 })
|
|
271
|
-
}
|
|
272
|
-
// A sliding-window fragment is only noise while the longer surface it lives in
|
|
273
|
-
// is at least as well attested: `南宫晚` and `宫晚晴` carry exactly the documents
|
|
274
|
-
// `南宫晚晴` does, so the 4-char form wins and the two windows never reach the
|
|
275
|
-
// queue. A short name that also stands on its own (`星港`, whose 4-char neighbours
|
|
276
|
-
// appear in a single memory) keeps the higher df and survives. Terms with direct
|
|
277
|
-
// surface evidence (quote / identifier / name-intro / user lexicon) are never
|
|
278
|
-
// dropped here — that is evidence, not a statistic.
|
|
279
|
-
// Indexed by fragment instead of compared pairwise: a big library has tens of
|
|
280
|
-
// thousands of candidate n-grams and O(n²) `includes` does not belong in a sweep.
|
|
281
|
-
const statistical = rows.filter((item) => !item.evidenced)
|
|
282
|
-
const longestAttested = new Map()
|
|
283
|
-
for (const { row } of statistical) {
|
|
284
|
-
const chars = [...row.term]
|
|
285
|
-
for (let start = 0; start < chars.length; start += 1) {
|
|
286
|
-
for (let size = 1; start + size <= chars.length; size += 1) {
|
|
287
|
-
if (start === 0 && size === chars.length) continue // only proper substrings count as fragments
|
|
288
|
-
const fragment = chars.slice(start, start + size).join('')
|
|
289
|
-
const known = longestAttested.get(fragment)
|
|
290
|
-
if (known === undefined || row.df > known) longestAttested.set(fragment, row.df)
|
|
291
|
-
}
|
|
292
|
-
}
|
|
293
|
-
}
|
|
294
|
-
const subsumed = new Set(statistical
|
|
295
|
-
.filter(({ row }) => (longestAttested.get(row.term) || 0) >= row.df)
|
|
296
|
-
.map(({ row }) => row.term))
|
|
297
|
-
for (const { row, evidenced } of rows) {
|
|
298
|
-
if (subsumed.has(row.term)) continue
|
|
299
|
-
if (evidenced) tier1.push(row)
|
|
300
|
-
else tier2.push(row)
|
|
301
|
-
}
|
|
302
|
-
const byScore = (a, b) => b.score - a.score || a.term.localeCompare(b.term)
|
|
303
|
-
tier1.sort(byScore)
|
|
304
|
-
tier2.sort(byScore)
|
|
305
|
-
return {
|
|
306
|
-
tier1: tier1.slice(0, policy.tier1Max),
|
|
307
|
-
tier2: tier2.slice(0, policy.tier2Max),
|
|
308
|
-
}
|
|
309
|
-
}
|
|
310
|
-
|
|
311
|
-
export default { buildTermStats, rankCandidates, looksGeneric }
|
|
1
|
+
// Nomination layer: local, zero-token term statistics used ONLY to rank a review
|
|
2
|
+
// queue. Nothing here decides that an entity exists or that an edge is written —
|
|
3
|
+
// statistical scores remain within the candidate list.
|
|
4
|
+
|
|
5
|
+
import { AUTOLINK_POLICY_V3 } from './policy.js'
|
|
6
|
+
import { normalizeForIndex } from './normalize.js'
|
|
7
|
+
|
|
8
|
+
const CJK_RUN = /[\u3400-\u9fff\uf900-\ufaff]+/g
|
|
9
|
+
const LATIN_RUN = /[a-z0-9][a-z0-9._-]*/g
|
|
10
|
+
const AV_CAP = 24
|
|
11
|
+
|
|
12
|
+
// Characters that make a CJK string grammatical glue rather than a name.
|
|
13
|
+
const FUNCTION_CHARS = new Set('的了是和与也就都很又还你我他她它们这那哪什么吗呢吧啊呀哦嗯之其而且但却被让给对从向于为及或并着过得地有不想要会可能可以说去来'.split(''))
|
|
14
|
+
// Measure-word templates: 一条/两只/这个/那些… A name never starts with one.
|
|
15
|
+
const MEASURE_PREFIX = /^(一|两|三|几|每|这|那|半)?[条只把张个位次件场顿盘杯碗袋包串支根颗头匹群套双对份页篇段句声口]/
|
|
16
|
+
|
|
17
|
+
const QUOTED_SURFACE = /「([^」\n]+)」|『([^』\n]+)』|《([^》\n]+)》|“([^”\n]+)”|‘([^’\n]+)’|"([^"\n]+)"|'([^'\n]+)'/g
|
|
18
|
+
const INTRO_RE = /(?:名叫|名字(?:是|叫|为)?|称呼(?:是|为)?|自称|叫|\busername\b|\bnickname\b)[ \t]*:?[ \t]*/g
|
|
19
|
+
const SURFACE_RUN = /[\p{L}\p{N}_]+(?:[.-][\p{L}\p{N}_]+)*/gu
|
|
20
|
+
const START_SURFACE = new RegExp('^' + SURFACE_RUN.source, 'u')
|
|
21
|
+
const WHOLE_SURFACE = /^(?:[\u3400-\u9fff\uf900-\ufaff]+|[a-z0-9][a-z0-9._-]*)$/
|
|
22
|
+
|
|
23
|
+
/** Terms whose surface shape cannot be a name on its own (ranking hint only). */
|
|
24
|
+
export function looksGeneric(token) {
|
|
25
|
+
const text = String(token || '')
|
|
26
|
+
if (!text) return true
|
|
27
|
+
if ([...text].some(ch => FUNCTION_CHARS.has(ch))) return true
|
|
28
|
+
if (MEASURE_PREFIX.test(text) && text.length <= 3) return true
|
|
29
|
+
return false
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
function isLatinTerm(term) {
|
|
33
|
+
return /^[a-z0-9]/.test(term) && !/[\u3400-\u9fff\uf900-\ufaff]/.test(term)
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
// Keep weak statistics for the entire corpus, but give strong evidence only to
|
|
37
|
+
// an exact surface. Record CJK fragments even when the parent itself is longer
|
|
38
|
+
// than the statistical n-gram cap.
|
|
39
|
+
function collectSurface(value, evidence, fragments, policy) {
|
|
40
|
+
const surface = value.trim()
|
|
41
|
+
if (WHOLE_SURFACE.test(surface)) evidence.add(surface)
|
|
42
|
+
for (const run of surface.match(CJK_RUN) || []) {
|
|
43
|
+
for (let size = policy.ngramCjkMin; size <= Math.min(policy.ngramCjkMax, run.length); size += 1) {
|
|
44
|
+
for (let i = 0; i + size <= run.length; i += 1) {
|
|
45
|
+
const fragment = run.slice(i, i + size)
|
|
46
|
+
if (fragment !== surface) fragments.add(fragment)
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
function surfaceEvidence(docs, policy) {
|
|
53
|
+
const quoted = new Set()
|
|
54
|
+
const intro = new Set()
|
|
55
|
+
const fragments = new Set()
|
|
56
|
+
const fullRuns = new Set()
|
|
57
|
+
for (const { text } of docs) {
|
|
58
|
+
const source = String(text || '').normalize('NFKC').toLowerCase()
|
|
59
|
+
const quotesByStart = new Map()
|
|
60
|
+
for (const match of source.matchAll(QUOTED_SURFACE)) {
|
|
61
|
+
const value = match.slice(1).find(part => part !== undefined)
|
|
62
|
+
quotesByStart.set(match.index, value)
|
|
63
|
+
collectSurface(value, quoted, fragments, policy)
|
|
64
|
+
}
|
|
65
|
+
for (const match of source.matchAll(INTRO_RE)) {
|
|
66
|
+
const start = match.index + match[0].length
|
|
67
|
+
const value = quotesByStart.get(start) ?? source.slice(start).match(START_SURFACE)?.[0]
|
|
68
|
+
if (value) collectSurface(value, intro, fragments, policy)
|
|
69
|
+
}
|
|
70
|
+
for (const run of source.match(SURFACE_RUN) || []) fullRuns.add(run)
|
|
71
|
+
}
|
|
72
|
+
return { quoted, intro, fragments, fullRuns }
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
function llrFor(term, tf, unigram, ngramTotals) {
|
|
76
|
+
if (term.length < 2) return 0
|
|
77
|
+
const prefix = term.slice(0, -1)
|
|
78
|
+
const suffix = term.slice(1)
|
|
79
|
+
const countOf = (part) => (part.length === 1 ? (unigram.get(part) || 0) : (tf.get(part) || 0))
|
|
80
|
+
const a = tf.get(term) || 0
|
|
81
|
+
const b = Math.max(0, countOf(prefix) - a)
|
|
82
|
+
const c = Math.max(0, countOf(suffix) - a)
|
|
83
|
+
const total = Math.max(1, ngramTotals.get(term.length) || 0)
|
|
84
|
+
const d = Math.max(0, total - a - b - c)
|
|
85
|
+
const rows = [
|
|
86
|
+
[a, b, a + b],
|
|
87
|
+
[c, d, c + d],
|
|
88
|
+
]
|
|
89
|
+
const cols = [a + c, b + d, a + b + c + d]
|
|
90
|
+
let llr = 0
|
|
91
|
+
for (let i = 0; i < 2; i += 1) {
|
|
92
|
+
for (let j = 0; j < 2; j += 1) {
|
|
93
|
+
const observed = rows[i][j]
|
|
94
|
+
if (!observed) continue
|
|
95
|
+
const expected = (rows[i][2] * cols[j]) / Math.max(1, cols[2])
|
|
96
|
+
if (expected > 0) llr += observed * Math.log(observed / expected)
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
return 2 * llr
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
function pmiFor(term, tf, unigram, totalChars) {
|
|
103
|
+
if (!totalChars) return 0
|
|
104
|
+
const chars = [...term]
|
|
105
|
+
const termCount = tf.get(term) || 0
|
|
106
|
+
if (!termCount) return 0
|
|
107
|
+
let product = 1
|
|
108
|
+
for (const ch of chars) product *= (unigram.get(ch) || 0) / totalChars
|
|
109
|
+
if (product <= 0) return 0
|
|
110
|
+
return Math.log2((termCount / totalChars) / product)
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/**
|
|
114
|
+
* Single pass over title+content per document. Returns Map(term -> statistics):
|
|
115
|
+
* tf/df/titleDf, boundary variety, cohesion/freedom, PMI, LLR and the surface
|
|
116
|
+
* shape bits (latin, quoted/intro membership is applied during ranking).
|
|
117
|
+
*/
|
|
118
|
+
export function buildTermStats(entries, policy = AUTOLINK_POLICY_V3) {
|
|
119
|
+
const tf = new Map()
|
|
120
|
+
const df = new Map()
|
|
121
|
+
const titleDf = new Map()
|
|
122
|
+
const unigram = new Map()
|
|
123
|
+
const leftSets = new Map()
|
|
124
|
+
const rightSets = new Map()
|
|
125
|
+
const ngramTotals = new Map()
|
|
126
|
+
let totalChars = 0
|
|
127
|
+
|
|
128
|
+
const bump = (map, key, by = 1) => map.set(key, (map.get(key) || 0) + by)
|
|
129
|
+
const addNeighbour = (map, key, value) => {
|
|
130
|
+
let set = map.get(key)
|
|
131
|
+
if (!set) { set = new Set(); map.set(key, set) }
|
|
132
|
+
if (set.size < AV_CAP) set.add(value)
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
for (const { text, title } of entries) {
|
|
136
|
+
const normalized = String(text || '').normalize('NFKC').toLowerCase()
|
|
137
|
+
const perDoc = new Set()
|
|
138
|
+
for (const match of normalized.matchAll(CJK_RUN)) {
|
|
139
|
+
const run = match[0]
|
|
140
|
+
const start = match.index || 0
|
|
141
|
+
totalChars += [...run].length
|
|
142
|
+
for (const ch of run) bump(unigram, ch)
|
|
143
|
+
for (let size = policy.ngramCjkMin; size <= Math.min(policy.ngramCjkMax, run.length); size += 1) {
|
|
144
|
+
for (let i = 0; i + size <= run.length; i += 1) {
|
|
145
|
+
const term = run.slice(i, i + size)
|
|
146
|
+
bump(tf, term)
|
|
147
|
+
bump(ngramTotals, size)
|
|
148
|
+
perDoc.add(term)
|
|
149
|
+
const offset = Math.max(0, start) + i
|
|
150
|
+
addNeighbour(leftSets, term, offset > 0 ? normalized[offset - 1] : '^')
|
|
151
|
+
addNeighbour(rightSets, term, offset + size < normalized.length ? normalized[offset + size] : '$')
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
for (const token of normalized.match(LATIN_RUN) || []) {
|
|
156
|
+
if (token.length < policy.latinMin || token.length > policy.latinMax || /^\d+$/.test(token)) continue
|
|
157
|
+
bump(tf, token)
|
|
158
|
+
bump(ngramTotals, token.length)
|
|
159
|
+
perDoc.add(token)
|
|
160
|
+
}
|
|
161
|
+
for (const term of perDoc) bump(df, term)
|
|
162
|
+
const normalizedTitle = String(title || '').normalize('NFKC').toLowerCase()
|
|
163
|
+
if (normalizedTitle) {
|
|
164
|
+
const titleTerms = new Set()
|
|
165
|
+
for (const run of normalizedTitle.match(CJK_RUN) || []) {
|
|
166
|
+
for (let size = policy.ngramCjkMin; size <= Math.min(policy.ngramCjkMax, run.length); size += 1) {
|
|
167
|
+
for (let i = 0; i + size <= run.length; i += 1) titleTerms.add(run.slice(i, i + size))
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
for (const token of normalizedTitle.match(LATIN_RUN) || []) {
|
|
171
|
+
if (token.length >= policy.latinMin && token.length <= policy.latinMax) titleTerms.add(token)
|
|
172
|
+
}
|
|
173
|
+
for (const term of titleTerms) bump(titleDf, term)
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
const stats = new Map()
|
|
178
|
+
for (const [term, count] of tf) {
|
|
179
|
+
if (/^\d+$/.test(term)) continue
|
|
180
|
+
const latin = isLatinTerm(term)
|
|
181
|
+
const leftPart = term.slice(0, -1)
|
|
182
|
+
const rightPart = term.slice(1)
|
|
183
|
+
const base = (part) => (part.length === 1 ? (unigram.get(part) || 1) : (tf.get(part) || 1))
|
|
184
|
+
const cohesion = latin ? 1 : count / Math.max(1, Math.min(base(leftPart), base(rightPart)))
|
|
185
|
+
const avLeft = latin ? Math.min(3, df.get(term) || 1) : (leftSets.get(term)?.size || 0)
|
|
186
|
+
const avRight = latin ? Math.min(3, df.get(term) || 1) : (rightSets.get(term)?.size || 0)
|
|
187
|
+
stats.set(term, {
|
|
188
|
+
term,
|
|
189
|
+
tf: count,
|
|
190
|
+
df: df.get(term) || 0,
|
|
191
|
+
titleDf: titleDf.get(term) || 0,
|
|
192
|
+
cohesion,
|
|
193
|
+
avLeft,
|
|
194
|
+
avRight,
|
|
195
|
+
freedom: Math.min(avLeft, avRight),
|
|
196
|
+
pmi: latin ? 0 : pmiFor(term, tf, unigram, totalChars),
|
|
197
|
+
llr: latin ? 0 : llrFor(term, tf, unigram, ngramTotals),
|
|
198
|
+
latin,
|
|
199
|
+
})
|
|
200
|
+
}
|
|
201
|
+
return stats
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
function scoreOf(stat, { size, quoted, mixed, intro, titleBoost, lexiconTier1, lexiconModel, policy }) {
|
|
205
|
+
const rarity = 1 - Math.min(1, stat.df / Math.max(4, size * 0.25))
|
|
206
|
+
const boundary = Math.min(stat.avLeft, stat.avRight)
|
|
207
|
+
const pmi = Math.max(0, Math.min(12, stat.pmi)) / 12
|
|
208
|
+
const llr = Math.max(0, Math.min(1, Math.log10(1 + stat.llr) / 6))
|
|
209
|
+
const titleFocus = stat.titleDf >= policy.minTitleDf ? Math.min(1, stat.titleDf / 3) : 0
|
|
210
|
+
return boundary * 0.35
|
|
211
|
+
+ Math.min(stat.cohesion, 3) * 0.35
|
|
212
|
+
+ rarity * 0.8
|
|
213
|
+
+ pmi * 0.5
|
|
214
|
+
+ llr * 0.5
|
|
215
|
+
+ titleFocus * 0.6
|
|
216
|
+
+ (quoted ? 2.5 : 0)
|
|
217
|
+
+ (mixed ? 2.0 : 0)
|
|
218
|
+
+ (intro ? 2.0 : 0)
|
|
219
|
+
+ (titleBoost ? 1.2 : 0)
|
|
220
|
+
+ (lexiconTier1 ? 2.5 : 0)
|
|
221
|
+
+ (lexiconModel ? 0.8 : 0)
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
/**
|
|
225
|
+
* Two review tiers. Tier 1 carries surface evidence (quote / identifier /
|
|
226
|
+
* name-intro / user lexicon) and is cheap to confirm; tier 2 is statistical
|
|
227
|
+
* only. Scores order the queue; they never gate an edge write.
|
|
228
|
+
*/
|
|
229
|
+
export function rankCandidates(entries, stats, { policy = AUTOLINK_POLICY_V3, lexiconUser = new Set(), lexiconModel = new Set() } = {}) {
|
|
230
|
+
const docs = entries.map(({ text, title }) => ({ text: `${title || ''}\n${text || ''}` }))
|
|
231
|
+
const { quoted, intro, fragments, fullRuns } = surfaceEvidence(docs, policy)
|
|
232
|
+
const size = Math.max(1, entries.length)
|
|
233
|
+
const tier1 = []
|
|
234
|
+
const tier2 = []
|
|
235
|
+
const rows = []
|
|
236
|
+
for (const stat of stats.values()) {
|
|
237
|
+
const term = stat.term
|
|
238
|
+
if (stat.df < policy.minDf) continue
|
|
239
|
+
if (stat.df > Math.max(policy.minDf, Math.floor(size * policy.maxDfRatio))) continue
|
|
240
|
+
if (looksGeneric(term)) continue
|
|
241
|
+
// Boundary variety affects ranking but does not exclude a real
|
|
242
|
+
// name that only ever appears at a title's start/end still belongs in the queue.
|
|
243
|
+
if (/^\d{4}[-/年.]\d{1,2}/.test(term)) continue
|
|
244
|
+
if ((term.match(/\d/g) || []).length >= Math.ceil(term.length / 2)) continue
|
|
245
|
+
const normalized = normalizeForIndex(term)
|
|
246
|
+
const isQuoted = quoted.has(term)
|
|
247
|
+
const isMixed = /[a-z].*\d|\d.*[a-z]/i.test(term)
|
|
248
|
+
const isIntro = intro.has(term)
|
|
249
|
+
const lexiconTier1 = lexiconUser.has(normalized)
|
|
250
|
+
const lexiconModelHit = !lexiconTier1 && lexiconModel.has(normalized)
|
|
251
|
+
if (fragments.has(term) && !isQuoted && !isIntro && !lexiconTier1 && !fullRuns.has(term)) continue
|
|
252
|
+
const titleBoost = stat.titleDf >= policy.minTitleDf
|
|
253
|
+
const row = {
|
|
254
|
+
term,
|
|
255
|
+
score: scoreOf(stat, { size, quoted: isQuoted, mixed: isMixed, intro: isIntro, titleBoost, lexiconTier1, lexiconModel: lexiconModelHit, policy }),
|
|
256
|
+
df: stat.df,
|
|
257
|
+
tf: stat.tf,
|
|
258
|
+
titleDf: stat.titleDf,
|
|
259
|
+
cohesion: Number(stat.cohesion.toFixed(2)),
|
|
260
|
+
avLeft: stat.avLeft,
|
|
261
|
+
avRight: stat.avRight,
|
|
262
|
+
freedom: stat.freedom,
|
|
263
|
+
pmi: Number(stat.pmi.toFixed(2)),
|
|
264
|
+
llr: Number(stat.llr.toFixed(2)),
|
|
265
|
+
quoted: isQuoted,
|
|
266
|
+
mixed: isMixed,
|
|
267
|
+
intro: isIntro,
|
|
268
|
+
lexicon: lexiconTier1 ? 'user' : (lexiconModelHit ? 'model-proposal' : null),
|
|
269
|
+
}
|
|
270
|
+
rows.push({ row, evidenced: isQuoted || isMixed || isIntro || lexiconTier1 })
|
|
271
|
+
}
|
|
272
|
+
// A sliding-window fragment is only noise while the longer surface it lives in
|
|
273
|
+
// is at least as well attested: `南宫晚` and `宫晚晴` carry exactly the documents
|
|
274
|
+
// `南宫晚晴` does, so the 4-char form wins and the two windows never reach the
|
|
275
|
+
// queue. A short name that also stands on its own (`星港`, whose 4-char neighbours
|
|
276
|
+
// appear in a single memory) keeps the higher df and survives. Terms with direct
|
|
277
|
+
// surface evidence (quote / identifier / name-intro / user lexicon) are never
|
|
278
|
+
// dropped here — that is evidence, not a statistic.
|
|
279
|
+
// Indexed by fragment instead of compared pairwise: a big library has tens of
|
|
280
|
+
// thousands of candidate n-grams and O(n²) `includes` does not belong in a sweep.
|
|
281
|
+
const statistical = rows.filter((item) => !item.evidenced)
|
|
282
|
+
const longestAttested = new Map()
|
|
283
|
+
for (const { row } of statistical) {
|
|
284
|
+
const chars = [...row.term]
|
|
285
|
+
for (let start = 0; start < chars.length; start += 1) {
|
|
286
|
+
for (let size = 1; start + size <= chars.length; size += 1) {
|
|
287
|
+
if (start === 0 && size === chars.length) continue // only proper substrings count as fragments
|
|
288
|
+
const fragment = chars.slice(start, start + size).join('')
|
|
289
|
+
const known = longestAttested.get(fragment)
|
|
290
|
+
if (known === undefined || row.df > known) longestAttested.set(fragment, row.df)
|
|
291
|
+
}
|
|
292
|
+
}
|
|
293
|
+
}
|
|
294
|
+
const subsumed = new Set(statistical
|
|
295
|
+
.filter(({ row }) => (longestAttested.get(row.term) || 0) >= row.df)
|
|
296
|
+
.map(({ row }) => row.term))
|
|
297
|
+
for (const { row, evidenced } of rows) {
|
|
298
|
+
if (subsumed.has(row.term)) continue
|
|
299
|
+
if (evidenced) tier1.push(row)
|
|
300
|
+
else tier2.push(row)
|
|
301
|
+
}
|
|
302
|
+
const byScore = (a, b) => b.score - a.score || a.term.localeCompare(b.term)
|
|
303
|
+
tier1.sort(byScore)
|
|
304
|
+
tier2.sort(byScore)
|
|
305
|
+
return {
|
|
306
|
+
tier1: tier1.slice(0, policy.tier1Max),
|
|
307
|
+
tier2: tier2.slice(0, policy.tier2Max),
|
|
308
|
+
}
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
export default { buildTermStats, rankCandidates, looksGeneric }
|