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.
Files changed (389) hide show
  1. package/AGENTS.md +108 -108
  2. package/CHANGELOG.md +169 -848
  3. package/LICENSE +21 -21
  4. package/README.md +368 -374
  5. package/README.zh.md +354 -360
  6. package/assets/icon.svg +7 -7
  7. package/cordis.patch.yml +8 -8
  8. package/docs/active-memory-ab.md +279 -385
  9. package/docs/binding-lifecycle.md +99 -99
  10. package/docs/client-conventions.md +75 -72
  11. package/docs/contributing.md +217 -217
  12. package/docs/emotion-model-spec.md +247 -281
  13. package/docs/env-and-commands.md +149 -152
  14. package/docs/host-adaptation.md +339 -360
  15. package/docs/host-api.md +131 -137
  16. package/docs/host-versions.md +117 -120
  17. package/docs/mcp-porting.md +146 -0
  18. package/docs/memory-semantics.md +271 -259
  19. package/docs/pending-work.md +44 -51
  20. package/docs/troubleshooting.md +909 -840
  21. package/lib/active-memory.js +160 -165
  22. package/lib/activity-log.js +207 -207
  23. package/lib/auto-link/apply.js +248 -249
  24. package/lib/auto-link/candidates.js +163 -163
  25. package/lib/auto-link/decide.js +300 -300
  26. package/lib/auto-link/normalize.js +99 -99
  27. package/lib/auto-link/policy.js +42 -42
  28. package/lib/auto-link/suppression.js +101 -101
  29. package/lib/auto-link/terminology.js +311 -311
  30. package/lib/backup.js +1254 -1254
  31. package/lib/binding-diagnostics.js +634 -634
  32. package/lib/budget.js +118 -118
  33. package/lib/client.js +9820 -9648
  34. package/lib/commitment.js +178 -138
  35. package/lib/consolidation-ledger.js +434 -438
  36. package/lib/consolidation-receipt.js +386 -387
  37. package/lib/consolidation-snapshot.js +420 -405
  38. package/lib/consolidation-worker.js +240 -241
  39. package/lib/context.js +33 -33
  40. package/lib/curator-evidence.js +131 -131
  41. package/lib/curator-policy.js +198 -202
  42. package/lib/curator.js +1813 -1811
  43. package/lib/cycle.js +524 -513
  44. package/lib/diagnostics.js +524 -524
  45. package/lib/embedding-catalog.js +1051 -1055
  46. package/lib/embedding-download.js +637 -607
  47. package/lib/embedding-runtime.js +946 -946
  48. package/lib/engine.js +1103 -1035
  49. package/lib/entity-repair.js +285 -285
  50. package/lib/environment-check.js +394 -394
  51. package/lib/fork-model.js +312 -312
  52. package/lib/freshness.js +128 -121
  53. package/lib/global-graph.js +389 -389
  54. package/lib/graph.js +1193 -1193
  55. package/lib/host-surface.js +30 -30
  56. package/lib/inbound.js +284 -281
  57. package/lib/index.js +506 -511
  58. package/lib/inject.js +2639 -2619
  59. package/lib/lexicon-scope.js +143 -143
  60. package/lib/lexicon.js +1183 -1192
  61. package/lib/lifecycle-audit.js +37 -0
  62. package/lib/local-embedding-entry.js +145 -145
  63. package/lib/local-embedding-manager.js +306 -306
  64. package/lib/local-embedding-protocol.js +210 -210
  65. package/lib/local-embedding-worker.js +682 -682
  66. package/lib/local-vector-service.js +506 -453
  67. package/lib/maintenance-ledger.js +138 -0
  68. package/lib/maintenance-review.js +103 -0
  69. package/lib/maintenance-runner.js +267 -0
  70. package/lib/managed-runtime.js +118 -118
  71. package/lib/media.js +607 -513
  72. package/lib/memory.js +5035 -4911
  73. package/lib/memu-config.js +213 -213
  74. package/lib/memu.js +565 -565
  75. package/lib/migrate.js +200 -200
  76. package/lib/mood.js +300 -300
  77. package/lib/paths.js +453 -457
  78. package/lib/port-surface.js +82 -0
  79. package/lib/preset-mount.js +79 -0
  80. package/lib/preset-scope.js +126 -126
  81. package/lib/private-links.js +567 -567
  82. package/lib/private.js +2198 -2209
  83. package/lib/prompts/global-curator.md +135 -135
  84. package/lib/prompts/image-caption.md +1 -1
  85. package/lib/prompts/private-consolidation.coding.md +39 -39
  86. package/lib/prompts/private-consolidation.md +32 -32
  87. package/lib/prompts/private-consolidation.mixed.md +37 -37
  88. package/lib/prompts/private-consolidation.rp.md +47 -47
  89. package/lib/prompts/private-policy.coding.md +35 -35
  90. package/lib/prompts/private-policy.md +36 -36
  91. package/lib/prompts/private-policy.mixed.md +29 -29
  92. package/lib/prompts/private-policy.rp.md +43 -43
  93. package/lib/prompts/system-guide.coding.md +20 -20
  94. package/lib/prompts/system-guide.md +25 -25
  95. package/lib/prompts/system-guide.mixed.md +22 -22
  96. package/lib/prompts/system-guide.rp.md +23 -23
  97. package/lib/prompts.js +331 -331
  98. package/lib/recall-cache.js +212 -212
  99. package/lib/remote-summary.js +123 -123
  100. package/lib/rpc.js +2531 -2518
  101. package/lib/salient-wake.js +438 -438
  102. package/lib/snippet.js +125 -125
  103. package/lib/state.js +1948 -1928
  104. package/lib/stats.js +236 -236
  105. package/lib/temporal.js +345 -348
  106. package/lib/text-retrieval.js +992 -1001
  107. package/lib/text-similarity.js +305 -305
  108. package/lib/tokenizer-v2.js +271 -271
  109. package/lib/tools.js +1098 -1066
  110. package/lib/turn-log.js +545 -545
  111. package/lib/vector-migration.js +928 -930
  112. package/lib/vector-profile.js +1353 -1359
  113. package/lib/visibility.js +59 -59
  114. package/lib/webui/graph-LICENSE.txt +1 -1
  115. package/lib/webui/graph-view.bundle.js +2 -2
  116. package/lib/webui/graph-view.js +1171 -1175
  117. package/lib/webui/mark.svg +7 -7
  118. package/lib/webui/standalone.css +1178 -1178
  119. package/lib/webui/standalone.js +238 -238
  120. package/lib/webui.js +136 -136
  121. package/lib/worker-pool.js +1015 -979
  122. package/package.json +153 -152
  123. package/requirements.lock +34 -34
  124. package/scripts/acceptance-local.mjs +946 -946
  125. package/scripts/active-memory-ab-live.mjs +653 -655
  126. package/scripts/active-memory-ab.mjs +1302 -1302
  127. package/scripts/audit-memory-lifecycle.mjs +55 -0
  128. package/scripts/bench-recall.mjs +142 -142
  129. package/scripts/build-graph.mjs +44 -45
  130. package/scripts/chain-matrix.mjs +541 -541
  131. package/scripts/check-all.mjs +68 -74
  132. package/scripts/check-doc-drift.mjs +547 -547
  133. package/scripts/check-graph-browser.mjs +261 -261
  134. package/scripts/check-i18n.mjs +81 -83
  135. package/scripts/check-idle-compositing.mjs +61 -61
  136. package/scripts/check-seed-compat.mjs +115 -118
  137. package/scripts/check-text-format.mjs +55 -0
  138. package/scripts/curator-pair-calibrate.mjs +259 -259
  139. package/scripts/diagnose-bindings.mjs +176 -176
  140. package/scripts/drive-session.mjs +863 -864
  141. package/scripts/engine-smoke.mjs +69 -69
  142. package/scripts/entity-dedupe.mjs +110 -110
  143. package/scripts/lexicon-calibrate.mjs +230 -230
  144. package/scripts/lexicon-dedupe.mjs +318 -318
  145. package/scripts/local-runtime-install.mjs +142 -142
  146. package/scripts/local-runtime-verify.mjs +56 -56
  147. package/scripts/local-vector-verify.mjs +93 -93
  148. package/scripts/make-readme-shots.mjs +59 -59
  149. package/scripts/migrate-visibility.mjs +94 -94
  150. package/scripts/mock-llm.mjs +938 -903
  151. package/scripts/preview.mjs +58 -58
  152. package/scripts/prune-sessions.mjs +31 -34
  153. package/scripts/prune-turnlogs.mjs +29 -30
  154. package/scripts/prune-vectors.mjs +24 -24
  155. package/scripts/rebuild-auto-links.mjs +252 -252
  156. package/scripts/recall-bench.mjs +820 -820
  157. package/scripts/repetition-ab-scenarios.mjs +93 -93
  158. package/scripts/repetition-detector-snapshot.mjs +314 -314
  159. package/scripts/repetition-eval-live.mjs +360 -360
  160. package/scripts/repetition-eval.mjs +702 -702
  161. package/scripts/replay.mjs +705 -575
  162. package/scripts/setup.mjs +46 -46
  163. package/scripts/simulate-injection.mjs +299 -301
  164. package/tests/absorb-review.test.mjs +354 -354
  165. package/tests/activation.test.mjs +89 -89
  166. package/tests/active-memory-ab.test.mjs +745 -745
  167. package/tests/active-memory.test.mjs +129 -129
  168. package/tests/activity-log.test.mjs +126 -126
  169. package/tests/activity-wiring.test.mjs +155 -155
  170. package/tests/appendix-b.test.mjs +217 -217
  171. package/tests/appendix-b2.test.mjs +166 -166
  172. package/tests/audit-batch3.test.mjs +247 -247
  173. package/tests/audit-regression.test.mjs +275 -275
  174. package/tests/audit-safety.test.mjs +227 -227
  175. package/tests/auto-link-candidates.test.mjs +245 -245
  176. package/tests/auto-link-decide.test.mjs +512 -512
  177. package/tests/auto-link-migration.test.mjs +133 -133
  178. package/tests/backend-compensation.test.mjs +272 -272
  179. package/tests/backup.test.mjs +793 -793
  180. package/tests/binding-diagnostics.test.mjs +720 -720
  181. package/tests/browser.test.mjs +476 -455
  182. package/tests/client-export.test.mjs +521 -520
  183. package/tests/client-render.test.mjs +2008 -1727
  184. package/tests/coalesce.test.mjs +113 -113
  185. package/tests/commitment.test.mjs +243 -144
  186. package/tests/config.test.mjs +159 -159
  187. package/tests/consolidation-credential.test.mjs +330 -330
  188. package/tests/consolidation-feed.test.mjs +122 -122
  189. package/tests/consolidation-fork.test.mjs +1586 -1539
  190. package/tests/consolidation-ledger.test.mjs +389 -389
  191. package/tests/consolidation-snapshot.test.mjs +567 -505
  192. package/tests/consolidation-value.test.mjs +89 -89
  193. package/tests/context-scope.test.mjs +40 -40
  194. package/tests/cross-library-recall.test.mjs +269 -269
  195. package/tests/cue.test.mjs +58 -58
  196. package/tests/curator-absorb.test.mjs +444 -444
  197. package/tests/curator-calibrate.test.mjs +173 -173
  198. package/tests/curator-clusters.test.mjs +306 -306
  199. package/tests/curator-commit.test.mjs +325 -325
  200. package/tests/curator-contract.test.mjs +191 -191
  201. package/tests/curator-evidence.test.mjs +102 -102
  202. package/tests/curator-link.test.mjs +317 -317
  203. package/tests/curator-pairing.test.mjs +339 -339
  204. package/tests/curator-probe.test.mjs +490 -490
  205. package/tests/curator-review-mode.test.mjs +315 -315
  206. package/tests/curator.test.mjs +152 -152
  207. package/tests/cycle.test.mjs +567 -568
  208. package/tests/diagnostics.test.mjs +278 -278
  209. package/tests/disclosure.test.mjs +249 -249
  210. package/tests/doc-drift.test.mjs +342 -342
  211. package/tests/drive-session.test.mjs +152 -152
  212. package/tests/dynamic-rrf.test.mjs +182 -182
  213. package/tests/dynamic-threshold.test.mjs +52 -52
  214. package/tests/embedding-catalog.test.mjs +374 -374
  215. package/tests/embedding-download.test.mjs +529 -486
  216. package/tests/embedding-runtime.test.mjs +449 -449
  217. package/tests/emotion-chain.test.mjs +84 -84
  218. package/tests/emotion-contract.test.mjs +445 -445
  219. package/tests/engine.test.mjs +108 -48
  220. package/tests/entity-merge.test.mjs +278 -278
  221. package/tests/environment-check.test.mjs +187 -187
  222. package/tests/fact-version.test.mjs +146 -146
  223. package/tests/fixtures/active-memory-ab/README.md +56 -56
  224. package/tests/fixtures/active-memory-ab/cases/01-clean-dense-turn.json +351 -351
  225. package/tests/fixtures/active-memory-ab/cases/02-clean-thin-turn.json +122 -122
  226. package/tests/fixtures/active-memory-ab/cases/03-clean-starved-small.json +125 -125
  227. package/tests/fixtures/active-memory-ab/cases/04-clean-large-thin.json +137 -137
  228. package/tests/fixtures/active-memory-ab/cases/05-clean-half-step.json +166 -166
  229. package/tests/fixtures/active-memory-ab/cases/06-clean-duplicate-reread.json +197 -197
  230. package/tests/fixtures/active-memory-ab/cases/07-clean-recent-recall.json +125 -125
  231. package/tests/fixtures/active-memory-ab/cases/08-global-relevant.json +111 -111
  232. package/tests/fixtures/active-memory-ab/cases/09-global-irrelevant-conflict.json +158 -158
  233. package/tests/fixtures/active-memory-ab/cases/10-no-human-turn.json +97 -97
  234. package/tests/fixtures/active-memory-ab/cases/11-clean-scale-100.json +137 -137
  235. package/tests/fixtures/active-memory-ab/cases/12-clean-scale-1000.json +137 -137
  236. package/tests/fixtures/active-memory-ab/cases/13-clean-scale-5000.json +137 -137
  237. package/tests/fixtures/active-memory-ab/cases/14-clean-scale-20000.json +137 -137
  238. package/tests/fixtures/active-memory-ab/lead-ai-reviewed-reference.json +191 -191
  239. package/tests/fixtures/active-memory-ab/manifest.json +199 -199
  240. package/tests/fixtures/curator-pairs/labeled.v1.jsonl +90 -90
  241. package/tests/fixtures/lexicon-stub-hooks.mjs +15 -15
  242. package/tests/fixtures/lexicon-stub.mjs +284 -284
  243. package/tests/fixtures/mock-llm/reply.txt +1 -1
  244. package/tests/fixtures/recall-bench/01-paraphrase.json +183 -183
  245. package/tests/fixtures/recall-bench/02-exact.json +152 -152
  246. package/tests/fixtures/recall-bench/03-negation.json +172 -172
  247. package/tests/fixtures/recall-bench/04-no-answer.json +161 -161
  248. package/tests/fixtures/recall-bench/05-conflict.json +193 -193
  249. package/tests/fixtures/recall-bench/06-boundary.json +272 -272
  250. package/tests/fixtures/recall-bench/07-secret.json +190 -190
  251. package/tests/fixtures/recall-bench/08-coding.json +163 -163
  252. package/tests/fixtures/recall-bench-gold-candidates/01-paraphrase.json +193 -193
  253. package/tests/fixtures/recall-bench-gold-candidates/02-exact.json +197 -197
  254. package/tests/fixtures/recall-bench-gold-candidates/03-negation.json +244 -244
  255. package/tests/fixtures/recall-bench-gold-candidates/04-no-answer.json +189 -189
  256. package/tests/fixtures/recall-bench-gold-candidates/05-conflict.json +245 -245
  257. package/tests/fixtures/recall-bench-gold-candidates/06-boundary.json +279 -279
  258. package/tests/fixtures/recall-bench-gold-candidates/07-secret.json +224 -224
  259. package/tests/fixtures/recall-bench-gold-candidates/08-coding.json +218 -218
  260. package/tests/fixtures/repetition-eval/01-zh-rp.json +92 -92
  261. package/tests/fixtures/repetition-eval/02-en.json +96 -96
  262. package/tests/fixtures/repetition-eval/03-code.json +90 -90
  263. package/tests/fixtures/repetition-eval/04-names.json +115 -115
  264. package/tests/fixtures/repetition-eval/05-user-quote.json +95 -95
  265. package/tests/fixtures/repetition-eval/06-agreement.json +85 -85
  266. package/tests/fixtures/tokenizer-cases.mjs +27 -27
  267. package/tests/fork-model.test.mjs +345 -345
  268. package/tests/freshness.test.mjs +140 -140
  269. package/tests/global-graph.test.mjs +106 -106
  270. package/tests/global-lifecycle.test.mjs +149 -149
  271. package/tests/graph-cascade.test.mjs +363 -363
  272. package/tests/graph-view.test.mjs +414 -414
  273. package/tests/graph.test.mjs +371 -371
  274. package/tests/help-page.test.mjs +416 -415
  275. package/tests/hook-order.test.mjs +72 -72
  276. package/tests/humanlike.test.mjs +232 -232
  277. package/tests/hybrid-recall.test.mjs +610 -610
  278. package/tests/inbound.test.mjs +441 -441
  279. package/tests/inject-conflict.test.mjs +173 -173
  280. package/tests/inject-guide.test.mjs +513 -513
  281. package/tests/inject.test.mjs +384 -384
  282. package/tests/injection-budget-settings.test.mjs +35 -35
  283. package/tests/injection-budget.test.mjs +165 -165
  284. package/tests/injection-chain.test.mjs +442 -442
  285. package/tests/injection-intent-budget.test.mjs +92 -92
  286. package/tests/injection-rollback.test.mjs +428 -428
  287. package/tests/issue2-chain.test.mjs +169 -169
  288. package/tests/lexical-bm25.test.mjs +171 -171
  289. package/tests/lexicon-calibrate.test.mjs +48 -48
  290. package/tests/lexicon-dedupe.test.mjs +171 -171
  291. package/tests/lexicon-frequency.test.mjs +195 -195
  292. package/tests/lexicon-inject.test.mjs +459 -459
  293. package/tests/lexicon-perf.test.mjs +464 -464
  294. package/tests/lexicon-scope.test.mjs +256 -256
  295. package/tests/lexicon-ui.test.mjs +667 -667
  296. package/tests/lexicon.test.mjs +922 -922
  297. package/tests/lifecycle-audit.test.mjs +56 -0
  298. package/tests/loader-register.mjs +3 -3
  299. package/tests/loader.mjs +17 -17
  300. package/tests/local-embedding-entry.test.mjs +95 -95
  301. package/tests/local-embedding-env.test.mjs +51 -51
  302. package/tests/local-embedding-manager.test.mjs +494 -494
  303. package/tests/local-embedding-protocol.test.mjs +121 -121
  304. package/tests/local-embedding-worker.test.mjs +440 -440
  305. package/tests/local-vector-service.test.mjs +41 -0
  306. package/tests/maintenance-status.test.mjs +77 -0
  307. package/tests/maintenance.test.mjs +438 -0
  308. package/tests/managed-memory.test.mjs +1234 -1234
  309. package/tests/managed-runtime.test.mjs +72 -72
  310. package/tests/media-injection.test.mjs +225 -0
  311. package/tests/media.test.mjs +135 -135
  312. package/tests/memory-chain.test.mjs +169 -169
  313. package/tests/memory-fields.test.mjs +134 -134
  314. package/tests/memu-resident-route.test.mjs +130 -130
  315. package/tests/memu-resident.test.mjs +33 -33
  316. package/tests/migration-payload.test.mjs +40 -42
  317. package/tests/mock-llm.test.mjs +263 -225
  318. package/tests/mood.test.mjs +109 -109
  319. package/tests/multiprocess.test.mjs +29 -29
  320. package/tests/negation-polarity.test.mjs +135 -135
  321. package/tests/new-session-gate.test.mjs +617 -616
  322. package/tests/open-loop-date.test.mjs +416 -416
  323. package/tests/ops-hardening.test.mjs +209 -209
  324. package/tests/package-shipping.test.mjs +88 -88
  325. package/tests/pending-injection.test.mjs +107 -107
  326. package/tests/port-surface.test.mjs +138 -0
  327. package/tests/preset-mount.test.mjs +124 -0
  328. package/tests/preset-scope.test.mjs +212 -212
  329. package/tests/private-links.test.mjs +493 -493
  330. package/tests/prompt-semantics.test.mjs +51 -51
  331. package/tests/prompts.test.mjs +315 -315
  332. package/tests/query-decompose.test.mjs +62 -62
  333. package/tests/react-snapshot.test.mjs +24 -23
  334. package/tests/recall-bench.test.mjs +317 -317
  335. package/tests/recall-cache.test.mjs +292 -292
  336. package/tests/recall-corpus-eligibility.test.mjs +51 -51
  337. package/tests/recall-dedup.test.mjs +446 -446
  338. package/tests/recall-intent.test.mjs +172 -172
  339. package/tests/regression-sweep.test.mjs +311 -311
  340. package/tests/reminder-fairness.test.mjs +55 -0
  341. package/tests/remote.test.mjs +140 -140
  342. package/tests/rename.test.mjs +30 -30
  343. package/tests/repetition-detector-snapshot.test.mjs +231 -231
  344. package/tests/repetition-eval-live.test.mjs +177 -177
  345. package/tests/repetition-eval.test.mjs +373 -373
  346. package/tests/salience-domain.test.mjs +173 -173
  347. package/tests/salient-date.test.mjs +142 -142
  348. package/tests/salient-wake.test.mjs +389 -389
  349. package/tests/settings-beat.test.mjs +222 -221
  350. package/tests/settings-coverage.test.mjs +97 -97
  351. package/tests/settings-plumbing.test.mjs +79 -79
  352. package/tests/short-term.test.mjs +182 -166
  353. package/tests/sidebar-beat.test.mjs +213 -212
  354. package/tests/sidebar-refresh.test.mjs +123 -123
  355. package/tests/sidebar.test.mjs +102 -74
  356. package/tests/simulate-injection.test.mjs +76 -76
  357. package/tests/slot-similarity.test.mjs +153 -153
  358. package/tests/snippet.test.mjs +79 -79
  359. package/tests/source-kind.test.mjs +52 -52
  360. package/tests/speaker-provenance.test.mjs +120 -120
  361. package/tests/stale-maintenance.test.mjs +206 -131
  362. package/tests/state-gc.test.mjs +34 -34
  363. package/tests/state.test.mjs +155 -155
  364. package/tests/stats.test.mjs +112 -112
  365. package/tests/storage.test.mjs +125 -125
  366. package/tests/stubs/child-process-spy.mjs +14 -14
  367. package/tests/stubs/dsh-llm-pi-ai.js +13 -13
  368. package/tests/stubs/dsh-llm.js +5 -5
  369. package/tests/stubs/dsh-schedule.js +140 -140
  370. package/tests/stubs/dsh-session-query.js +26 -26
  371. package/tests/stubs/dsh-session.js +7 -7
  372. package/tests/stubs/dsh-tools.js +101 -101
  373. package/tests/temporal-repair.test.mjs +78 -0
  374. package/tests/temporal.test.mjs +124 -124
  375. package/tests/text-format.test.mjs +24 -0
  376. package/tests/tokenizer-v2.test.mjs +142 -142
  377. package/tests/tool-schema.test.mjs +126 -126
  378. package/tests/tools.test.mjs +810 -810
  379. package/tests/turn-log.test.mjs +487 -487
  380. package/tests/ui-defaults.test.mjs +57 -57
  381. package/tests/update-fields.test.mjs +138 -138
  382. package/tests/vector-gc.test.mjs +37 -37
  383. package/tests/vector-migration.test.mjs +810 -810
  384. package/tests/vector-profile.test.mjs +449 -449
  385. package/tests/visibility-migration.test.mjs +152 -152
  386. package/tests/webui-auth.test.mjs +963 -963
  387. package/tests/webui.test.mjs +421 -414
  388. package/tests/windows-env.test.mjs +89 -89
  389. package/tests/worker-lifecycle.test.mjs +1521 -1429
package/lib/lexicon.js CHANGED
@@ -1,1192 +1,1183 @@
1
- // ── 词典层(Lexicon)核心:P0 存储安全 + 生命周期 active/archived + P1 读取检索 ──
2
- // 契约:docs/memory-semantics.md §8.13(当前生命周期与注入语义)。
3
- // 词典不替代记忆、不触发下载、不接 settings:冷却与预算全部用本模块常量 + 模块内
4
- // 状态(见 lexiconCooldownStore)。
5
- //
6
- // 存储安全不变量(§1-§2,每一条都有对应测试):
7
- // * 路径只能是 dataDir()/lexicon/<libraryId>.json,libraryId 过 isSafeId(拒绝
8
- // 绝对路径、..、路径分隔符——isSafeId 的白名单字符集天然挡掉它们)。
9
- // * 读:缺失 → 空结构;损坏/IO 失败/曾 quarantined → typed error,绝不当空处理
10
- // (paths.readJsonStrict 的口径:吞掉的读失败会把下一次写变成整库覆盖)。
11
- // * 写:一切写函数在 withFileLock 内重读磁盘上的最新 revision 再改(CAS),
12
- // revision 单调 +1 后 writeJson 原子替换(tmp + fsync + rename)。锁是同步作用
13
- // 域,从不跨 await。调用方手里的任何旧副本都写不回磁盘——写路径不接受外部对象。
14
- // * 记录格式 §1.2:normalizedTerm/normalizedAliases、evidence 短证据、hitCounts
15
- // 三计数(candidate/injection/query)。
16
- // * 生命周期(§2.1):公开两态 active/archived;`pending` 只作为旧版的 legacy
17
- // 数据被读(迁移见 migrateLegacyLexiconStatuses),`rejected` 只作为内部墓碑 +
18
- // fingerprint 存在(永不注入、永不列出、永不计数)。新写路径不再产出这两种状态。
19
- // * 读路径(§10 P1):每本词典一份 revision-keyed 内存快照 + 派生索引,见
20
- // lexiconIndexCache 的注释——JSON 是唯一主事实,索引永远是可重建的派生物。
21
- import fs from 'node:fs'
22
- import path from 'node:path'
23
- import { dataDir, readJsonStrict, readFailure, writeJson, withFileLock, isSafeId, shortHash, warn, stamp } from './paths.js'
24
- import { normalizeMemoryContext, contextVisible, sameFactContext } from './context.js'
25
- import { bigrams, dice } from './text-similarity.js'
26
- import { estTokens } from './budget.js'
27
-
28
- // 容量与长度上限(§1.2)。刻意不接 settings:容量是存储安全边界,不该被运行时配置放宽。
29
- export const LEXICON_CAP = 5000
30
- const TERM_MAX_CHARS = 80
31
- const MEANING_MAX_CHARS = 500
32
- const USAGE_MAX_CHARS = 300
33
- const ALIAS_MAX_COUNT = 8
34
- const ALIAS_MAX_CHARS = 80
35
- const EXAMPLE_MAX_COUNT = 5
36
- const EXAMPLE_MAX_CHARS = 200
37
- const EVIDENCE_MAX_COUNT = 10
38
- const EVIDENCE_QUOTE_MAX_CHARS = 200
39
-
40
- // 匹配流水线常量(§3.1-§3.2)。threshold 0.60 是起步标定值,P4 用标注样本复核。
41
- export const LEXICON_DICE_THRESHOLD = 0.6
42
- export const LEXICON_MAX_BUCKETS = 16
43
- export const LEXICON_MAX_CANDIDATES = 64
44
- export const LEXICON_MAX_TERMS = 8
45
- // 词面包含(includes)命中的最小规范化长度:单字词在 CJK 里到处出现,放进精确层
46
- // 只会制造噪声。等值匹配(整句恰好等于词条)不受此限制。
47
- export const LEXICON_MIN_INCLUDE_LEN = 2
48
- // 前缀桶宽度:词条侧取 normalizedTerm 的前 2 字符做桶键,文本侧穷举 2 字符窗口。
49
- const BUCKET_WIDTH = 2
50
-
51
- // 冷却与回合预算(§3.3)。冷却按 binding/session 记,选择"模块内 Map"而不是
52
- // binding 字段:binding 持久化在 state.json,注入路径每回合都写会把状态文件变成
53
- // 热路径,而冷却丢一批(进程重启)最坏只是同一个词多注入一次,代价不对称。
54
- // key = binding 的 sessionId(一个 session 只有一个 binding → 一本私有库)。
55
- export const LEXICON_RECALL_COOLDOWN_MINUTES = 30
56
- export const LEXICON_MAX_PER_TURN = 2
57
- export const lexiconCooldownStore = new Map() // key: sessionKey → Map(termId → lastInjectedAt ms)
58
-
59
- // 频率先验:三计数的写入上限与 Wilson 下界的 z 值。上限挡住
60
- // 病态数据把 effective 因子顶出 [0.85,1.00] 的界;z=1.96 即 95% 单侧置信。
61
- export const HIT_COUNT_CAP = 1_000_000
62
- export const WILSON_Z = 1.96
63
-
64
- const KINDS = ['slang', 'meme', 'trigger', 'term']
65
- // 公开生命周期只有两态(§2.1)。pending/rejected 仍是磁盘上可能存在的 legacy 状态,
66
- // 但新调用方不能把词条写成它们(见 upsertLexiconTerm 的 status 收口)。
67
- const PUBLIC_STATUSES = ['active', 'archived']
68
- const SOURCES = ['user', 'curator', 'model-proposal']
69
-
70
- function lexiconError(code, message) {
71
- const error = new Error(message)
72
- error.code = code
73
- return error
74
- }
75
-
76
- function clip(text, max) {
77
- const s = String(text ?? '')
78
- return s.length > max ? s.slice(0, max) : s
79
- }
80
-
81
- /**
82
- * 词条词面的统一规范化:NFKC → 大小写折叠 → 去空白/标点/符号。
83
- * 与 lib/text-similarity.js clean()(memory.js 矛盾检测的既有预处理)同风格,
84
- * 只多一步 NFKC:全角/半角和兼容字符必须折叠成同一个词面,否则唯一性约束会被
85
- * 「糖刀」和「糖刀」(全角感叹号)绕开。
86
- */
87
- export function normalizeLexeme(text) {
88
- return String(text ?? '').normalize('NFKC').toLowerCase().replace(/[\s\p{P}\p{S}]+/gu, '')
89
- }
90
-
91
- function lexiconDir() {
92
- return path.join(dataDir(), 'lexicon')
93
- }
94
-
95
- // 全局词典与私有词典同格式、同锁、同缓存,只是占一个保留的存储名。
96
- // 私有库 id 一律是 `lib_<hex>`(state.js libraryIdForScope),所以 `global` 不可能
97
- // 是某本私有库——`data/lexicon/global.json` 与 `index/global.json`(全局记忆)对齐。
98
- export const GLOBAL_LEXICON_ID = 'global'
99
-
100
- // 「全部词典」聚合浏览的保留作用域名(不是存储):lexiconList 收到它时合并全局词典
101
- // 与所有私有库的词条,只读聚合,写操作仍按词条所属库路由。与 GLOBAL_LEXICON_ID 一样
102
- // 不可能撞私有库 id(`lib_<hex>`)。前端 client.js 复写同一个值,漂移由测试钉住。
103
- export const ALL_LEXICON_ID = 'all'
104
-
105
- function lexiconFile(libraryId) {
106
- // isSafeId 只放行 [A-Za-z0-9._-]{1,128} 且拒绝 . / ..:绝对路径、反斜杠、
107
- // ../ 和任意文件名在这里就死掉,不会拼进路径。
108
- if (!isSafeId(libraryId)) throw lexiconError('LEXICON_INVALID_LIBRARY_ID', `invalid lexicon library id: ${clip(libraryId, 40)}`)
109
- return path.join(lexiconDir(), `${libraryId}.json`)
110
- }
111
-
112
- function emptyLexicon(libraryId) {
113
- return { version: 1, revision: 0, libraryId, terms: {}, rejected: {} }
114
- }
115
-
116
- function readLexiconStrict(file, libraryId) {
117
- // 曾被 quarantine(读失败被挪走)的库不能当空库处理:读回来是"空"的下一个写
118
- // 就会把整本词典覆盖掉。这里宁可 typed error 也绝不静默清零。
119
- const failure = readFailure(file)
120
- if (failure) {
121
- throw lexiconError('LEXICON_READ_FAILED', `lexicon ${libraryId} is write-protected by an earlier read failure (${failure.code || failure.message})`)
122
- }
123
- const result = readJsonStrict(file)
124
- if (result.missing) return emptyLexicon(libraryId)
125
- if (!result.ok) {
126
- const error = lexiconError('LEXICON_CORRUPT', `lexicon ${libraryId} could not be read (${result.kind === 'corrupt' ? 'invalid JSON' : result.error?.code || 'read failed'}); nothing is treated as empty and writes stay blocked until it is restored`)
127
- if (result.error) error.cause = result.error
128
- throw error
129
- }
130
- const value = result.value
131
- // 形状校验:合法 JSON 但不是词典(数组、version 不对、terms 不是对象表、行不是
132
- // 对象)同样是"损坏"——照单全收会让下一次写把陌生形状固化下来。
133
- if (!value || typeof value !== 'object' || Array.isArray(value)
134
- || (value.version !== undefined && value.version !== 1)
135
- || !value.terms || typeof value.terms !== 'object' || Array.isArray(value.terms)) {
136
- throw lexiconError('LEXICON_CORRUPT', `lexicon ${libraryId} has an invalid data shape; refusing to treat it as empty`)
137
- }
138
- for (const [termId, entry] of Object.entries(value.terms)) {
139
- if (!entry || typeof entry !== 'object' || Array.isArray(entry)) {
140
- throw lexiconError('LEXICON_CORRUPT', `lexicon ${libraryId} entry ${termId} is not an object`)
141
- }
142
- }
143
- return {
144
- version: 1,
145
- revision: Number.isSafeInteger(value.revision) && value.revision >= 0 ? value.revision : 0,
146
- libraryId,
147
- terms: value.terms,
148
- rejected: value.rejected && typeof value.rejected === 'object' && !Array.isArray(value.rejected) ? value.rejected : {},
149
- }
150
- }
151
-
152
- // ── revision-keyed 内存索引(§10 P1 / §8.2 的 O(N) 优化项)───────────────────
153
- // 每本词典在进程内保留一份「读取快照 + 派生索引」,key = `${libraryId}@${revision}`:
154
- // data 严格读取出的词典对象(JSON 永远是主事实,快照只是派生物)
155
- // activeEntries / archivedEntries / pendingEntries 构建时分好 status 并按展示序
156
- // 排好的词条;archived 里可能包含 legacy revision 草稿(带 revisionOf,
157
- // 由 restoreLexiconTerm 拒绝恢复);pendingEntries 只服务迁移/审计,
158
- // 任何注入/检索/列表面都不读它;rejected 不进任何列表(墓碑)。
159
- // byNormalizedTerm / byAlias 等值查询:Map<规范化词面, termId[]>
160
- // prefixBuckets Map<词面前 BUCKET_WIDTH 字, Set<termId>>(dice 候选 + 正向包含候选)
161
- // grams Map<词面任意 2 字 gram, Set<termId>>(searchLexicon 反向包含候选)
162
- // surfacesByTerm Map<termId, [{ surface, via }]>(term 在前、aliases 随后,含/等值判定用)
163
- //
164
- // 失效策略(正确性红线:任何绕过本进程的文件改动不得让缓存返回旧数据):
165
- // * 进程内一切写都走 mutateLexicon → 写成功后立即用刚落盘的对象重建快照
166
- // (revision 已 +1,旧 key 随之作废)。
167
- // * 进程外的改动(测试直写 paths.writeJson、backup 恢复、手工修复文件):缓存
168
- // 命中前对文件 stat 一次并比对 mtimeMs + size。一次 stat(µs 级)远比全量
169
- // JSON.parse(N=5k 时 ms 级)便宜;mtime 与 size 同时不变的覆写只剩「同毫秒内
170
- // 等字节覆写」一条理论缝,在 NTFS/APFS/ext4(亚毫秒 mtime 精度)上实际不可达。
171
- // 选 stat 比对而不是 revision 校验:revision 在 JSON 内部,读它就得先 parse,
172
- // 等于放弃缓存。quarantine 把文件挪走 → stat 失败 → 必然 miss 回严格读取,
173
- // typed error 语义不变。
174
- // * 文件缺失(空库)不缓存:外部新建的文件必须立刻被下一次读取看见。
175
- const lexiconIndexCache = new Map() // key: `${libraryId}@${revision}` → snapshot
176
- const lexiconIndexHint = new Map() // libraryId → { key, mtimeMs, size }
177
-
178
- // 展示序:strength → updatedAt → termId(构建索引与 merged 列表共用同一把尺)。
179
- function displayRank(a, b) {
180
- return (Number(b.entry.strength) || 0) - (Number(a.entry.strength) || 0)
181
- || String(b.entry.updatedAt || '').localeCompare(String(a.entry.updatedAt || ''))
182
- || String(a.termId).localeCompare(String(b.termId))
183
- }
184
-
185
- function buildLexiconIndex(data) {
186
- const byNormalizedTerm = new Map()
187
- const byAlias = new Map()
188
- const prefixBuckets = new Map()
189
- const grams = new Map()
190
- const surfacesByTerm = new Map()
191
- const activeEntries = []
192
- const archivedEntries = []
193
- const pendingEntries = []
194
- for (const [termId, entry] of Object.entries(data.terms)) {
195
- const status = entry.status || 'active'
196
- if (status === 'active') activeEntries.push({ termId, entry })
197
- else if (status === 'archived') archivedEntries.push({ termId, entry })
198
- else if (status === 'pending') pendingEntries.push({ termId, entry })
199
- const surfaces = []
200
- if (entry.normalizedTerm) surfaces.push({ surface: entry.normalizedTerm, via: 'term' })
201
- const aliases = Array.isArray(entry.normalizedAliases) ? entry.normalizedAliases : []
202
- for (const alias of aliases) {
203
- if (alias && alias !== entry.normalizedTerm) surfaces.push({ surface: alias, via: 'alias' })
204
- }
205
- if (surfaces.length) surfacesByTerm.set(termId, surfaces)
206
- for (const { surface, via } of surfaces) {
207
- const target = via === 'term' ? byNormalizedTerm : byAlias
208
- let ids = target.get(surface)
209
- if (!ids) { ids = []; target.set(surface, ids) }
210
- ids.push(termId)
211
- // 前缀桶:与原 bucketKeysOf 同口径——词面前 BUCKET_WIDTH 字,过短词面用自身。
212
- const prefixKey = surface.length >= BUCKET_WIDTH ? surface.slice(0, BUCKET_WIDTH) : surface
213
- let bucket = prefixBuckets.get(prefixKey)
214
- if (!bucket) { bucket = new Set(); prefixBuckets.set(prefixKey, bucket) }
215
- bucket.add(termId)
216
- // gram 倒排:searchLexicon 的反向包含(query ⊆ 词面)靠它收候选。正向包含
217
- // (词面 ⊆ query)也可以用它,但前缀桶的候选集更小(词面必须以该窗口开头),
218
- // 所以正向走前缀桶。
219
- for (let i = 0; i + BUCKET_WIDTH <= surface.length; i++) {
220
- const gram = surface.slice(i, i + BUCKET_WIDTH)
221
- let set = grams.get(gram)
222
- if (!set) { set = new Set(); grams.set(gram, set) }
223
- set.add(termId)
224
- }
225
- }
226
- }
227
- // 展示序在构建时定死(strength → updatedAt → termId):过滤是保序的,调用方
228
- // 不必再对可见子集排序——排序键全是静态字段,与可见性无关,两个顺序等价。
229
- activeEntries.sort(displayRank)
230
- archivedEntries.sort(displayRank)
231
- pendingEntries.sort(displayRank)
232
- return { data, activeEntries, archivedEntries, pendingEntries, byNormalizedTerm, byAlias, prefixBuckets, grams, surfacesByTerm }
233
- }
234
-
235
- function storeLexiconIndex(libraryId, file, data) {
236
- const snapshot = buildLexiconIndex(data)
237
- const key = `${libraryId}@${data.revision}`
238
- const previous = lexiconIndexHint.get(libraryId)
239
- if (previous) lexiconIndexCache.delete(previous.key)
240
- let stat = null
241
- try { stat = fs.statSync(file) } catch {}
242
- if (stat) {
243
- lexiconIndexCache.set(key, snapshot)
244
- lexiconIndexHint.set(libraryId, { key, mtimeMs: stat.mtimeMs, size: stat.size })
245
- } else {
246
- // 空库(文件还不存在)不缓存缺失状态。
247
- lexiconIndexHint.delete(libraryId)
248
- }
249
- return snapshot
250
- }
251
-
252
- /** 带缓存的内部读取:命中走 stat 比对,未命中走严格读取 + 建索引。 */
253
- function lexiconIndex(libraryId) {
254
- const file = lexiconFile(libraryId)
255
- // quarantine(读失败保护)优先于一切缓存:曾 quarantined 的库必须继续 typed error。
256
- const failure = readFailure(file)
257
- if (failure) {
258
- throw lexiconError('LEXICON_READ_FAILED', `lexicon ${libraryId} is write-protected by an earlier read failure (${failure.code || failure.message})`)
259
- }
260
- const hint = lexiconIndexHint.get(libraryId)
261
- if (hint) {
262
- let stat = null
263
- try { stat = fs.statSync(file) } catch {}
264
- if (stat && stat.mtimeMs === hint.mtimeMs && stat.size === hint.size) {
265
- const snapshot = lexiconIndexCache.get(hint.key)
266
- if (snapshot) return snapshot
267
- }
268
- }
269
- const data = readLexiconStrict(file, libraryId)
270
- return storeLexiconIndex(libraryId, file, data)
271
- }
272
-
273
- /**
274
- * 读一本词典。缺失 → 空结构(revision 0);损坏 → LEXICON_CORRUPT,绝不当空处理。
275
- * 命中缓存时返回快照的浅拷贝:顶层字段与 terms 表逐键复制,防止调用方增删键污染
276
- * 缓存;词条对象按只读契约共享——库内全部读路径都不改词条对象,测试里「改完立刻
277
- * 写盘」的直改模式由 mtime 失效兜底(写盘 ⇒ 下一次 stat 必不匹配 ⇒ 重建)。
278
- */
279
- export function loadLexicon(libraryId) {
280
- const snapshot = lexiconIndex(libraryId)
281
- return { ...snapshot.data, terms: { ...snapshot.data.terms } }
282
- }
283
-
284
- /**
285
- * 一切写操作的唯一入口:锁内重读最新 revision(CAS)→ mutator 同步改 → revision+1
286
- * → writeJson 原子替换。mutator 必须同步(withFileLock 的锁不能跨 await)。
287
- * 写成功后用刚落盘的对象重建内存索引:省掉下一次读取的整个 JSON.parse,重建成本
288
- * 与建索引同阶且本来就在锁内。
289
- *
290
- * `onlyWhenChanged` 给迁移类写用(migrateLegacyLexiconStatuses):mutator 通过
291
- * `changed === true` 声明真的改了数据;否则不落盘、不 bump revision——没有变化的
292
- * 迁移不该把文件变成热写(revision 是别的进程判新的依据,空转 +1 只会制造噪声)。
293
- */
294
- function mutateLexicon(libraryId, mutator, { onlyWhenChanged = false } = {}) {
295
- const file = lexiconFile(libraryId)
296
- return withFileLock(file, () => {
297
- const current = readLexiconStrict(file, libraryId)
298
- const outcome = mutator(current) || {}
299
- if (onlyWhenChanged && outcome.changed !== true) return outcome
300
- current.revision = (Number(current.revision) || 0) + 1
301
- current.libraryId = libraryId
302
- current.version = 1
303
- writeJson(file, current)
304
- storeLexiconIndex(libraryId, file, current)
305
- return outcome
306
- })
307
- }
308
-
309
- function withTermId(entry, termId) {
310
- return { termId, ...entry }
311
- }
312
-
313
- function normalizeEvidence(evidence) {
314
- if (evidence === undefined || evidence === null) return []
315
- if (!Array.isArray(evidence)) throw lexiconError('LEXICON_INVALID_EVIDENCE', 'evidence must be an array of { kind, id, quote }')
316
- return evidence
317
- .filter(item => item && typeof item === 'object')
318
- .map(item => ({
319
- kind: clip(typeof item.kind === 'string' ? item.kind : 'message', 40),
320
- id: clip(typeof item.id === 'string' ? item.id : '', 160),
321
- quote: clip(typeof item.quote === 'string' ? item.quote : '', EVIDENCE_QUOTE_MAX_CHARS),
322
- }))
323
- .filter(item => item.quote.trim() || item.id)
324
- .slice(0, EVIDENCE_MAX_COUNT)
325
- }
326
-
327
- function normalizeStringList(value, { maxCount, maxChars, label }) {
328
- if (value === undefined || value === null) return []
329
- if (!Array.isArray(value)) throw lexiconError(`LEXICON_INVALID_${label}`, `${label} must be an array of strings`)
330
- return value
331
- .map(item => clip(String(item ?? ''), maxChars))
332
- .map(item => item.trim())
333
- .filter(Boolean)
334
- .slice(0, maxCount)
335
- }
336
-
337
- /**
338
- * 同一规范化 term/alias 在同一可见范围内的冲突检查。返回撞线的既有条目或 null。
339
- * 可见范围 = sameFactContext(channel/speaker/character/world/branch 身份组一致)。
340
- *
341
- * 状态口径(§2.1):
342
- * * includeArchived=false:归档条目完全不参与(旧口径;恢复检查用)。
343
- * * includeArchived=true:归档条目按 term 等值参与(via: 'archived')——归档不占
344
- * 别名位置,但同规范词的新写入必须看见它,否则用户/模型会在归档条目旁边建出
345
- * 一条同词重复,之后 restore 必然撞线。
346
- * * skipRejected=true:rejected 是墓碑,不占命名空间(恢复一个归档条目时,墓碑
347
- * 不该阻止它回到 active)。
348
- * * legacy revision 草稿(带 revisionOf)排在普通词条之后:同词同时存在目标与草稿
349
- * 时,撞线对象永远是目标词条,草稿只作为兜底被看见。
350
- */
351
- function findScopeCollision(terms, {
352
- normalizedTerm, normalizedAliases, context, ignoreTermId = null, includeArchived = false, skipRejected = false,
353
- }) {
354
- let best = null
355
- let bestRank = Infinity
356
- for (const [termId, entry] of Object.entries(terms)) {
357
- if (termId === ignoreTermId) continue
358
- const status = entry.status || 'active'
359
- let via = null
360
- if (status === 'archived') {
361
- if (!includeArchived) continue
362
- if (entry.normalizedTerm === normalizedTerm) via = 'archived'
363
- } else if (status === 'rejected' && skipRejected) {
364
- continue
365
- } else if (sameFactContext(entry.context || {}, context || {})) {
366
- if (entry.normalizedTerm === normalizedTerm) via = 'term'
367
- else if ((entry.normalizedAliases || []).includes(normalizedTerm)) via = 'alias'
368
- else if (normalizedAliases.includes(entry.normalizedTerm)) via = 'new-alias-is-term'
369
- else if ((entry.normalizedAliases || []).some(alias => normalizedAliases.includes(alias))) via = 'alias'
370
- }
371
- if (!via) continue
372
- const rank = (status === 'archived' ? 1 : 0) + (entry.revisionOf ? 2 : 0)
373
- if (rank < bestRank) { best = { termId, entry, via }; bestRank = rank }
374
- }
375
- return best
376
- }
377
-
378
- // active 条目的敏感字段(§2.3 + 契约):这些字段变化时不许非用户来源静默覆盖。
379
- // usage/aliases/examples/confidence/strength/evidence 属于非敏感字段,原地更新。
380
- const SENSITIVE_FIELDS = ['term', 'kind', 'sensitivity', 'context', 'meaning']
381
-
382
- function sensitiveDelta(existing, next) {
383
- const changed = []
384
- for (const field of SENSITIVE_FIELDS) {
385
- const before = field === 'context' ? JSON.stringify(existing.context || {}) : String(existing[field] ?? '')
386
- const after = field === 'context' ? JSON.stringify(next.context || {}) : String(next[field] ?? '')
387
- if (before !== after) changed.push(field)
388
- }
389
- return changed
390
- }
391
-
392
- /**
393
- * 写入/更新一个词条(§2 统一 op 的落点)。
394
- *
395
- * 公开生命周期只有 active / archived(§2.1);pending / rejected 只作为 legacy 数据
396
- * 与内部墓碑存在,任何新写都不会产出它们:
397
- * * 来源 'user':用户显式操作,字段(含敏感字段)直接生效。显式 status:'archived'
398
- * 允许;pending/rejected 一律收口成 active。撞上 archived / rejected / legacy
399
- * pending 词条 = 复活并应用字段(rejected 同时清掉拒绝指纹)。
400
- * * 来源 'model-proposal' / 'curator':普通词条直接 active(不再 pending、不再
401
- * needs_review)。sensitive trigger 一律 typed 拒绝(LEXICON_SENSITIVE_FORBIDDEN);
402
- * 已存在的 sensitive trigger 的任何更新同样拒绝——只有用户能管敏感词。
403
- * * 非用户更新 active / legacy pending 普通词条:敏感字段(term/kind/sensitivity/
404
- * context/meaning)有任何变化 → typed 拒绝(LEXICON_SENSITIVE_FIELDS_FORBIDDEN),
405
- * 绝不生成 pending revision;非敏感字段(usage/aliases/examples/confidence/
406
- * strength/evidence)原地更新。visibility 也不归非用户改(secret 是披露边界,
407
- * 不在 §2.1 的非敏感名单里)。legacy pending 被非用户写入时收口为 active。
408
- * * 撞上 archived 词条:非用户不复活、不新建(notOwned);撞上 rejected 墓碑:
409
- * model-proposal 仍是 LEXICON_PROPOSAL_REJECTED,curator 得到 notOwned;
410
- * 撞上 legacy revision 草稿(revisionOf):非用户不复活(notOwned)。
411
- * * 同规范词(term)在 sameFactContext 作用域内唯一;别名撞线仍是
412
- * LEXICON_ALIAS_CONFLICT(不静默合并——合并会改写别人的记录)。
413
- * * `domain` 是写入会话的领域戳(跨库召回判同域用,§8.15):给了就覆盖,没给就
414
- * 保留既有条目的原值。归档 / 恢复 / 删除这些生命周期动作不碰它。
415
- */
416
- export function upsertLexiconTerm({
417
- libraryId, term, kind = 'term', meaning = '', usage = '', aliases = [], examples = [],
418
- context = {}, knownBy = [], visibility = 'shared', sensitivity, confidence, strength,
419
- evidence = [], source = 'user', status, domain,
420
- }) {
421
- if (!SOURCES.includes(source)) throw lexiconError('LEXICON_INVALID_SOURCE', `lexicon source must be one of ${SOURCES.join(', ')}`)
422
- const isUser = source === 'user'
423
- const rawTerm = String(term ?? '').trim()
424
- if (!rawTerm) throw lexiconError('LEXICON_INVALID_TERM', 'lexicon term must be a non-empty string')
425
- if (rawTerm.length > TERM_MAX_CHARS) throw lexiconError('LEXICON_INVALID_TERM', `lexicon term exceeds ${TERM_MAX_CHARS} characters`)
426
- if (!KINDS.includes(kind)) throw lexiconError('LEXICON_INVALID_KIND', `lexicon kind must be one of ${KINDS.join(', ')}`)
427
- if (!['shared', 'secret'].includes(visibility)) throw lexiconError('LEXICON_INVALID_VISIBILITY', 'lexicon visibility must be shared or secret')
428
- // trigger 默认 sensitive(§1.2);显式传值也只接受两个档位。
429
- const resolvedSensitivity = sensitivity === undefined || sensitivity === null
430
- ? (kind === 'trigger' ? 'sensitive' : 'normal')
431
- : String(sensitivity)
432
- if (!['normal', 'sensitive'].includes(resolvedSensitivity)) throw lexiconError('LEXICON_INVALID_SENSITIVITY', 'lexicon sensitivity must be normal or sensitive')
433
- // 敏感触发词不允许模型/curator 猜(§0.2 / §2.1):非用户来源建 sensitive trigger
434
- // 直接 typed 拒绝,只有用户能管理敏感词。
435
- if (!isUser && kind === 'trigger' && resolvedSensitivity === 'sensitive') {
436
- throw lexiconError('LEXICON_SENSITIVE_FORBIDDEN', `${source} cannot create sensitive triggers; sensitive vocabulary is user-managed`)
437
- }
438
- const normalizedContext = normalizeMemoryContext(context && typeof context === 'object' ? context : {})
439
- const normalizedKnownBy = normalizeStringList(knownBy, { maxCount: 30, maxChars: 128, label: 'KNOWNBY' })
440
- if (normalizedKnownBy.length) normalizedContext.knownBy = normalizedKnownBy
441
- const normalizedTerm = normalizeLexeme(rawTerm)
442
- if (!normalizedTerm) throw lexiconError('LEXICON_INVALID_TERM', 'lexicon term normalizes to empty')
443
- const aliasList = normalizeStringList(aliases, { maxCount: ALIAS_MAX_COUNT, maxChars: ALIAS_MAX_CHARS, label: 'ALIASES' })
444
- const normalizedAliases = aliasList.map(normalizeLexeme).filter(Boolean)
445
- .filter(alias => alias !== normalizedTerm)
446
- const resolvedConfidence = Number.isFinite(Number(confidence)) ? Math.max(0, Math.min(1, Number(confidence))) : 0.8
447
- // strength 是展示权重不是语义字段(不在 SENSITIVE_FIELDS):改它走原地更新。
448
- // 未提供时保留既有值/默认 0.6。
449
- const resolvedStrength = Number.isFinite(Number(strength)) ? Math.max(0, Math.min(1, Number(strength))) : null
450
- // 公开两态(§2.1):pending/rejected 不再由新调用方可设,统一收口为 active;
451
- // 非用户来源连 archived 也不能设(归档是用户动作)。
452
- const explicitStatus = status !== undefined && status !== null && String(status).trim() !== ''
453
- const requestedStatus = PUBLIC_STATUSES.includes(String(status ?? '')) ? String(status) : 'active'
454
- const wantedStatus = isUser ? requestedStatus : 'active'
455
- // 输入侧归一化一次,创建与更新共用(敏感字段比较用同一份结果)。
456
- const fields = {
457
- kind,
458
- meaning: clip(String(meaning ?? ''), MEANING_MAX_CHARS),
459
- usage: clip(String(usage ?? ''), USAGE_MAX_CHARS),
460
- aliases: aliasList,
461
- normalizedAliases,
462
- examples: normalizeStringList(examples, { maxCount: EXAMPLE_MAX_COUNT, maxChars: EXAMPLE_MAX_CHARS, label: 'EXAMPLES' }),
463
- context: normalizedContext,
464
- visibility,
465
- sensitivity: resolvedSensitivity,
466
- confidence: resolvedConfidence,
467
- evidence: normalizeEvidence(evidence),
468
- }
469
-
470
- // domain 是「哪个领域写得了这条词」的戳,跨库召回靠它判是否同域(§8.15)。
471
- // 它不是敏感字段(不进 SENSITIVE_FIELDS):非用户来源也能带它落库;未提供时
472
- // 保留既有条目的原值,绝不清空。
473
- const normalizedDomain = String(domain ?? '').trim().slice(0, 40)
474
- const domainStamp = normalizedDomain ? { domain: normalizedDomain } : null
475
-
476
- return mutateLexicon(libraryId, (lex) => {
477
- const terms = lex.terms
478
- // 同 fingerprint 的 model-proposal 再来 → 直接拒绝(§2.3):rejected 留指纹就是
479
- // 为了让同一句错话不要每轮重放。
480
- const fingerprint = shortHash(normalizedTerm)
481
- if (source === 'model-proposal' && lex.rejected?.[fingerprint]) {
482
- const prior = lex.rejected[fingerprint]
483
- throw lexiconError('LEXICON_PROPOSAL_REJECTED', `this normalized term was already rejected${prior?.reason ? `: ${prior.reason}` : ''}`)
484
- }
485
- const collision = findScopeCollision(terms, {
486
- normalizedTerm, normalizedAliases, context: normalizedContext, includeArchived: true,
487
- })
488
- const now = stamp()
489
-
490
- if (collision && (collision.via === 'term' || collision.via === 'archived')) {
491
- const { termId, entry } = collision
492
- const entryStatus = entry.status || 'active'
493
- // 兜底的指纹拦截:rejected 留在 terms 表里,指纹表缺失(手工修复过的文件)时
494
- // 也不能让 model-proposal 把一条被拒的词条洗回生命周期。
495
- if (source === 'model-proposal' && entryStatus === 'rejected') {
496
- throw lexiconError('LEXICON_PROPOSAL_REJECTED', 'this normalized term was already rejected; resubmission is blocked')
497
- }
498
- // 归档 / 墓碑 / 修订草稿:非用户来源一律不复活、不改写,返回既有条目并标
499
- // notOwned —— 这些状态只由用户(或迁移)处置。
500
- const immutable = entryStatus === 'archived' || entryStatus === 'rejected'
501
- || (entryStatus === 'pending' && Boolean(entry.revisionOf))
502
- if (immutable && !isUser) {
503
- return { term: withTermId(entry, termId), created: false, notOwned: true }
504
- }
505
- if (!isUser) {
506
- // 已存在的 sensitive trigger:所有非用户更新都拒绝(conservative,§2.1)。
507
- if (entry.kind === 'trigger' && entry.sensitivity === 'sensitive') {
508
- throw lexiconError('LEXICON_SENSITIVE_FIELDS_FORBIDDEN', `${source} cannot update the sensitive trigger "${entry.term}"; only the user manages sensitive entries`)
509
- }
510
- // visibility 不在"非敏感字段"名单里(§2.1 只列 usage/aliases/examples/
511
- // confidence/strength/evidence):secret 是披露边界,模型/curator 不得通过更新
512
- // 把一条 secret 词条洗成 shared。沉默忽略也不好——调用方会以为写成功了。
513
- if ((entry.visibility || 'shared') !== visibility) {
514
- throw lexiconError('LEXICON_SENSITIVE_FIELDS_FORBIDDEN', `${source} cannot change the visibility of "${entry.term}" (${entry.visibility || 'shared'} → ${visibility}); only the user can`)
515
- }
516
- const next = {
517
- ...entry, ...fields, updatedAt: now, strength: resolvedStrength ?? (Number(entry.strength) || 0.6),
518
- ...(domainStamp || {}),
519
- }
520
- // 敏感字段变化 → typed 拒绝(§2.1:不再生成 pending revision 等人审)。
521
- const changedSensitive = sensitiveDelta(entry, next)
522
- if (changedSensitive.length) {
523
- throw lexiconError('LEXICON_SENSITIVE_FIELDS_FORBIDDEN', `${source} cannot change sensitive fields (${changedSensitive.join(', ')}) of the existing term "${entry.term}"; ask the user to edit it`)
524
- }
525
- // legacy pending 普通词条:非用户写入直接收口为 active(迁移前的过渡路径)。
526
- if (entryStatus === 'pending') next.status = 'active'
527
- next.normalizedTerm = normalizedTerm
528
- terms[termId] = next
529
- return { term: withTermId(next, termId), created: false }
530
- }
531
- // 用户:直接应用(含敏感字段)。编辑一条已归档词条不应等于悄悄恢复:
532
- // 只有显式 status(或 restoreLexiconTerm)才把它带回 active。显式 status 的
533
- // 复活会断开草稿链(revisionOf 是"某条 active 的下一版草稿"的标记)。
534
- const userStatus = entryStatus === 'archived' && !explicitStatus ? 'archived' : wantedStatus
535
- const next = {
536
- ...entry,
537
- ...fields,
538
- updatedAt: now,
539
- strength: resolvedStrength ?? (Number(entry.strength) || 0.6),
540
- status: userStatus,
541
- normalizedTerm,
542
- fingerprint,
543
- ...(domainStamp || {}),
544
- }
545
- delete next.revisionOf
546
- delete next.previousRevision
547
- const revived = entryStatus !== 'active' && userStatus === 'active'
548
- if (revived) {
549
- next.reviewedAt = now
550
- next.reviewedBy = source
551
- next.reviewReason = null
552
- // rejected 的翻案:清掉拒绝指纹,同词的 model-proposal 不再被无限拦截。
553
- if (entry.fingerprint && lex.rejected?.[entry.fingerprint]) delete lex.rejected[entry.fingerprint]
554
- }
555
- terms[termId] = next
556
- return { term: withTermId(next, termId), created: false, ...(revived ? { revived: true } : {}) }
557
- }
558
-
559
- if (collision) {
560
- // 新词条的 alias 撞了别的词条:宁可报错也不静默合并——合并会改写别人的记录。
561
- throw lexiconError('LEXICON_ALIAS_CONFLICT', `normalized alias collides with existing term "${collision.entry.term}" (${collision.termId})`)
562
- }
563
-
564
- if (Object.keys(terms).length >= LEXICON_CAP) {
565
- throw lexiconError('LEXICON_CAP_REACHED', `lexicon ${libraryId} is at its ${LEXICON_CAP} term capacity; archive or delete before adding`)
566
- }
567
-
568
- const termId = newTermId()
569
- const entry = {
570
- term: rawTerm,
571
- normalizedTerm,
572
- ...fields,
573
- strength: resolvedStrength ?? 0.6,
574
- status: wantedStatus,
575
- source,
576
- fingerprint,
577
- createdAt: now,
578
- updatedAt: now,
579
- reviewedAt: null,
580
- reviewedBy: null,
581
- reviewReason: null,
582
- hitCounts: { candidate: 0, injection: 0, query: 0 },
583
- lastInjectedAt: null,
584
- ...(domainStamp || {}),
585
- }
586
- terms[termId] = entry
587
- return { term: withTermId(entry, termId), created: true }
588
- })
589
- }
590
-
591
- function newTermId() {
592
- return `lex-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`
593
- }
594
-
595
- /**
596
- * 归档(§2.1 / §2.3):只有 active → archived;其余状态 typed 拒绝(legacy pending
597
- * 先走迁移收口,rejected 是墓碑、没有归档语义)。归档不写 rejected 指纹——归档是
598
- * 可恢复的退场,不是拒绝。
599
- */
600
- export function archiveLexiconTerm({ libraryId, termId }) {
601
- return mutateLexicon(libraryId, (lex) => {
602
- const entry = lex.terms[termId]
603
- if (!entry) throw lexiconError('LEXICON_NOT_FOUND', `lexicon term ${termId} does not exist in ${libraryId}`)
604
- const status = entry.status || 'active'
605
- if (status !== 'active') throw lexiconError('LEXICON_INVALID_STATUS', `only active terms can be archived; ${termId} is ${status}`)
606
- const now = stamp()
607
- entry.status = 'archived'
608
- entry.updatedAt = now
609
- return { term: withTermId(entry, termId), termId, action: 'archive' }
610
- })
611
- }
612
-
613
- /**
614
- * 恢复(§2.1 / §2.3):只有 archived → active。两条硬拒绝:
615
- * * legacy revision 草稿(revisionOf 指向仍 active 的目标)不能独立恢复——它是
616
- * 目标词条的下一版草稿,不是词条(LEXICON_REVISION_IMMUTABLE)。
617
- * * 恢复会与同作用域的 active 词条撞同一个规范词面/别名 → LEXICON_ALIAS_CONFLICT
618
- * (不制造同词重复;用户想合并就在两个词条上分别编辑)。
619
- * 墓碑(rejected)不参与撞线:它不占命名空间。
620
- */
621
- export function restoreLexiconTerm({ libraryId, termId }) {
622
- return mutateLexicon(libraryId, (lex) => {
623
- const entry = lex.terms[termId]
624
- if (!entry) throw lexiconError('LEXICON_NOT_FOUND', `lexicon term ${termId} does not exist in ${libraryId}`)
625
- const status = entry.status || 'active'
626
- if (status !== 'archived') throw lexiconError('LEXICON_INVALID_STATUS', `only archived terms can be restored; ${termId} is ${status}`)
627
- if (entry.revisionOf && (lex.terms[entry.revisionOf]?.status || 'active') === 'active') {
628
- throw lexiconError('LEXICON_REVISION_IMMUTABLE', `lexicon term ${termId} is a legacy revision draft of ${entry.revisionOf}; edit the active term instead`)
629
- }
630
- const normalizedAliases = Array.isArray(entry.normalizedAliases) ? entry.normalizedAliases : []
631
- const collision = findScopeCollision(lex.terms, {
632
- normalizedTerm: entry.normalizedTerm,
633
- normalizedAliases,
634
- context: entry.context || {},
635
- ignoreTermId: termId,
636
- skipRejected: true,
637
- })
638
- if (collision) {
639
- throw lexiconError('LEXICON_ALIAS_CONFLICT', `restoring "${entry.term}" would collide with active term "${collision.entry.term}" (${collision.termId})`)
640
- }
641
- const now = stamp()
642
- entry.status = 'active'
643
- entry.updatedAt = now
644
- return { term: withTermId(entry, termId), termId, action: 'restore' }
645
- })
646
- }
647
-
648
- /**
649
- * 删除词条。刻意只暴露给管理面(RPC/UI/P3):模型没有任何删除路径——
650
- * tools.js 的模型工具面拿不到这个函数,curator op 白名单里也没有 delete。
651
- */
652
- export function deleteLexiconTerm({ libraryId, termId }) {
653
- return mutateLexicon(libraryId, (lex) => {
654
- const entry = lex.terms[termId]
655
- if (!entry) throw lexiconError('LEXICON_NOT_FOUND', `lexicon term ${termId} does not exist in ${libraryId}`)
656
- delete lex.terms[termId]
657
- if (entry.fingerprint && lex.rejected?.[entry.fingerprint]?.termId === termId) {
658
- delete lex.rejected[entry.fingerprint]
659
- }
660
- return { deleted: true, termId, term: entry.term }
661
- })
662
- }
663
-
664
- /**
665
- * §1.3 / §2.1:可见词条,逐条过与记忆同一把尺子(contextVisible)。过滤失败的绝不返回。
666
- * 默认只有 active;`includeArchived: true`(管理面/浏览器)追加已归档词条(含 legacy
667
- * revision 草稿)。pending/rejected 永远不出现——前者只服务迁移,后者是内部墓碑。
668
- * 状态分组与展示序都在索引构建时定好,这里只剩 contextVisible 过滤本身;active 与
669
- * archived 混排时重排一次(两段各自有序,合并后必须保持同一把展示序)。
670
- */
671
- export function visibleLexiconTerms(libraryId, memoryContext, { includeArchived = false } = {}) {
672
- const index = lexiconIndex(libraryId)
673
- const out = []
674
- for (const { termId, entry } of index.activeEntries) {
675
- if (!contextVisible(entry.context, memoryContext)) continue
676
- out.push(withTermId(entry, termId))
677
- }
678
- if (includeArchived) {
679
- for (const { termId, entry } of index.archivedEntries) {
680
- if (!contextVisible(entry.context, memoryContext)) continue
681
- out.push(withTermId(entry, termId))
682
- }
683
- out.sort((a, b) => (Number(b.strength) || 0) - (Number(a.strength) || 0)
684
- || String(b.updatedAt || '').localeCompare(String(a.updatedAt || ''))
685
- || String(a.termId).localeCompare(String(b.termId)))
686
- }
687
- return out
688
- }
689
-
690
- function clamp01(value) {
691
- const n = Number(value)
692
- if (!Number.isFinite(n)) return 0
693
- return Math.max(0, Math.min(1, n))
694
- }
695
-
696
- /**
697
- * Wilson 下界(§6.3 包 C 的有界频率先验,A-13:同源分子/分母)。
698
- *
699
- * 分母 n 优先取 priorAttempts——「该词条被召回的总尝试次数」这一同源计数;
700
- * 成功数 success = injection + query,即「被召回后确实被注入/查询命中」的
701
- * 同源事件。旧实现把 candidate(候选池大小,另一条计数通道)当分母,再把
702
- * injection+query clamp 到它,两个不相干的计数被硬凑成一个比例,口径不严谨
703
- * (虽然有界、不会 runaway)。
704
- *
705
- * 兼容近似:当前写入路径还没有记录 priorAttempts,缺失(或非正数)时退回
706
- * candidate 作为分母,并在此文档化这一假设——candidate 是「进过匹配结果」的
707
- * 次数,是现有数据里与「被召回」最接近的代理;success 仍被 min(n, ...) 钳住,
708
- * 公式保持有界。写入侧按同源事件补上 priorAttempts 后,先验自动切换到严格口径。
709
- *
710
- * 设计约束不变:
711
- * * n=0 → 0(从未候选过的词条没有任何频率证据,因子取下限 0.85)。
712
- * * 1/1 的下界 ≈ 0.207,因子最多 ~3% 差距——一条偶发命中压不过长期稳定使用的词。
713
- * * 100/120 的下界明显更高——长期被真正使用的词条温和提升。
714
- * * 输出 clamp 到 [0,1],与 strength/confidence 的 clamp01 同口径;乘上
715
- * (0.85 + 0.15 * lb) 后 effective 因子恒在 [0.85,1.00],不 runaway。
716
- */
717
- export function usageLowerBound(counts) {
718
- const attempts = Math.max(0, Math.floor(Number(counts?.priorAttempts) || 0))
719
- const n = attempts > 0 ? attempts : Math.max(0, Math.floor(Number(counts?.candidate) || 0))
720
- if (n === 0) return 0
721
- const success = Math.min(n, Math.max(0, (Number(counts?.injection) || 0) + (Number(counts?.query) || 0)))
722
- const p = success / n
723
- const z = WILSON_Z, z2 = z * z
724
- const lb = (p + z2 / (2 * n) - z * Math.sqrt((p * (1 - p) + z2 / (4 * n)) / n)) / (1 + z2 / n)
725
- return clamp01(lb)
726
- }
727
-
728
- /**
729
- * effective 展示权重(§6.3 排序键):strength × confidence × (0.85 + 0.15 × Wilson
730
- * 下界)。因子固定在 [0.85,1.00],只做温和的先验,绝不压过 exact/alias/Dice 的
731
- * 匹配层级——那三层在 stableRank 里先于 effective 生效。
732
- */
733
- function effectiveWeight(hit) {
734
- return clamp01(hit.strength) * clamp01(hit.confidence) * (0.85 + 0.15 * usageLowerBound(hit.hitCounts))
735
- }
736
-
737
- /** §3.2 稳定排序:排序键固定,末位 id 字典序,绝不用当前时间或遍历序做 tie-break。 */
738
- function stableRank(hits) {
739
- return [...hits].sort((a, b) => {
740
- const sa = sensitivityRank(a), sb = sensitivityRank(b)
741
- if (sa !== sb) return sb - sa
742
- const ea = exactRank(a.kindOfHit), eb = exactRank(b.kindOfHit)
743
- if (ea !== eb) return eb - ea
744
- if (ea === 1 && Math.abs((b.score || 0) - (a.score || 0)) > 1e-9) return (b.score || 0) - (a.score || 0)
745
- const wa = effectiveWeight(a), wb = effectiveWeight(b)
746
- if (Math.abs(wb - wa) > 1e-9) return wb - wa
747
- const ga = scopeSpecificity(a.context), gb = scopeSpecificity(b.context)
748
- if (ga !== gb) return gb - ga
749
- const ta = String(a.updatedAt || ''), tb = String(b.updatedAt || '')
750
- if (ta !== tb) return tb.localeCompare(ta)
751
- return String(a.termId).localeCompare(String(b.termId))
752
- })
753
- }
754
-
755
- // 敏感优先的定义(§8.3 统一项):与锚点摘要(lexiconAnchorSummary 按
756
- // sensitivity === 'sensitive' 单列)同一把尺——sensitivity 即敏感,不再要求
757
- // kind === 'trigger'。旧实现 B 通道只抬 trigger+sensitive、锚点按全部 sensitive
758
- // 分组,两条通道对"敏感"的判定不一致;统一为「只要 sensitive 就优先」,与
759
- // §8.1「敏感词安全高于自动化」一致,也和写入侧 trigger 默认 sensitive 的口径互补。
760
- function sensitivityRank(hit) {
761
- return hit.sensitivity === 'sensitive' ? 1 : 0
762
- }
763
-
764
- // exact term > exact alias > dice(§3.2 的 2-4 键)。
765
- function exactRank(kindOfHit) {
766
- if (kindOfHit === 'exact-term') return 3
767
- if (kindOfHit === 'exact-alias') return 2
768
- return 1
769
- }
770
-
771
- // 作用域具体度(§3.2 排序键之一,显式定义):词条 context 里已定义的身份字段个数。
772
- // 字段集与 lib/context.js 的 IDENTITIES 完全同组(channelId/speakerId/characterId/
773
- // worldId/branchId),非空数越多越具体,具体者优先。knownBy 是可见性边界
774
- // (contextVisible 的事),不是作用域,不计入;空白 context = 全场景共享,具体度
775
- // 0,排在任何带作用域的词条之后。
776
- function scopeSpecificity(context) {
777
- if (!context || typeof context !== 'object') return 0
778
- return ['channelId', 'speakerId', 'characterId', 'worldId', 'branchId'].filter(key => context[key]).length
779
- }
780
-
781
- /**
782
- * 文本侧窗口(A-8):穷举 BUCKET_WIDTH 字符窗口并去重,按「该窗口在前缀桶里
783
- * 命中的词条数」降序取 top-N。旧实现按出现顺序取前 16 个窗口:长文本里真正
784
- * 含错字变体的窗口(例如 40 字闲聊末尾的「糖刀文雪」)常常落在第 17 个之后,
785
- * 模糊层连候选都收不到——召不回不是因为 Dice 不够,而是窗口根本没被展开。
786
- * 命中数相同的窗口保持出现顺序(sort 稳定),输出可复现。
787
- *
788
- * 命中数取索引里该桶的全量大小(含 archived/pending):窗口排序只是「哪些窗口
789
- * 值得展开」的成本决策,可见性仍由逐候选的 isVisible 复核,不会被这里放宽。
790
- */
791
- function textBuckets(normalizedText, index, maxBuckets = LEXICON_MAX_BUCKETS) {
792
- const keys = []
793
- const seen = new Set()
794
- for (let i = 0; i + BUCKET_WIDTH <= normalizedText.length; i++) {
795
- const key = normalizedText.slice(i, i + BUCKET_WIDTH)
796
- if (seen.has(key)) continue
797
- seen.add(key)
798
- keys.push(key)
799
- }
800
- return keys
801
- .map((key, order) => ({ key, order, hits: index?.prefixBuckets?.get(key)?.size || 0 }))
802
- .sort((a, b) => b.hits - a.hits || a.order - b.order)
803
- .slice(0, maxBuckets)
804
- .map((item) => item.key)
805
- }
806
-
807
- /**
808
- * 桶内 dice 兜底:对每个候选词条,在文本里定位它桶键的出现位置,取等长窗口算
809
- * Dice,取最大值。候选 ≤ maxCandidates、命中 ≤ maxTerms,O(C) 有界(§6)。
810
- */
811
- function diceFallback(normalizedText, candidates, { threshold = LEXICON_DICE_THRESHOLD, maxCandidates = LEXICON_MAX_CANDIDATES, maxTerms = LEXICON_MAX_TERMS } = {}) {
812
- const textGrams = bigrams(normalizedText)
813
- if (!textGrams.size) return []
814
- const scored = []
815
- for (const hit of candidates.slice(0, maxCandidates)) {
816
- let best = 0
817
- for (const surface of [hit.normalizedTerm, ...(hit.normalizedAliases || [])]) {
818
- if (!surface || surface.length < BUCKET_WIDTH) continue
819
- const key = surface.slice(0, BUCKET_WIDTH)
820
- let pos = normalizedText.indexOf(key)
821
- while (pos >= 0) {
822
- const window = normalizedText.slice(pos, pos + surface.length)
823
- const score = dice(bigrams(window), bigrams(surface))
824
- if (score > best) best = score
825
- if (best >= 1) break
826
- pos = normalizedText.indexOf(key, pos + 1)
827
- }
828
- if (best >= threshold) break
829
- }
830
- if (best >= threshold) scored.push({ ...hit, kindOfHit: 'dice', score: best })
831
- }
832
- scored.sort((a, b) => (b.score - a.score)
833
- || (Number(b.strength) || 0) * (Number(b.confidence) || 0) - (Number(a.strength) || 0) * (Number(a.confidence) || 0)
834
- || String(a.termId).localeCompare(String(b.termId)))
835
- return scored.slice(0, maxTerms)
836
- }
837
-
838
- function hitOf(entry, termId, kindOfHit, score) {
839
- return {
840
- termId,
841
- term: entry.term,
842
- normalizedTerm: entry.normalizedTerm,
843
- kind: entry.kind,
844
- meaning: entry.meaning,
845
- usage: entry.usage,
846
- sensitivity: entry.sensitivity,
847
- strength: entry.strength,
848
- confidence: entry.confidence,
849
- // 频率先验(§6.3)的输入:stableRank 的 effective 因子按三计数算 Wilson 下界。
850
- hitCounts: entry.hitCounts && typeof entry.hitCounts === 'object' ? entry.hitCounts : { candidate: 0, injection: 0, query: 0 },
851
- context: entry.context,
852
- updatedAt: entry.updatedAt,
853
- status: entry.status,
854
- kindOfHit,
855
- score,
856
- }
857
- }
858
-
859
- /**
860
- * §3.1-§3.2 匹配流水线:精确(等值/包含)→ 前缀桶 → 桶内 dice 兜底 → stableRank。
861
- * 只读不写:candidate/injection 计数由调用方(inject.js)在真正发生时记。
862
- * 只匹配 active 词条:archived 已退场、rejected 是墓碑、legacy pending 等迁移收口,
863
- * 三种状态都不进注入(§2.1)。
864
- *
865
- * 全部走 revision-keyed 索引(§10 P1):等值 O(1) 查 Map;包含层用「词面 ⊆ 文本
866
- * ⇒ 词面前缀 = 文本某个 2 字窗口」的性质从前缀桶收候选(窗口穷举不设 16 上限——
867
- * 16 上限只属于 dice 候选,精确层语义从来没有窗口上限);dice 兜底仍按桶扫且
868
- * C ≤ 64 不变(§6),但窗口按命中词条数排序、候选按与 query 的共享 gram 数
869
- * 排序(A-8:候选准入看相关性,不看 strength)。可见性(status +
870
- * contextVisible)在收候选时逐个复核。
871
- */
872
- export function matchLexiconHits(libraryId, userText, memoryContext) {
873
- const normalizedText = normalizeLexeme(userText)
874
- if (!normalizedText) return []
875
- const index = lexiconIndex(libraryId)
876
- const data = index.data
877
- const isVisible = termId => {
878
- const entry = data.terms[termId]
879
- return Boolean(entry) && (entry.status || 'active') === 'active' && contextVisible(entry.context, memoryContext)
880
- }
881
- // 精确层·等值:Map 直查(同库同词面可有多条跨 scope 词条,值是 termId 列表)。
882
- const hits = []
883
- const exactIds = new Set()
884
- const pushExact = (termId, kindOfHit) => {
885
- if (exactIds.has(termId) || !isVisible(termId)) return
886
- exactIds.add(termId)
887
- hits.push(hitOf(data.terms[termId], termId, kindOfHit, 1))
888
- }
889
- for (const termId of index.byNormalizedTerm.get(normalizedText) || []) pushExact(termId, 'exact-term')
890
- for (const termId of index.byAlias.get(normalizedText) || []) pushExact(termId, 'exact-alias')
891
- // 精确层·包含:词面(≥MIN_INCLUDE_LEN)出现在文本里。前缀桶给出候选超集,
892
- // 逐候选复核 includes 并保留原判定序(term 在前、aliases 随后,第一个命中的
893
- // 词面决定 exact-term / exact-alias 标签)。
894
- const containIds = []
895
- for (let i = 0; i + BUCKET_WIDTH <= normalizedText.length; i++) {
896
- for (const termId of index.prefixBuckets.get(normalizedText.slice(i, i + BUCKET_WIDTH)) || []) {
897
- if (!exactIds.has(termId) && !containIds.includes(termId)) containIds.push(termId)
898
- }
899
- }
900
- for (const termId of containIds) {
901
- if (!isVisible(termId)) continue
902
- const entry = data.terms[termId]
903
- let matched = null
904
- for (const item of index.surfacesByTerm.get(termId) || []) {
905
- if (item.surface.length >= LEXICON_MIN_INCLUDE_LEN && normalizedText.includes(item.surface)) { matched = item; break }
906
- }
907
- if (matched) {
908
- exactIds.add(termId)
909
- hits.push(hitOf(entry, termId, matched.via === 'term' ? 'exact-term' : 'exact-alias', 1))
910
- }
911
- }
912
- // dice 候选:窗口数仍以 LEXICON_MAX_BUCKETS 封顶(§4.2 的 C≤64 语义不变),
913
- // 但窗口与候选都按「与 query 的相关性」排:窗口按命中词条数降序(见
914
- // textBuckets),候选按与 query 共享的 gram 数降序。旧实现把候选按
915
- // strength×confidence 取前 64——候选池被一批不一定相关的强词条占满,真正
916
- // 只差一个字的弱词条反而进不了 diceFallback。strength 与 termId 只做确定性
917
- // tiebreak(与 diceFallback 的末位排序同口径)。
918
- const candidateIds = new Set()
919
- for (const key of textBuckets(normalizedText, index)) {
920
- for (const termId of index.prefixBuckets.get(key) || []) {
921
- if (exactIds.has(termId) || !isVisible(termId)) continue
922
- candidateIds.add(termId)
923
- }
924
- }
925
- const textGrams = bigrams(normalizedText)
926
- const sharedGramCount = termId => {
927
- let best = 0
928
- for (const { surface } of index.surfacesByTerm.get(termId) || []) {
929
- let shared = 0
930
- for (const gram of bigrams(surface)) if (textGrams.has(gram)) shared += 1
931
- if (shared > best) best = shared
932
- }
933
- return best
934
- }
935
- const weightOf = termId => (Number(data.terms[termId].strength) || 0) * (Number(data.terms[termId].confidence) || 0)
936
- const candidates = [...candidateIds]
937
- .map(termId => ({ termId, shared: sharedGramCount(termId) }))
938
- .sort((a, b) => b.shared - a.shared
939
- || weightOf(b.termId) - weightOf(a.termId)
940
- || String(a.termId).localeCompare(String(b.termId)))
941
- .map(({ termId }) => hitOf(data.terms[termId], termId, 'dice', 0))
942
- const fuzzy = diceFallback(normalizedText, candidates)
943
- // stableRank 的末位 tie-break 是唯一 termId,命中顺序不影响最终排序。
944
- return stableRank([...hits, ...fuzzy])
945
- }
946
-
947
- /**
948
- * 精确层检索(§3.3 通道 C 的数据面):等值 + includes,不做 dice、不做语义。
949
- * 默认只回 active;`includeArchived: true` 让管理面/浏览器显式看到归档词条。
950
- * pending(迁移前的老提案)与 rejected(墓碑)在任何模式下都不出现。
951
- * 走 revision-keyed 索引:等值 O(1) 查 Map;正向包含(词面 ⊆ query)用前缀桶
952
- * 收候选(穷举窗口、不设 16 上限——精确层语义没有窗口上限);反向包含
953
- * (query ⊆ 词面)用 gram 倒排收候选。两个候选集都是超集,逐候选复核原始谓词。
954
- */
955
- export function searchLexicon({ libraryId, query, memoryContext }, { includeArchived = false } = {}) {
956
- const normalizedQuery = normalizeLexeme(query)
957
- const out = []
958
- if (!normalizedQuery) return out
959
- const index = lexiconIndex(libraryId)
960
- const data = index.data
961
- const matched = []
962
- const considered = new Set()
963
- const consider = termId => {
964
- if (considered.has(termId)) return
965
- considered.add(termId)
966
- const entry = data.terms[termId]
967
- const status = entry.status || 'active'
968
- if (status !== 'active' && !(includeArchived && status === 'archived')) return
969
- if (!contextVisible(entry.context, memoryContext)) return
970
- const aliases = Array.isArray(entry.normalizedAliases) ? entry.normalizedAliases : []
971
- let matchedBy = null
972
- if (entry.normalizedTerm === normalizedQuery) matchedBy = 'term'
973
- else if (aliases.includes(normalizedQuery)) matchedBy = 'alias'
974
- else if (entry.normalizedTerm.length >= LEXICON_MIN_INCLUDE_LEN
975
- && (normalizedQuery.includes(entry.normalizedTerm) || entry.normalizedTerm.includes(normalizedQuery))) matchedBy = 'contains'
976
- else if (aliases.some(alias => alias.length >= LEXICON_MIN_INCLUDE_LEN
977
- && (normalizedQuery.includes(alias) || alias.includes(normalizedQuery)))) matchedBy = 'alias-contains'
978
- if (matchedBy) matched.push({ ...withTermId(entry, termId), matchedBy })
979
- }
980
- for (const termId of index.byNormalizedTerm.get(normalizedQuery) || []) consider(termId)
981
- for (const termId of index.byAlias.get(normalizedQuery) || []) consider(termId)
982
- if (normalizedQuery.length >= BUCKET_WIDTH) {
983
- const forward = new Set()
984
- const reverse = new Set()
985
- for (let i = 0; i + BUCKET_WIDTH <= normalizedQuery.length; i++) {
986
- const window = normalizedQuery.slice(i, i + BUCKET_WIDTH)
987
- for (const termId of index.prefixBuckets.get(window) || []) {
988
- if (!considered.has(termId)) forward.add(termId)
989
- }
990
- for (const termId of index.grams.get(window) || []) {
991
- if (!considered.has(termId) && !forward.has(termId)) reverse.add(termId)
992
- }
993
- }
994
- for (const termId of forward) consider(termId)
995
- for (const termId of reverse) consider(termId)
996
- } else {
997
- // 单字 query 没有 2 字窗口,反向包含(词面含该字)退化为对索引词面表的全扫:
998
- // 原生 includes 逐词面跑,N=5k 时仍是毫秒级;语义与逐条扫描完全一致。
999
- for (const [termId, surfaces] of index.surfacesByTerm) {
1000
- if (considered.has(termId)) continue
1001
- if (surfaces.some(item => item.surface.length >= LEXICON_MIN_INCLUDE_LEN && item.surface.includes(normalizedQuery))) {
1002
- consider(termId)
1003
- }
1004
- }
1005
- }
1006
- matched.sort((a, b) => {
1007
- const ra = a.matchedBy === 'term' ? 3 : a.matchedBy === 'alias' ? 2 : 1
1008
- const rb = b.matchedBy === 'term' ? 3 : b.matchedBy === 'alias' ? 2 : 1
1009
- if (ra !== rb) return rb - ra
1010
- return String(a.termId).localeCompare(String(b.termId))
1011
- })
1012
- // query 计数(§3.3 三计数之一):显式查询是注意力,best-effort 记账,失败不影响
1013
- // 结果。只给 active 记账——管理面翻归档(includeArchived)不是"这次检索用到了它",
1014
- // 归档词条不进注入,给它加 query 计数只会污染频率先验。一次批量记账 = 一次锁内
1015
- // CAS 写,不把检索变成 N 次磁盘写。
1016
- const countable = matched.filter(item => (item.status || 'active') === 'active').slice(0, 20)
1017
- if (countable.length) {
1018
- try { lexiconRecordHits(libraryId, countable.map(item => item.termId), 'query') } catch (error) {
1019
- warn(`lexicon query accounting failed: ${error?.message || error}`)
1020
- }
1021
- }
1022
- return matched
1023
- }
1024
-
1025
- /**
1026
- * B 通道的渲染与成本共用同一把尺:cooldownAndBudget 按 estTokens(line) 扣预算。
1027
- * “词典也是标题”(§2.2):term 是标题(≤40 字),meaning/usage 只给短义(≤80 字),
1028
- * 不展开 usage/examples——注入行永远是「标题 + 短释义」。
1029
- */
1030
- export function lexiconTurnLine(hit) {
1031
- const body = clip(String(hit.meaning || hit.usage || ''), 80)
1032
- return `「${clip(String(hit.term || ''), 40)}」${body ? `:${body}` : ''}`
1033
- }
1034
-
1035
- /**
1036
- * 冷却 + 每回合预算(§3.3):冷却内的词条仍出现在 hits 里(可计 candidate),
1037
- * 但不进 selected(不计 injection)。预算按渲染行的 estTokens 顺序扣,扣不动就停。
1038
- * bindingState 传 sessionId(string)或带 sessionId 的 binding 对象。
1039
- */
1040
- export function cooldownAndBudget(hits, bindingState, tokenBudget) {
1041
- const sessionKey = typeof bindingState === 'string' ? bindingState : String(bindingState?.sessionId || '')
1042
- const now = Date.now()
1043
- const cooldownMs = LEXICON_RECALL_COOLDOWN_MINUTES * 60_000
1044
- const last = lexiconCooldownStore.get(sessionKey)
1045
- const selected = []
1046
- const onCooldown = []
1047
- let used = 0
1048
- const budget = Math.max(0, Number(tokenBudget) || 0)
1049
- for (const hit of hits) {
1050
- const injectedAt = last?.get(hit.termId) || 0
1051
- if (injectedAt && now - injectedAt < cooldownMs) { onCooldown.push(hit); continue }
1052
- if (selected.length >= LEXICON_MAX_PER_TURN) continue
1053
- const cost = estTokens(lexiconTurnLine(hit)) + (selected.length ? 1 : 0)
1054
- if (used + cost > budget) continue
1055
- used += cost
1056
- selected.push(hit)
1057
- }
1058
- return { selected, onCooldown, used }
1059
- }
1060
-
1061
- /** 注入真的发生之后才调用:记冷却,下一次同词在冷却窗口内只做 candidate。 */
1062
- export function lexiconMarkInjected(bindingKey, termIds, now = Date.now()) {
1063
- const sessionKey = String(bindingKey || '')
1064
- if (!sessionKey || !Array.isArray(termIds) || termIds.length === 0) return
1065
- let last = lexiconCooldownStore.get(sessionKey)
1066
- if (!last) { last = new Map(); lexiconCooldownStore.set(sessionKey, last) }
1067
- for (const termId of termIds) last.set(termId, now)
1068
- // Map 只增不减会陪着进程活着变大;词条冷却窗口 30 分钟,过期键在读取时本就无效,
1069
- // 这里顺手把整本已过期的 session 键清掉,成本 O(sessions)。
1070
- if (lexiconCooldownStore.size > 512) {
1071
- for (const [key, value] of lexiconCooldownStore) {
1072
- const freshest = Math.max(...value.values())
1073
- if (now - freshest >= cooldownWindowMs()) lexiconCooldownStore.delete(key)
1074
- }
1075
- }
1076
- }
1077
-
1078
- function cooldownWindowMs() { return LEXICON_RECALL_COOLDOWN_MINUTES * 60_000 }
1079
-
1080
- export function lexiconOnCooldown(bindingKey, termId, now = Date.now()) {
1081
- const last = lexiconCooldownStore.get(String(bindingKey || ''))?.get(termId) || 0
1082
- return last > 0 && now - last < cooldownWindowMs()
1083
- }
1084
-
1085
- /**
1086
- * 三计数分开累加(§3.3):candidate(进过匹配结果)/ injection(真的注入了)/
1087
- * query(显式检索命中)。写路径走 mutateLexicon(锁内 CAS + revision+1)。
1088
- */
1089
- export function lexiconRecordHit(libraryId, termId, kindOfHit) {
1090
- if (!['candidate', 'injection', 'query'].includes(kindOfHit)) {
1091
- throw lexiconError('LEXICON_INVALID_HIT_KIND', 'hit kind must be candidate, injection or query')
1092
- }
1093
- const result = lexiconRecordHits(libraryId, [termId], kindOfHit)
1094
- return { termId, hitCounts: result.counts[termId] }
1095
- }
1096
-
1097
- /** 一次锁内写累加多个词条的同一类计数;未知词条抛 LEXICON_NOT_FOUND。 */
1098
- export function lexiconRecordHits(libraryId, termIds, kindOfHit) {
1099
- return mutateLexicon(libraryId, (lex) => {
1100
- const counts = {}
1101
- for (const termId of termIds) {
1102
- const entry = lex.terms[termId]
1103
- if (!entry) throw lexiconError('LEXICON_NOT_FOUND', `lexicon term ${termId} does not exist in ${libraryId}`)
1104
- entry.hitCounts = entry.hitCounts && typeof entry.hitCounts === 'object'
1105
- ? entry.hitCounts
1106
- : { candidate: 0, injection: 0, query: 0 }
1107
- // 计数上限(§6.3 HIT_COUNT_CAP):累加后 clamp 到 1,000,000——既有值越界
1108
- // (手工修复/损坏数据)也在同一步被拉回界内,effective 因子的输入永远有界。
1109
- for (const key of ['candidate', 'injection', 'query']) {
1110
- entry.hitCounts[key] = Math.min(HIT_COUNT_CAP, Math.max(0, Number(entry.hitCounts[key]) || 0))
1111
- }
1112
- entry.hitCounts[kindOfHit] = Math.min(HIT_COUNT_CAP, (Number(entry.hitCounts[kindOfHit]) || 0) + 1)
1113
- if (kindOfHit === 'injection') entry.lastInjectedAt = stamp()
1114
- counts[termId] = { ...entry.hitCounts }
1115
- }
1116
- return { counts }
1117
- })
1118
- }
1119
-
1120
- /** §3.2 稳定排序的对外出口:跨源合并后必须用同一把尺重排,不许调用方自定排序。 */
1121
- export function rankLexiconHits(hits) {
1122
- return stableRank(hits)
1123
- }
1124
-
1125
- /**
1126
- * 锚点摘要(§3.3 通道 A 的数据面):top 8 by strength;敏感词条单列且 ≤2。
1127
- * 行已按优先级排好——inject.js 超 300 token 时从尾部丢,丢的永远是最弱的一条。
1128
- *
1129
- * visibility 与记忆同一套语义(lib/memory.js visibleToSession 的契约:secret 只是
1130
- * "不主动浮出",不改变"被点名时"的可见性):锚点是主动浮出,secret 词条不进摘要;
1131
- * B 通道是用户消息点到了词面(等价于按词点名),secret 词条仍然命中并解释。
1132
- *
1133
- * 入参是「已按可见性过滤好的词条」,所以单库摘要与跨源合并摘要共用同一份渲染与
1134
- * 取舍规则(lexiconAnchorSummary 是本函数在单库上的包装)。
1135
- */
1136
- export function lexiconAnchorLines(entries) {
1137
- const anchorable = (Array.isArray(entries) ? entries : []).filter(entry => entry.visibility !== 'secret')
1138
- const sensitive = anchorable.filter(entry => entry.sensitivity === 'sensitive')
1139
- const normal = anchorable.filter(entry => entry.sensitivity !== 'sensitive')
1140
- const line = entry => `「${clip(String(entry.term || ''), 40)}」(${entry.kind})${entry.meaning ? ` ${clip(String(entry.meaning), 80)}` : ''}`
1141
- const byStrength = list => [...list].sort((a, b) => (Number(b.strength) || 0) - (Number(a.strength) || 0)
1142
- || String(b.updatedAt || '').localeCompare(String(a.updatedAt || ''))
1143
- || String(a.termId).localeCompare(String(b.termId)))
1144
- return {
1145
- lines: byStrength(normal).slice(0, 8).map(line),
1146
- sensitiveTriggers: byStrength(sensitive).slice(0, 2).map(line),
1147
- }
1148
- }
1149
-
1150
- export function lexiconAnchorSummary(libraryId, memoryContext) {
1151
- return lexiconAnchorLines(visibleLexiconTerms(libraryId, memoryContext))
1152
- }
1153
-
1154
- /**
1155
- * legacy 生命周期迁移(§2.1):旧版 pending 在当前生命周期不再存在,读到就跑一次收口。
1156
- * * pending 且 !revisionOf(老提案)→ active;敏感词 → archived(敏感词只能由用户
1157
- * 显式管理,不能因为迁移悄悄进入注入面)。legacy 数据缺 sensitivity 的 trigger
1158
- * 默认按 sensitive 处理(§1.2 的缺省值),同样归档。
1159
- * * pending 且 revisionOf(老修订草稿)→ archived:目标词条不动,草稿留审计。
1160
- * * rejected → 原样保留(内部墓碑 + fingerprint 不变)。
1161
- * 只写有变化的文件:没有 pending 时直接返回,不 bump revision(迁移是巡检常客,
1162
- * 空转写盘会让 revision 变成噪声,也会把没改过的文件推成热文件)。
1163
- * 返回 { libraryId, migrated, details? };损坏/读失败仍是 typed error(调用方决定
1164
- * 是否吞掉——lib/migrate.js 的巡检按库 catch)。
1165
- */
1166
- export function migrateLegacyLexiconStatuses(libraryId) {
1167
- // 快速路径:索引已经知道有没有 legacy pending;没有就不进锁、不写盘。
1168
- const index = lexiconIndex(libraryId)
1169
- if (!index.pendingEntries.length) return { libraryId, migrated: 0 }
1170
- const outcome = mutateLexicon(libraryId, (lex) => {
1171
- const now = stamp()
1172
- const details = []
1173
- for (const [termId, entry] of Object.entries(lex.terms)) {
1174
- if ((entry.status || 'active') !== 'pending') continue
1175
- // trigger 的 sensitivity 缺省是 sensitive(§1.2);legacy 数据可能没写这个字段。
1176
- const sensitive = entry.sensitivity === 'sensitive'
1177
- || (entry.kind === 'trigger' && entry.sensitivity !== 'normal')
1178
- const next = entry.revisionOf || sensitive ? 'archived' : 'active'
1179
- entry.status = next
1180
- entry.migratedFromStatus = 'pending'
1181
- entry.statusMigratedAt = now
1182
- details.push({
1183
- termId,
1184
- status: next,
1185
- reason: entry.revisionOf ? 'revision-draft' : sensitive ? 'sensitive' : 'proposal',
1186
- ...(entry.revisionOf ? { revisionOf: entry.revisionOf } : {}),
1187
- })
1188
- }
1189
- return { changed: details.length > 0, migrated: details.length, details }
1190
- }, { onlyWhenChanged: true })
1191
- return { libraryId, migrated: outcome.migrated, details: outcome.details }
1192
- }
1
+ // ── 词典层(Lexicon)核心:P0 存储安全 + 生命周期 active/archived + P1 读取检索 ──
2
+ // 契约:docs/memory-semantics.md §8.13(当前生命周期与注入语义)。
3
+ // 词典不替代记忆、不触发下载、不接 settings:冷却与预算全部用本模块常量 + 模块内
4
+ // 状态(见 lexiconCooldownStore)。
5
+ //
6
+ // 存储安全不变量(§1-§2,每一条都有对应测试):
7
+ // * 路径只能是 dataDir()/lexicon/<libraryId>.json,libraryId 过 isSafeId(拒绝
8
+ // 绝对路径、..、路径分隔符——isSafeId 的白名单字符集天然挡掉它们)。
9
+ // * 读:缺失 → 空结构;损坏/IO 失败/曾 quarantined → typed error,绝不当空处理
10
+ // (paths.readJsonStrict 的口径:吞掉的读失败会把下一次写变成整库覆盖)。
11
+ // * 写:一切写函数在 withFileLock 内重读磁盘上的最新 revision 再改(CAS),
12
+ // revision 单调 +1 后 writeJson 原子替换(tmp + fsync + rename)。锁是同步作用
13
+ // 域,从不跨 await。调用方手里的任何旧副本都写不回磁盘——写路径不接受外部对象。
14
+ // * 记录格式 §1.2:normalizedTerm/normalizedAliases、evidence 短证据、hitCounts
15
+ // 三计数(candidate/injection/query)。
16
+ // * 生命周期(§2.1):公开两态 active/archived;`pending` 只作为旧版的 legacy
17
+ // 数据被读(迁移见 migrateLegacyLexiconStatuses),`rejected` 只作为内部墓碑 +
18
+ // fingerprint 存在(永不注入、永不列出、永不计数)。新写路径不再产出这两种状态。
19
+ // * 读路径(§10 P1):每本词典一份 revision-keyed 内存快照 + 派生索引,见
20
+ // lexiconIndexCache 的注释——JSON 是唯一主事实,索引永远是可重建的派生物。
21
+ import fs from 'node:fs'
22
+ import path from 'node:path'
23
+ import { dataDir, readJsonStrict, readFailure, writeJson, withFileLock, isSafeId, shortHash, warn, stamp } from './paths.js'
24
+ import { normalizeMemoryContext, contextVisible, sameFactContext } from './context.js'
25
+ import { bigrams, dice } from './text-similarity.js'
26
+ import { estTokens } from './budget.js'
27
+
28
+ // 容量与长度上限(§1.2)。刻意不接 settings:容量是存储安全边界,不该被运行时配置放宽。
29
+ export const LEXICON_CAP = 5000
30
+ const TERM_MAX_CHARS = 80
31
+ const MEANING_MAX_CHARS = 500
32
+ const USAGE_MAX_CHARS = 300
33
+ const ALIAS_MAX_COUNT = 8
34
+ const ALIAS_MAX_CHARS = 80
35
+ const EXAMPLE_MAX_COUNT = 5
36
+ const EXAMPLE_MAX_CHARS = 200
37
+ const EVIDENCE_MAX_COUNT = 10
38
+ const EVIDENCE_QUOTE_MAX_CHARS = 200
39
+
40
+ // 匹配流水线常量(§3.1-§3.2)。threshold 0.60 是起步标定值,P4 用标注样本复核。
41
+ export const LEXICON_DICE_THRESHOLD = 0.6
42
+ export const LEXICON_MAX_BUCKETS = 16
43
+ export const LEXICON_MAX_CANDIDATES = 64
44
+ export const LEXICON_MAX_TERMS = 8
45
+ // 词面包含(includes)命中的最小规范化长度:单字词在 CJK 里到处出现,放进精确层
46
+ // 只会制造噪声。等值匹配(整句恰好等于词条)不受此限制。
47
+ export const LEXICON_MIN_INCLUDE_LEN = 2
48
+ // 前缀桶宽度:词条侧取 normalizedTerm 的前 2 字符做桶键,文本侧穷举 2 字符窗口。
49
+ const BUCKET_WIDTH = 2
50
+
51
+ // 冷却与回合预算(§3.3)。冷却按 binding/session 记,选择"模块内 Map"而不是
52
+ // binding 字段:binding 持久化在 state.json,注入路径每回合都写会把状态文件变成
53
+ // 热路径,而冷却丢一批(进程重启)最坏只是同一个词多注入一次,代价不对称。
54
+ // key = binding 的 sessionId(一个 session 只有一个 binding → 一本私有库)。
55
+ export const LEXICON_RECALL_COOLDOWN_MINUTES = 30
56
+ export const LEXICON_MAX_PER_TURN = 2
57
+ export const lexiconCooldownStore = new Map() // key: sessionKey → Map(termId → lastInjectedAt ms)
58
+
59
+ // 频率先验:三计数的写入上限与 Wilson 下界的 z 值。上限挡住
60
+ // 病态数据把 effective 因子顶出 [0.85,1.00] 的界;z=1.96 即 95% 单侧置信。
61
+ export const HIT_COUNT_CAP = 1_000_000
62
+ export const WILSON_Z = 1.96
63
+
64
+ const KINDS = ['slang', 'meme', 'trigger', 'term']
65
+ // 公开生命周期只有两态(§2.1)。pending/rejected 仍是磁盘上可能存在的 legacy 状态,
66
+ // 但新调用方不能把词条写成它们(见 upsertLexiconTerm 的 status 收口)。
67
+ const PUBLIC_STATUSES = ['active', 'archived']
68
+ const SOURCES = ['user', 'curator', 'model-proposal']
69
+
70
+ function lexiconError(code, message) {
71
+ const error = new Error(message)
72
+ error.code = code
73
+ return error
74
+ }
75
+
76
+ function clip(text, max) {
77
+ const s = String(text ?? '')
78
+ return s.length > max ? s.slice(0, max) : s
79
+ }
80
+
81
+ /**
82
+ * 词条词面的统一规范化:NFKC → 大小写折叠 → 去空白/标点/符号。
83
+ * 与 lib/text-similarity.js clean()(memory.js 矛盾检测的既有预处理)同风格,
84
+ * 只多一步 NFKC:全角/半角和兼容字符必须折叠成同一个词面,否则唯一性约束会被
85
+ * 「糖刀」和「糖刀」(全角感叹号)绕开。
86
+ */
87
+ export function normalizeLexeme(text) {
88
+ return String(text ?? '').normalize('NFKC').toLowerCase().replace(/[\s\p{P}\p{S}]+/gu, '')
89
+ }
90
+
91
+ function lexiconDir() {
92
+ return path.join(dataDir(), 'lexicon')
93
+ }
94
+
95
+ // 全局词典与私有词典同格式、同锁、同缓存,只是占一个保留的存储名。
96
+ // 私有库 id 一律是 `lib_<hex>`(state.js libraryIdForScope),所以 `global` 不可能
97
+ // 是某本私有库——`data/lexicon/global.json` 与 `index/global.json`(全局记忆)对齐。
98
+ export const GLOBAL_LEXICON_ID = 'global'
99
+
100
+ // 「全部词典」聚合浏览的保留作用域名(不是存储):lexiconList 收到它时合并全局词典
101
+ // 与所有私有库的词条,只读聚合,写操作仍按词条所属库路由。与 GLOBAL_LEXICON_ID 一样
102
+ // 不可能撞私有库 id(`lib_<hex>`)。前端 client.js 复写同一个值,漂移由测试钉住。
103
+ export const ALL_LEXICON_ID = 'all'
104
+
105
+ function lexiconFile(libraryId) {
106
+ // isSafeId 只放行 [A-Za-z0-9._-]{1,128} 且拒绝 . / ..:绝对路径、反斜杠、
107
+ // ../ 和任意文件名在这里就死掉,不会拼进路径。
108
+ if (!isSafeId(libraryId)) throw lexiconError('LEXICON_INVALID_LIBRARY_ID', `invalid lexicon library id: ${clip(libraryId, 40)}`)
109
+ return path.join(lexiconDir(), `${libraryId}.json`)
110
+ }
111
+
112
+ function emptyLexicon(libraryId) {
113
+ return { version: 1, revision: 0, libraryId, terms: {}, rejected: {} }
114
+ }
115
+
116
+ function readLexiconStrict(file, libraryId) {
117
+ // 曾被 quarantine(读失败被挪走)的库不能当空库处理:读回来是"空"的下一个写
118
+ // 就会把整本词典覆盖掉。这里宁可 typed error 也绝不静默清零。
119
+ const failure = readFailure(file)
120
+ if (failure) {
121
+ throw lexiconError('LEXICON_READ_FAILED', `lexicon ${libraryId} is write-protected by an earlier read failure (${failure.code || failure.message})`)
122
+ }
123
+ const result = readJsonStrict(file)
124
+ if (result.missing) return emptyLexicon(libraryId)
125
+ if (!result.ok) {
126
+ const error = lexiconError('LEXICON_CORRUPT', `lexicon ${libraryId} could not be read (${result.kind === 'corrupt' ? 'invalid JSON' : result.error?.code || 'read failed'}); nothing is treated as empty and writes stay blocked until it is restored`)
127
+ if (result.error) error.cause = result.error
128
+ throw error
129
+ }
130
+ const value = result.value
131
+ // 形状校验:合法 JSON 但不是词典(数组、version 不对、terms 不是对象表、行不是
132
+ // 对象)同样是"损坏"——照单全收会让下一次写把陌生形状固化下来。
133
+ if (!value || typeof value !== 'object' || Array.isArray(value)
134
+ || (value.version !== undefined && value.version !== 1)
135
+ || !value.terms || typeof value.terms !== 'object' || Array.isArray(value.terms)) {
136
+ throw lexiconError('LEXICON_CORRUPT', `lexicon ${libraryId} has an invalid data shape; refusing to treat it as empty`)
137
+ }
138
+ for (const [termId, entry] of Object.entries(value.terms)) {
139
+ if (!entry || typeof entry !== 'object' || Array.isArray(entry)) {
140
+ throw lexiconError('LEXICON_CORRUPT', `lexicon ${libraryId} entry ${termId} is not an object`)
141
+ }
142
+ }
143
+ return {
144
+ version: 1,
145
+ revision: Number.isSafeInteger(value.revision) && value.revision >= 0 ? value.revision : 0,
146
+ libraryId,
147
+ terms: value.terms,
148
+ rejected: value.rejected && typeof value.rejected === 'object' && !Array.isArray(value.rejected) ? value.rejected : {},
149
+ }
150
+ }
151
+
152
+ // ── revision-keyed 内存索引(§10 P1 / §8.2 的 O(N) 优化项)───────────────────
153
+ // 每本词典在进程内保留一份「读取快照 + 派生索引」,key = `${libraryId}@${revision}`:
154
+ // data 严格读取出的词典对象(JSON 永远是主事实,快照只是派生物)
155
+ // activeEntries / archivedEntries / pendingEntries 构建时分好 status 并按展示序
156
+ // 排好的词条;archived 里可能包含 legacy revision 草稿(带 revisionOf,
157
+ // 由 restoreLexiconTerm 拒绝恢复);pendingEntries 只服务迁移/审计,
158
+ // 任何注入/检索/列表面都不读它;rejected 不进任何列表(墓碑)。
159
+ // byNormalizedTerm / byAlias 等值查询:Map<规范化词面, termId[]>
160
+ // prefixBuckets Map<词面前 BUCKET_WIDTH 字, Set<termId>>(dice 候选 + 正向包含候选)
161
+ // grams Map<词面任意 2 字 gram, Set<termId>>(searchLexicon 反向包含候选)
162
+ // surfacesByTerm Map<termId, [{ surface, via }]>(term 在前、aliases 随后,含/等值判定用)
163
+ //
164
+ // 失效策略(正确性红线:任何绕过本进程的文件改动不得让缓存返回旧数据):
165
+ // * 进程内一切写都走 mutateLexicon → 写成功后立即用刚落盘的对象重建快照
166
+ // (revision 已 +1,旧 key 随之作废)。
167
+ // * 进程外的改动(测试直写 paths.writeJson、backup 恢复、手工修复文件):缓存
168
+ // 命中前对文件 stat 一次并比对 mtimeMs + size。一次 stat(µs 级)远比全量
169
+ // JSON.parse(N=5k 时 ms 级)便宜;mtime 与 size 同时不变的覆写只剩「同毫秒内
170
+ // 等字节覆写」一条理论缝,在 NTFS/APFS/ext4(亚毫秒 mtime 精度)上实际不可达。
171
+ // 选 stat 比对而不是 revision 校验:revision 在 JSON 内部,读它就得先 parse,
172
+ // 等于放弃缓存。quarantine 把文件挪走 → stat 失败 → 必然 miss 回严格读取,
173
+ // typed error 语义不变。
174
+ // * 文件缺失(空库)不缓存:外部新建的文件必须立刻被下一次读取看见。
175
+ const lexiconIndexCache = new Map() // key: `${libraryId}@${revision}` → snapshot
176
+ const lexiconIndexHint = new Map() // libraryId → { key, mtimeMs, size }
177
+
178
+ // 展示序:strength → updatedAt → termId(构建索引与 merged 列表共用同一把尺)。
179
+ function displayRank(a, b) {
180
+ return (Number(b.entry.strength) || 0) - (Number(a.entry.strength) || 0)
181
+ || String(b.entry.updatedAt || '').localeCompare(String(a.entry.updatedAt || ''))
182
+ || String(a.termId).localeCompare(String(b.termId))
183
+ }
184
+
185
+ function buildLexiconIndex(data) {
186
+ const byNormalizedTerm = new Map()
187
+ const byAlias = new Map()
188
+ const prefixBuckets = new Map()
189
+ const grams = new Map()
190
+ const surfacesByTerm = new Map()
191
+ const activeEntries = []
192
+ const archivedEntries = []
193
+ const pendingEntries = []
194
+ for (const [termId, entry] of Object.entries(data.terms)) {
195
+ const status = entry.status || 'active'
196
+ if (status === 'active') activeEntries.push({ termId, entry })
197
+ else if (status === 'archived') archivedEntries.push({ termId, entry })
198
+ else if (status === 'pending') pendingEntries.push({ termId, entry })
199
+ const surfaces = []
200
+ if (entry.normalizedTerm) surfaces.push({ surface: entry.normalizedTerm, via: 'term' })
201
+ const aliases = Array.isArray(entry.normalizedAliases) ? entry.normalizedAliases : []
202
+ for (const alias of aliases) {
203
+ if (alias && alias !== entry.normalizedTerm) surfaces.push({ surface: alias, via: 'alias' })
204
+ }
205
+ if (surfaces.length) surfacesByTerm.set(termId, surfaces)
206
+ for (const { surface, via } of surfaces) {
207
+ const target = via === 'term' ? byNormalizedTerm : byAlias
208
+ let ids = target.get(surface)
209
+ if (!ids) { ids = []; target.set(surface, ids) }
210
+ ids.push(termId)
211
+ // 前缀桶:与原 bucketKeysOf 同口径——词面前 BUCKET_WIDTH 字,过短词面用自身。
212
+ const prefixKey = surface.length >= BUCKET_WIDTH ? surface.slice(0, BUCKET_WIDTH) : surface
213
+ let bucket = prefixBuckets.get(prefixKey)
214
+ if (!bucket) { bucket = new Set(); prefixBuckets.set(prefixKey, bucket) }
215
+ bucket.add(termId)
216
+ // gram 倒排:searchLexicon 的反向包含(query ⊆ 词面)靠它收候选。正向包含
217
+ // (词面 ⊆ query)也可以用它,但前缀桶的候选集更小(词面必须以该窗口开头),
218
+ // 所以正向走前缀桶。
219
+ for (let i = 0; i + BUCKET_WIDTH <= surface.length; i++) {
220
+ const gram = surface.slice(i, i + BUCKET_WIDTH)
221
+ let set = grams.get(gram)
222
+ if (!set) { set = new Set(); grams.set(gram, set) }
223
+ set.add(termId)
224
+ }
225
+ }
226
+ }
227
+ // 展示序在构建时定死(strength → updatedAt → termId):过滤是保序的,调用方
228
+ // 不必再对可见子集排序——排序键全是静态字段,与可见性无关,两个顺序等价。
229
+ activeEntries.sort(displayRank)
230
+ archivedEntries.sort(displayRank)
231
+ pendingEntries.sort(displayRank)
232
+ return { data, activeEntries, archivedEntries, pendingEntries, byNormalizedTerm, byAlias, prefixBuckets, grams, surfacesByTerm }
233
+ }
234
+
235
+ function storeLexiconIndex(libraryId, file, data) {
236
+ const snapshot = buildLexiconIndex(data)
237
+ const key = `${libraryId}@${data.revision}`
238
+ const previous = lexiconIndexHint.get(libraryId)
239
+ if (previous) lexiconIndexCache.delete(previous.key)
240
+ let stat = null
241
+ try { stat = fs.statSync(file) } catch {}
242
+ if (stat) {
243
+ lexiconIndexCache.set(key, snapshot)
244
+ lexiconIndexHint.set(libraryId, { key, mtimeMs: stat.mtimeMs, size: stat.size })
245
+ } else {
246
+ // 空库(文件还不存在)不缓存缺失状态。
247
+ lexiconIndexHint.delete(libraryId)
248
+ }
249
+ return snapshot
250
+ }
251
+
252
+ /** 带缓存的内部读取:命中走 stat 比对,未命中走严格读取 + 建索引。 */
253
+ function lexiconIndex(libraryId) {
254
+ const file = lexiconFile(libraryId)
255
+ // quarantine(读失败保护)优先于一切缓存:曾 quarantined 的库必须继续 typed error。
256
+ const failure = readFailure(file)
257
+ if (failure) {
258
+ throw lexiconError('LEXICON_READ_FAILED', `lexicon ${libraryId} is write-protected by an earlier read failure (${failure.code || failure.message})`)
259
+ }
260
+ const hint = lexiconIndexHint.get(libraryId)
261
+ if (hint) {
262
+ let stat = null
263
+ try { stat = fs.statSync(file) } catch {}
264
+ if (stat && stat.mtimeMs === hint.mtimeMs && stat.size === hint.size) {
265
+ const snapshot = lexiconIndexCache.get(hint.key)
266
+ if (snapshot) return snapshot
267
+ }
268
+ }
269
+ const data = readLexiconStrict(file, libraryId)
270
+ return storeLexiconIndex(libraryId, file, data)
271
+ }
272
+
273
+ /**
274
+ * 读一本词典。缺失 → 空结构(revision 0);损坏 → LEXICON_CORRUPT,绝不当空处理。
275
+ * 命中缓存时返回快照的浅拷贝:顶层字段与 terms 表逐键复制,防止调用方增删键污染
276
+ * 缓存;词条对象按只读契约共享——库内全部读路径都不改词条对象,测试里「改完立刻
277
+ * 写盘」的直改模式由 mtime 失效兜底(写盘 ⇒ 下一次 stat 必不匹配 ⇒ 重建)。
278
+ */
279
+ export function loadLexicon(libraryId) {
280
+ const snapshot = lexiconIndex(libraryId)
281
+ return { ...snapshot.data, terms: { ...snapshot.data.terms } }
282
+ }
283
+
284
+ /**
285
+ * 一切写操作的唯一入口:锁内重读最新 revision(CAS)→ mutator 同步改 → revision+1
286
+ * → writeJson 原子替换。mutator 必须同步(withFileLock 的锁不能跨 await)。
287
+ * 写成功后用刚落盘的对象重建内存索引:省掉下一次读取的整个 JSON.parse,重建成本
288
+ * 与建索引同阶且本来就在锁内。
289
+ *
290
+ * `onlyWhenChanged` 给迁移类写用(migrateLegacyLexiconStatuses):mutator 通过
291
+ * `changed === true` 声明真的改了数据;否则不落盘、不 bump revision——没有变化的
292
+ * 迁移不该把文件变成热写(revision 是别的进程判新的依据,空转 +1 只会制造噪声)。
293
+ */
294
+ function mutateLexicon(libraryId, mutator, { onlyWhenChanged = false } = {}) {
295
+ const file = lexiconFile(libraryId)
296
+ return withFileLock(file, () => {
297
+ const current = readLexiconStrict(file, libraryId)
298
+ const outcome = mutator(current) || {}
299
+ if (onlyWhenChanged && outcome.changed !== true) return outcome
300
+ current.revision = (Number(current.revision) || 0) + 1
301
+ current.libraryId = libraryId
302
+ current.version = 1
303
+ writeJson(file, current)
304
+ storeLexiconIndex(libraryId, file, current)
305
+ return outcome
306
+ })
307
+ }
308
+
309
+ function withTermId(entry, termId) {
310
+ return { termId, ...entry }
311
+ }
312
+
313
+ function normalizeEvidence(evidence) {
314
+ if (evidence === undefined || evidence === null) return []
315
+ if (!Array.isArray(evidence)) throw lexiconError('LEXICON_INVALID_EVIDENCE', 'evidence must be an array of { kind, id, quote }')
316
+ return evidence
317
+ .filter(item => item && typeof item === 'object')
318
+ .map(item => ({
319
+ kind: clip(typeof item.kind === 'string' ? item.kind : 'message', 40),
320
+ id: clip(typeof item.id === 'string' ? item.id : '', 160),
321
+ quote: clip(typeof item.quote === 'string' ? item.quote : '', EVIDENCE_QUOTE_MAX_CHARS),
322
+ }))
323
+ .filter(item => item.quote.trim() || item.id)
324
+ .slice(0, EVIDENCE_MAX_COUNT)
325
+ }
326
+
327
+ function normalizeStringList(value, { maxCount, maxChars, label }) {
328
+ if (value === undefined || value === null) return []
329
+ if (!Array.isArray(value)) throw lexiconError(`LEXICON_INVALID_${label}`, `${label} must be an array of strings`)
330
+ return value
331
+ .map(item => clip(String(item ?? ''), maxChars))
332
+ .map(item => item.trim())
333
+ .filter(Boolean)
334
+ .slice(0, maxCount)
335
+ }
336
+
337
+ /**
338
+ * 同一规范化 term/alias 在同一可见范围内的冲突检查。返回撞线的既有条目或 null。
339
+ * 可见范围 = sameFactContext(channel/speaker/character/world/branch 身份组一致)。
340
+ *
341
+ * 状态口径(§2.1):
342
+ * * includeArchived=false:归档条目完全不参与(旧口径;恢复检查用)。
343
+ * * includeArchived=true:归档条目按 term 等值参与(via: 'archived')——归档不占
344
+ * 别名位置,但同规范词的新写入必须看见它,否则用户/模型会在归档条目旁边建出
345
+ * 一条同词重复,之后 restore 必然撞线。
346
+ * * skipRejected=true:rejected 是墓碑,不占命名空间(恢复一个归档条目时,墓碑
347
+ * 不该阻止它回到 active)。
348
+ * * legacy revision 草稿(带 revisionOf)排在普通词条之后:同词同时存在目标与草稿
349
+ * 时,撞线对象永远是目标词条,草稿只作为兜底被看见。
350
+ */
351
+ function findScopeCollision(terms, {
352
+ normalizedTerm, normalizedAliases, context, ignoreTermId = null, includeArchived = false, skipRejected = false,
353
+ }) {
354
+ let best = null
355
+ let bestRank = Infinity
356
+ for (const [termId, entry] of Object.entries(terms)) {
357
+ if (termId === ignoreTermId) continue
358
+ const status = entry.status || 'active'
359
+ let via = null
360
+ if (status === 'archived') {
361
+ if (!includeArchived) continue
362
+ if (entry.normalizedTerm === normalizedTerm) via = 'archived'
363
+ } else if (status === 'rejected' && skipRejected) {
364
+ continue
365
+ } else if (sameFactContext(entry.context || {}, context || {})) {
366
+ if (entry.normalizedTerm === normalizedTerm) via = 'term'
367
+ else if ((entry.normalizedAliases || []).includes(normalizedTerm)) via = 'alias'
368
+ else if (normalizedAliases.includes(entry.normalizedTerm)) via = 'new-alias-is-term'
369
+ else if ((entry.normalizedAliases || []).some(alias => normalizedAliases.includes(alias))) via = 'alias'
370
+ }
371
+ if (!via) continue
372
+ const rank = (status === 'archived' ? 1 : 0) + (entry.revisionOf ? 2 : 0)
373
+ if (rank < bestRank) { best = { termId, entry, via }; bestRank = rank }
374
+ }
375
+ return best
376
+ }
377
+
378
+ // active 条目的敏感字段(§2.3 + 契约):这些字段变化时不许非用户来源静默覆盖。
379
+ // usage/aliases/examples/confidence/strength/evidence 属于非敏感字段,原地更新。
380
+ const SENSITIVE_FIELDS = ['term', 'kind', 'sensitivity', 'context', 'meaning']
381
+
382
+ function sensitiveDelta(existing, next) {
383
+ const changed = []
384
+ for (const field of SENSITIVE_FIELDS) {
385
+ const before = field === 'context' ? JSON.stringify(existing.context || {}) : String(existing[field] ?? '')
386
+ const after = field === 'context' ? JSON.stringify(next.context || {}) : String(next[field] ?? '')
387
+ if (before !== after) changed.push(field)
388
+ }
389
+ return changed
390
+ }
391
+
392
+ /**
393
+ * 写入/更新一个词条(§2 统一 op 的落点)。
394
+ *
395
+ * 公开生命周期只有 active / archived(§2.1);pending / rejected 只作为 legacy 数据
396
+ * 与内部墓碑存在,任何新写都不会产出它们:
397
+ * * 来源 'user':用户显式操作,字段(含敏感字段)直接生效。显式 status:'archived'
398
+ * 允许;pending/rejected 一律收口成 active。撞上 archived / rejected / legacy
399
+ * pending 词条 = 复活并应用字段(rejected 同时清掉拒绝指纹)。
400
+ * * 来源 'model-proposal' / 'curator':普通词条直接 active(不再 pending、不再
401
+ * needs_review)。sensitive trigger 一律 typed 拒绝(LEXICON_SENSITIVE_FORBIDDEN);
402
+ * 已存在的 sensitive trigger 的任何更新同样拒绝——只有用户能管敏感词。
403
+ * * 非用户更新 active / legacy pending 普通词条:敏感字段(term/kind/sensitivity/
404
+ * context/meaning)有任何变化 → typed 拒绝(LEXICON_SENSITIVE_FIELDS_FORBIDDEN),
405
+ * 绝不生成 pending revision;非敏感字段(usage/aliases/examples/confidence/
406
+ * strength/evidence)原地更新。visibility 也不归非用户改(secret 是披露边界,
407
+ * 不在 §2.1 的非敏感名单里)。legacy pending 被非用户写入时收口为 active。
408
+ * * 撞上 archived 词条:非用户不复活、不新建(notOwned);撞上 rejected 墓碑:
409
+ * model-proposal 仍是 LEXICON_PROPOSAL_REJECTED,curator 得到 notOwned;
410
+ * 撞上 legacy revision 草稿(revisionOf):非用户不复活(notOwned)。
411
+ * * 同规范词(term)在 sameFactContext 作用域内唯一;别名撞线仍是
412
+ * LEXICON_ALIAS_CONFLICT(不静默合并——合并会改写别人的记录)。
413
+ * * `domain` 是写入会话的领域戳(跨库召回判同域用,§8.15):给了就覆盖,没给就
414
+ * 保留既有条目的原值。归档 / 恢复 / 删除这些生命周期动作不碰它。
415
+ */
416
+ export function upsertLexiconTerm({
417
+ libraryId, term, kind = 'term', meaning = '', usage = '', aliases = [], examples = [],
418
+ context = {}, knownBy = [], visibility = 'shared', sensitivity, confidence, strength,
419
+ evidence = [], source = 'user', status, domain,
420
+ }) {
421
+ if (!SOURCES.includes(source)) throw lexiconError('LEXICON_INVALID_SOURCE', `lexicon source must be one of ${SOURCES.join(', ')}`)
422
+ const isUser = source === 'user'
423
+ const rawTerm = String(term ?? '').trim()
424
+ if (!rawTerm) throw lexiconError('LEXICON_INVALID_TERM', 'lexicon term must be a non-empty string')
425
+ if (rawTerm.length > TERM_MAX_CHARS) throw lexiconError('LEXICON_INVALID_TERM', `lexicon term exceeds ${TERM_MAX_CHARS} characters`)
426
+ if (!KINDS.includes(kind)) throw lexiconError('LEXICON_INVALID_KIND', `lexicon kind must be one of ${KINDS.join(', ')}`)
427
+ if (!['shared', 'secret'].includes(visibility)) throw lexiconError('LEXICON_INVALID_VISIBILITY', 'lexicon visibility must be shared or secret')
428
+ // trigger 默认 sensitive(§1.2);显式传值也只接受两个档位。
429
+ const resolvedSensitivity = sensitivity === undefined || sensitivity === null
430
+ ? (kind === 'trigger' ? 'sensitive' : 'normal')
431
+ : String(sensitivity)
432
+ if (!['normal', 'sensitive'].includes(resolvedSensitivity)) throw lexiconError('LEXICON_INVALID_SENSITIVITY', 'lexicon sensitivity must be normal or sensitive')
433
+ // 敏感触发词不允许模型/curator 猜(§0.2 / §2.1):非用户来源建 sensitive trigger
434
+ // 直接 typed 拒绝,只有用户能管理敏感词。
435
+ if (!isUser && kind === 'trigger' && resolvedSensitivity === 'sensitive') {
436
+ throw lexiconError('LEXICON_SENSITIVE_FORBIDDEN', `${source} cannot create sensitive triggers; sensitive vocabulary is user-managed`)
437
+ }
438
+ const normalizedContext = normalizeMemoryContext(context && typeof context === 'object' ? context : {})
439
+ const normalizedKnownBy = normalizeStringList(knownBy, { maxCount: 30, maxChars: 128, label: 'KNOWNBY' })
440
+ if (normalizedKnownBy.length) normalizedContext.knownBy = normalizedKnownBy
441
+ const normalizedTerm = normalizeLexeme(rawTerm)
442
+ if (!normalizedTerm) throw lexiconError('LEXICON_INVALID_TERM', 'lexicon term normalizes to empty')
443
+ const aliasList = normalizeStringList(aliases, { maxCount: ALIAS_MAX_COUNT, maxChars: ALIAS_MAX_CHARS, label: 'ALIASES' })
444
+ const normalizedAliases = aliasList.map(normalizeLexeme).filter(Boolean)
445
+ .filter(alias => alias !== normalizedTerm)
446
+ const resolvedConfidence = Number.isFinite(Number(confidence)) ? Math.max(0, Math.min(1, Number(confidence))) : 0.8
447
+ // strength 是展示权重不是语义字段(不在 SENSITIVE_FIELDS):改它走原地更新。
448
+ // 未提供时保留既有值/默认 0.6。
449
+ const resolvedStrength = Number.isFinite(Number(strength)) ? Math.max(0, Math.min(1, Number(strength))) : null
450
+ // 公开两态(§2.1):pending/rejected 不再由新调用方可设,统一收口为 active;
451
+ // 非用户来源连 archived 也不能设(归档是用户动作)。
452
+ const explicitStatus = status !== undefined && status !== null && String(status).trim() !== ''
453
+ const requestedStatus = PUBLIC_STATUSES.includes(String(status ?? '')) ? String(status) : 'active'
454
+ const wantedStatus = isUser ? requestedStatus : 'active'
455
+ // 输入侧归一化一次,创建与更新共用(敏感字段比较用同一份结果)。
456
+ const fields = {
457
+ kind,
458
+ meaning: clip(String(meaning ?? ''), MEANING_MAX_CHARS),
459
+ usage: clip(String(usage ?? ''), USAGE_MAX_CHARS),
460
+ aliases: aliasList,
461
+ normalizedAliases,
462
+ examples: normalizeStringList(examples, { maxCount: EXAMPLE_MAX_COUNT, maxChars: EXAMPLE_MAX_CHARS, label: 'EXAMPLES' }),
463
+ context: normalizedContext,
464
+ visibility,
465
+ sensitivity: resolvedSensitivity,
466
+ confidence: resolvedConfidence,
467
+ evidence: normalizeEvidence(evidence),
468
+ }
469
+
470
+ // domain 是「哪个领域写得了这条词」的戳,跨库召回靠它判是否同域(§8.15)。
471
+ // 它不是敏感字段(不进 SENSITIVE_FIELDS):非用户来源也能带它落库;未提供时
472
+ // 保留既有条目的原值,绝不清空。
473
+ const normalizedDomain = String(domain ?? '').trim().slice(0, 40)
474
+ const domainStamp = normalizedDomain ? { domain: normalizedDomain } : null
475
+
476
+ return mutateLexicon(libraryId, (lex) => {
477
+ const terms = lex.terms
478
+ // 同 fingerprint 的 model-proposal 再来 → 直接拒绝(§2.3):rejected 留指纹就是
479
+ // 为了让同一句错话不要每轮重放。
480
+ const fingerprint = shortHash(normalizedTerm)
481
+ if (source === 'model-proposal' && lex.rejected?.[fingerprint]) {
482
+ const prior = lex.rejected[fingerprint]
483
+ throw lexiconError('LEXICON_PROPOSAL_REJECTED', `this normalized term was already rejected${prior?.reason ? `: ${prior.reason}` : ''}`)
484
+ }
485
+ const collision = findScopeCollision(terms, {
486
+ normalizedTerm, normalizedAliases, context: normalizedContext, includeArchived: true,
487
+ })
488
+ const now = stamp()
489
+
490
+ if (collision && (collision.via === 'term' || collision.via === 'archived')) {
491
+ const { termId, entry } = collision
492
+ const entryStatus = entry.status || 'active'
493
+ // 兜底的指纹拦截:rejected 留在 terms 表里,指纹表缺失(手工修复过的文件)时
494
+ // 也不能让 model-proposal 把一条被拒的词条洗回生命周期。
495
+ if (source === 'model-proposal' && entryStatus === 'rejected') {
496
+ throw lexiconError('LEXICON_PROPOSAL_REJECTED', 'this normalized term was already rejected; resubmission is blocked')
497
+ }
498
+ // 归档 / 墓碑 / 修订草稿:非用户来源一律不复活、不改写,返回既有条目并标
499
+ // notOwned —— 这些状态只由用户(或迁移)处置。
500
+ const immutable = entryStatus === 'archived' || entryStatus === 'rejected'
501
+ || (entryStatus === 'pending' && Boolean(entry.revisionOf))
502
+ if (immutable && !isUser) {
503
+ return { term: withTermId(entry, termId), created: false, notOwned: true }
504
+ }
505
+ if (!isUser) {
506
+ // 已存在的 sensitive trigger:所有非用户更新都拒绝(conservative,§2.1)。
507
+ if (entry.kind === 'trigger' && entry.sensitivity === 'sensitive') {
508
+ throw lexiconError('LEXICON_SENSITIVE_FIELDS_FORBIDDEN', `${source} cannot update the sensitive trigger "${entry.term}"; only the user manages sensitive entries`)
509
+ }
510
+ // visibility 不在"非敏感字段"名单里(§2.1 只列 usage/aliases/examples/
511
+ // confidence/strength/evidence):secret 是披露边界,模型/curator 不得通过更新
512
+ // 把一条 secret 词条洗成 shared。沉默忽略也不好——调用方会以为写成功了。
513
+ if ((entry.visibility || 'shared') !== visibility) {
514
+ throw lexiconError('LEXICON_SENSITIVE_FIELDS_FORBIDDEN', `${source} cannot change the visibility of "${entry.term}" (${entry.visibility || 'shared'} → ${visibility}); only the user can`)
515
+ }
516
+ const next = {
517
+ ...entry, ...fields, updatedAt: now, strength: resolvedStrength ?? (Number(entry.strength) || 0.6),
518
+ ...(domainStamp || {}),
519
+ }
520
+ // 敏感字段变化 → typed 拒绝(§2.1:不再生成 pending revision 等人审)。
521
+ const changedSensitive = sensitiveDelta(entry, next)
522
+ if (changedSensitive.length) {
523
+ throw lexiconError('LEXICON_SENSITIVE_FIELDS_FORBIDDEN', `${source} cannot change sensitive fields (${changedSensitive.join(', ')}) of the existing term "${entry.term}"; ask the user to edit it`)
524
+ }
525
+ // legacy pending 普通词条:非用户写入直接收口为 active(迁移前的过渡路径)。
526
+ if (entryStatus === 'pending') next.status = 'active'
527
+ next.normalizedTerm = normalizedTerm
528
+ terms[termId] = next
529
+ return { term: withTermId(next, termId), created: false }
530
+ }
531
+ // 用户:直接应用(含敏感字段)。编辑一条已归档词条不应等于悄悄恢复:
532
+ // 只有显式 status(或 restoreLexiconTerm)才把它带回 active。显式 status 的
533
+ // 复活会断开草稿链(revisionOf 是"某条 active 的下一版草稿"的标记)。
534
+ const userStatus = entryStatus === 'archived' && !explicitStatus ? 'archived' : wantedStatus
535
+ const next = {
536
+ ...entry,
537
+ ...fields,
538
+ updatedAt: now,
539
+ strength: resolvedStrength ?? (Number(entry.strength) || 0.6),
540
+ status: userStatus,
541
+ normalizedTerm,
542
+ fingerprint,
543
+ ...(domainStamp || {}),
544
+ }
545
+ delete next.revisionOf
546
+ delete next.previousRevision
547
+ const revived = entryStatus !== 'active' && userStatus === 'active'
548
+ if (revived) {
549
+ next.reviewedAt = now
550
+ next.reviewedBy = source
551
+ next.reviewReason = null
552
+ // rejected 的翻案:清掉拒绝指纹,同词的 model-proposal 不再被无限拦截。
553
+ if (entry.fingerprint && lex.rejected?.[entry.fingerprint]) delete lex.rejected[entry.fingerprint]
554
+ }
555
+ terms[termId] = next
556
+ return { term: withTermId(next, termId), created: false, ...(revived ? { revived: true } : {}) }
557
+ }
558
+
559
+ if (collision) {
560
+ // 新词条的 alias 撞了别的词条:宁可报错也不静默合并——合并会改写别人的记录。
561
+ throw lexiconError('LEXICON_ALIAS_CONFLICT', `normalized alias collides with existing term "${collision.entry.term}" (${collision.termId})`)
562
+ }
563
+
564
+ if (Object.keys(terms).length >= LEXICON_CAP) {
565
+ throw lexiconError('LEXICON_CAP_REACHED', `lexicon ${libraryId} is at its ${LEXICON_CAP} term capacity; archive or delete before adding`)
566
+ }
567
+
568
+ const termId = newTermId()
569
+ const entry = {
570
+ term: rawTerm,
571
+ normalizedTerm,
572
+ ...fields,
573
+ strength: resolvedStrength ?? 0.6,
574
+ status: wantedStatus,
575
+ source,
576
+ fingerprint,
577
+ createdAt: now,
578
+ updatedAt: now,
579
+ reviewedAt: null,
580
+ reviewedBy: null,
581
+ reviewReason: null,
582
+ hitCounts: { candidate: 0, injection: 0, query: 0 },
583
+ lastInjectedAt: null,
584
+ ...(domainStamp || {}),
585
+ }
586
+ terms[termId] = entry
587
+ return { term: withTermId(entry, termId), created: true }
588
+ })
589
+ }
590
+
591
+ function newTermId() {
592
+ return `lex-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`
593
+ }
594
+
595
+ /**
596
+ * 归档(§2.1 / §2.3):只有 active → archived;其余状态 typed 拒绝(legacy pending
597
+ * 先走迁移收口,rejected 是墓碑、没有归档语义)。归档不写 rejected 指纹——归档是
598
+ * 可恢复的退场,不是拒绝。
599
+ */
600
+ export function archiveLexiconTerm({ libraryId, termId }) {
601
+ return mutateLexicon(libraryId, (lex) => {
602
+ const entry = lex.terms[termId]
603
+ if (!entry) throw lexiconError('LEXICON_NOT_FOUND', `lexicon term ${termId} does not exist in ${libraryId}`)
604
+ const status = entry.status || 'active'
605
+ if (status !== 'active') throw lexiconError('LEXICON_INVALID_STATUS', `only active terms can be archived; ${termId} is ${status}`)
606
+ const now = stamp()
607
+ entry.status = 'archived'
608
+ entry.updatedAt = now
609
+ return { term: withTermId(entry, termId), termId, action: 'archive' }
610
+ })
611
+ }
612
+
613
+ /**
614
+ * 恢复(§2.1 / §2.3):只有 archived → active。两条硬拒绝:
615
+ * * legacy revision 草稿(revisionOf 指向仍 active 的目标)不能独立恢复——它是
616
+ * 目标词条的下一版草稿,不是词条(LEXICON_REVISION_IMMUTABLE)。
617
+ * * 恢复会与同作用域的 active 词条撞同一个规范词面/别名 → LEXICON_ALIAS_CONFLICT
618
+ * (不制造同词重复;用户想合并就在两个词条上分别编辑)。
619
+ * 墓碑(rejected)不参与撞线:它不占命名空间。
620
+ */
621
+ export function restoreLexiconTerm({ libraryId, termId }) {
622
+ return mutateLexicon(libraryId, (lex) => {
623
+ const entry = lex.terms[termId]
624
+ if (!entry) throw lexiconError('LEXICON_NOT_FOUND', `lexicon term ${termId} does not exist in ${libraryId}`)
625
+ const status = entry.status || 'active'
626
+ if (status !== 'archived') throw lexiconError('LEXICON_INVALID_STATUS', `only archived terms can be restored; ${termId} is ${status}`)
627
+ if (entry.revisionOf && (lex.terms[entry.revisionOf]?.status || 'active') === 'active') {
628
+ throw lexiconError('LEXICON_REVISION_IMMUTABLE', `lexicon term ${termId} is a legacy revision draft of ${entry.revisionOf}; edit the active term instead`)
629
+ }
630
+ const normalizedAliases = Array.isArray(entry.normalizedAliases) ? entry.normalizedAliases : []
631
+ const collision = findScopeCollision(lex.terms, {
632
+ normalizedTerm: entry.normalizedTerm,
633
+ normalizedAliases,
634
+ context: entry.context || {},
635
+ ignoreTermId: termId,
636
+ skipRejected: true,
637
+ })
638
+ if (collision) {
639
+ throw lexiconError('LEXICON_ALIAS_CONFLICT', `restoring "${entry.term}" would collide with active term "${collision.entry.term}" (${collision.termId})`)
640
+ }
641
+ const now = stamp()
642
+ entry.status = 'active'
643
+ entry.updatedAt = now
644
+ return { term: withTermId(entry, termId), termId, action: 'restore' }
645
+ })
646
+ }
647
+
648
+ /**
649
+ * 删除词条。刻意只暴露给管理面(RPC/UI/P3):模型没有任何删除路径——
650
+ * tools.js 的模型工具面拿不到这个函数,curator op 白名单里也没有 delete。
651
+ */
652
+ export function deleteLexiconTerm({ libraryId, termId }) {
653
+ return mutateLexicon(libraryId, (lex) => {
654
+ const entry = lex.terms[termId]
655
+ if (!entry) throw lexiconError('LEXICON_NOT_FOUND', `lexicon term ${termId} does not exist in ${libraryId}`)
656
+ delete lex.terms[termId]
657
+ if (entry.fingerprint && lex.rejected?.[entry.fingerprint]?.termId === termId) {
658
+ delete lex.rejected[entry.fingerprint]
659
+ }
660
+ return { deleted: true, termId, term: entry.term }
661
+ })
662
+ }
663
+
664
+ /**
665
+ * §1.3 / §2.1:可见词条,逐条过与记忆同一把尺子(contextVisible)。过滤失败的绝不返回。
666
+ * 默认只有 active;`includeArchived: true`(管理面/浏览器)追加已归档词条(含 legacy
667
+ * revision 草稿)。pending/rejected 永远不出现——前者只服务迁移,后者是内部墓碑。
668
+ * 状态分组与展示序都在索引构建时定好,这里只剩 contextVisible 过滤本身;active 与
669
+ * archived 混排时重排一次(两段各自有序,合并后必须保持同一把展示序)。
670
+ */
671
+ export function visibleLexiconTerms(libraryId, memoryContext, { includeArchived = false } = {}) {
672
+ const index = lexiconIndex(libraryId)
673
+ const out = []
674
+ for (const { termId, entry } of index.activeEntries) {
675
+ if (!contextVisible(entry.context, memoryContext)) continue
676
+ out.push(withTermId(entry, termId))
677
+ }
678
+ if (includeArchived) {
679
+ for (const { termId, entry } of index.archivedEntries) {
680
+ if (!contextVisible(entry.context, memoryContext)) continue
681
+ out.push(withTermId(entry, termId))
682
+ }
683
+ out.sort((a, b) => (Number(b.strength) || 0) - (Number(a.strength) || 0)
684
+ || String(b.updatedAt || '').localeCompare(String(a.updatedAt || ''))
685
+ || String(a.termId).localeCompare(String(b.termId)))
686
+ }
687
+ return out
688
+ }
689
+
690
+ function clamp01(value) {
691
+ const n = Number(value)
692
+ if (!Number.isFinite(n)) return 0
693
+ return Math.max(0, Math.min(1, n))
694
+ }
695
+
696
+ /**
697
+ * Wilson 下界作为有界频率先验,分子与分母使用同一数据来源。
698
+ *
699
+ * 分母 n 优先取 priorAttempts——「该词条被召回的总尝试次数」这一同源计数;
700
+ * 成功数 success = injection + query,即「被召回后确实被注入/查询命中」的
701
+ * 同源事件。缺失 priorAttempts 时采用下述有界近似,不将其解释为严格的使用概率。
702
+ *
703
+ * 兼容近似:当前写入路径还没有记录 priorAttempts,缺失(或非正数)时退回
704
+ * candidate 作为分母,并在此文档化这一假设——candidate 是「进过匹配结果」的
705
+ * 次数,是现有数据里与「被召回」最接近的代理;success 仍被 min(n, ...) 钳住,
706
+ * 公式保持有界。写入侧按同源事件补上 priorAttempts 后,先验自动切换到严格口径。
707
+ *
708
+ * 设计约束不变:
709
+ * * n=0 → 0(从未候选过的词条没有任何频率证据,因子取下限 0.85)。
710
+ * * 1/1 的下界 ≈ 0.207,因子最多 ~3% 差距——一条偶发命中压不过长期稳定使用的词。
711
+ * * 100/120 的下界明显更高——长期被真正使用的词条温和提升。
712
+ * * 输出 clamp 到 [0,1],与 strength/confidence 的 clamp01 同口径;乘上
713
+ * (0.85 + 0.15 * lb) 后 effective 因子恒在 [0.85,1.00],不 runaway。
714
+ */
715
+ export function usageLowerBound(counts) {
716
+ const attempts = Math.max(0, Math.floor(Number(counts?.priorAttempts) || 0))
717
+ const n = attempts > 0 ? attempts : Math.max(0, Math.floor(Number(counts?.candidate) || 0))
718
+ if (n === 0) return 0
719
+ const success = Math.min(n, Math.max(0, (Number(counts?.injection) || 0) + (Number(counts?.query) || 0)))
720
+ const p = success / n
721
+ const z = WILSON_Z, z2 = z * z
722
+ const lb = (p + z2 / (2 * n) - z * Math.sqrt((p * (1 - p) + z2 / (4 * n)) / n)) / (1 + z2 / n)
723
+ return clamp01(lb)
724
+ }
725
+
726
+ /**
727
+ * effective 展示权重(§6.3 排序键):strength × confidence × (0.85 + 0.15 × Wilson
728
+ * 下界)。因子固定在 [0.85,1.00],只做温和的先验,绝不压过 exact/alias/Dice 的
729
+ * 匹配层级——那三层在 stableRank 里先于 effective 生效。
730
+ */
731
+ function effectiveWeight(hit) {
732
+ return clamp01(hit.strength) * clamp01(hit.confidence) * (0.85 + 0.15 * usageLowerBound(hit.hitCounts))
733
+ }
734
+
735
+ /** §3.2 稳定排序:排序键固定,末位 id 字典序,绝不用当前时间或遍历序做 tie-break。 */
736
+ function stableRank(hits) {
737
+ return [...hits].sort((a, b) => {
738
+ const sa = sensitivityRank(a), sb = sensitivityRank(b)
739
+ if (sa !== sb) return sb - sa
740
+ const ea = exactRank(a.kindOfHit), eb = exactRank(b.kindOfHit)
741
+ if (ea !== eb) return eb - ea
742
+ if (ea === 1 && Math.abs((b.score || 0) - (a.score || 0)) > 1e-9) return (b.score || 0) - (a.score || 0)
743
+ const wa = effectiveWeight(a), wb = effectiveWeight(b)
744
+ if (Math.abs(wb - wa) > 1e-9) return wb - wa
745
+ const ga = scopeSpecificity(a.context), gb = scopeSpecificity(b.context)
746
+ if (ga !== gb) return gb - ga
747
+ const ta = String(a.updatedAt || ''), tb = String(b.updatedAt || '')
748
+ if (ta !== tb) return tb.localeCompare(ta)
749
+ return String(a.termId).localeCompare(String(b.termId))
750
+ })
751
+ }
752
+
753
+ // 与 lexiconAnchorSummary 使用相同的敏感优先规则:只按 sensitivity 判定,
754
+ // 不额外要求 kind === 'trigger';写入侧仍为 trigger 默认设置 sensitive。
755
+ function sensitivityRank(hit) {
756
+ return hit.sensitivity === 'sensitive' ? 1 : 0
757
+ }
758
+
759
+ // exact term > exact alias > dice(§3.2 的 2-4 键)。
760
+ function exactRank(kindOfHit) {
761
+ if (kindOfHit === 'exact-term') return 3
762
+ if (kindOfHit === 'exact-alias') return 2
763
+ return 1
764
+ }
765
+
766
+ // 作用域具体度(§3.2 排序键之一,显式定义):词条 context 里已定义的身份字段个数。
767
+ // 字段集与 lib/context.js 的 IDENTITIES 完全同组(channelId/speakerId/characterId/
768
+ // worldId/branchId),非空数越多越具体,具体者优先。knownBy 是可见性边界
769
+ // (contextVisible 的事),不是作用域,不计入;空白 context = 全场景共享,具体度
770
+ // 0,排在任何带作用域的词条之后。
771
+ function scopeSpecificity(context) {
772
+ if (!context || typeof context !== 'object') return 0
773
+ return ['channelId', 'speakerId', 'characterId', 'worldId', 'branchId'].filter(key => context[key]).length
774
+ }
775
+
776
+ /**
777
+ * 文本侧窗口:穷举 BUCKET_WIDTH 字符窗口并去重,按前缀桶中命中的词条数
778
+ * 降序取 top-N,避免仅按出现顺序截断时遗漏长文本后部的相关窗口。
779
+ * 命中数相同的窗口保持出现顺序(sort 稳定),输出可复现。
780
+ *
781
+ * 命中数取索引里该桶的全量大小(含 archived/pending):窗口排序只是「哪些窗口
782
+ * 值得展开」的成本决策,可见性仍由逐候选的 isVisible 复核,不会被这里放宽。
783
+ */
784
+ function textBuckets(normalizedText, index, maxBuckets = LEXICON_MAX_BUCKETS) {
785
+ const keys = []
786
+ const seen = new Set()
787
+ for (let i = 0; i + BUCKET_WIDTH <= normalizedText.length; i++) {
788
+ const key = normalizedText.slice(i, i + BUCKET_WIDTH)
789
+ if (seen.has(key)) continue
790
+ seen.add(key)
791
+ keys.push(key)
792
+ }
793
+ return keys
794
+ .map((key, order) => ({ key, order, hits: index?.prefixBuckets?.get(key)?.size || 0 }))
795
+ .sort((a, b) => b.hits - a.hits || a.order - b.order)
796
+ .slice(0, maxBuckets)
797
+ .map((item) => item.key)
798
+ }
799
+
800
+ /**
801
+ * 桶内 dice 兜底:对每个候选词条,在文本里定位它桶键的出现位置,取等长窗口算
802
+ * Dice,取最大值。候选 ≤ maxCandidates、命中 ≤ maxTerms,O(C) 有界(§6)。
803
+ */
804
+ function diceFallback(normalizedText, candidates, { threshold = LEXICON_DICE_THRESHOLD, maxCandidates = LEXICON_MAX_CANDIDATES, maxTerms = LEXICON_MAX_TERMS } = {}) {
805
+ const textGrams = bigrams(normalizedText)
806
+ if (!textGrams.size) return []
807
+ const scored = []
808
+ for (const hit of candidates.slice(0, maxCandidates)) {
809
+ let best = 0
810
+ for (const surface of [hit.normalizedTerm, ...(hit.normalizedAliases || [])]) {
811
+ if (!surface || surface.length < BUCKET_WIDTH) continue
812
+ const key = surface.slice(0, BUCKET_WIDTH)
813
+ let pos = normalizedText.indexOf(key)
814
+ while (pos >= 0) {
815
+ const window = normalizedText.slice(pos, pos + surface.length)
816
+ const score = dice(bigrams(window), bigrams(surface))
817
+ if (score > best) best = score
818
+ if (best >= 1) break
819
+ pos = normalizedText.indexOf(key, pos + 1)
820
+ }
821
+ if (best >= threshold) break
822
+ }
823
+ if (best >= threshold) scored.push({ ...hit, kindOfHit: 'dice', score: best })
824
+ }
825
+ scored.sort((a, b) => (b.score - a.score)
826
+ || (Number(b.strength) || 0) * (Number(b.confidence) || 0) - (Number(a.strength) || 0) * (Number(a.confidence) || 0)
827
+ || String(a.termId).localeCompare(String(b.termId)))
828
+ return scored.slice(0, maxTerms)
829
+ }
830
+
831
+ function hitOf(entry, termId, kindOfHit, score) {
832
+ return {
833
+ termId,
834
+ term: entry.term,
835
+ normalizedTerm: entry.normalizedTerm,
836
+ kind: entry.kind,
837
+ meaning: entry.meaning,
838
+ usage: entry.usage,
839
+ sensitivity: entry.sensitivity,
840
+ strength: entry.strength,
841
+ confidence: entry.confidence,
842
+ // 频率先验(§6.3)的输入:stableRank 的 effective 因子按三计数算 Wilson 下界。
843
+ hitCounts: entry.hitCounts && typeof entry.hitCounts === 'object' ? entry.hitCounts : { candidate: 0, injection: 0, query: 0 },
844
+ context: entry.context,
845
+ updatedAt: entry.updatedAt,
846
+ status: entry.status,
847
+ kindOfHit,
848
+ score,
849
+ }
850
+ }
851
+
852
+ /**
853
+ * §3.1-§3.2 匹配流水线:精确(等值/包含)→ 前缀桶 → 桶内 dice 兜底 → stableRank。
854
+ * 只读不写:candidate/injection 计数由调用方(inject.js)在真正发生时记。
855
+ * 只匹配 active 词条:archived 已退场、rejected 是墓碑、legacy pending 等迁移收口,
856
+ * 三种状态都不进注入(§2.1)。
857
+ *
858
+ * 全部走 revision-keyed 索引(§10 P1):等值 O(1) 查 Map;包含层用「词面 ⊆ 文本
859
+ * ⇒ 词面前缀 = 文本某个 2 字窗口」的性质从前缀桶收候选(窗口穷举不设 16 上限——
860
+ * 16 上限只属于 dice 候选,精确层语义从来没有窗口上限);dice 兜底仍按桶扫且
861
+ * C ≤ 64 不变(§6),但窗口按命中词条数排序、候选按与 query 的共享 gram 数
862
+ * 排序(A-8:候选准入看相关性,不看 strength)。可见性(status +
863
+ * contextVisible)在收候选时逐个复核。
864
+ */
865
+ export function matchLexiconHits(libraryId, userText, memoryContext) {
866
+ const normalizedText = normalizeLexeme(userText)
867
+ if (!normalizedText) return []
868
+ const index = lexiconIndex(libraryId)
869
+ const data = index.data
870
+ const isVisible = termId => {
871
+ const entry = data.terms[termId]
872
+ return Boolean(entry) && (entry.status || 'active') === 'active' && contextVisible(entry.context, memoryContext)
873
+ }
874
+ // 精确层·等值:Map 直查(同库同词面可有多条跨 scope 词条,值是 termId 列表)。
875
+ const hits = []
876
+ const exactIds = new Set()
877
+ const pushExact = (termId, kindOfHit) => {
878
+ if (exactIds.has(termId) || !isVisible(termId)) return
879
+ exactIds.add(termId)
880
+ hits.push(hitOf(data.terms[termId], termId, kindOfHit, 1))
881
+ }
882
+ for (const termId of index.byNormalizedTerm.get(normalizedText) || []) pushExact(termId, 'exact-term')
883
+ for (const termId of index.byAlias.get(normalizedText) || []) pushExact(termId, 'exact-alias')
884
+ // 精确层·包含:词面(≥MIN_INCLUDE_LEN)出现在文本里。前缀桶给出候选超集,
885
+ // 逐候选复核 includes 并保留原判定序(term 在前、aliases 随后,第一个命中的
886
+ // 词面决定 exact-term / exact-alias 标签)。
887
+ const containIds = []
888
+ for (let i = 0; i + BUCKET_WIDTH <= normalizedText.length; i++) {
889
+ for (const termId of index.prefixBuckets.get(normalizedText.slice(i, i + BUCKET_WIDTH)) || []) {
890
+ if (!exactIds.has(termId) && !containIds.includes(termId)) containIds.push(termId)
891
+ }
892
+ }
893
+ for (const termId of containIds) {
894
+ if (!isVisible(termId)) continue
895
+ const entry = data.terms[termId]
896
+ let matched = null
897
+ for (const item of index.surfacesByTerm.get(termId) || []) {
898
+ if (item.surface.length >= LEXICON_MIN_INCLUDE_LEN && normalizedText.includes(item.surface)) { matched = item; break }
899
+ }
900
+ if (matched) {
901
+ exactIds.add(termId)
902
+ hits.push(hitOf(entry, termId, matched.via === 'term' ? 'exact-term' : 'exact-alias', 1))
903
+ }
904
+ }
905
+ // dice 候选:窗口数仍以 LEXICON_MAX_BUCKETS 封顶(§4.2 的 C≤64 语义不变),
906
+ // 但窗口与候选都按「与 query 的相关性」排:窗口按命中词条数降序(见
907
+ // textBuckets),候选按与 query 共享的 gram 数降序,确保相关性优先于强度。
908
+ // strength 与 termId 仅用于确定性排序收尾,与 diceFallback 保持一致。
909
+ const candidateIds = new Set()
910
+ for (const key of textBuckets(normalizedText, index)) {
911
+ for (const termId of index.prefixBuckets.get(key) || []) {
912
+ if (exactIds.has(termId) || !isVisible(termId)) continue
913
+ candidateIds.add(termId)
914
+ }
915
+ }
916
+ const textGrams = bigrams(normalizedText)
917
+ const sharedGramCount = termId => {
918
+ let best = 0
919
+ for (const { surface } of index.surfacesByTerm.get(termId) || []) {
920
+ let shared = 0
921
+ for (const gram of bigrams(surface)) if (textGrams.has(gram)) shared += 1
922
+ if (shared > best) best = shared
923
+ }
924
+ return best
925
+ }
926
+ const weightOf = termId => (Number(data.terms[termId].strength) || 0) * (Number(data.terms[termId].confidence) || 0)
927
+ const candidates = [...candidateIds]
928
+ .map(termId => ({ termId, shared: sharedGramCount(termId) }))
929
+ .sort((a, b) => b.shared - a.shared
930
+ || weightOf(b.termId) - weightOf(a.termId)
931
+ || String(a.termId).localeCompare(String(b.termId)))
932
+ .map(({ termId }) => hitOf(data.terms[termId], termId, 'dice', 0))
933
+ const fuzzy = diceFallback(normalizedText, candidates)
934
+ // stableRank 的末位 tie-break 是唯一 termId,命中顺序不影响最终排序。
935
+ return stableRank([...hits, ...fuzzy])
936
+ }
937
+
938
+ /**
939
+ * 精确层检索(§3.3 通道 C 的数据面):等值 + includes,不做 dice、不做语义。
940
+ * 默认只回 active;`includeArchived: true` 让管理面/浏览器显式看到归档词条。
941
+ * pending(迁移前的老提案)与 rejected(墓碑)在任何模式下都不出现。
942
+ * 走 revision-keyed 索引:等值 O(1) 查 Map;正向包含(词面 ⊆ query)用前缀桶
943
+ * 收候选(穷举窗口、不设 16 上限——精确层语义没有窗口上限);反向包含
944
+ * (query ⊆ 词面)用 gram 倒排收候选。两个候选集都是超集,逐候选复核原始谓词。
945
+ */
946
+ export function searchLexicon({ libraryId, query, memoryContext }, { includeArchived = false } = {}) {
947
+ const normalizedQuery = normalizeLexeme(query)
948
+ const out = []
949
+ if (!normalizedQuery) return out
950
+ const index = lexiconIndex(libraryId)
951
+ const data = index.data
952
+ const matched = []
953
+ const considered = new Set()
954
+ const consider = termId => {
955
+ if (considered.has(termId)) return
956
+ considered.add(termId)
957
+ const entry = data.terms[termId]
958
+ const status = entry.status || 'active'
959
+ if (status !== 'active' && !(includeArchived && status === 'archived')) return
960
+ if (!contextVisible(entry.context, memoryContext)) return
961
+ const aliases = Array.isArray(entry.normalizedAliases) ? entry.normalizedAliases : []
962
+ let matchedBy = null
963
+ if (entry.normalizedTerm === normalizedQuery) matchedBy = 'term'
964
+ else if (aliases.includes(normalizedQuery)) matchedBy = 'alias'
965
+ else if (entry.normalizedTerm.length >= LEXICON_MIN_INCLUDE_LEN
966
+ && (normalizedQuery.includes(entry.normalizedTerm) || entry.normalizedTerm.includes(normalizedQuery))) matchedBy = 'contains'
967
+ else if (aliases.some(alias => alias.length >= LEXICON_MIN_INCLUDE_LEN
968
+ && (normalizedQuery.includes(alias) || alias.includes(normalizedQuery)))) matchedBy = 'alias-contains'
969
+ if (matchedBy) matched.push({ ...withTermId(entry, termId), matchedBy })
970
+ }
971
+ for (const termId of index.byNormalizedTerm.get(normalizedQuery) || []) consider(termId)
972
+ for (const termId of index.byAlias.get(normalizedQuery) || []) consider(termId)
973
+ if (normalizedQuery.length >= BUCKET_WIDTH) {
974
+ const forward = new Set()
975
+ const reverse = new Set()
976
+ for (let i = 0; i + BUCKET_WIDTH <= normalizedQuery.length; i++) {
977
+ const window = normalizedQuery.slice(i, i + BUCKET_WIDTH)
978
+ for (const termId of index.prefixBuckets.get(window) || []) {
979
+ if (!considered.has(termId)) forward.add(termId)
980
+ }
981
+ for (const termId of index.grams.get(window) || []) {
982
+ if (!considered.has(termId) && !forward.has(termId)) reverse.add(termId)
983
+ }
984
+ }
985
+ for (const termId of forward) consider(termId)
986
+ for (const termId of reverse) consider(termId)
987
+ } else {
988
+ // 单字 query 没有 2 字窗口,反向包含(词面含该字)退化为对索引词面表的全扫:
989
+ // 原生 includes 逐词面跑,N=5k 时仍是毫秒级;语义与逐条扫描完全一致。
990
+ for (const [termId, surfaces] of index.surfacesByTerm) {
991
+ if (considered.has(termId)) continue
992
+ if (surfaces.some(item => item.surface.length >= LEXICON_MIN_INCLUDE_LEN && item.surface.includes(normalizedQuery))) {
993
+ consider(termId)
994
+ }
995
+ }
996
+ }
997
+ matched.sort((a, b) => {
998
+ const ra = a.matchedBy === 'term' ? 3 : a.matchedBy === 'alias' ? 2 : 1
999
+ const rb = b.matchedBy === 'term' ? 3 : b.matchedBy === 'alias' ? 2 : 1
1000
+ if (ra !== rb) return rb - ra
1001
+ return String(a.termId).localeCompare(String(b.termId))
1002
+ })
1003
+ // query 计数(§3.3 三计数之一):显式查询是注意力,best-effort 记账,失败不影响
1004
+ // 结果。只给 active 记账——管理面翻归档(includeArchived)不是"这次检索用到了它",
1005
+ // 归档词条不进注入,给它加 query 计数只会污染频率先验。一次批量记账 = 一次锁内
1006
+ // CAS 写,不把检索变成 N 次磁盘写。
1007
+ const countable = matched.filter(item => (item.status || 'active') === 'active').slice(0, 20)
1008
+ if (countable.length) {
1009
+ try { lexiconRecordHits(libraryId, countable.map(item => item.termId), 'query') } catch (error) {
1010
+ warn(`lexicon query accounting failed: ${error?.message || error}`)
1011
+ }
1012
+ }
1013
+ return matched
1014
+ }
1015
+
1016
+ /**
1017
+ * B 通道的渲染与成本共用同一把尺:cooldownAndBudget 按 estTokens(line) 扣预算。
1018
+ * “词典也是标题”(§2.2):term 是标题(≤40 字),meaning/usage 只给短义(≤80 字),
1019
+ * 不展开 usage/examples——注入行永远是「标题 + 短释义」。
1020
+ */
1021
+ export function lexiconTurnLine(hit) {
1022
+ const body = clip(String(hit.meaning || hit.usage || ''), 80)
1023
+ return `「${clip(String(hit.term || ''), 40)}」${body ? `:${body}` : ''}`
1024
+ }
1025
+
1026
+ /**
1027
+ * 冷却 + 每回合预算(§3.3):冷却内的词条仍出现在 hits 里(可计 candidate),
1028
+ * 但不进 selected(不计 injection)。预算按渲染行的 estTokens 顺序扣,扣不动就停。
1029
+ * bindingState 传 sessionId(string)或带 sessionId 的 binding 对象。
1030
+ */
1031
+ export function cooldownAndBudget(hits, bindingState, tokenBudget) {
1032
+ const sessionKey = typeof bindingState === 'string' ? bindingState : String(bindingState?.sessionId || '')
1033
+ const now = Date.now()
1034
+ const cooldownMs = LEXICON_RECALL_COOLDOWN_MINUTES * 60_000
1035
+ const last = lexiconCooldownStore.get(sessionKey)
1036
+ const selected = []
1037
+ const onCooldown = []
1038
+ let used = 0
1039
+ const budget = Math.max(0, Number(tokenBudget) || 0)
1040
+ for (const hit of hits) {
1041
+ const injectedAt = last?.get(hit.termId) || 0
1042
+ if (injectedAt && now - injectedAt < cooldownMs) { onCooldown.push(hit); continue }
1043
+ if (selected.length >= LEXICON_MAX_PER_TURN) continue
1044
+ const cost = estTokens(lexiconTurnLine(hit)) + (selected.length ? 1 : 0)
1045
+ if (used + cost > budget) continue
1046
+ used += cost
1047
+ selected.push(hit)
1048
+ }
1049
+ return { selected, onCooldown, used }
1050
+ }
1051
+
1052
+ /** 注入真的发生之后才调用:记冷却,下一次同词在冷却窗口内只做 candidate。 */
1053
+ export function lexiconMarkInjected(bindingKey, termIds, now = Date.now()) {
1054
+ const sessionKey = String(bindingKey || '')
1055
+ if (!sessionKey || !Array.isArray(termIds) || termIds.length === 0) return
1056
+ let last = lexiconCooldownStore.get(sessionKey)
1057
+ if (!last) { last = new Map(); lexiconCooldownStore.set(sessionKey, last) }
1058
+ for (const termId of termIds) last.set(termId, now)
1059
+ // Map 只增不减会陪着进程活着变大;词条冷却窗口 30 分钟,过期键在读取时本就无效,
1060
+ // 这里顺手把整本已过期的 session 键清掉,成本 O(sessions)。
1061
+ if (lexiconCooldownStore.size > 512) {
1062
+ for (const [key, value] of lexiconCooldownStore) {
1063
+ const freshest = Math.max(...value.values())
1064
+ if (now - freshest >= cooldownWindowMs()) lexiconCooldownStore.delete(key)
1065
+ }
1066
+ }
1067
+ }
1068
+
1069
+ function cooldownWindowMs() { return LEXICON_RECALL_COOLDOWN_MINUTES * 60_000 }
1070
+
1071
+ export function lexiconOnCooldown(bindingKey, termId, now = Date.now()) {
1072
+ const last = lexiconCooldownStore.get(String(bindingKey || ''))?.get(termId) || 0
1073
+ return last > 0 && now - last < cooldownWindowMs()
1074
+ }
1075
+
1076
+ /**
1077
+ * 三计数分开累加(§3.3):candidate(进过匹配结果)/ injection(真的注入了)/
1078
+ * query(显式检索命中)。写路径走 mutateLexicon(锁内 CAS + revision+1)。
1079
+ */
1080
+ export function lexiconRecordHit(libraryId, termId, kindOfHit) {
1081
+ if (!['candidate', 'injection', 'query'].includes(kindOfHit)) {
1082
+ throw lexiconError('LEXICON_INVALID_HIT_KIND', 'hit kind must be candidate, injection or query')
1083
+ }
1084
+ const result = lexiconRecordHits(libraryId, [termId], kindOfHit)
1085
+ return { termId, hitCounts: result.counts[termId] }
1086
+ }
1087
+
1088
+ /** 一次锁内写累加多个词条的同一类计数;未知词条抛 LEXICON_NOT_FOUND。 */
1089
+ export function lexiconRecordHits(libraryId, termIds, kindOfHit) {
1090
+ return mutateLexicon(libraryId, (lex) => {
1091
+ const counts = {}
1092
+ for (const termId of termIds) {
1093
+ const entry = lex.terms[termId]
1094
+ if (!entry) throw lexiconError('LEXICON_NOT_FOUND', `lexicon term ${termId} does not exist in ${libraryId}`)
1095
+ entry.hitCounts = entry.hitCounts && typeof entry.hitCounts === 'object'
1096
+ ? entry.hitCounts
1097
+ : { candidate: 0, injection: 0, query: 0 }
1098
+ // 计数上限(§6.3 HIT_COUNT_CAP):累加后 clamp 到 1,000,000——既有值越界
1099
+ // (手工修复/损坏数据)也在同一步被拉回界内,effective 因子的输入永远有界。
1100
+ for (const key of ['candidate', 'injection', 'query']) {
1101
+ entry.hitCounts[key] = Math.min(HIT_COUNT_CAP, Math.max(0, Number(entry.hitCounts[key]) || 0))
1102
+ }
1103
+ entry.hitCounts[kindOfHit] = Math.min(HIT_COUNT_CAP, (Number(entry.hitCounts[kindOfHit]) || 0) + 1)
1104
+ if (kindOfHit === 'injection') entry.lastInjectedAt = stamp()
1105
+ counts[termId] = { ...entry.hitCounts }
1106
+ }
1107
+ return { counts }
1108
+ })
1109
+ }
1110
+
1111
+ /** §3.2 稳定排序的对外出口:跨源合并后必须用同一把尺重排,不许调用方自定排序。 */
1112
+ export function rankLexiconHits(hits) {
1113
+ return stableRank(hits)
1114
+ }
1115
+
1116
+ /**
1117
+ * 锚点摘要(§3.3 通道 A 的数据面):top 8 by strength;敏感词条单列且 ≤2。
1118
+ * 行已按优先级排好——inject.js 超 300 token 时从尾部丢,丢的永远是最弱的一条。
1119
+ *
1120
+ * visibility 与记忆同一套语义(lib/memory.js visibleToSession 的契约:secret 只是
1121
+ * "不主动浮出",不改变"被点名时"的可见性):锚点是主动浮出,secret 词条不进摘要;
1122
+ * B 通道是用户消息点到了词面(等价于按词点名),secret 词条仍然命中并解释。
1123
+ *
1124
+ * 入参是「已按可见性过滤好的词条」,所以单库摘要与跨源合并摘要共用同一份渲染与
1125
+ * 取舍规则(lexiconAnchorSummary 是本函数在单库上的包装)。
1126
+ */
1127
+ export function lexiconAnchorLines(entries) {
1128
+ const anchorable = (Array.isArray(entries) ? entries : []).filter(entry => entry.visibility !== 'secret')
1129
+ const sensitive = anchorable.filter(entry => entry.sensitivity === 'sensitive')
1130
+ const normal = anchorable.filter(entry => entry.sensitivity !== 'sensitive')
1131
+ const line = entry => `「${clip(String(entry.term || ''), 40)}」(${entry.kind})${entry.meaning ? ` ${clip(String(entry.meaning), 80)}` : ''}`
1132
+ const byStrength = list => [...list].sort((a, b) => (Number(b.strength) || 0) - (Number(a.strength) || 0)
1133
+ || String(b.updatedAt || '').localeCompare(String(a.updatedAt || ''))
1134
+ || String(a.termId).localeCompare(String(b.termId)))
1135
+ return {
1136
+ lines: byStrength(normal).slice(0, 8).map(line),
1137
+ sensitiveTriggers: byStrength(sensitive).slice(0, 2).map(line),
1138
+ }
1139
+ }
1140
+
1141
+ export function lexiconAnchorSummary(libraryId, memoryContext) {
1142
+ return lexiconAnchorLines(visibleLexiconTerms(libraryId, memoryContext))
1143
+ }
1144
+
1145
+ /**
1146
+ * legacy 生命周期迁移(§2.1):旧版 pending 在当前生命周期不再存在,读到就跑一次收口。
1147
+ * * pending 且 !revisionOf(老提案)→ active;敏感词 → archived(敏感词只能由用户
1148
+ * 显式管理,不能因为迁移悄悄进入注入面)。legacy 数据缺 sensitivity 的 trigger
1149
+ * 默认按 sensitive 处理(§1.2 的缺省值),同样归档。
1150
+ * * pending 且 revisionOf(老修订草稿)→ archived:目标词条不动,草稿留审计。
1151
+ * * rejected → 原样保留(内部墓碑 + fingerprint 不变)。
1152
+ * 只写有变化的文件:没有 pending 时直接返回,不 bump revision(迁移是巡检常客,
1153
+ * 空转写盘会让 revision 变成噪声,也会把没改过的文件推成热文件)。
1154
+ * 返回 { libraryId, migrated, details? };损坏/读失败仍是 typed error(调用方决定
1155
+ * 是否吞掉——lib/migrate.js 的巡检按库 catch)。
1156
+ */
1157
+ export function migrateLegacyLexiconStatuses(libraryId) {
1158
+ // 快速路径:索引已经知道有没有 legacy pending;没有就不进锁、不写盘。
1159
+ const index = lexiconIndex(libraryId)
1160
+ if (!index.pendingEntries.length) return { libraryId, migrated: 0 }
1161
+ const outcome = mutateLexicon(libraryId, (lex) => {
1162
+ const now = stamp()
1163
+ const details = []
1164
+ for (const [termId, entry] of Object.entries(lex.terms)) {
1165
+ if ((entry.status || 'active') !== 'pending') continue
1166
+ // trigger 的 sensitivity 缺省是 sensitive(§1.2);legacy 数据可能没写这个字段。
1167
+ const sensitive = entry.sensitivity === 'sensitive'
1168
+ || (entry.kind === 'trigger' && entry.sensitivity !== 'normal')
1169
+ const next = entry.revisionOf || sensitive ? 'archived' : 'active'
1170
+ entry.status = next
1171
+ entry.migratedFromStatus = 'pending'
1172
+ entry.statusMigratedAt = now
1173
+ details.push({
1174
+ termId,
1175
+ status: next,
1176
+ reason: entry.revisionOf ? 'revision-draft' : sensitive ? 'sensitive' : 'proposal',
1177
+ ...(entry.revisionOf ? { revisionOf: entry.revisionOf } : {}),
1178
+ })
1179
+ }
1180
+ return { changed: details.length > 0, migrated: details.length, details }
1181
+ }, { onlyWhenChanged: true })
1182
+ return { libraryId, migrated: outcome.migrated, details: outcome.details }
1183
+ }