@open-livex-wiki/core 0.2.0 → 0.2.2

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 (130) hide show
  1. package/dist/coverage/handles.d.ts +5 -0
  2. package/dist/coverage/handles.d.ts.map +1 -0
  3. package/dist/coverage/handles.js +116 -0
  4. package/dist/coverage/handles.js.map +1 -0
  5. package/dist/coverage/targets.d.ts +22 -0
  6. package/dist/coverage/targets.d.ts.map +1 -0
  7. package/dist/coverage/targets.js +117 -0
  8. package/dist/coverage/targets.js.map +1 -0
  9. package/dist/coverage/visuals.d.ts +19 -0
  10. package/dist/coverage/visuals.d.ts.map +1 -0
  11. package/dist/coverage/visuals.js +103 -0
  12. package/dist/coverage/visuals.js.map +1 -0
  13. package/dist/coverage.d.ts.map +1 -1
  14. package/dist/coverage.js +83 -168
  15. package/dist/coverage.js.map +1 -1
  16. package/dist/discover/designators.d.ts +26 -0
  17. package/dist/discover/designators.d.ts.map +1 -0
  18. package/dist/discover/designators.js +361 -0
  19. package/dist/discover/designators.js.map +1 -0
  20. package/dist/discover/document-types.d.ts +90 -0
  21. package/dist/discover/document-types.d.ts.map +1 -0
  22. package/dist/discover/document-types.js +2 -0
  23. package/dist/discover/document-types.js.map +1 -0
  24. package/dist/discover/index-builder.d.ts +28 -0
  25. package/dist/discover/index-builder.d.ts.map +1 -0
  26. package/dist/discover/index-builder.js +286 -0
  27. package/dist/discover/index-builder.js.map +1 -0
  28. package/dist/discover/postings.d.ts +9 -0
  29. package/dist/discover/postings.d.ts.map +1 -0
  30. package/dist/discover/postings.js +183 -0
  31. package/dist/discover/postings.js.map +1 -0
  32. package/dist/discover/query-expansion.d.ts +4 -0
  33. package/dist/discover/query-expansion.d.ts.map +1 -0
  34. package/dist/discover/query-expansion.js +109 -0
  35. package/dist/discover/query-expansion.js.map +1 -0
  36. package/dist/discover/scene-document.d.ts +40 -0
  37. package/dist/discover/scene-document.d.ts.map +1 -0
  38. package/dist/discover/scene-document.js +417 -0
  39. package/dist/discover/scene-document.js.map +1 -0
  40. package/dist/discover/scene-ranking.d.ts +14 -0
  41. package/dist/discover/scene-ranking.d.ts.map +1 -0
  42. package/dist/discover/scene-ranking.js +217 -0
  43. package/dist/discover/scene-ranking.js.map +1 -0
  44. package/dist/discover/scoring.d.ts +34 -0
  45. package/dist/discover/scoring.d.ts.map +1 -0
  46. package/dist/discover/scoring.js +425 -0
  47. package/dist/discover/scoring.js.map +1 -0
  48. package/dist/discover/subscene.d.ts +11 -0
  49. package/dist/discover/subscene.d.ts.map +1 -0
  50. package/dist/discover/subscene.js +121 -0
  51. package/dist/discover/subscene.js.map +1 -0
  52. package/dist/discover/term-scoring.d.ts +25 -0
  53. package/dist/discover/term-scoring.d.ts.map +1 -0
  54. package/dist/discover/term-scoring.js +374 -0
  55. package/dist/discover/term-scoring.js.map +1 -0
  56. package/dist/discover/tokenizer.d.ts +35 -0
  57. package/dist/discover/tokenizer.d.ts.map +1 -0
  58. package/dist/discover/tokenizer.js +282 -0
  59. package/dist/discover/tokenizer.js.map +1 -0
  60. package/dist/discover.d.ts +5 -60
  61. package/dist/discover.d.ts.map +1 -1
  62. package/dist/discover.js +78 -2192
  63. package/dist/discover.js.map +1 -1
  64. package/dist/loader/config.d.ts +29 -0
  65. package/dist/loader/config.d.ts.map +1 -0
  66. package/dist/loader/config.js +80 -0
  67. package/dist/loader/config.js.map +1 -0
  68. package/dist/loader/domain.d.ts +19 -0
  69. package/dist/loader/domain.d.ts.map +1 -0
  70. package/dist/loader/domain.js +152 -0
  71. package/dist/loader/domain.js.map +1 -0
  72. package/dist/loader/paths.d.ts +4 -0
  73. package/dist/loader/paths.d.ts.map +1 -0
  74. package/dist/loader/paths.js +29 -0
  75. package/dist/loader/paths.js.map +1 -0
  76. package/dist/loader/scene.d.ts +16 -0
  77. package/dist/loader/scene.d.ts.map +1 -0
  78. package/dist/loader/scene.js +266 -0
  79. package/dist/loader/scene.js.map +1 -0
  80. package/dist/loader.d.ts +2 -2
  81. package/dist/loader.d.ts.map +1 -1
  82. package/dist/loader.js +11 -506
  83. package/dist/loader.js.map +1 -1
  84. package/dist/schemas.d.ts +14 -11
  85. package/dist/schemas.d.ts.map +1 -1
  86. package/dist/schemas.js +2 -1
  87. package/dist/schemas.js.map +1 -1
  88. package/dist/types.d.ts +2 -0
  89. package/dist/types.d.ts.map +1 -1
  90. package/dist/utils/markdown-scanner.d.ts +20 -0
  91. package/dist/utils/markdown-scanner.d.ts.map +1 -0
  92. package/dist/utils/markdown-scanner.js +303 -0
  93. package/dist/utils/markdown-scanner.js.map +1 -0
  94. package/dist/utils/markdown.d.ts +48 -0
  95. package/dist/utils/markdown.d.ts.map +1 -0
  96. package/dist/utils/markdown.js +370 -0
  97. package/dist/utils/markdown.js.map +1 -0
  98. package/dist/utils/paths.d.ts +38 -0
  99. package/dist/utils/paths.d.ts.map +1 -0
  100. package/dist/utils/paths.js +257 -0
  101. package/dist/utils/paths.js.map +1 -0
  102. package/dist/utils/regexp.d.ts +2 -0
  103. package/dist/utils/regexp.d.ts.map +1 -0
  104. package/dist/utils/regexp.js +4 -0
  105. package/dist/utils/regexp.js.map +1 -0
  106. package/dist/utils/symbols.d.ts +9 -0
  107. package/dist/utils/symbols.d.ts.map +1 -0
  108. package/dist/utils/symbols.js +324 -0
  109. package/dist/utils/symbols.js.map +1 -0
  110. package/dist/utils.d.ts +4 -96
  111. package/dist/utils.d.ts.map +1 -1
  112. package/dist/utils.js +3 -1250
  113. package/dist/utils.js.map +1 -1
  114. package/dist/validator/anchor-checker.d.ts +26 -0
  115. package/dist/validator/anchor-checker.d.ts.map +1 -0
  116. package/dist/validator/anchor-checker.js +299 -0
  117. package/dist/validator/anchor-checker.js.map +1 -0
  118. package/dist/validator/git-remotes.d.ts +12 -0
  119. package/dist/validator/git-remotes.d.ts.map +1 -0
  120. package/dist/validator/git-remotes.js +223 -0
  121. package/dist/validator/git-remotes.js.map +1 -0
  122. package/dist/validator/source-resolver.d.ts +29 -0
  123. package/dist/validator/source-resolver.d.ts.map +1 -0
  124. package/dist/validator/source-resolver.js +315 -0
  125. package/dist/validator/source-resolver.js.map +1 -0
  126. package/dist/validator.d.ts +3 -45
  127. package/dist/validator.d.ts.map +1 -1
  128. package/dist/validator.js +6 -823
  129. package/dist/validator.js.map +1 -1
  130. package/package.json +1 -1
package/dist/discover.js CHANGED
@@ -1,2005 +1,15 @@
1
- import { toPosixPath } from "./utils.js";
2
- const QUERY_PUNCT_SPLIT_REGEX = /[\s,;,;、。??!!|/\\()()[\]【】<>::"'`]+/;
3
- const CJK_CHAR_REGEX = /[\u3400-\u9fff\uf900-\ufaff]/;
4
- const CJK_RUN_OR_OTHER_REGEX = /[\u3400-\u9fff\uf900-\ufaff]+|[^\u3400-\u9fff\uf900-\ufaff]+/g;
5
- const CJK_PREFIX_FILLERS = ["关于", "请问", "帮我", "如何", "怎么", "什么", "查询", "查看", "排查"];
6
- const CJK_SUFFIX_FILLERS = ["相关", "模块", "逻辑", "功能", "问题", "异常", "吗", "呢", "了"];
7
- const CJK_BOUNDARY_PARTICLES = ["的", "与", "和", "及", "在"];
8
- const CJK_STOP_WORDS_SET = new Set([
9
- ...CJK_PREFIX_FILLERS,
10
- ...CJK_SUFFIX_FILLERS,
11
- ...CJK_BOUNDARY_PARTICLES,
12
- ]);
13
- const GENERIC_CJK_SUFFIX_BIGRAMS = new Set([
14
- "协议",
15
- "契约",
16
- "接口",
17
- "服务",
18
- "系统",
19
- "平台",
20
- "管理",
21
- "中心",
22
- "规范",
23
- "标准",
24
- "机制",
25
- "流程",
26
- "链路",
27
- "方案",
28
- "组件",
29
- "引擎",
30
- ]);
31
- const SOURCE_FILE_EXT_REGEX = /\.(?:py|ts|tsx|js|jsx|mjs|cjs|go|java|rs|rb|php|cs|cpp|cc|c|h|hpp|sql|json|yaml|yml|toml|md|pdf|png|jpg|jpeg|webp|svg|csv|parquet)$/i;
32
- const IDENTIFIER_NOISE_SUBTOKENS = new Set([
33
- "py",
34
- "ts",
35
- "tsx",
36
- "js",
37
- "jsx",
38
- "mjs",
39
- "cjs",
40
- "go",
41
- "rs",
42
- "rb",
43
- "md",
44
- "src",
45
- "lib",
46
- ]);
47
- const NON_DESIGNATOR_PREFIX_WORDS = new Set([
48
- // Document / UI structural nouns & citation handle prefixes
49
- "figure",
50
- "figures",
51
- "fig",
52
- "figs",
53
- "table",
54
- "tables",
55
- "tab",
56
- "tbl",
57
- "section",
58
- "sections",
59
- "sec",
60
- "secs",
61
- "chapter",
62
- "chapters",
63
- "chap",
64
- "chaps",
65
- "page",
66
- "pages",
67
- "pg",
68
- "pp",
69
- "part",
70
- "parts",
71
- "appendix",
72
- "appendices",
73
- "item",
74
- "items",
75
- "step",
76
- "steps",
77
- "stage",
78
- "stages",
79
- "phase",
80
- "phases",
81
- "tier",
82
- "tiers",
83
- "level",
84
- "levels",
85
- "version",
86
- "versions",
87
- "ver",
88
- "vol",
89
- "volume",
90
- "issue",
91
- "line",
92
- "lines",
93
- "row",
94
- "rows",
95
- "col",
96
- "cols",
97
- "column",
98
- "columns",
99
- "chart",
100
- "charts",
101
- "graph",
102
- "diagram",
103
- "anc",
104
- "anchor",
105
- "scene",
106
- "scenes",
107
- "domain",
108
- "domains",
109
- "chain",
110
- "chains",
111
- "doc",
112
- "docs",
113
- "file",
114
- "files",
115
- "test",
116
- "tests",
117
- "task",
118
- "tasks",
119
- // Time / fiscal / calendar / common units
120
- "fy",
121
- "cy",
122
- "ty",
123
- "year",
124
- "years",
125
- "yr",
126
- "yrs",
127
- "month",
128
- "months",
129
- "mo",
130
- "week",
131
- "weeks",
132
- "wk",
133
- "day",
134
- "days",
135
- "hour",
136
- "hours",
137
- "hr",
138
- "hrs",
139
- "min",
140
- "mins",
141
- "minute",
142
- "minutes",
143
- "second",
144
- "seconds",
145
- "jan",
146
- "feb",
147
- "mar",
148
- "apr",
149
- "jun",
150
- "jul",
151
- "aug",
152
- "sep",
153
- "sept",
154
- "oct",
155
- "nov",
156
- "dec",
157
- // Common English prepositions, conjunctions, verbs, articles, tech tokens
158
- "the",
159
- "and",
160
- "for",
161
- "with",
162
- "from",
163
- "into",
164
- "over",
165
- "under",
166
- "between",
167
- "about",
168
- "after",
169
- "before",
170
- "during",
171
- "within",
172
- "through",
173
- "across",
174
- "among",
175
- "than",
176
- "per",
177
- "via",
178
- "see",
179
- "ref",
180
- "note",
181
- "notes",
182
- "report",
183
- "reports",
184
- "compare",
185
- "versus",
186
- "top",
187
- "max",
188
- "limit",
189
- "port",
190
- "code",
191
- "type",
192
- "mode",
193
- "node",
194
- "edge",
195
- "utf",
196
- "sha",
197
- "int",
198
- "uint",
199
- "float",
200
- "win",
201
- "ipv",
202
- "http",
203
- "https",
204
- "tcp",
205
- "udp",
206
- ]);
207
- const SPACE_STOP_PREFIXES = new Set([
208
- "in",
209
- "on",
210
- "at",
211
- "to",
212
- "of",
213
- "by",
214
- "or",
215
- "as",
216
- "is",
217
- "be",
218
- "an",
219
- "no",
220
- "so",
221
- "up",
222
- "if",
223
- "do",
224
- "go",
225
- "we",
226
- "it",
227
- "he",
228
- "me",
229
- "my",
230
- "us",
231
- "vs",
232
- ]);
233
- /**
234
- * Normalizes a single alphanumeric model, weapon, report, or standard designator
235
- * (e.g. `"FFG-62"`, `"FFG 62"`, `"FFG62"` -> `"ffg62"`; `"ATP 7-100.1"` -> `"atp71001"`).
236
- * Returns `undefined` for ordinary prose words, pure numbers, commit SHAs, or structural labels.
237
- */
238
- export function normalizeDesignatorToken(text) {
239
- if (typeof text !== "string") {
240
- return undefined;
241
- }
242
- const cleaned = text
243
- .trim()
244
- .replace(/^[([{"'`]+|[)\]}"'`,.;:!?]+$/g, "")
245
- .trim();
246
- if (!cleaned) {
247
- return undefined;
248
- }
249
- // Must start with 1..10 ASCII letters and contain only ASCII letters, digits, spaces, and ./_- separators
250
- if (!/^[A-Za-z]{1,10}(?:[\s./_-]+[A-Za-z0-9]+|[0-9][A-Za-z0-9./_-]*)+$/.test(cleaned)) {
251
- return undefined;
252
- }
253
- if (!/[A-Za-z]/.test(cleaned) || !/[0-9]/.test(cleaned)) {
254
- return undefined;
255
- }
256
- // Reject unseparated hex SHA-1/SHA-256/short-SHA digests and UUIDs
257
- if (!/[\s./_-]/.test(cleaned) && /^[0-9a-f]{7,64}$/i.test(cleaned)) {
258
- return undefined;
259
- }
260
- if (/^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/i.test(cleaned)) {
261
- return undefined;
262
- }
263
- // Reject semver / version tags like v1, v1.2, v0.2.0 (while keeping hyphenated V-22!)
264
- if (/^v\s*\d+(?:\.\d+)*$/i.test(cleaned)) {
265
- return undefined;
266
- }
267
- // Reject source filenames with extensions (e.g. `v2.ts`, `route_v1.py`)
268
- if (SOURCE_FILE_EXT_REGEX.test(cleaned)) {
269
- return undefined;
270
- }
271
- const collapsed = cleaned.replace(/[^A-Za-z0-9]+/g, "").toLowerCase();
272
- if (collapsed.length < 3 || collapsed.length > 32) {
273
- return undefined;
274
- }
275
- const prefixMatch = /^([A-Za-z]+)/.exec(cleaned);
276
- const rawPrefix = prefixMatch?.[1] ?? "";
277
- const lowerPrefix = rawPrefix.toLowerCase();
278
- if (!rawPrefix || NON_DESIGNATOR_PREFIX_WORDS.has(lowerPrefix)) {
279
- return undefined;
280
- }
281
- // Guard space-separated prefixes against lowercase articles/prepositions ("a 10", "in 2025", "if 2")
282
- const afterPrefix = cleaned.slice(rawPrefix.length);
283
- if (/^\s/.test(afterPrefix)) {
284
- if (rawPrefix.length === 1 && rawPrefix === lowerPrefix) {
285
- return undefined;
286
- }
287
- if (SPACE_STOP_PREFIXES.has(lowerPrefix)) {
288
- const isUppercaseCrsReport = rawPrefix === rawPrefix.toUpperCase() && /^[A-Z]{2}\s+\d{4,5}[A-Z]?$/.test(cleaned);
289
- if (!isUppercaseCrsReport) {
290
- return undefined;
291
- }
292
- }
293
- }
294
- return collapsed;
295
- }
296
- function buildDesignatorVariants(rawText, primaryCanonical) {
297
- const variants = [primaryCanonical];
298
- const parts = rawText
299
- .trim()
300
- .split(/[\s/_-]+/)
301
- .filter(Boolean);
302
- if (parts.length >= 2 && /^[A-Za-z]+$/.test(parts[0] ?? "")) {
303
- const suffixRaw = parts.slice(1).join("-");
304
- if (/^[A-Za-z]/.test(suffixRaw) && /[0-9]/.test(suffixRaw)) {
305
- const subNorm = normalizeDesignatorToken(suffixRaw);
306
- if (subNorm && !variants.includes(subNorm)) {
307
- variants.push(subNorm);
308
- }
309
- }
310
- }
311
- return variants;
312
- }
313
- /**
314
- * Scans arbitrary text and returns structured designator mentions (preserving original span + canonical variants).
315
- */
316
- export function extractDesignatorMentions(text) {
317
- if (typeof text !== "string" || !text || !/[0-9]/.test(text) || !/[A-Za-z]/.test(text)) {
318
- return [];
319
- }
320
- // Mask URLs and SCP remotes with spaces only when `://` or `@` is actually present
321
- let masked = text;
322
- if (masked.includes("://")) {
323
- masked = masked.replace(/(?:git\+)?(?:https?|ssh|git):\/\/[^\s)>\]"']+/gi, " ");
324
- }
325
- if (masked.includes("@")) {
326
- masked = masked.replace(/[A-Za-z0-9._+-]+@[A-Za-z0-9.-]+:[^\s)>\]"']+/g, " ");
327
- }
328
- const spans = [];
329
- for (const m of masked.matchAll(/[A-Za-z0-9]+(?:[-/.][A-Za-z0-9]+)*/g)) {
330
- const tokenText = m[0];
331
- const start = m.index ?? 0;
332
- if (tokenText) {
333
- spans.push({ text: tokenText, start, end: start + tokenText.length });
334
- }
335
- }
336
- const mentions = [];
337
- const seenPrimary = new Set();
338
- for (let i = 0; i < spans.length; i++) {
339
- const cur = spans[i];
340
- const next = spans[i + 1];
341
- if (next && /^[A-Za-z]{1,8}(?:[-/][A-Za-z]{1,8})?$/.test(cur.text)) {
342
- const between = masked.slice(cur.end, next.start);
343
- const isSpaceOnly = /^[ \t]+$/.test(between);
344
- const isSpacedContinuation = /^[0-9][0-9A-Za-z]*(?:[-/.][0-9A-Za-z]+)*$/.test(next.text) ||
345
- /^[A-Za-z]{1,2}[0-9]{3,}[A-Za-z]?$/.test(next.text);
346
- if (isSpaceOnly && isSpacedContinuation) {
347
- const combinedRaw = `${cur.text} ${next.text}`;
348
- const combinedNorm = normalizeDesignatorToken(combinedRaw);
349
- if (combinedNorm) {
350
- if (!seenPrimary.has(combinedNorm)) {
351
- seenPrimary.add(combinedNorm);
352
- mentions.push({
353
- raw: combinedRaw,
354
- canonical: combinedNorm,
355
- variants: buildDesignatorVariants(combinedRaw, combinedNorm),
356
- });
357
- }
358
- i += 1;
359
- continue;
360
- }
361
- }
362
- }
363
- if (!/[0-9]/.test(cur.text)) {
364
- continue;
365
- }
366
- const singleNorm = normalizeDesignatorToken(cur.text);
367
- if (singleNorm && !seenPrimary.has(singleNorm)) {
368
- seenPrimary.add(singleNorm);
369
- mentions.push({
370
- raw: cur.text,
371
- canonical: singleNorm,
372
- variants: buildDesignatorVariants(cur.text, singleNorm),
373
- });
374
- }
375
- }
376
- return mentions;
377
- }
378
- /**
379
- * Extracts deduplicated canonical alphanumeric designator tokens from arbitrary text
380
- * (e.g. `"CRS-R44972"` -> `["crsr44972", "r44972"]`, `"FFG 62"` -> `["ffg62"]`, `"ATP 7-100.1"` -> `["atp71001"]`).
381
- */
382
- export function extractDesignatorTokens(text) {
383
- const out = new Set();
384
- for (const mention of extractDesignatorMentions(text)) {
385
- for (const v of mention.variants) {
386
- out.add(v);
387
- }
388
- }
389
- return Array.from(out);
390
- }
391
- function isPureCjk(text) {
392
- return text.length > 0 && /^[\u3400-\u9fff\uf900-\ufaff]+$/.test(text);
393
- }
394
- function stripCjkFillers(rawCjk) {
395
- let cleaned = rawCjk;
396
- // Iteratively strip prefix/suffix query filler words while remaining length >= 2
397
- let changed = true;
398
- while (changed && cleaned.length > 2) {
399
- changed = false;
400
- for (const prefix of CJK_PREFIX_FILLERS) {
401
- if (cleaned.startsWith(prefix) && cleaned.length - prefix.length >= 2) {
402
- cleaned = cleaned.slice(prefix.length);
403
- changed = true;
404
- }
405
- }
406
- for (const suffix of CJK_SUFFIX_FILLERS) {
407
- if (cleaned.endsWith(suffix) && cleaned.length - suffix.length >= 2) {
408
- cleaned = cleaned.slice(0, -suffix.length);
409
- changed = true;
410
- }
411
- }
412
- for (const particle of CJK_BOUNDARY_PARTICLES) {
413
- if (cleaned.startsWith(particle) && cleaned.length - particle.length >= 2) {
414
- cleaned = cleaned.slice(particle.length);
415
- changed = true;
416
- }
417
- if (cleaned.endsWith(particle) && cleaned.length - particle.length >= 2) {
418
- cleaned = cleaned.slice(0, -particle.length);
419
- changed = true;
420
- }
421
- }
422
- }
423
- // Split conjunctive CJK phrases like "飞书和微信" or "网关的协议" when both sides have >= 2 chars
424
- const parts = cleaned.split(/[的与和及]/).filter((p) => p.length >= 2);
425
- if (parts.length >= 2) {
426
- return parts;
427
- }
428
- return [cleaned];
429
- }
430
- function buildCjkGroup(cjkToken, rawOriginal) {
431
- const threeGrams = [];
432
- const twoGrams = [];
433
- if (cjkToken.length >= 3) {
434
- const trailingBigram = cjkToken.length >= 4 ? cjkToken.slice(-2) : "";
435
- const hasGenericSuffix = cjkToken.length >= 4 &&
436
- GENERIC_CJK_SUFFIX_BIGRAMS.has(trailingBigram) &&
437
- cjkToken.length - 2 >= 2;
438
- if (hasGenericSuffix) {
439
- // Preserve morpheme boundary `<head><genericSuffix>` (e.g. "中台" + "服务") so cross-boundary
440
- // phantom n-grams ("台服务", "台服") never false-match unrelated siblings ("前台服务")!
441
- const head = cjkToken.slice(0, -2);
442
- if (head.length === 3 && !CJK_STOP_WORDS_SET.has(head)) {
443
- threeGrams.push(head);
444
- }
445
- else if (head.length >= 4) {
446
- for (let i = 0; i <= head.length - 3; i++) {
447
- const tri = head.slice(i, i + 3);
448
- if (!CJK_STOP_WORDS_SET.has(tri)) {
449
- threeGrams.push(tri);
450
- }
451
- }
452
- }
453
- for (let i = 0; i <= head.length - 2; i++) {
454
- const bi = head.slice(i, i + 2);
455
- if (!CJK_STOP_WORDS_SET.has(bi)) {
456
- twoGrams.push(bi);
457
- }
458
- }
459
- if (!CJK_STOP_WORDS_SET.has(trailingBigram)) {
460
- twoGrams.push(trailingBigram);
461
- }
462
- }
463
- else {
464
- if (cjkToken.length >= 4) {
465
- for (let i = 0; i <= cjkToken.length - 3; i++) {
466
- const tri = cjkToken.slice(i, i + 3);
467
- if (!CJK_STOP_WORDS_SET.has(tri)) {
468
- threeGrams.push(tri);
469
- }
470
- }
471
- }
472
- for (let i = 0; i <= cjkToken.length - 2; i++) {
473
- const bi = cjkToken.slice(i, i + 2);
474
- if (!CJK_STOP_WORDS_SET.has(bi)) {
475
- twoGrams.push(bi);
476
- }
477
- }
478
- }
479
- }
480
- const isStrippedStem = Boolean(rawOriginal && rawOriginal !== cjkToken);
481
- return {
482
- primary: cjkToken,
483
- ...(isStrippedStem && rawOriginal ? { rawToken: rawOriginal, isStrippedStem: true } : {}),
484
- threeGrams: Array.from(new Set(threeGrams)),
485
- twoGrams: Array.from(new Set(twoGrams)),
486
- };
487
- }
488
- function extractIdentifierSubTokens(rawAsciiToken, lowerPrimary) {
489
- const withoutExt = rawAsciiToken.trim().replace(SOURCE_FILE_EXT_REGEX, "");
490
- // Split camelCase ("AgentAPI" -> "Agent API", "HTMLParser" -> "HTML Parser") and snake/kebab/path separators
491
- const camelSplit = withoutExt
492
- .replace(/([a-z0-9])([A-Z])/g, "$1 $2")
493
- .replace(/([A-Z]+)([A-Z][a-z])/g, "$1 $2");
494
- const rawParts = camelSplit
495
- .toLowerCase()
496
- .split(/[^a-z0-9]+/)
497
- .map((p) => p.trim())
498
- .filter((p) => p.length >= 2 && p !== lowerPrimary && !IDENTIFIER_NOISE_SUBTOKENS.has(p));
499
- const deduped = Array.from(new Set(rawParts));
500
- return deduped.length >= 2 ? deduped : [];
501
- }
502
- function escapeRegExpLiteral(str) {
503
- return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
504
- }
505
- /**
506
- * Smart CJK + Mixed-Script + Designator-Aware tokenizer for progressive discovery queries.
507
- * - Splits on whitespace and punctuation while preserving `.`, `-`, `_`, `#` inside identifiers/filenames.
508
- * - Canonicalizes alphanumeric designators (`"FFG-62"` / `"FFG 62"` -> `"ffg62"`, `"CRS-R44972"` -> `["crsr44972", "r44972"]`).
509
- * - Splits CJK <-> ASCII/number transitions (`"iOS内购"` -> `["ios", "内购"]`, `"LLM网关"` -> `["llm", "网关"]`).
510
- * - Strips Chinese filler/stop particles when remaining CJK length >= 2.
511
- * - Emits overlapping CJK 2-grams and 3-grams for CJK compound tokens of length >= 3.
512
- * - Decomposes compound code/file identifiers (`"settings_api.py"` -> `["settings", "api"]`) for fallback co-occurrence matching.
513
- */
514
- export function tokenizeDiscoveryQuery(query) {
515
- const trimmedOriginal = query.trim();
516
- const normalizedPhrase = trimmedOriginal.toLowerCase();
517
- if (!normalizedPhrase) {
518
- return { normalizedPhrase: "", groups: [] };
519
- }
520
- const rawSegments = trimmedOriginal.split(QUERY_PUNCT_SPLIT_REGEX).filter(Boolean);
521
- const seenPrimary = new Set();
522
- const groups = [];
523
- function addToken(rawTok, rawCjkRun) {
524
- const cleanedOriginal = rawTok.trim().replace(/^[._#-]+|[._#-]+$/g, "");
525
- const t = cleanedOriginal.toLowerCase();
526
- if (!t || seenPrimary.has(t)) {
527
- return;
528
- }
529
- if (isPureCjk(t)) {
530
- if (CJK_STOP_WORDS_SET.has(t) && normalizedPhrase !== t) {
531
- return;
532
- }
533
- seenPrimary.add(t);
534
- groups.push(buildCjkGroup(t, rawCjkRun?.toLowerCase()));
535
- return;
536
- }
537
- if (t.length < 2 && normalizedPhrase.length >= 2) {
538
- return;
539
- }
540
- seenPrimary.add(t);
541
- const subTokens = extractIdentifierSubTokens(cleanedOriginal, t);
542
- const normDesig = normalizeDesignatorToken(cleanedOriginal);
543
- const designators = normDesig ? buildDesignatorVariants(cleanedOriginal, normDesig) : [];
544
- groups.push({
545
- primary: t,
546
- threeGrams: [],
547
- twoGrams: [],
548
- ...(subTokens.length > 0 ? { subTokens } : {}),
549
- ...(designators.length > 0 ? { designators } : {}),
550
- });
551
- }
552
- for (let idx = 0; idx < rawSegments.length; idx++) {
553
- const segment = rawSegments[idx];
554
- const nextSeg = rawSegments[idx + 1];
555
- // Coalesce adjacent space-separated designators (e.g. "FFG 62", "SSBN 826", "CRS R44972", "ATP 7-100.1")
556
- if (nextSeg &&
557
- !CJK_CHAR_REGEX.test(segment) &&
558
- !CJK_CHAR_REGEX.test(nextSeg) &&
559
- /^[A-Za-z]{1,8}(?:-[A-Za-z]{1,8})?$/.test(segment) &&
560
- (/^[0-9][0-9A-Za-z._-]*$/.test(nextSeg) || /^[A-Za-z]{1,2}[0-9]{3,}[A-Za-z]?$/.test(nextSeg))) {
561
- const spacedRegex = new RegExp(`(?<![A-Za-z0-9_])${escapeRegExpLiteral(segment)}[ \\t]+${escapeRegExpLiteral(nextSeg)}(?![A-Za-z0-9_])`);
562
- const combinedRaw = `${segment} ${nextSeg}`;
563
- const combinedNorm = spacedRegex.test(trimmedOriginal)
564
- ? normalizeDesignatorToken(combinedRaw)
565
- : undefined;
566
- if (combinedNorm) {
567
- const primaryLower = combinedRaw.toLowerCase();
568
- if (!seenPrimary.has(primaryLower)) {
569
- seenPrimary.add(primaryLower);
570
- const subTokens = extractIdentifierSubTokens(`${segment}-${nextSeg}`, primaryLower);
571
- const designators = buildDesignatorVariants(combinedRaw, combinedNorm);
572
- groups.push({
573
- primary: primaryLower,
574
- threeGrams: [],
575
- twoGrams: [],
576
- ...(subTokens.length > 0 ? { subTokens } : {}),
577
- designators,
578
- });
579
- }
580
- idx += 1;
581
- continue;
582
- }
583
- }
584
- const hasMixedScript = CJK_CHAR_REGEX.test(segment) && /[^\u3400-\u9fff\uf900-\ufaff]/.test(segment);
585
- if (!hasMixedScript) {
586
- if (isPureCjk(segment)) {
587
- for (const stripped of stripCjkFillers(segment)) {
588
- addToken(stripped, segment);
589
- }
590
- }
591
- else {
592
- addToken(segment);
593
- }
594
- continue;
595
- }
596
- // Split CJK <-> ASCII/number runs (e.g. "iOS内购" -> ["ios", "内购"], "LLM网关" -> ["llm", "网关"])
597
- const runs = segment.match(CJK_RUN_OR_OTHER_REGEX) ?? [segment];
598
- for (const run of runs) {
599
- if (isPureCjk(run)) {
600
- for (const stripped of stripCjkFillers(run)) {
601
- addToken(stripped, run);
602
- }
603
- }
604
- else {
605
- addToken(run);
606
- }
607
- }
608
- }
609
- if (groups.length === 0) {
610
- groups.push(isPureCjk(normalizedPhrase)
611
- ? buildCjkGroup(normalizedPhrase)
612
- : { primary: normalizedPhrase, threeGrams: [], twoGrams: [] });
613
- }
614
- return { normalizedPhrase, groups };
615
- }
616
- function extractInlineCodeSpans(markdown) {
617
- const spans = [];
618
- const lines = markdown.split(/\r?\n/);
619
- let inFence = false;
620
- let fenceChar = "";
621
- let fenceLen = 0;
622
- for (const rawLine of lines) {
623
- if (!inFence) {
624
- const open = /^ {0,3}(`{3,}|~{3,})(.*)$/.exec(rawLine);
625
- if (open?.[1] && !(open[1][0] === "`" && (open[2] ?? "").includes("`"))) {
626
- inFence = true;
627
- fenceChar = open[1][0] ?? "`";
628
- fenceLen = open[1].length;
629
- continue;
630
- }
631
- }
632
- else {
633
- const close = /^ {0,3}(`{3,}|~{3,})[ \t]*$/.exec(rawLine);
634
- if (close?.[1] && close[1][0] === fenceChar && close[1].length >= fenceLen) {
635
- inFence = false;
636
- }
637
- continue;
638
- }
639
- const matches = rawLine.matchAll(/`([^`\r\n]+)`/g);
640
- for (const m of matches) {
641
- const code = m[1]?.trim();
642
- if (code) {
643
- spans.push(code);
644
- }
645
- }
646
- }
647
- return spans;
648
- }
649
- function sanitizeMarkdownForSnippet(markdown) {
650
- const withoutComments = markdown.replace(/<!--[\s\S]*?-->/g, " ");
651
- let out = "";
652
- for (let i = 0; i < withoutComments.length; i++) {
653
- const code = withoutComments.charCodeAt(i);
654
- out += code <= 0x1f || code === 0x7f ? " " : withoutComments[i];
655
- }
656
- return out.replace(/\s+/g, " ").trim();
657
- }
658
- function extractMatchSnippet(sources, matchedTerms, targetLength = 80) {
659
- if (matchedTerms.length === 0 || sources.length === 0) {
660
- return undefined;
661
- }
662
- // Sort matched terms longest first so snippet centers on the most specific term
663
- const sortedTerms = Array.from(new Set(matchedTerms))
664
- .filter((t) => t.length > 0)
665
- .sort((a, b) => b.length - a.length);
666
- for (const rawSource of sources) {
667
- const clean = sanitizeMarkdownForSnippet(rawSource);
668
- if (!clean) {
669
- continue;
670
- }
671
- const cleanLower = clean.toLowerCase();
672
- for (const term of sortedTerms) {
673
- const idx = cleanLower.indexOf(term.toLowerCase());
674
- if (idx === -1) {
675
- continue;
676
- }
677
- if (clean.length <= targetLength) {
678
- return clean;
679
- }
680
- const half = Math.max(10, Math.floor((targetLength - term.length) / 2));
681
- let start = Math.max(0, idx - half);
682
- const end = Math.min(clean.length, start + targetLength);
683
- if (end - start < targetLength) {
684
- start = Math.max(0, end - targetLength);
685
- }
686
- const slice = clean.slice(start, end).trim();
687
- const prefix = start > 0 ? "..." : "";
688
- const suffix = end < clean.length ? "..." : "";
689
- return `${prefix}${slice}${suffix}`;
690
- }
691
- }
692
- return undefined;
693
- }
694
- const WIKI_INDEX_CACHE = new WeakMap();
695
- function toPathTerm(raw) {
696
- const lower = toPosixPath(raw).toLowerCase();
697
- const base = lower.split("/").pop() ?? lower;
698
- return { lower, base };
699
- }
700
- function collectDesignatorsFromStrings(strings, rawMap) {
701
- const out = new Set();
702
- for (const s of strings) {
703
- if (!s) {
704
- continue;
705
- }
706
- for (const mention of extractDesignatorMentions(s)) {
707
- for (const v of mention.variants) {
708
- out.add(v);
709
- if (rawMap && !rawMap.has(v)) {
710
- rawMap.set(v, mention.raw);
711
- }
712
- }
713
- }
714
- }
715
- return out;
716
- }
717
- export function formatAnchorSummaryLabel(anchor) {
718
- const owner = anchor.source ?? anchor.repo ?? "anchor";
719
- const pagePart = anchor.pageRange ? `#p${anchor.pageRange[0]}-${anchor.pageRange[1]}` : "";
720
- const symbolPart = anchor.symbol ? `#${anchor.symbol}` : "";
721
- const extraPart = anchor.assetId
722
- ? ` (${anchor.assetId})`
723
- : anchor.sectionTitle
724
- ? ` (${anchor.sectionTitle})`
725
- : "";
726
- const handlePrefix = anchor.handle ? `[${anchor.handle}] ` : "";
727
- return `${handlePrefix}${owner}:${toPosixPath(anchor.file)}${pagePart}${symbolPart}${extraPart}`;
728
- }
729
- export function toMatchedAnchorSummary(anchor) {
730
- return {
731
- label: formatAnchorSummaryLabel(anchor),
732
- ...(anchor.repo ? { repo: anchor.repo } : {}),
733
- ...(anchor.source ? { source: anchor.source } : {}),
734
- file: anchor.file,
735
- ...(anchor.symbol ? { symbol: anchor.symbol } : {}),
736
- ...(anchor.kind ? { kind: anchor.kind } : {}),
737
- ...(anchor.pageRange
738
- ? { pageRange: [anchor.pageRange[0], anchor.pageRange[1]] }
739
- : {}),
740
- ...(anchor.sectionTitle ? { sectionTitle: anchor.sectionTitle } : {}),
741
- ...(anchor.assetId ? { assetId: anchor.assetId } : {}),
742
- ...(anchor.handle ? { handle: anchor.handle } : {}),
743
- ...(anchor.scopeNote ? { scopeNote: anchor.scopeNote } : {}),
744
- };
745
- }
746
- function collectAnchorSearchStrings(anchor) {
747
- const raw = [anchor.file];
748
- if (anchor.symbol) {
749
- raw.push(anchor.symbol);
750
- }
751
- if (anchor.sectionTitle) {
752
- raw.push(anchor.sectionTitle);
753
- }
754
- if (anchor.assetId) {
755
- raw.push(anchor.assetId);
756
- }
757
- if (anchor.handle) {
758
- raw.push(anchor.handle);
759
- }
760
- if (anchor.scopeNote) {
761
- raw.push(anchor.scopeNote);
762
- }
763
- if (anchor.pageRange) {
764
- raw.push(`p.${anchor.pageRange[0]}-${anchor.pageRange[1]}`);
765
- raw.push(`p${anchor.pageRange[0]}-${anchor.pageRange[1]}`);
766
- }
767
- return raw;
768
- }
769
- function buildSceneIndexedDoc(scene) {
770
- const repoNames = scene.frontmatter.repositories.map((r) => r.repo);
771
- const sourceRefs = scene.frontmatter.sources ?? [];
772
- const sourceNames = sourceRefs.map((s) => s.source);
773
- const sourceSearchRaw = sourceRefs.flatMap((s) => [s.source, ...(s.path ? [s.path] : [])]);
774
- const chainNames = scene.chains.map((c) => c.title);
775
- const rawByDesignator = new Map();
776
- const chainEntries = scene.chains.map((c) => {
777
- const terms = [c.id, c.title, ...(c.entryPoint ? [c.entryPoint] : [])];
778
- return {
779
- title: c.title,
780
- termsLower: terms.map((t) => t.toLowerCase()),
781
- bodyLower: c.markdown.toLowerCase(),
782
- designators: collectDesignatorsFromStrings([...terms, c.markdown], rawByDesignator),
783
- };
784
- });
785
- const detailEntries = scene.details.map((d) => ({
786
- name: d.name,
787
- nameLower: d.name.toLowerCase(),
788
- titleLower: d.title.toLowerCase(),
789
- contentLower: d.content.toLowerCase(),
790
- designators: collectDesignatorsFromStrings([d.name, d.title, d.content], rawByDesignator),
791
- }));
792
- const anchorEntries = (scene.frontmatter.anchors ?? []).map((a) => {
793
- const rawStrings = collectAnchorSearchStrings(a);
794
- return {
795
- anchor: a,
796
- summary: toMatchedAnchorSummary(a),
797
- terms: rawStrings.map(toPathTerm),
798
- designators: collectDesignatorsFromStrings(rawStrings, rawByDesignator),
799
- };
800
- });
801
- const chainTermsRaw = scene.chains.flatMap((c) => [
802
- c.id,
803
- c.title,
804
- ...(c.entryPoint ? [c.entryPoint] : []),
805
- ]);
806
- const anchorTerms = anchorEntries.flatMap((ae) => ae.terms);
807
- const repoTermsRaw = [
808
- ...repoNames,
809
- ...(scene.frontmatter.anchors ?? []).flatMap((a) => (a.repo ? [a.repo] : [])),
810
- ];
811
- const sourceTermsAllRaw = [
812
- ...sourceSearchRaw,
813
- ...(scene.frontmatter.anchors ?? []).flatMap((a) => (a.source ? [a.source] : [])),
814
- ];
815
- const repoTerms = Array.from(new Set(repoTermsRaw)).map(toPathTerm);
816
- const sourceTerms = Array.from(new Set(sourceTermsAllRaw)).map(toPathTerm);
817
- const detailTitlesRaw = scene.details.flatMap((d) => [d.name, d.title]);
818
- const rawCodeSpans = [
819
- ...extractInlineCodeSpans(scene.content),
820
- ...scene.details.flatMap((d) => extractInlineCodeSpans(d.content)),
821
- ];
822
- const codeSpans = rawCodeSpans.map((span) => {
823
- const lower = toPosixPath(span).toLowerCase();
824
- return {
825
- lower,
826
- parts: lower.split(/[/:.#\s]/).filter(Boolean),
827
- };
828
- });
829
- const idLower = scene.id.toLowerCase();
830
- const shortIdLower = scene.sceneId.toLowerCase();
831
- const titleLower = scene.frontmatter.title.toLowerCase();
832
- const aliasesLower = scene.frontmatter.aliases.map((a) => a.toLowerCase());
833
- const chainTermsLower = chainTermsRaw.map((c) => c.toLowerCase());
834
- const summaryLower = scene.frontmatter.summary.toLowerCase();
835
- const headingsLower = scene.headings.map((h) => h.toLowerCase());
836
- const detailTitlesLower = detailTitlesRaw.map((t) => t.toLowerCase());
837
- const bodyLower = scene.content.toLowerCase();
838
- const detailBodySourcesLower = detailEntries.map((d) => d.contentLower);
839
- const tier34GateLower = [
840
- summaryLower,
841
- ...headingsLower,
842
- ...detailTitlesLower,
843
- ...codeSpans.map((c) => c.lower),
844
- bodyLower,
845
- ...detailBodySourcesLower,
846
- ].join("\n");
847
- const allTextLower = [
848
- idLower,
849
- shortIdLower,
850
- titleLower,
851
- ...aliasesLower,
852
- ...chainTermsLower,
853
- ...anchorTerms.map((a) => a.lower),
854
- ...repoTerms.map((r) => r.lower),
855
- ...sourceTerms.map((s) => s.lower),
856
- tier34GateLower,
857
- ].join("\n");
858
- const idDesig = collectDesignatorsFromStrings([scene.id, scene.sceneId], rawByDesignator);
859
- const titleDesig = collectDesignatorsFromStrings([scene.frontmatter.title], rawByDesignator);
860
- const aliasDesig = collectDesignatorsFromStrings(scene.frontmatter.aliases, rawByDesignator);
861
- const chainDesig = collectDesignatorsFromStrings(chainTermsRaw, rawByDesignator);
862
- const anchorDesig = new Set();
863
- for (const ae of anchorEntries) {
864
- for (const d of ae.designators) {
865
- anchorDesig.add(d);
866
- }
867
- }
868
- const repoDesig = collectDesignatorsFromStrings(repoTermsRaw, rawByDesignator);
869
- const sourceDesig = collectDesignatorsFromStrings(sourceTermsAllRaw, rawByDesignator);
870
- const summaryDesig = collectDesignatorsFromStrings([scene.frontmatter.summary], rawByDesignator);
871
- const headingDesig = collectDesignatorsFromStrings(scene.headings, rawByDesignator);
872
- const detailTitleDesig = collectDesignatorsFromStrings(detailTitlesRaw, rawByDesignator);
873
- const codeDesig = collectDesignatorsFromStrings(rawCodeSpans, rawByDesignator);
874
- const bodyDesig = collectDesignatorsFromStrings([scene.content, ...scene.details.map((d) => d.content)], rawByDesignator);
875
- const allDesig = new Set([
876
- ...idDesig,
877
- ...titleDesig,
878
- ...aliasDesig,
879
- ...chainDesig,
880
- ...anchorDesig,
881
- ...repoDesig,
882
- ...sourceDesig,
883
- ...summaryDesig,
884
- ...headingDesig,
885
- ...detailTitleDesig,
886
- ...codeDesig,
887
- ...bodyDesig,
888
- ]);
889
- const emptySet = new Set();
890
- const reverseCandidatesLower = Array.from(new Set([
891
- ...(shortIdLower.length >= 3 ? [shortIdLower] : []),
892
- ...(titleLower.length >= 2 ? [titleLower] : []),
893
- ...aliasesLower.filter((a) => a.length >= 2),
894
- ...chainTermsLower.filter((c) => c.length >= 3),
895
- ...anchorTerms.map((a) => a.base).filter((b) => b.length >= 3),
896
- ...repoTerms.map((r) => r.base).filter((b) => b.length >= 3),
897
- ...sourceTerms.map((s) => s.base).filter((b) => b.length >= 3),
898
- ]));
899
- return {
900
- scene,
901
- repoNames,
902
- sourceNames,
903
- chainNames,
904
- doc: {
905
- idLower,
906
- idCollapsed: idLower.replace(/[^a-z0-9]+/g, ""),
907
- shortIdLower,
908
- shortIdCollapsed: shortIdLower.replace(/[^a-z0-9]+/g, ""),
909
- titleLower,
910
- titleCollapsed: titleLower.replace(/[^a-z0-9]+/g, ""),
911
- aliasesLower,
912
- chainTermsLower,
913
- anchorTerms,
914
- repoTerms,
915
- sourceTerms,
916
- summaryLower,
917
- headingsLower,
918
- detailTitlesLower,
919
- childHighTermsLower: [],
920
- childAnchorTerms: [],
921
- childRepoTerms: [],
922
- childSourceTerms: [],
923
- childBodySourcesLower: [],
924
- codeSpans,
925
- bodySourcesLower: [bodyLower],
926
- detailBodySourcesLower,
927
- tier34GateLower,
928
- allTextLower,
929
- reverseCandidatesLower,
930
- rawSnippetSources: [scene.content, ...scene.details.map((d) => d.content)],
931
- designators: {
932
- id: idDesig,
933
- title: titleDesig,
934
- alias: aliasDesig,
935
- chain: chainDesig,
936
- anchor: anchorDesig,
937
- repo: repoDesig,
938
- source: sourceDesig,
939
- summary: summaryDesig,
940
- heading: headingDesig,
941
- detail: detailTitleDesig,
942
- scene: emptySet,
943
- code: codeDesig,
944
- body: bodyDesig,
945
- all: allDesig,
946
- rawByDesignator,
947
- },
948
- chainEntries,
949
- detailEntries,
950
- anchorEntries,
951
- },
952
- };
953
- }
954
- function buildDomainIndexedDoc(domain, sceneById) {
955
- const rawByDesignator = new Map();
956
- const childHighTermsLower = [];
957
- const childAnchorTerms = [];
958
- const childRepoTerms = [];
959
- const childSourceTerms = [];
960
- const childBodySourcesLower = [];
961
- const rawSnippetSources = [domain.content];
962
- const domainRawCodeSpans = extractInlineCodeSpans(domain.content);
963
- const codeSpans = domainRawCodeSpans.map((span) => {
964
- const lower = toPosixPath(span).toLowerCase();
965
- return {
966
- lower,
967
- parts: lower.split(/[/:.#\s]/).filter(Boolean),
968
- };
969
- });
970
- const sceneDesig = new Set();
971
- const childAnchorDesig = new Set();
972
- const childRepoDesig = new Set();
973
- const childSourceDesig = new Set();
974
- const childBodyDesig = new Set();
975
- const codeDesig = collectDesignatorsFromStrings(domainRawCodeSpans, rawByDesignator);
976
- for (const sceneId of domain.sceneIds) {
977
- const prepScene = sceneById.get(sceneId);
978
- if (!prepScene) {
979
- continue;
980
- }
981
- const sDoc = prepScene.doc;
982
- if (sDoc.shortIdLower) {
983
- childHighTermsLower.push(sDoc.shortIdLower);
984
- }
985
- childHighTermsLower.push(sDoc.titleLower, ...sDoc.aliasesLower, sDoc.summaryLower, ...sDoc.headingsLower, ...sDoc.chainTermsLower, ...sDoc.detailTitlesLower);
986
- childAnchorTerms.push(...sDoc.anchorTerms);
987
- childRepoTerms.push(...sDoc.repoTerms);
988
- childSourceTerms.push(...sDoc.sourceTerms);
989
- codeSpans.push(...sDoc.codeSpans);
990
- childBodySourcesLower.push(...sDoc.bodySourcesLower, ...sDoc.detailBodySourcesLower);
991
- rawSnippetSources.push(...sDoc.rawSnippetSources);
992
- for (const d of [
993
- ...sDoc.designators.id,
994
- ...sDoc.designators.title,
995
- ...sDoc.designators.alias,
996
- ...sDoc.designators.summary,
997
- ...sDoc.designators.heading,
998
- ...sDoc.designators.chain,
999
- ...sDoc.designators.detail,
1000
- ]) {
1001
- sceneDesig.add(d);
1002
- const raw = sDoc.designators.rawByDesignator.get(d);
1003
- if (raw && !rawByDesignator.has(d)) {
1004
- rawByDesignator.set(d, raw);
1005
- }
1006
- }
1007
- for (const d of sDoc.designators.anchor) {
1008
- childAnchorDesig.add(d);
1009
- const raw = sDoc.designators.rawByDesignator.get(d);
1010
- if (raw && !rawByDesignator.has(d)) {
1011
- rawByDesignator.set(d, raw);
1012
- }
1013
- }
1014
- for (const d of sDoc.designators.repo) {
1015
- childRepoDesig.add(d);
1016
- }
1017
- for (const d of sDoc.designators.source) {
1018
- childSourceDesig.add(d);
1019
- }
1020
- for (const d of sDoc.designators.code) {
1021
- codeDesig.add(d);
1022
- const raw = sDoc.designators.rawByDesignator.get(d);
1023
- if (raw && !rawByDesignator.has(d)) {
1024
- rawByDesignator.set(d, raw);
1025
- }
1026
- }
1027
- for (const d of sDoc.designators.body) {
1028
- childBodyDesig.add(d);
1029
- const raw = sDoc.designators.rawByDesignator.get(d);
1030
- if (raw && !rawByDesignator.has(d)) {
1031
- rawByDesignator.set(d, raw);
1032
- }
1033
- }
1034
- }
1035
- const idLower = domain.domainId.toLowerCase();
1036
- const titleLower = domain.frontmatter.title.toLowerCase();
1037
- const aliasesLower = domain.frontmatter.aliases.map((a) => a.toLowerCase());
1038
- const summaryLower = domain.frontmatter.summary.toLowerCase();
1039
- const headingsLower = domain.headings.map((h) => h.toLowerCase());
1040
- const domainBodyLower = domain.content.toLowerCase();
1041
- const tier34GateLower = [
1042
- summaryLower,
1043
- ...headingsLower,
1044
- ...codeSpans.map((c) => c.lower),
1045
- domainBodyLower,
1046
- ...childBodySourcesLower,
1047
- ].join("\n");
1048
- const allTextLower = [
1049
- idLower,
1050
- titleLower,
1051
- ...aliasesLower,
1052
- ...childHighTermsLower,
1053
- ...childAnchorTerms.map((a) => a.lower),
1054
- ...childRepoTerms.map((r) => r.lower),
1055
- ...childSourceTerms.map((s) => s.lower),
1056
- tier34GateLower,
1057
- ].join("\n");
1058
- const idDesig = collectDesignatorsFromStrings([domain.domainId], rawByDesignator);
1059
- const titleDesig = collectDesignatorsFromStrings([domain.frontmatter.title], rawByDesignator);
1060
- const aliasDesig = collectDesignatorsFromStrings(domain.frontmatter.aliases, rawByDesignator);
1061
- const summaryDesig = collectDesignatorsFromStrings([domain.frontmatter.summary], rawByDesignator);
1062
- const headingDesig = collectDesignatorsFromStrings(domain.headings, rawByDesignator);
1063
- const domainBodyDesig = collectDesignatorsFromStrings([domain.content], rawByDesignator);
1064
- for (const d of domainBodyDesig) {
1065
- childBodyDesig.add(d);
1066
- }
1067
- const emptySet = new Set();
1068
- const allDesig = new Set([
1069
- ...idDesig,
1070
- ...titleDesig,
1071
- ...aliasDesig,
1072
- ...summaryDesig,
1073
- ...headingDesig,
1074
- ...sceneDesig,
1075
- ...childAnchorDesig,
1076
- ...childRepoDesig,
1077
- ...childSourceDesig,
1078
- ...codeDesig,
1079
- ...childBodyDesig,
1080
- ]);
1081
- const reverseCandidatesLower = Array.from(new Set([
1082
- ...(titleLower.length >= 2 ? [titleLower] : []),
1083
- ...aliasesLower.filter((a) => a.length >= 2),
1084
- ...childHighTermsLower.filter((c) => c.length >= 2),
1085
- ]));
1086
- return {
1087
- domain,
1088
- doc: {
1089
- idLower,
1090
- idCollapsed: idLower.replace(/[^a-z0-9]+/g, ""),
1091
- titleLower,
1092
- titleCollapsed: titleLower.replace(/[^a-z0-9]+/g, ""),
1093
- aliasesLower,
1094
- chainTermsLower: [],
1095
- anchorTerms: [],
1096
- repoTerms: [],
1097
- sourceTerms: [],
1098
- summaryLower,
1099
- headingsLower,
1100
- detailTitlesLower: [],
1101
- childHighTermsLower,
1102
- childAnchorTerms,
1103
- childRepoTerms,
1104
- childSourceTerms,
1105
- childBodySourcesLower,
1106
- codeSpans,
1107
- bodySourcesLower: [domainBodyLower],
1108
- detailBodySourcesLower: [],
1109
- tier34GateLower,
1110
- allTextLower,
1111
- reverseCandidatesLower,
1112
- rawSnippetSources,
1113
- designators: {
1114
- id: idDesig,
1115
- title: titleDesig,
1116
- alias: aliasDesig,
1117
- chain: emptySet,
1118
- anchor: childAnchorDesig,
1119
- repo: childRepoDesig,
1120
- source: childSourceDesig,
1121
- summary: summaryDesig,
1122
- heading: headingDesig,
1123
- detail: emptySet,
1124
- scene: sceneDesig,
1125
- code: codeDesig,
1126
- body: childBodyDesig,
1127
- all: allDesig,
1128
- rawByDesignator,
1129
- },
1130
- },
1131
- };
1132
- }
1133
- function getPrecomputedWikiIndex(wiki) {
1134
- const cached = WIKI_INDEX_CACHE.get(wiki);
1135
- if (cached &&
1136
- cached.domainCount === wiki.domains.size &&
1137
- cached.sceneCount === wiki.scenes.size) {
1138
- return cached;
1139
- }
1140
- const sceneById = new Map();
1141
- const scenes = [];
1142
- for (const scene of wiki.scenes.values()) {
1143
- const prep = buildSceneIndexedDoc(scene);
1144
- scenes.push(prep);
1145
- sceneById.set(scene.id, prep);
1146
- }
1147
- const index = {
1148
- domainCount: wiki.domains.size,
1149
- sceneCount: wiki.scenes.size,
1150
- scenes,
1151
- sceneById,
1152
- termDfCache: new Map(),
1153
- designatorDfCache: new Map(),
1154
- };
1155
- WIKI_INDEX_CACHE.set(wiki, index);
1156
- return index;
1157
- }
1158
- function getPrecomputedDomains(wiki, index) {
1159
- if (index.domains) {
1160
- return index.domains;
1161
- }
1162
- const domains = [];
1163
- for (const domain of wiki.domains.values()) {
1164
- domains.push(buildDomainIndexedDoc(domain, index.sceneById));
1165
- }
1166
- index.domains = domains;
1167
- return domains;
1168
- }
1169
- function getSceneTermDf(index, term) {
1170
- const cached = index.termDfCache.get(term);
1171
- if (cached !== undefined) {
1172
- return cached;
1173
- }
1174
- let df = 0;
1175
- for (const entry of index.scenes) {
1176
- if (entry.doc.allTextLower.includes(term)) {
1177
- df += 1;
1178
- }
1179
- }
1180
- index.termDfCache.set(term, df);
1181
- return df;
1182
- }
1183
- function getSceneDesignatorDf(index, designator) {
1184
- const cached = index.designatorDfCache.get(designator);
1185
- if (cached !== undefined) {
1186
- return cached;
1187
- }
1188
- let df = 0;
1189
- for (const entry of index.scenes) {
1190
- if (entry.doc.designators.all.has(designator)) {
1191
- df += 1;
1192
- }
1193
- }
1194
- index.designatorDfCache.set(designator, df);
1195
- return df;
1196
- }
1197
- const IDF_SCALING_MIN_SCENES = 8;
1198
- function computeIdfProfileForGroup(index, group) {
1199
- const totalScenes = index.sceneCount;
1200
- if (totalScenes < IDF_SCALING_MIN_SCENES) {
1201
- return { multiplier: 1, docRatio: 0 };
1202
- }
1203
- let effectiveDf = getSceneTermDf(index, group.primary);
1204
- if (group.designators && group.designators.length > 0) {
1205
- let minDesigDf = Number.POSITIVE_INFINITY;
1206
- for (const d of group.designators) {
1207
- const dDf = getSceneDesignatorDf(index, d);
1208
- if (dDf > 0 && dDf < minDesigDf) {
1209
- minDesigDf = dDf;
1210
- }
1211
- }
1212
- if (Number.isFinite(minDesigDf)) {
1213
- effectiveDf = effectiveDf > 0 ? Math.min(effectiveDf, minDesigDf) : minDesigDf;
1214
- }
1215
- }
1216
- else if (effectiveDf === 0 && group.subTokens && group.subTokens.length >= 2) {
1217
- // Upper-bound co-occurrence DF by the rarest required sub-token
1218
- let minSubDf = Number.POSITIVE_INFINITY;
1219
- for (const st of group.subTokens) {
1220
- const sDf = getSceneTermDf(index, st);
1221
- if (sDf < minSubDf) {
1222
- minSubDf = sDf;
1223
- }
1224
- }
1225
- if (Number.isFinite(minSubDf)) {
1226
- effectiveDf = minSubDf;
1227
- }
1228
- }
1229
- const clampedDf = Math.max(1, effectiveDf);
1230
- const docRatio = clampedDf / totalScenes;
1231
- const normIdf = Math.log((totalScenes + 1) / (clampedDf + 0.5)) / Math.log(totalScenes + 1);
1232
- let mult;
1233
- if (docRatio > 0.4) {
1234
- const t = Math.min(1, (docRatio - 0.4) / 0.6);
1235
- mult = 0.62 - t * 0.27;
1236
- }
1237
- else {
1238
- const scarcity = 1 - docRatio / 0.4;
1239
- mult = 0.62 + 0.58 * scarcity + 1.0 * normIdf ** 1.35;
1240
- }
1241
- if (group.designators && group.designators.length > 0 && docRatio <= 0.25) {
1242
- mult = Math.max(mult, 1.45);
1243
- }
1244
- return {
1245
- multiplier: Math.max(0.35, Math.min(2.2, mult)),
1246
- docRatio,
1247
- };
1248
- }
1249
- const FIELD_DISPLAY_ORDER = [
1250
- "id",
1251
- "title",
1252
- "alias",
1253
- "chain",
1254
- "anchor",
1255
- "repo",
1256
- "source",
1257
- "summary",
1258
- "heading",
1259
- "detail",
1260
- "scene",
1261
- "code",
1262
- "body",
1263
- ];
1264
- const EMPTY_FIELD_SET = new Set();
1265
- function scoreTermAgainstDoc(term, doc) {
1266
- if (!doc.allTextLower.includes(term) &&
1267
- !doc.reverseCandidatesLower.some((rc) => term.length > rc.length && term.includes(rc))) {
1268
- return {
1269
- bestScore: 0,
1270
- fields: EMPTY_FIELD_SET,
1271
- matchedHigherThanBody: false,
1272
- matchedCodeOrDetail: false,
1273
- matchedBodyText: false,
1274
- };
1275
- }
1276
- let best = 0;
1277
- const fields = new Set();
1278
- let matchedHigherThanBody = false;
1279
- let matchedCodeOrDetail = false;
1280
- let matchedBodyText = false;
1281
- function record(score, field, tier) {
1282
- if (score <= 0) {
1283
- return;
1284
- }
1285
- best = Math.max(best, score);
1286
- fields.add(field);
1287
- if (tier === "high") {
1288
- matchedHigherThanBody = true;
1289
- }
1290
- else if (tier === "code") {
1291
- matchedCodeOrDetail = true;
1292
- }
1293
- else {
1294
- matchedBodyText = true;
1295
- }
1296
- }
1297
- // Tier 1: id / shortId, title, aliases
1298
- const idLower = doc.idLower;
1299
- const shortIdLower = doc.shortIdLower;
1300
- if (idLower === term || shortIdLower === term) {
1301
- record(120, "id", "high");
1302
- }
1303
- else if (idLower.startsWith(term) || shortIdLower?.startsWith(term)) {
1304
- record(86, "id", "high");
1305
- }
1306
- else if (idLower.includes(term)) {
1307
- record(66, "id", "high");
1308
- }
1309
- else if (shortIdLower && shortIdLower.length >= 3 && term.includes(shortIdLower)) {
1310
- record(58, "id", "high");
1311
- }
1312
- const titleLower = doc.titleLower;
1313
- if (titleLower === term) {
1314
- record(115, "title", "high");
1315
- }
1316
- else if (titleLower.startsWith(term)) {
1317
- record(84, "title", "high");
1318
- }
1319
- else if (titleLower.includes(term)) {
1320
- record(64, "title", "high");
1321
- }
1322
- else if (titleLower.length >= 2 && term.length >= 2 && term.includes(titleLower)) {
1323
- record(58, "title", "high");
1324
- }
1325
- for (const aliasLower of doc.aliasesLower) {
1326
- if (aliasLower === term) {
1327
- record(110, "alias", "high");
1328
- }
1329
- else if (aliasLower.startsWith(term)) {
1330
- record(80, "alias", "high");
1331
- }
1332
- else if (aliasLower.includes(term)) {
1333
- record(60, "alias", "high");
1334
- }
1335
- else if (aliasLower.length >= 2 && term.length >= 2 && term.includes(aliasLower)) {
1336
- record(56, "alias", "high");
1337
- }
1338
- }
1339
- // Tier 2: chainNames, anchors, repositories, sources
1340
- for (const cLower of doc.chainTermsLower) {
1341
- if (cLower === term) {
1342
- record(95, "chain", "high");
1343
- }
1344
- else if (cLower.startsWith(term)) {
1345
- record(72, "chain", "high");
1346
- }
1347
- else if (cLower.includes(term)) {
1348
- record(52, "chain", "high");
1349
- }
1350
- else if (cLower.length >= 3 && term.length >= 3 && term.includes(cLower)) {
1351
- record(46, "chain", "high");
1352
- }
1353
- }
1354
- for (const anchorTerm of doc.anchorTerms) {
1355
- const aLower = anchorTerm.lower;
1356
- const baseName = anchorTerm.base;
1357
- if (aLower === term || baseName === term) {
1358
- record(92, "anchor", "high");
1359
- }
1360
- else if (baseName.startsWith(term) || aLower.startsWith(term)) {
1361
- record(68, "anchor", "high");
1362
- }
1363
- else if (aLower.includes(term)) {
1364
- record(50, "anchor", "high");
1365
- }
1366
- else if (baseName.length >= 3 && term.includes(baseName)) {
1367
- record(44, "anchor", "high");
1368
- }
1369
- }
1370
- for (const repoTerm of doc.repoTerms) {
1371
- const rLower = repoTerm.lower;
1372
- const repoBase = repoTerm.base;
1373
- if (rLower === term || repoBase === term) {
1374
- record(82, "repo", "high");
1375
- }
1376
- else if (rLower.includes(term)) {
1377
- record(44, "repo", "high");
1378
- }
1379
- else if (repoBase.length >= 3 && term.includes(repoBase)) {
1380
- record(38, "repo", "high");
1381
- }
1382
- }
1383
- for (const srcTerm of doc.sourceTerms) {
1384
- const sLower = srcTerm.lower;
1385
- const srcBase = srcTerm.base;
1386
- if (sLower === term || srcBase === term) {
1387
- record(82, "source", "high");
1388
- }
1389
- else if (sLower.includes(term)) {
1390
- record(44, "source", "high");
1391
- }
1392
- else if (srcBase.length >= 3 && term.includes(srcBase)) {
1393
- record(38, "source", "high");
1394
- }
1395
- }
1396
- // Domain child high-tier terms (include reverse substring check)
1397
- for (const chLower of doc.childHighTermsLower) {
1398
- if (chLower === term) {
1399
- record(72, "scene", "high");
1400
- }
1401
- else if (chLower.startsWith(term)) {
1402
- record(52, "scene", "high");
1403
- }
1404
- else if (chLower.includes(term)) {
1405
- record(40, "scene", "high");
1406
- }
1407
- else if (chLower.length >= 2 && term.length >= 2 && term.includes(chLower)) {
1408
- record(38, "scene", "high");
1409
- }
1410
- }
1411
- for (const chAnchor of doc.childAnchorTerms) {
1412
- if (chAnchor.lower === term || chAnchor.base === term) {
1413
- record(64, "anchor", "high");
1414
- }
1415
- else if (chAnchor.lower.includes(term)) {
1416
- record(38, "anchor", "high");
1417
- }
1418
- }
1419
- for (const chRepo of doc.childRepoTerms) {
1420
- if (chRepo.lower === term || chRepo.base === term) {
1421
- record(58, "repo", "high");
1422
- }
1423
- else if (chRepo.lower.includes(term)) {
1424
- record(34, "repo", "high");
1425
- }
1426
- }
1427
- for (const chSrc of doc.childSourceTerms) {
1428
- if (chSrc.lower === term || chSrc.base === term) {
1429
- record(58, "source", "high");
1430
- }
1431
- else if (chSrc.lower.includes(term)) {
1432
- record(34, "source", "high");
1433
- }
1434
- }
1435
- // Tier 3 & Tier 4: gated by single O(1) pre-concatenated lowercase check
1436
- if (doc.tier34GateLower.includes(term)) {
1437
- const summaryLower = doc.summaryLower;
1438
- if (summaryLower === term) {
1439
- record(60, "summary", "high");
1440
- }
1441
- else if (summaryLower.includes(term)) {
1442
- record(36, "summary", "high");
1443
- }
1444
- for (const hLower of doc.headingsLower) {
1445
- if (hLower === term) {
1446
- record(56, "heading", "high");
1447
- }
1448
- else if (hLower.includes(term)) {
1449
- record(34, "heading", "high");
1450
- }
1451
- }
1452
- for (const dLower of doc.detailTitlesLower) {
1453
- if (dLower === term) {
1454
- record(62, "detail", "high");
1455
- }
1456
- else if (dLower.includes(term)) {
1457
- record(38, "detail", "high");
1458
- }
1459
- }
1460
- if (term.length >= 2) {
1461
- for (const span of doc.codeSpans) {
1462
- if (span.lower === term || span.parts.includes(term)) {
1463
- record(28, "code", "code");
1464
- }
1465
- else if (span.lower.includes(term)) {
1466
- record(22, "code", "code");
1467
- }
1468
- }
1469
- for (const bodyLower of doc.bodySourcesLower) {
1470
- if (bodyLower.includes(term)) {
1471
- record(16, "body", "body");
1472
- break;
1473
- }
1474
- }
1475
- for (const dBodyLower of doc.detailBodySourcesLower) {
1476
- if (dBodyLower.includes(term)) {
1477
- record(14, "detail", "code");
1478
- break;
1479
- }
1480
- }
1481
- for (const cBodyLower of doc.childBodySourcesLower) {
1482
- if (cBodyLower.includes(term)) {
1483
- record(12, "body", "body");
1484
- break;
1485
- }
1486
- }
1487
- }
1488
- }
1489
- return {
1490
- bestScore: best,
1491
- fields,
1492
- matchedHigherThanBody,
1493
- matchedCodeOrDetail,
1494
- matchedBodyText,
1495
- };
1496
- }
1497
- function scoreDesignatorsAgainstDoc(designators, doc) {
1498
- let best = 0;
1499
- const fields = new Set();
1500
- let matchedHigherThanBody = false;
1501
- let matchedCodeOrDetail = false;
1502
- let matchedBodyText = false;
1503
- let matchedSnippetTerm;
1504
- function record(score, field, tier, d) {
1505
- best = Math.max(best, score);
1506
- fields.add(field);
1507
- if (tier === "high") {
1508
- matchedHigherThanBody = true;
1509
- }
1510
- else if (tier === "code") {
1511
- matchedCodeOrDetail = true;
1512
- matchedSnippetTerm ??= doc.designators.rawByDesignator.get(d);
1513
- }
1514
- else {
1515
- matchedBodyText = true;
1516
- matchedSnippetTerm ??= doc.designators.rawByDesignator.get(d);
1517
- }
1518
- }
1519
- for (let idx = 0; idx < designators.length; idx++) {
1520
- const d = designators[idx];
1521
- if (!doc.designators.all.has(d)) {
1522
- continue;
1523
- }
1524
- // Slight discount only when matching a stripped sub-designator (e.g. `r44972` from `CRS-R44972`)
1525
- const weight = idx === 0 ? 1 : 0.92;
1526
- const tiers = doc.designators;
1527
- if (tiers.id.has(d)) {
1528
- const idExact = doc.idCollapsed === d || doc.shortIdCollapsed === d;
1529
- record(Math.round((idExact ? 115 : 66) * weight), "id", "high", d);
1530
- }
1531
- if (tiers.title.has(d)) {
1532
- const titleExact = doc.titleCollapsed === d;
1533
- record(Math.round((titleExact ? 112 : 78) * weight), "title", "high", d);
1534
- }
1535
- if (tiers.alias.has(d)) {
1536
- record(Math.round(108 * weight), "alias", "high", d);
1537
- }
1538
- if (tiers.chain.has(d)) {
1539
- record(Math.round(94 * weight), "chain", "high", d);
1540
- }
1541
- if (tiers.anchor.has(d)) {
1542
- record(Math.round(92 * weight), "anchor", "high", d);
1543
- }
1544
- if (tiers.repo.has(d)) {
1545
- record(Math.round(80 * weight), "repo", "high", d);
1546
- }
1547
- if (tiers.source.has(d)) {
1548
- record(Math.round(80 * weight), "source", "high", d);
1549
- }
1550
- if (tiers.scene.has(d)) {
1551
- record(Math.round(70 * weight), "scene", "high", d);
1552
- }
1553
- if (tiers.detail.has(d)) {
1554
- record(Math.round(60 * weight), "detail", "high", d);
1555
- }
1556
- if (tiers.summary.has(d)) {
1557
- record(Math.round(56 * weight), "summary", "high", d);
1558
- }
1559
- if (tiers.heading.has(d)) {
1560
- record(Math.round(52 * weight), "heading", "high", d);
1561
- }
1562
- if (tiers.code.has(d)) {
1563
- record(Math.round(48 * weight), "code", "code", d);
1564
- }
1565
- if (tiers.body.has(d)) {
1566
- // Formal model/report designators in body tables/prose carry much stronger identity signal than casual words
1567
- record(Math.round(46 * weight), "body", "body", d);
1568
- }
1569
- }
1570
- return {
1571
- hit: {
1572
- bestScore: best,
1573
- fields,
1574
- matchedHigherThanBody,
1575
- matchedCodeOrDetail,
1576
- matchedBodyText,
1577
- },
1578
- ...(matchedSnippetTerm ? { matchedSnippetTerm } : {}),
1579
- };
1580
- }
1581
- function mergeTermHits(a, b) {
1582
- if (b.bestScore === 0) {
1583
- return a;
1584
- }
1585
- if (a.bestScore === 0) {
1586
- return b;
1587
- }
1588
- const mergedFields = new Set([...a.fields, ...b.fields]);
1589
- return {
1590
- bestScore: Math.max(a.bestScore, b.bestScore),
1591
- fields: mergedFields,
1592
- matchedHigherThanBody: a.matchedHigherThanBody || b.matchedHigherThanBody,
1593
- matchedCodeOrDetail: a.matchedCodeOrDetail || b.matchedCodeOrDetail,
1594
- matchedBodyText: a.matchedBodyText || b.matchedBodyText,
1595
- };
1596
- }
1597
- function pinpointSubSceneMatches(doc, pinpointTerms, pinpointDesignators) {
1598
- const matchedChains = [];
1599
- const matchedDetails = [];
1600
- const matchedAnchors = [];
1601
- if (pinpointTerms.length === 0 && pinpointDesignators.size === 0) {
1602
- return { matchedChains, matchedDetails, matchedAnchors };
1603
- }
1604
- const usableTerms = pinpointTerms.filter((t) => t.length >= 2);
1605
- for (const chain of doc.chainEntries ?? []) {
1606
- let hit = false;
1607
- for (const d of pinpointDesignators) {
1608
- if (chain.designators.has(d)) {
1609
- hit = true;
1610
- break;
1611
- }
1612
- }
1613
- if (!hit) {
1614
- for (const term of usableTerms) {
1615
- if (chain.termsLower.some((ct) => ct.includes(term) || (ct.length >= 3 && term.includes(ct))) ||
1616
- chain.bodyLower.includes(term)) {
1617
- hit = true;
1618
- break;
1619
- }
1620
- }
1621
- }
1622
- if (hit) {
1623
- matchedChains.push(chain.title);
1624
- }
1625
- }
1626
- for (const detail of doc.detailEntries ?? []) {
1627
- let hit = false;
1628
- for (const d of pinpointDesignators) {
1629
- if (detail.designators.has(d)) {
1630
- hit = true;
1631
- break;
1632
- }
1633
- }
1634
- if (!hit) {
1635
- for (const term of usableTerms) {
1636
- if (detail.nameLower.includes(term) ||
1637
- detail.titleLower.includes(term) ||
1638
- detail.contentLower.includes(term)) {
1639
- hit = true;
1640
- break;
1641
- }
1642
- }
1643
- }
1644
- if (hit) {
1645
- matchedDetails.push(detail.name);
1646
- }
1647
- }
1648
- for (const ae of doc.anchorEntries ?? []) {
1649
- let hit = false;
1650
- for (const d of pinpointDesignators) {
1651
- if (ae.designators.has(d)) {
1652
- hit = true;
1653
- break;
1654
- }
1655
- }
1656
- if (!hit) {
1657
- for (const term of usableTerms) {
1658
- if (ae.terms.some((at) => at.lower.includes(term) ||
1659
- at.base === term ||
1660
- (at.base.length >= 3 && term.includes(at.base)))) {
1661
- hit = true;
1662
- break;
1663
- }
1664
- }
1665
- }
1666
- if (hit) {
1667
- matchedAnchors.push(ae.summary);
1668
- }
1669
- }
1670
- return { matchedChains, matchedDetails, matchedAnchors };
1671
- }
1672
- function buildPreparedQueryPlan(query, index) {
1673
- const tokenized = tokenizeDiscoveryQuery(query);
1674
- const useCorpusIdf = index.sceneCount >= IDF_SCALING_MIN_SCENES;
1675
- const groupIdf = tokenized.groups.map((g) => computeIdfProfileForGroup(index, g));
1676
- let phraseIdfMultiplier = 1;
1677
- const selectiveBigrams = [];
1678
- if (useCorpusIdf && tokenized.normalizedPhrase) {
1679
- const phraseDf = Math.max(1, getSceneTermDf(index, tokenized.normalizedPhrase));
1680
- const phraseRatio = phraseDf / index.sceneCount;
1681
- if (phraseRatio > 0.4) {
1682
- phraseIdfMultiplier = Math.max(0.35, 0.62 - ((phraseRatio - 0.4) / 0.6) * 0.27);
1683
- }
1684
- else if (tokenized.groups.length === 1 && groupIdf[0]) {
1685
- phraseIdfMultiplier = groupIdf[0].multiplier;
1686
- }
1687
- else {
1688
- const avgMult = groupIdf.reduce((acc, g) => acc + g.multiplier, 0) / Math.max(1, groupIdf.length);
1689
- phraseIdfMultiplier = Math.max(0.6, Math.min(2.2, avgMult));
1690
- }
1691
- // Extract selective adjacent non-designator 2-word concept phrases (e.g. "program performance", "bar charts")
1692
- const seenPhrases = new Set();
1693
- for (let i = 0; i < tokenized.groups.length - 1; i++) {
1694
- const g1 = tokenized.groups[i];
1695
- const g2 = tokenized.groups[i + 1];
1696
- if (g1.designators?.length || g2.designators?.length) {
1697
- continue;
1698
- }
1699
- const w1 = g1.primary;
1700
- const w2 = g2.primary;
1701
- if (w1.length < 2 || w2.length < 2 || isPureCjk(w1) || isPureCjk(w2)) {
1702
- continue;
1703
- }
1704
- const phrase = `${w1} ${w2}`;
1705
- if (seenPhrases.has(phrase)) {
1706
- continue;
1707
- }
1708
- seenPhrases.add(phrase);
1709
- const biDf = getSceneTermDf(index, phrase);
1710
- if (biDf > 0 && biDf / index.sceneCount <= 0.25) {
1711
- const biScarcity = 1 - biDf / (index.sceneCount * 0.3);
1712
- const bodyBoost = Math.max(32, Math.round(78 * biScarcity));
1713
- selectiveBigrams.push({
1714
- phrase,
1715
- bodyBoost,
1716
- highBoost: bodyBoost + 26,
1717
- });
1718
- }
1719
- }
1720
- }
1721
- return {
1722
- tokenized,
1723
- groupIdf,
1724
- phraseIdfMultiplier,
1725
- useCorpusIdf,
1726
- selectiveBigrams,
1727
- };
1728
- }
1729
- function evaluatePreparedQuery(plan, doc, includePinpoint) {
1730
- const { tokenized, groupIdf, phraseIdfMultiplier, useCorpusIdf } = plan;
1731
- if (!tokenized.normalizedPhrase) {
1732
- return { score: 1, matchedFields: [] };
1733
- }
1734
- const allMatchedFields = new Set();
1735
- const bodySnippetTerms = [];
1736
- const specificPinpointTerms = [];
1737
- const fallbackPinpointTerms = [];
1738
- const specificPinpointDesignators = new Set();
1739
- const fallbackPinpointDesignators = new Set();
1740
- const rawPhraseHit = scoreTermAgainstDoc(tokenized.normalizedPhrase, doc);
1741
- const weightedPhraseScore = rawPhraseHit.bestScore > 0
1742
- ? Math.max(1, Math.round(rawPhraseHit.bestScore * phraseIdfMultiplier))
1743
- : 0;
1744
- if (rawPhraseHit.bestScore > 0) {
1745
- for (const f of rawPhraseHit.fields) {
1746
- allMatchedFields.add(f);
1747
- }
1748
- if (rawPhraseHit.matchedBodyText || rawPhraseHit.matchedCodeOrDetail) {
1749
- bodySnippetTerms.push(tokenized.normalizedPhrase);
1750
- }
1751
- }
1752
- const groupScores = [];
1753
- let matchedGroupCount = 0;
1754
- let specificMatchedGroupCount = 0;
1755
- for (let gIdx = 0; gIdx < tokenized.groups.length; gIdx++) {
1756
- const group = tokenized.groups[gIdx];
1757
- const idfProfile = groupIdf[gIdx] ?? { multiplier: 1, docRatio: 0 };
1758
- const isSpecificGroup = !useCorpusIdf || idfProfile.docRatio <= 0.35;
1759
- let primaryHit;
1760
- let effectivePrimaryTerm = group.primary;
1761
- if (group.isStrippedStem && group.rawToken) {
1762
- const rawHit = scoreTermAgainstDoc(group.rawToken, doc);
1763
- const stemHit = scoreTermAgainstDoc(group.primary, doc);
1764
- const discountedStemScore = stemHit.bestScore > 0 ? Math.max(1, Math.round(stemHit.bestScore * 0.45)) : 0;
1765
- if (rawHit.bestScore >= discountedStemScore && rawHit.bestScore > 0) {
1766
- primaryHit = rawHit;
1767
- effectivePrimaryTerm = group.rawToken;
1768
- }
1769
- else {
1770
- primaryHit = {
1771
- ...stemHit,
1772
- bestScore: discountedStemScore,
1773
- };
1774
- }
1775
- }
1776
- else {
1777
- primaryHit = scoreTermAgainstDoc(group.primary, doc);
1778
- }
1779
- // Match canonical designator variants ("FFG-62" <-> "FFG 62" <-> "FFG62", "CRS-R44972" <-> "R44972") at full tier strength
1780
- if (group.designators && group.designators.length > 0) {
1781
- const desigEval = scoreDesignatorsAgainstDoc(group.designators, doc);
1782
- if (desigEval.hit.bestScore > 0) {
1783
- primaryHit = mergeTermHits(primaryHit, desigEval.hit);
1784
- if (desigEval.matchedSnippetTerm) {
1785
- effectivePrimaryTerm = desigEval.matchedSnippetTerm;
1786
- }
1787
- }
1788
- }
1789
- // Also normalize single-letter hyphenated acronyms ("M-SHORAD" <-> "M SHORAD")
1790
- if (primaryHit.bestScore === 0 && /^[a-z]-[a-z]{4,}$/.test(group.primary)) {
1791
- const spacedAcronym = group.primary.replace(/-/g, " ");
1792
- const spacedHit = scoreTermAgainstDoc(spacedAcronym, doc);
1793
- if (spacedHit.bestScore > 0) {
1794
- primaryHit = spacedHit;
1795
- effectivePrimaryTerm = spacedAcronym;
1796
- }
1797
- }
1798
- let bestTriScore = 0;
1799
- let secondTriScore = 0;
1800
- const triFields = new Set();
1801
- const triBodyTerms = [];
1802
- for (const tri of group.threeGrams) {
1803
- const h = scoreTermAgainstDoc(tri, doc);
1804
- if (h.bestScore > 0) {
1805
- for (const f of h.fields) {
1806
- triFields.add(f);
1807
- }
1808
- if (h.matchedBodyText || h.matchedCodeOrDetail) {
1809
- triBodyTerms.push(tri);
1810
- }
1811
- if (h.bestScore >= bestTriScore) {
1812
- secondTriScore = bestTriScore;
1813
- bestTriScore = h.bestScore;
1814
- }
1815
- else if (h.bestScore > secondTriScore) {
1816
- secondTriScore = h.bestScore;
1817
- }
1818
- }
1819
- }
1820
- const stemDiscount = group.isStrippedStem ? 0.45 : 1;
1821
- const weightedTri = Math.round((bestTriScore * 0.6 + secondTriScore * 0.2) * stemDiscount);
1822
- const biHits = [];
1823
- for (const bi of group.twoGrams) {
1824
- const h = scoreTermAgainstDoc(bi, doc);
1825
- if (h.bestScore > 0) {
1826
- biHits.push({ term: bi, hit: h });
1827
- }
1828
- }
1829
- // Precision guard on body-only 2-gram hits: require >= 2 distinct 2-grams if ONLY matching body prose
1830
- const usableBiHits = biHits.filter((item) => item.hit.matchedHigherThanBody ||
1831
- item.hit.matchedCodeOrDetail ||
1832
- primaryHit.bestScore > 0 ||
1833
- bestTriScore > 0 ||
1834
- biHits.length >= 2);
1835
- const hasSpecificHeadBigram = group.twoGrams.some((bi) => !GENERIC_CJK_SUFFIX_BIGRAMS.has(bi));
1836
- const matchedOnlyGenericSuffix = hasSpecificHeadBigram &&
1837
- usableBiHits.length > 0 &&
1838
- usableBiHits.every((item) => GENERIC_CJK_SUFFIX_BIGRAMS.has(item.term));
1839
- usableBiHits.sort((a, b) => b.hit.bestScore - a.hit.bestScore);
1840
- let weightedBi = 0;
1841
- if (usableBiHits.length > 0 && !matchedOnlyGenericSuffix) {
1842
- const topBiSum = usableBiHits.slice(0, 3).reduce((acc, cur) => acc + cur.hit.bestScore, 0);
1843
- const coBiBonus = usableBiHits.length >= 2 ? (usableBiHits.length - 1) * 12 : 0;
1844
- const rawBi = Math.round((topBiSum * 0.38 + coBiBonus) * stemDiscount);
1845
- if (usableBiHits.length === 1) {
1846
- weightedBi = Math.min(rawBi, 28);
1847
- }
1848
- else {
1849
- weightedBi = rawBi;
1850
- }
1851
- }
1852
- // Per-group identifier sub-token co-occurrence fallback whenever primaryHit.bestScore === 0
1853
- const subTokHits = [];
1854
- if (primaryHit.bestScore === 0 && group.subTokens && group.subTokens.length >= 2) {
1855
- for (const st of group.subTokens) {
1856
- const h = scoreTermAgainstDoc(st, doc);
1857
- if (h.bestScore > 0) {
1858
- // Do not treat a parent domainId prefix match as an 86-pt sceneId prefix during subToken decomposition
1859
- const onlyDomainPrefixId = Boolean(doc.shortIdLower) &&
1860
- !st.includes("/") &&
1861
- !doc.shortIdLower.includes(st) &&
1862
- h.fields.size === 1 &&
1863
- h.fields.has("id");
1864
- const adjustedHit = onlyDomainPrefixId
1865
- ? { ...h, bestScore: Math.min(h.bestScore, 42) }
1866
- : h;
1867
- subTokHits.push({ term: st, hit: adjustedHit });
1868
- }
1869
- }
1870
- }
1871
- let weightedSubTok = 0;
1872
- if (subTokHits.length >= 2) {
1873
- subTokHits.sort((a, b) => b.hit.bestScore - a.hit.bestScore);
1874
- const leadSub = subTokHits[0]?.hit.bestScore ?? 0;
1875
- const restSubSum = subTokHits.slice(1, 3).reduce((acc, cur) => acc + cur.hit.bestScore, 0);
1876
- const allPartsMatched = Boolean(group.subTokens && subTokHits.length === group.subTokens.length);
1877
- const coSubBonus = (subTokHits.length - 1) * 14 + (allPartsMatched ? 6 : 0);
1878
- // Cap below verbatim anchor/chain/alias/title/id matches (>= 92) while beating single noisy words
1879
- weightedSubTok = Math.min(88, Math.round(leadSub * 0.62 + restSubSum * 0.45) + coSubBonus);
1880
- }
1881
- const subGramScore = Math.max(weightedTri, weightedBi, weightedSubTok);
1882
- let rawGroupScore = 0;
1883
- const matchedTermsForGroup = [];
1884
- if (primaryHit.bestScore > 0) {
1885
- rawGroupScore = primaryHit.bestScore + (subGramScore > primaryHit.bestScore ? 8 : 0);
1886
- for (const f of primaryHit.fields) {
1887
- allMatchedFields.add(f);
1888
- }
1889
- matchedTermsForGroup.push(effectivePrimaryTerm);
1890
- if (primaryHit.matchedBodyText || primaryHit.matchedCodeOrDetail) {
1891
- bodySnippetTerms.push(effectivePrimaryTerm);
1892
- }
1893
- }
1894
- else if (subGramScore > 0) {
1895
- rawGroupScore = subGramScore;
1896
- if (weightedTri >= weightedBi && weightedTri >= weightedSubTok) {
1897
- for (const f of triFields) {
1898
- allMatchedFields.add(f);
1899
- }
1900
- matchedTermsForGroup.push(...triBodyTerms, ...group.threeGrams);
1901
- bodySnippetTerms.push(...triBodyTerms);
1902
- }
1903
- else if (weightedSubTok > weightedBi) {
1904
- for (const st of subTokHits) {
1905
- for (const f of st.hit.fields) {
1906
- allMatchedFields.add(f);
1907
- }
1908
- matchedTermsForGroup.push(st.term);
1909
- if (st.hit.matchedBodyText || st.hit.matchedCodeOrDetail) {
1910
- bodySnippetTerms.push(st.term);
1911
- }
1912
- }
1913
- }
1914
- else {
1915
- for (const b of usableBiHits) {
1916
- for (const f of b.hit.fields) {
1917
- allMatchedFields.add(f);
1918
- }
1919
- matchedTermsForGroup.push(b.term);
1920
- if (b.hit.matchedBodyText || b.hit.matchedCodeOrDetail) {
1921
- bodySnippetTerms.push(b.term);
1922
- }
1923
- }
1924
- }
1925
- }
1926
- if (rawGroupScore > 0) {
1927
- matchedGroupCount += 1;
1928
- if (isSpecificGroup) {
1929
- specificMatchedGroupCount += 1;
1930
- specificPinpointTerms.push(...matchedTermsForGroup);
1931
- for (const d of group.designators ?? []) {
1932
- specificPinpointDesignators.add(d);
1933
- }
1934
- }
1935
- else {
1936
- fallbackPinpointTerms.push(...matchedTermsForGroup);
1937
- for (const d of group.designators ?? []) {
1938
- fallbackPinpointDesignators.add(d);
1939
- }
1940
- }
1941
- const scaledScore = Math.max(1, Math.round(rawGroupScore * idfProfile.multiplier));
1942
- groupScores.push(scaledScore);
1943
- }
1944
- }
1945
- if (matchedGroupCount === 0 && weightedPhraseScore === 0) {
1946
- return { score: 0, matchedFields: [] };
1947
- }
1948
- groupScores.sort((a, b) => b - a);
1949
- const topGroupSum = groupScores.slice(0, 4).reduce((sum, s) => sum + s, 0);
1950
- // On >= 8 scene wikis, only specific (non-ubiquitous) matched groups earn full +25 coordination bonus
1951
- let multiTokenBonus = 0;
1952
- if (!useCorpusIdf) {
1953
- multiTokenBonus =
1954
- matchedGroupCount >= 2
1955
- ? (matchedGroupCount - 1) * 25 + (matchedGroupCount === tokenized.groups.length ? 15 : 0)
1956
- : 0;
1957
- }
1958
- else {
1959
- const specificBonus = specificMatchedGroupCount >= 2 ? (specificMatchedGroupCount - 1) * 25 : 0;
1960
- const crossSupportBonus = specificMatchedGroupCount >= 1 && matchedGroupCount > specificMatchedGroupCount
1961
- ? Math.min(18, (matchedGroupCount - specificMatchedGroupCount) * 6)
1962
- : 0;
1963
- const fullMatchBonus = specificMatchedGroupCount >= 1 && matchedGroupCount === tokenized.groups.length ? 12 : 0;
1964
- multiTokenBonus = specificBonus + crossSupportBonus + fullMatchBonus;
1965
- }
1966
- let selectivePhraseBonus = 0;
1967
- for (const sb of plan.selectiveBigrams) {
1968
- if (!doc.allTextLower.includes(sb.phrase)) {
1969
- continue;
1970
- }
1971
- const inHighField = doc.titleLower.includes(sb.phrase) ||
1972
- doc.summaryLower.includes(sb.phrase) ||
1973
- doc.headingsLower.some((h) => h.includes(sb.phrase)) ||
1974
- doc.chainTermsLower.some((c) => c.includes(sb.phrase));
1975
- selectivePhraseBonus += inHighField ? sb.highBoost : sb.bodyBoost;
1976
- bodySnippetTerms.push(sb.phrase);
1977
- }
1978
- const combinedScore = Math.max(weightedPhraseScore, topGroupSum +
1979
- multiTokenBonus +
1980
- selectivePhraseBonus +
1981
- (tokenized.groups.length > 1 ? Math.round(weightedPhraseScore * 0.35) : 0));
1982
- const orderedFields = FIELD_DISPLAY_ORDER.filter((f) => allMatchedFields.has(f));
1983
- let activeTerms;
1984
- let activeDesigs;
1985
- if (includePinpoint) {
1986
- activeTerms =
1987
- specificPinpointTerms.length > 0 || specificPinpointDesignators.size > 0
1988
- ? specificPinpointTerms
1989
- : fallbackPinpointTerms;
1990
- activeDesigs =
1991
- specificPinpointTerms.length > 0 || specificPinpointDesignators.size > 0
1992
- ? specificPinpointDesignators
1993
- : fallbackPinpointDesignators;
1994
- }
1995
- return {
1996
- score: combinedScore,
1997
- matchedFields: orderedFields,
1998
- ...(bodySnippetTerms.length > 0 ? { bodySnippetTerms } : {}),
1999
- ...(activeTerms && activeTerms.length > 0 ? { pinpointTerms: activeTerms } : {}),
2000
- ...(activeDesigs && activeDesigs.size > 0 ? { pinpointDesignators: activeDesigs } : {}),
2001
- };
2002
- }
1
+ import { escapeRegExp } from "./utils/regexp.js";
2
+ import { getPrecomputedDomains, getPrecomputedWikiIndex, } from "./discover/index-builder.js";
3
+ import { termRows } from "./discover/postings.js";
4
+ import { expandMultiEntitySingleQuery } from "./discover/query-expansion.js";
5
+ import { filterWeakBodyOnlyHits, rankSceneCandidates } from "./discover/scene-ranking.js";
6
+ import { buildPreparedQueryPlan, evaluatePreparedQuery, } from "./discover/scoring.js";
7
+ import { extractMatchSnippet, pinpointSubSceneMatches } from "./discover/subscene.js";
8
+ import { FIELD_DISPLAY_ORDER } from "./discover/term-scoring.js";
9
+ export { extractDesignatorMentions, extractDesignatorTokens, normalizeDesignatorToken, sourceYearMentions, } from "./discover/designators.js";
10
+ export { inspectSceneCoverageData } from "./discover/index-builder.js";
11
+ export { formatAnchorSummaryLabel, toMatchedAnchorSummary } from "./discover/scene-document.js";
12
+ export { tokenizeDiscoveryQuery, } from "./discover/tokenizer.js";
2003
13
  function collectActiveQueries(query, queries) {
2004
14
  const active = [];
2005
15
  if (query?.trim()) {
@@ -2013,28 +23,6 @@ function collectActiveQueries(query, queries) {
2013
23
  }
2014
24
  return active;
2015
25
  }
2016
- function filterWeakBodyOnlyHits(items) {
2017
- if (items.length <= 1) {
2018
- return items;
2019
- }
2020
- let topStructuredScore = 0;
2021
- for (const item of items) {
2022
- const hasStructuredField = item.matchedFields?.some((f) => f !== "body") ?? false;
2023
- if (hasStructuredField && (item.score ?? 0) > topStructuredScore) {
2024
- topStructuredScore = item.score ?? 0;
2025
- }
2026
- }
2027
- if (topStructuredScore < 65) {
2028
- return items;
2029
- }
2030
- const minBodyOnlyScore = Math.max(25, Math.round(topStructuredScore * 0.25));
2031
- return items.filter((item) => {
2032
- const isBodyOnly = item.matchedFields !== undefined &&
2033
- item.matchedFields.length === 1 &&
2034
- item.matchedFields[0] === "body";
2035
- return !isBodyOnly || (item.score ?? 0) >= minBodyOnlyScore;
2036
- });
2037
- }
2038
26
  function applyLimit(items, limit) {
2039
27
  if (limit === undefined) {
2040
28
  return items;
@@ -2176,105 +164,38 @@ export function discoverDomains(wiki, options = {}) {
2176
164
  };
2177
165
  });
2178
166
  }
2179
- const COMPARISON_GLUE_WORDS = new Set([
2180
- "compare",
2181
- "comparing",
2182
- "comparison",
2183
- "between",
2184
- "versus",
2185
- "vs",
2186
- "and",
2187
- "or",
2188
- "for",
2189
- "with",
2190
- "from",
2191
- "into",
2192
- "the",
2193
- "of",
2194
- "in",
2195
- "on",
2196
- "to",
2197
- "by",
2198
- ]);
2199
- function expandMultiEntitySingleQuery(rawQuery, index, candidateScenes) {
2200
- if (index.sceneCount < IDF_SCALING_MIN_SCENES) {
2201
- return [rawQuery];
2202
- }
2203
- const plan = buildPreparedQueryPlan(rawQuery, index);
2204
- const { tokenized, groupIdf } = plan;
2205
- if (tokenized.groups.length < 2) {
2206
- return [rawQuery];
2207
- }
2208
- const entityClusters = [];
2209
- const entityGroupIndices = new Set();
2210
- for (let i = 0; i < tokenized.groups.length; i++) {
2211
- if (entityGroupIndices.has(i)) {
2212
- continue;
167
+ /** Weight only the terms that actually occur inside the active search scope. */
168
+ function realizedSpecificity(plan, index, scope) {
169
+ const size = scope?.size ?? index.sceneCount;
170
+ let rarest = 1;
171
+ let found = 0;
172
+ for (const [i, group] of plan.tokenized.groups.entries()) {
173
+ const literal = termRows(index, group.primary);
174
+ const canonical = plan.designatorMatches[i];
175
+ const rows = canonical ? new Set([...canonical.keys(), ...literal]) : literal;
176
+ let hits = 0;
177
+ let canonicalHit = false;
178
+ for (const row of rows) {
179
+ if (scope && !scope.has(row))
180
+ continue;
181
+ hits++;
182
+ if (canonical?.has(row))
183
+ canonicalHit = true;
2213
184
  }
2214
- const g = tokenized.groups[i];
2215
- const idf = groupIdf[i];
2216
- const isModelOrDesignator = Boolean(g.designators && g.designators.length > 0) ||
2217
- /^[a-z]{1,6}-[a-z0-9]{2,}(?:-[a-z0-9]+)*$/.test(g.primary);
2218
- if (!isModelOrDesignator || idf.docRatio > 0.08) {
2219
- continue;
185
+ if (canonical && !canonicalHit) {
186
+ const exact = new RegExp(`(?<![a-z0-9])${escapeRegExp(group.primary)}(?![a-z0-9])`);
187
+ if (!literal.some((row) => (!scope || scope.has(row)) && exact.test(index.scenes[row].text)))
188
+ return 0.15;
2220
189
  }
2221
- const hasCorpusPresence = getSceneTermDf(index, g.primary) > 0 ||
2222
- (g.designators?.some((d) => getSceneDesignatorDf(index, d) > 0) ?? false);
2223
- if (!hasCorpusPresence) {
2224
- continue;
190
+ if (hits) {
191
+ found++;
192
+ rarest = Math.min(rarest, hits / size);
2225
193
  }
2226
- // Coalesce an immediately following rare model-variant token (e.g. "b-52" + "rmp" -> "b-52 rmp")
2227
- const nextGroup = tokenized.groups[i + 1];
2228
- const nextIdf = groupIdf[i + 1];
2229
- if (nextGroup &&
2230
- nextIdf &&
2231
- !nextGroup.designators?.length &&
2232
- /^[a-z0-9]{2,6}$/.test(nextGroup.primary) &&
2233
- nextIdf.docRatio <= 0.08 &&
2234
- getSceneTermDf(index, `${g.primary} ${nextGroup.primary}`) > 0) {
2235
- entityGroupIndices.add(i);
2236
- entityGroupIndices.add(i + 1);
2237
- entityClusters.push({
2238
- text: `${g.primary} ${nextGroup.primary}`,
2239
- groupIndices: [i, i + 1],
2240
- designators: g.designators ?? [],
2241
- primaryLower: `${g.primary} ${nextGroup.primary}`,
2242
- });
2243
- i += 1;
2244
- continue;
2245
- }
2246
- entityGroupIndices.add(i);
2247
- entityClusters.push({
2248
- text: g.primary,
2249
- groupIndices: [i],
2250
- designators: g.designators ?? [],
2251
- primaryLower: g.primary,
2252
- });
2253
- }
2254
- if (entityClusters.length < 2) {
2255
- return [rawQuery];
2256
194
  }
2257
- // Only decompose into per-entity RRF sub-queries when NO single scene contains all entities together
2258
- const singleSceneCoversAll = candidateScenes.some(({ doc }) => entityClusters.every((ent) => doc.allTextLower.includes(ent.primaryLower) ||
2259
- ent.designators.some((d) => doc.designators.all.has(d))));
2260
- if (singleSceneCoversAll) {
2261
- return [rawQuery];
2262
- }
2263
- const sharedContextTokens = [];
2264
- for (let i = 0; i < tokenized.groups.length; i++) {
2265
- if (entityGroupIndices.has(i)) {
2266
- continue;
2267
- }
2268
- const tok = tokenized.groups[i].primary;
2269
- if (!COMPARISON_GLUE_WORDS.has(tok)) {
2270
- sharedContextTokens.push(tok);
2271
- }
2272
- }
2273
- const sharedContext = sharedContextTokens.join(" ");
2274
- return [
2275
- rawQuery,
2276
- ...entityClusters.map((ent) => (sharedContext ? `${ent.text} ${sharedContext}` : ent.text)),
2277
- ];
195
+ if (rarest > 0.5)
196
+ return 0.2;
197
+ const specificity = Math.min(1, (1 - rarest) / 0.8);
198
+ return specificity * (0.5 + (0.5 * found) / plan.tokenized.groups.length);
2278
199
  }
2279
200
  /**
2280
201
  * Level-2 progressive discovery: lists scenes/infrastructure entries filtered by domain and/or query/queries.
@@ -2319,63 +240,25 @@ export function discoverScenes(wiki, options = {}) {
2319
240
  return applyLimit(out, options.limit);
2320
241
  }
2321
242
  const index = getPrecomputedWikiIndex(wiki);
2322
- const candidateScenes = index.scenes.filter((entry) => {
2323
- if (options.domainId && entry.scene.domainId !== options.domainId) {
2324
- return false;
2325
- }
2326
- if (kindFilter !== "all" && entry.scene.kind !== kindFilter) {
2327
- return false;
2328
- }
2329
- return true;
2330
- });
243
+ const scope = options.domainId || kindFilter !== "all" ? new Set() : undefined;
244
+ if (scope)
245
+ index.scenes.forEach(({ scene }, row) => {
246
+ if ((!options.domainId || scene.domainId === options.domainId) &&
247
+ (kindFilter === "all" || scene.kind === kindFilter))
248
+ scope.add(row);
249
+ });
250
+ const localScope = options.domainId && scope && scope.size >= 6 ? scope : undefined;
251
+ const firstQuery = rawActiveQueries[0];
252
+ const firstPlan = buildPreparedQueryPlan(firstQuery, index, localScope);
2331
253
  const activeQueries = rawActiveQueries.length === 1
2332
- ? expandMultiEntitySingleQuery(rawActiveQueries[0], index, candidateScenes)
254
+ ? expandMultiEntitySingleQuery(firstQuery, firstPlan, index, scope)
2333
255
  : rawActiveQueries;
2334
- function runSingleSceneQuery(q) {
2335
- const plan = buildPreparedQueryPlan(q, index);
2336
- const hits = [];
2337
- for (const { scene, repoNames, sourceNames, chainNames, doc } of candidateScenes) {
2338
- const evalRes = evaluatePreparedQuery(plan, doc, true);
2339
- if (evalRes.score <= 0) {
2340
- continue;
2341
- }
2342
- const item = {
2343
- id: scene.id,
2344
- domainId: scene.domainId,
2345
- sceneId: scene.sceneId,
2346
- kind: scene.kind,
2347
- title: scene.frontmatter.title,
2348
- aliases: scene.frontmatter.aliases,
2349
- summary: scene.frontmatter.summary,
2350
- maintainers: scene.frontmatter.maintainers,
2351
- ...(scene.frontmatter.confidence !== undefined
2352
- ? { confidence: scene.frontmatter.confidence }
2353
- : {}),
2354
- dependsOn: scene.frontmatter.dependsOn,
2355
- repositories: repoNames,
2356
- ...(sourceNames.length > 0 ? { sources: sourceNames } : {}),
2357
- chainNames,
2358
- hasPendingConfirmations: scene.hasPendingConfirmations,
2359
- detailCount: scene.details.length,
2360
- relativePath: scene.relativePath,
2361
- score: evalRes.score,
2362
- ...(evalRes.matchedFields.length > 0 ? { matchedFields: evalRes.matchedFields } : {}),
2363
- };
2364
- hits.push({
2365
- item,
2366
- score: evalRes.score,
2367
- matchedFields: item.matchedFields,
2368
- snippetTerms: evalRes.bodySnippetTerms,
2369
- pinpointTerms: evalRes.pinpointTerms,
2370
- pinpointDesignators: evalRes.pinpointDesignators,
2371
- });
2372
- }
2373
- const filtered = filterWeakBodyOnlyHits(hits);
2374
- filtered.sort((a, b) => b.score - a.score || a.item.id.localeCompare(b.item.id));
2375
- return filtered;
256
+ const rrfPerQueryCap = options.limit !== undefined ? Math.max(40, options.limit * 4) : 60;
257
+ function runSingleSceneQuery(q, plan) {
258
+ return rankSceneCandidates(q, plan, index, scope, activeQueries.length === 1 ? options.limit : rrfPerQueryCap);
2376
259
  }
2377
260
  function enrichSceneItem(base, snippetTerms, pTerms, pDesigs) {
2378
- const doc = index.sceneById.get(base.id)?.doc;
261
+ const doc = index.sceneById.get(base.id)?.entry.doc;
2379
262
  if (!doc) {
2380
263
  return base;
2381
264
  }
@@ -2393,27 +276,34 @@ export function discoverScenes(wiki, options = {}) {
2393
276
  }
2394
277
  if (activeQueries.length === 1) {
2395
278
  const emptyDesigs = new Set();
2396
- const limited = applyLimit(runSingleSceneQuery(activeQueries[0]), options.limit);
279
+ const limited = applyLimit(runSingleSceneQuery(activeQueries[0], firstPlan), options.limit);
2397
280
  return limited.map(({ item, snippetTerms, pinpointTerms, pinpointDesignators }) => enrichSceneItem(item, snippetTerms, pinpointTerms ?? [], pinpointDesignators ?? emptyDesigs));
2398
281
  }
2399
282
  // Multi-query Reciprocal Rank Fusion (RRF) so every queried entity/report gets top-K representation without cannibalization
2400
283
  const fusedById = new Map();
2401
- const rrfPerQueryCap = options.limit !== undefined ? Math.max(40, options.limit * 4) : 60;
2402
284
  for (const q of activeQueries) {
2403
- const subResults = runSingleSceneQuery(q);
285
+ const plan = q === firstQuery ? firstPlan : buildPreparedQueryPlan(q, index, localScope);
286
+ const subResults = runSingleSceneQuery(q, plan);
287
+ const weight = realizedSpecificity(plan, index, scope);
2404
288
  const topScore = Math.max(1, subResults[0]?.item.score ?? 1);
289
+ const distinctWinner = subResults[1]?.item.score !== topScore;
2405
290
  const windowLen = Math.min(subResults.length, rrfPerQueryCap);
2406
291
  for (let idx = 0; idx < windowLen; idx++) {
2407
292
  const { item, snippetTerms, pinpointTerms, pinpointDesignators } = subResults[idx];
2408
293
  const rank = idx + 1;
2409
294
  const rawScore = item.score ?? 0;
2410
- const rrfContribution = 1200 / (1 + rank) + 40 * (rawScore / topScore);
295
+ const rrfContribution = weight *
296
+ (1200 / (1 + rank) +
297
+ 40 * (rawScore / topScore) +
298
+ (weight > 0.2 && rank === 1 && rawScore >= 55 && distinctWinner
299
+ ? 650 * activeQueries.length
300
+ : 0));
2411
301
  const existing = fusedById.get(item.id);
2412
302
  if (!existing) {
2413
303
  fusedById.set(item.id, {
2414
304
  base: item,
2415
305
  rrfSum: rrfContribution,
2416
- maxRawScore: rawScore,
306
+ maxRawScore: weight * rawScore,
2417
307
  bestRank: rank,
2418
308
  fields: new Set(item.matchedFields ?? []),
2419
309
  pinpointTerms: new Set(pinpointTerms ?? []),
@@ -2423,7 +313,7 @@ export function discoverScenes(wiki, options = {}) {
2423
313
  }
2424
314
  else {
2425
315
  existing.rrfSum += rrfContribution;
2426
- existing.maxRawScore = Math.max(existing.maxRawScore, rawScore);
316
+ existing.maxRawScore = Math.max(existing.maxRawScore, weight * rawScore);
2427
317
  for (const f of item.matchedFields ?? []) {
2428
318
  existing.fields.add(f);
2429
319
  }
@@ -2449,6 +339,16 @@ export function discoverScenes(wiki, options = {}) {
2449
339
  fusedScore: Math.round(entry.rrfSum + 0.15 * entry.maxRawScore),
2450
340
  }))
2451
341
  .sort((a, b) => b.fusedScore - a.fusedScore || a.entry.base.id.localeCompare(b.entry.base.id));
342
+ if (!options.domainId && wiki.domains.size > 1) {
343
+ const domainSeenCount = new Map();
344
+ for (const hit of sortedFused) {
345
+ const domain = hit.entry.base.domainId;
346
+ const seen = domainSeenCount.get(domain) ?? 0;
347
+ hit.fusedScore = Math.round(hit.fusedScore / (1 + Math.min(seen, 4) * 0.12));
348
+ domainSeenCount.set(domain, seen + 1);
349
+ }
350
+ sortedFused.sort((left, right) => right.fusedScore - left.fusedScore || left.entry.base.id.localeCompare(right.entry.base.id));
351
+ }
2452
352
  return applyLimit(sortedFused, options.limit).map(({ entry, fusedScore }) => {
2453
353
  const orderedFields = FIELD_DISPLAY_ORDER.filter((f) => entry.fields.has(f));
2454
354
  const baseWithScore = {
@@ -2459,18 +359,4 @@ export function discoverScenes(wiki, options = {}) {
2459
359
  return enrichSceneItem(baseWithScore, entry.bestSnippetTerms, Array.from(entry.pinpointTerms), entry.pinpointDesignators);
2460
360
  });
2461
361
  }
2462
- /**
2463
- * Returns precomputed lowercase corpus text & canonical designator set for a scene in O(N_init) / O(1_cached).
2464
- */
2465
- export function inspectSceneCoverageData(wiki, sceneId) {
2466
- const index = getPrecomputedWikiIndex(wiki);
2467
- const found = index.sceneById.get(sceneId);
2468
- if (!found) {
2469
- return undefined;
2470
- }
2471
- return {
2472
- allTextLower: found.doc.allTextLower,
2473
- designators: found.doc.designators.all,
2474
- };
2475
- }
2476
362
  //# sourceMappingURL=discover.js.map