@open-livex-wiki/core 0.1.0 → 0.2.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/browser.d.ts +3 -3
- package/dist/browser.d.ts.map +1 -1
- package/dist/browser.js +2 -2
- package/dist/browser.js.map +1 -1
- package/dist/coverage.d.ts +8 -0
- package/dist/coverage.d.ts.map +1 -0
- package/dist/coverage.js +537 -0
- package/dist/coverage.js.map +1 -0
- package/dist/diff-impact.d.ts.map +1 -1
- package/dist/diff-impact.js +109 -45
- package/dist/diff-impact.js.map +1 -1
- package/dist/discover.d.ts +36 -3
- package/dist/discover.d.ts.map +1 -1
- package/dist/discover.js +2373 -301
- package/dist/discover.js.map +1 -1
- package/dist/frontmatter.d.ts.map +1 -1
- package/dist/frontmatter.js +96 -6
- package/dist/frontmatter.js.map +1 -1
- package/dist/gate.d.ts.map +1 -1
- package/dist/gate.js +2 -0
- package/dist/gate.js.map +1 -1
- package/dist/graph.d.ts.map +1 -1
- package/dist/graph.js +3 -0
- package/dist/graph.js.map +1 -1
- package/dist/index.d.ts +6 -5
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +5 -4
- package/dist/index.js.map +1 -1
- package/dist/loader.d.ts +2 -1
- package/dist/loader.d.ts.map +1 -1
- package/dist/loader.js +427 -178
- package/dist/loader.js.map +1 -1
- package/dist/schemas.d.ts +79 -3
- package/dist/schemas.d.ts.map +1 -1
- package/dist/schemas.js +49 -4
- package/dist/schemas.js.map +1 -1
- package/dist/types.d.ts +71 -3
- package/dist/types.d.ts.map +1 -1
- package/dist/utils.d.ts +11 -0
- package/dist/utils.d.ts.map +1 -1
- package/dist/utils.js +35 -2
- package/dist/utils.js.map +1 -1
- package/dist/validator.d.ts +32 -1
- package/dist/validator.d.ts.map +1 -1
- package/dist/validator.js +346 -26
- package/dist/validator.js.map +1 -1
- package/package.json +1 -1
package/dist/discover.js
CHANGED
|
@@ -1,5 +1,8 @@
|
|
|
1
1
|
import { toPosixPath } from "./utils.js";
|
|
2
2
|
const QUERY_PUNCT_SPLIT_REGEX = /[\s,;,;、。??!!|/\\()()[\]【】<>::"'`]+/;
|
|
3
|
+
const NUMBERED_LABEL = /\b(?:figures?|fig|tables?|tab|tbl|section|sec|chapter|chap|appendix|part|exhibit|chart)[ \t]+(?:\d{1,4}[a-z]?|[ivxlcdm]{1,5}|[a-d])\b/i;
|
|
4
|
+
const LABEL_SEGMENTS = new RegExp(`(${NUMBERED_LABEL.source})`, "gi");
|
|
5
|
+
const WHOLE_LABEL = new RegExp(`^${NUMBERED_LABEL.source}$`, "i");
|
|
3
6
|
const CJK_CHAR_REGEX = /[\u3400-\u9fff\uf900-\ufaff]/;
|
|
4
7
|
const CJK_RUN_OR_OTHER_REGEX = /[\u3400-\u9fff\uf900-\ufaff]+|[^\u3400-\u9fff\uf900-\ufaff]+/g;
|
|
5
8
|
const CJK_PREFIX_FILLERS = ["关于", "请问", "帮我", "如何", "怎么", "什么", "查询", "查看", "排查"];
|
|
@@ -28,7 +31,7 @@ const GENERIC_CJK_SUFFIX_BIGRAMS = new Set([
|
|
|
28
31
|
"组件",
|
|
29
32
|
"引擎",
|
|
30
33
|
]);
|
|
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)$/i;
|
|
34
|
+
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
35
|
const IDENTIFIER_NOISE_SUBTOKENS = new Set([
|
|
33
36
|
"py",
|
|
34
37
|
"ts",
|
|
@@ -44,6 +47,365 @@ const IDENTIFIER_NOISE_SUBTOKENS = new Set([
|
|
|
44
47
|
"src",
|
|
45
48
|
"lib",
|
|
46
49
|
]);
|
|
50
|
+
const NON_DESIGNATOR_PREFIX_WORDS = new Set([
|
|
51
|
+
// Document / UI structural nouns & citation handle prefixes
|
|
52
|
+
"figure",
|
|
53
|
+
"figures",
|
|
54
|
+
"fig",
|
|
55
|
+
"figs",
|
|
56
|
+
"table",
|
|
57
|
+
"tables",
|
|
58
|
+
"tab",
|
|
59
|
+
"tbl",
|
|
60
|
+
"section",
|
|
61
|
+
"sections",
|
|
62
|
+
"sec",
|
|
63
|
+
"secs",
|
|
64
|
+
"chapter",
|
|
65
|
+
"chapters",
|
|
66
|
+
"chap",
|
|
67
|
+
"chaps",
|
|
68
|
+
"page",
|
|
69
|
+
"pages",
|
|
70
|
+
"pg",
|
|
71
|
+
"pp",
|
|
72
|
+
"part",
|
|
73
|
+
"parts",
|
|
74
|
+
"appendix",
|
|
75
|
+
"appendices",
|
|
76
|
+
"item",
|
|
77
|
+
"items",
|
|
78
|
+
"step",
|
|
79
|
+
"steps",
|
|
80
|
+
"stage",
|
|
81
|
+
"stages",
|
|
82
|
+
"phase",
|
|
83
|
+
"phases",
|
|
84
|
+
"tier",
|
|
85
|
+
"tiers",
|
|
86
|
+
"level",
|
|
87
|
+
"levels",
|
|
88
|
+
"version",
|
|
89
|
+
"versions",
|
|
90
|
+
"ver",
|
|
91
|
+
"vol",
|
|
92
|
+
"volume",
|
|
93
|
+
"issue",
|
|
94
|
+
"line",
|
|
95
|
+
"lines",
|
|
96
|
+
"row",
|
|
97
|
+
"rows",
|
|
98
|
+
"col",
|
|
99
|
+
"cols",
|
|
100
|
+
"column",
|
|
101
|
+
"columns",
|
|
102
|
+
"chart",
|
|
103
|
+
"exhibit",
|
|
104
|
+
"charts",
|
|
105
|
+
"graph",
|
|
106
|
+
"diagram",
|
|
107
|
+
"anc",
|
|
108
|
+
"anchor",
|
|
109
|
+
"scene",
|
|
110
|
+
"scenes",
|
|
111
|
+
"domain",
|
|
112
|
+
"domains",
|
|
113
|
+
"chain",
|
|
114
|
+
"chains",
|
|
115
|
+
"doc",
|
|
116
|
+
"docs",
|
|
117
|
+
"file",
|
|
118
|
+
"files",
|
|
119
|
+
"test",
|
|
120
|
+
"tests",
|
|
121
|
+
"task",
|
|
122
|
+
"tasks",
|
|
123
|
+
// Time / fiscal / calendar / common units
|
|
124
|
+
"fy",
|
|
125
|
+
"cy",
|
|
126
|
+
"ty",
|
|
127
|
+
"year",
|
|
128
|
+
"years",
|
|
129
|
+
"yr",
|
|
130
|
+
"yrs",
|
|
131
|
+
"month",
|
|
132
|
+
"months",
|
|
133
|
+
"mo",
|
|
134
|
+
"week",
|
|
135
|
+
"weeks",
|
|
136
|
+
"wk",
|
|
137
|
+
"day",
|
|
138
|
+
"days",
|
|
139
|
+
"hour",
|
|
140
|
+
"hours",
|
|
141
|
+
"hr",
|
|
142
|
+
"hrs",
|
|
143
|
+
"min",
|
|
144
|
+
"mins",
|
|
145
|
+
"minute",
|
|
146
|
+
"minutes",
|
|
147
|
+
"second",
|
|
148
|
+
"seconds",
|
|
149
|
+
"jan",
|
|
150
|
+
"feb",
|
|
151
|
+
"mar",
|
|
152
|
+
"apr",
|
|
153
|
+
"jun",
|
|
154
|
+
"jul",
|
|
155
|
+
"aug",
|
|
156
|
+
"sep",
|
|
157
|
+
"sept",
|
|
158
|
+
"oct",
|
|
159
|
+
"nov",
|
|
160
|
+
"dec",
|
|
161
|
+
// Common English prepositions, conjunctions, verbs, articles, tech tokens
|
|
162
|
+
"the",
|
|
163
|
+
"and",
|
|
164
|
+
"for",
|
|
165
|
+
"with",
|
|
166
|
+
"from",
|
|
167
|
+
"into",
|
|
168
|
+
"over",
|
|
169
|
+
"under",
|
|
170
|
+
"between",
|
|
171
|
+
"about",
|
|
172
|
+
"after",
|
|
173
|
+
"before",
|
|
174
|
+
"during",
|
|
175
|
+
"within",
|
|
176
|
+
"through",
|
|
177
|
+
"across",
|
|
178
|
+
"among",
|
|
179
|
+
"than",
|
|
180
|
+
"per",
|
|
181
|
+
"via",
|
|
182
|
+
"see",
|
|
183
|
+
"ref",
|
|
184
|
+
"note",
|
|
185
|
+
"notes",
|
|
186
|
+
"report",
|
|
187
|
+
"reports",
|
|
188
|
+
"compare",
|
|
189
|
+
"versus",
|
|
190
|
+
"top",
|
|
191
|
+
"max",
|
|
192
|
+
"limit",
|
|
193
|
+
"port",
|
|
194
|
+
"code",
|
|
195
|
+
"type",
|
|
196
|
+
"mode",
|
|
197
|
+
"node",
|
|
198
|
+
"edge",
|
|
199
|
+
"utf",
|
|
200
|
+
"sha",
|
|
201
|
+
"int",
|
|
202
|
+
"uint",
|
|
203
|
+
"float",
|
|
204
|
+
"win",
|
|
205
|
+
"ipv",
|
|
206
|
+
"http",
|
|
207
|
+
"https",
|
|
208
|
+
"tcp",
|
|
209
|
+
"udp",
|
|
210
|
+
]);
|
|
211
|
+
const SPACE_STOP_PREFIXES = new Set([
|
|
212
|
+
"in",
|
|
213
|
+
"on",
|
|
214
|
+
"at",
|
|
215
|
+
"to",
|
|
216
|
+
"of",
|
|
217
|
+
"by",
|
|
218
|
+
"or",
|
|
219
|
+
"as",
|
|
220
|
+
"is",
|
|
221
|
+
"be",
|
|
222
|
+
"an",
|
|
223
|
+
"no",
|
|
224
|
+
"so",
|
|
225
|
+
"up",
|
|
226
|
+
"if",
|
|
227
|
+
"do",
|
|
228
|
+
"go",
|
|
229
|
+
"we",
|
|
230
|
+
"it",
|
|
231
|
+
"he",
|
|
232
|
+
"me",
|
|
233
|
+
"my",
|
|
234
|
+
"us",
|
|
235
|
+
"vs",
|
|
236
|
+
]);
|
|
237
|
+
export function sourceYearMentions(text) {
|
|
238
|
+
return Array.from(text.matchAll(/\b([a-z]+)[ \t]+(?:19[7-9]\d|20[0-4]\d)\b/gi)).filter((match) => {
|
|
239
|
+
const prefix = match[1].toLowerCase();
|
|
240
|
+
return !NON_DESIGNATOR_PREFIX_WORDS.has(prefix) && !SPACE_STOP_PREFIXES.has(prefix);
|
|
241
|
+
});
|
|
242
|
+
}
|
|
243
|
+
/**
|
|
244
|
+
* Normalizes a single alphanumeric model, weapon, report, or standard designator
|
|
245
|
+
* (e.g. `"FFG-62"`, `"FFG 62"`, `"FFG62"` -> `"ffg62"`; `"ATP 7-100.1"` -> `"atp71001"`).
|
|
246
|
+
* Returns `undefined` for ordinary prose words, pure numbers, commit SHAs, or structural labels.
|
|
247
|
+
*/
|
|
248
|
+
export function normalizeDesignatorToken(text) {
|
|
249
|
+
if (typeof text !== "string") {
|
|
250
|
+
return undefined;
|
|
251
|
+
}
|
|
252
|
+
const cleaned = text
|
|
253
|
+
.trim()
|
|
254
|
+
.replace(/^[([{"'`]+|[)\]}"'`,.;:!?]+$/g, "")
|
|
255
|
+
.trim();
|
|
256
|
+
if (!cleaned || /^[a-z]+\s+(?:19[7-9]\d|20[0-4]\d)$/i.test(cleaned)) {
|
|
257
|
+
return undefined;
|
|
258
|
+
}
|
|
259
|
+
// Must start with 1..10 ASCII letters and contain only ASCII letters, digits, spaces, and ./_- separators
|
|
260
|
+
if (!/^[A-Za-z]{1,10}(?:[\s./_-]+[A-Za-z0-9]+|[0-9][A-Za-z0-9./_-]*)+$/.test(cleaned)) {
|
|
261
|
+
return undefined;
|
|
262
|
+
}
|
|
263
|
+
if (!/[A-Za-z]/.test(cleaned) || !/[0-9]/.test(cleaned)) {
|
|
264
|
+
return undefined;
|
|
265
|
+
}
|
|
266
|
+
// Reject unseparated hex SHA-1/SHA-256/short-SHA digests and UUIDs
|
|
267
|
+
if (!/[\s./_-]/.test(cleaned) && /^[0-9a-f]{7,64}$/i.test(cleaned)) {
|
|
268
|
+
return undefined;
|
|
269
|
+
}
|
|
270
|
+
if (/^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/i.test(cleaned)) {
|
|
271
|
+
return undefined;
|
|
272
|
+
}
|
|
273
|
+
// Reject semver / version tags like v1, v1.2, v0.2.0 (while keeping hyphenated V-22!)
|
|
274
|
+
if (/^v\s*\d+(?:\.\d+)*$/i.test(cleaned)) {
|
|
275
|
+
return undefined;
|
|
276
|
+
}
|
|
277
|
+
// Reject source filenames with extensions (e.g. `v2.ts`, `route_v1.py`)
|
|
278
|
+
if (SOURCE_FILE_EXT_REGEX.test(cleaned)) {
|
|
279
|
+
return undefined;
|
|
280
|
+
}
|
|
281
|
+
const collapsed = cleaned.replace(/[^A-Za-z0-9]+/g, "").toLowerCase();
|
|
282
|
+
if (collapsed.length < 3 || collapsed.length > 32) {
|
|
283
|
+
return undefined;
|
|
284
|
+
}
|
|
285
|
+
const prefixMatch = /^([A-Za-z]+)/.exec(cleaned);
|
|
286
|
+
const rawPrefix = prefixMatch?.[1] ?? "";
|
|
287
|
+
const lowerPrefix = rawPrefix.toLowerCase();
|
|
288
|
+
if (!rawPrefix || NON_DESIGNATOR_PREFIX_WORDS.has(lowerPrefix)) {
|
|
289
|
+
return undefined;
|
|
290
|
+
}
|
|
291
|
+
// Guard space-separated prefixes against lowercase articles/prepositions ("a 10", "in 2025", "if 2")
|
|
292
|
+
const afterPrefix = cleaned.slice(rawPrefix.length);
|
|
293
|
+
if (/^\s/.test(afterPrefix)) {
|
|
294
|
+
if (rawPrefix.length === 1 && rawPrefix === lowerPrefix) {
|
|
295
|
+
return undefined;
|
|
296
|
+
}
|
|
297
|
+
if (SPACE_STOP_PREFIXES.has(lowerPrefix)) {
|
|
298
|
+
const isUppercaseCrsReport = rawPrefix === rawPrefix.toUpperCase() && /^[A-Z]{2}\s+\d{4,5}[A-Z]?$/.test(cleaned);
|
|
299
|
+
if (!isUppercaseCrsReport) {
|
|
300
|
+
return undefined;
|
|
301
|
+
}
|
|
302
|
+
}
|
|
303
|
+
}
|
|
304
|
+
return collapsed;
|
|
305
|
+
}
|
|
306
|
+
function buildDesignatorVariants(rawText, primaryCanonical) {
|
|
307
|
+
const variants = [primaryCanonical];
|
|
308
|
+
const parts = rawText
|
|
309
|
+
.trim()
|
|
310
|
+
.split(/[\s/_-]+/)
|
|
311
|
+
.filter(Boolean);
|
|
312
|
+
if (parts.length >= 2 && /^[A-Za-z]+$/.test(parts[0] ?? "")) {
|
|
313
|
+
const suffixRaw = parts.slice(1).join("-");
|
|
314
|
+
if (/^[A-Za-z]/.test(suffixRaw) && /[0-9]/.test(suffixRaw)) {
|
|
315
|
+
const subNorm = normalizeDesignatorToken(suffixRaw);
|
|
316
|
+
if (subNorm && !variants.includes(subNorm)) {
|
|
317
|
+
variants.push(subNorm);
|
|
318
|
+
}
|
|
319
|
+
}
|
|
320
|
+
}
|
|
321
|
+
return variants;
|
|
322
|
+
}
|
|
323
|
+
function asciiLetter(code) {
|
|
324
|
+
return (code | 32) >= 97 && (code | 32) <= 122;
|
|
325
|
+
}
|
|
326
|
+
function asciiAlnum(code) {
|
|
327
|
+
return asciiLetter(code) || (code >= 48 && code <= 57);
|
|
328
|
+
}
|
|
329
|
+
function tokenStart(text, end) {
|
|
330
|
+
let start = end;
|
|
331
|
+
while (start > 0) {
|
|
332
|
+
const prior = text.charCodeAt(start - 1);
|
|
333
|
+
if (asciiAlnum(prior))
|
|
334
|
+
start--;
|
|
335
|
+
else if (start < text.length &&
|
|
336
|
+
asciiAlnum(text.charCodeAt(start)) &&
|
|
337
|
+
(prior === 45 || prior === 46 || prior === 47) &&
|
|
338
|
+
asciiAlnum(text.charCodeAt(start - 2)))
|
|
339
|
+
start -= 2;
|
|
340
|
+
else
|
|
341
|
+
break;
|
|
342
|
+
}
|
|
343
|
+
return start;
|
|
344
|
+
}
|
|
345
|
+
/**
|
|
346
|
+
* Scans arbitrary text and returns structured designator mentions (preserving original span + canonical variants).
|
|
347
|
+
*/
|
|
348
|
+
export function extractDesignatorMentions(text) {
|
|
349
|
+
return scanDesignators(text, normalizeDesignatorToken);
|
|
350
|
+
}
|
|
351
|
+
function maskRemotes(text) {
|
|
352
|
+
let masked = text;
|
|
353
|
+
if (masked.includes("://")) {
|
|
354
|
+
masked = masked.replace(/(?:git\+)?(?:https?|ssh|git):\/\/[^\s)>\]"']+/gi, " ");
|
|
355
|
+
}
|
|
356
|
+
if (masked.includes("@")) {
|
|
357
|
+
masked = masked.replace(/[A-Za-z0-9._+-]+@[A-Za-z0-9.-]+:[^\s)>\]"']+/g, " ");
|
|
358
|
+
}
|
|
359
|
+
return masked;
|
|
360
|
+
}
|
|
361
|
+
function scanDesignators(text, normalize, signature) {
|
|
362
|
+
if (typeof text !== "string" || !text || !/[0-9]/.test(text) || !/[A-Za-z]/.test(text))
|
|
363
|
+
return [];
|
|
364
|
+
const masked = maskRemotes(text);
|
|
365
|
+
const mentions = [];
|
|
366
|
+
const seenPrimary = new Set();
|
|
367
|
+
const digits = /\d[a-z0-9]*(?:[-/.][a-z0-9]+)*/gi;
|
|
368
|
+
for (let match = digits.exec(masked); match; match = digits.exec(masked)) {
|
|
369
|
+
if (signature && (match[0][0] !== signature[0] || match[0].replace(/\D/g, "") !== signature))
|
|
370
|
+
continue;
|
|
371
|
+
const start = tokenStart(masked, match.index);
|
|
372
|
+
let raw = masked.slice(start, digits.lastIndex);
|
|
373
|
+
let canonical;
|
|
374
|
+
if ((masked[start - 1] === " " || masked[start - 1] === "\t") &&
|
|
375
|
+
/^(?:\d|[a-z]{1,2}\d{3,}[a-z]?$)/i.test(raw)) {
|
|
376
|
+
let end = start;
|
|
377
|
+
while (masked[end - 1] === " " || masked[end - 1] === "\t")
|
|
378
|
+
end--;
|
|
379
|
+
const previous = masked.slice(tokenStart(masked, end), end);
|
|
380
|
+
if (/^[a-z]{1,8}(?:[-/][a-z]{1,8})?$/i.test(previous)) {
|
|
381
|
+
const spaced = `${previous} ${raw}`;
|
|
382
|
+
canonical = normalize(spaced);
|
|
383
|
+
if (canonical)
|
|
384
|
+
raw = spaced;
|
|
385
|
+
}
|
|
386
|
+
}
|
|
387
|
+
if (!canonical && asciiLetter(raw.charCodeAt(0)))
|
|
388
|
+
canonical = normalize(raw);
|
|
389
|
+
if (canonical && !seenPrimary.has(canonical)) {
|
|
390
|
+
seenPrimary.add(canonical);
|
|
391
|
+
mentions.push({ raw, canonical, variants: buildDesignatorVariants(raw, canonical) });
|
|
392
|
+
}
|
|
393
|
+
}
|
|
394
|
+
return mentions;
|
|
395
|
+
}
|
|
396
|
+
/**
|
|
397
|
+
* Extracts deduplicated canonical alphanumeric designator tokens from arbitrary text
|
|
398
|
+
* (e.g. `"CRS-R44972"` -> `["crsr44972", "r44972"]`, `"FFG 62"` -> `["ffg62"]`, `"ATP 7-100.1"` -> `["atp71001"]`).
|
|
399
|
+
*/
|
|
400
|
+
export function extractDesignatorTokens(text) {
|
|
401
|
+
const out = new Set();
|
|
402
|
+
for (const mention of extractDesignatorMentions(text)) {
|
|
403
|
+
for (const v of mention.variants) {
|
|
404
|
+
out.add(v);
|
|
405
|
+
}
|
|
406
|
+
}
|
|
407
|
+
return Array.from(out);
|
|
408
|
+
}
|
|
47
409
|
function isPureCjk(text) {
|
|
48
410
|
return text.length > 0 && /^[\u3400-\u9fff\uf900-\ufaff]+$/.test(text);
|
|
49
411
|
}
|
|
@@ -155,9 +517,13 @@ function extractIdentifierSubTokens(rawAsciiToken, lowerPrimary) {
|
|
|
155
517
|
const deduped = Array.from(new Set(rawParts));
|
|
156
518
|
return deduped.length >= 2 ? deduped : [];
|
|
157
519
|
}
|
|
520
|
+
function escapeRegExpLiteral(str) {
|
|
521
|
+
return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
522
|
+
}
|
|
158
523
|
/**
|
|
159
|
-
* Smart CJK + Mixed-Script tokenizer for progressive discovery queries.
|
|
524
|
+
* Smart CJK + Mixed-Script + Designator-Aware tokenizer for progressive discovery queries.
|
|
160
525
|
* - Splits on whitespace and punctuation while preserving `.`, `-`, `_`, `#` inside identifiers/filenames.
|
|
526
|
+
* - Canonicalizes alphanumeric designators (`"FFG-62"` / `"FFG 62"` -> `"ffg62"`, `"CRS-R44972"` -> `["crsr44972", "r44972"]`).
|
|
161
527
|
* - Splits CJK <-> ASCII/number transitions (`"iOS内购"` -> `["ios", "内购"]`, `"LLM网关"` -> `["llm", "网关"]`).
|
|
162
528
|
* - Strips Chinese filler/stop particles when remaining CJK length >= 2.
|
|
163
529
|
* - Emits overlapping CJK 2-grams and 3-grams for CJK compound tokens of length >= 3.
|
|
@@ -169,10 +535,20 @@ export function tokenizeDiscoveryQuery(query) {
|
|
|
169
535
|
if (!normalizedPhrase) {
|
|
170
536
|
return { normalizedPhrase: "", groups: [] };
|
|
171
537
|
}
|
|
172
|
-
const rawSegments = trimmedOriginal
|
|
538
|
+
const rawSegments = trimmedOriginal
|
|
539
|
+
.split(LABEL_SEGMENTS)
|
|
540
|
+
.flatMap((part, index) => index % 2 ? [part.trim().replace(/\s+/, " ")] : part.split(QUERY_PUNCT_SPLIT_REGEX))
|
|
541
|
+
.filter(Boolean);
|
|
173
542
|
const seenPrimary = new Set();
|
|
174
543
|
const groups = [];
|
|
175
544
|
function addToken(rawTok, rawCjkRun) {
|
|
545
|
+
if (rawTok.includes(" ")) {
|
|
546
|
+
const primary = rawTok.toLowerCase();
|
|
547
|
+
if (!seenPrimary.has(primary))
|
|
548
|
+
groups.push({ primary, threeGrams: [], twoGrams: [] });
|
|
549
|
+
seenPrimary.add(primary);
|
|
550
|
+
return;
|
|
551
|
+
}
|
|
176
552
|
const cleanedOriginal = rawTok.trim().replace(/^[._#-]+|[._#-]+$/g, "");
|
|
177
553
|
const t = cleanedOriginal.toLowerCase();
|
|
178
554
|
if (!t || seenPrimary.has(t)) {
|
|
@@ -191,14 +567,48 @@ export function tokenizeDiscoveryQuery(query) {
|
|
|
191
567
|
}
|
|
192
568
|
seenPrimary.add(t);
|
|
193
569
|
const subTokens = extractIdentifierSubTokens(cleanedOriginal, t);
|
|
570
|
+
const normDesig = normalizeDesignatorToken(cleanedOriginal);
|
|
571
|
+
const designators = normDesig ? buildDesignatorVariants(cleanedOriginal, normDesig) : [];
|
|
194
572
|
groups.push({
|
|
195
573
|
primary: t,
|
|
196
574
|
threeGrams: [],
|
|
197
575
|
twoGrams: [],
|
|
198
576
|
...(subTokens.length > 0 ? { subTokens } : {}),
|
|
577
|
+
...(designators.length > 0 ? { designators } : {}),
|
|
199
578
|
});
|
|
200
579
|
}
|
|
201
|
-
for (
|
|
580
|
+
for (let idx = 0; idx < rawSegments.length; idx++) {
|
|
581
|
+
const segment = rawSegments[idx];
|
|
582
|
+
const nextSeg = rawSegments[idx + 1];
|
|
583
|
+
// Coalesce adjacent space-separated designators (e.g. "FFG 62", "SSBN 826", "CRS R44972", "ATP 7-100.1")
|
|
584
|
+
if (nextSeg &&
|
|
585
|
+
!CJK_CHAR_REGEX.test(segment) &&
|
|
586
|
+
!CJK_CHAR_REGEX.test(nextSeg) &&
|
|
587
|
+
/^[A-Za-z]{1,8}(?:-[A-Za-z]{1,8})?$/.test(segment) &&
|
|
588
|
+
(/^[0-9][0-9A-Za-z._-]*$/.test(nextSeg) || /^[A-Za-z]{1,2}[0-9]{3,}[A-Za-z]?$/.test(nextSeg))) {
|
|
589
|
+
const spacedRegex = new RegExp(`(?<![A-Za-z0-9_])${escapeRegExpLiteral(segment)}[ \\t]+${escapeRegExpLiteral(nextSeg)}(?![A-Za-z0-9_])`);
|
|
590
|
+
const combinedRaw = `${segment} ${nextSeg}`;
|
|
591
|
+
const combinedNorm = spacedRegex.test(trimmedOriginal)
|
|
592
|
+
? normalizeDesignatorToken(combinedRaw)
|
|
593
|
+
: undefined;
|
|
594
|
+
if (combinedNorm) {
|
|
595
|
+
const primaryLower = combinedRaw.toLowerCase();
|
|
596
|
+
if (!seenPrimary.has(primaryLower)) {
|
|
597
|
+
seenPrimary.add(primaryLower);
|
|
598
|
+
const subTokens = extractIdentifierSubTokens(`${segment}-${nextSeg}`, primaryLower);
|
|
599
|
+
const designators = buildDesignatorVariants(combinedRaw, combinedNorm);
|
|
600
|
+
groups.push({
|
|
601
|
+
primary: primaryLower,
|
|
602
|
+
threeGrams: [],
|
|
603
|
+
twoGrams: [],
|
|
604
|
+
...(subTokens.length > 0 ? { subTokens } : {}),
|
|
605
|
+
designators,
|
|
606
|
+
});
|
|
607
|
+
}
|
|
608
|
+
idx += 1;
|
|
609
|
+
continue;
|
|
610
|
+
}
|
|
611
|
+
}
|
|
202
612
|
const hasMixedScript = CJK_CHAR_REGEX.test(segment) && /[^\u3400-\u9fff\uf900-\ufaff]/.test(segment);
|
|
203
613
|
if (!hasMixedScript) {
|
|
204
614
|
if (isPureCjk(segment)) {
|
|
@@ -232,6 +642,8 @@ export function tokenizeDiscoveryQuery(query) {
|
|
|
232
642
|
return { normalizedPhrase, groups };
|
|
233
643
|
}
|
|
234
644
|
function extractInlineCodeSpans(markdown) {
|
|
645
|
+
if (!markdown.includes("`"))
|
|
646
|
+
return [];
|
|
235
647
|
const spans = [];
|
|
236
648
|
const lines = markdown.split(/\r?\n/);
|
|
237
649
|
let inFence = false;
|
|
@@ -309,6 +721,887 @@ function extractMatchSnippet(sources, matchedTerms, targetLength = 80) {
|
|
|
309
721
|
}
|
|
310
722
|
return undefined;
|
|
311
723
|
}
|
|
724
|
+
const WIKI_INDEX_CACHE = new WeakMap();
|
|
725
|
+
function toPathTerm(raw) {
|
|
726
|
+
const lower = toPosixPath(raw).toLowerCase();
|
|
727
|
+
const base = lower.split("/").pop() ?? lower;
|
|
728
|
+
return { lower, base };
|
|
729
|
+
}
|
|
730
|
+
function collectDesignatorsFromStrings(strings, rawMap, normalize = normalizeDesignatorToken, signature) {
|
|
731
|
+
const out = new Set();
|
|
732
|
+
for (const s of strings) {
|
|
733
|
+
if (signature ? !s.includes(signature[0]) : !/\d/.test(s)) {
|
|
734
|
+
continue;
|
|
735
|
+
}
|
|
736
|
+
for (const mention of scanDesignators(s, normalize, signature)) {
|
|
737
|
+
for (const v of mention.variants) {
|
|
738
|
+
out.add(v);
|
|
739
|
+
if (rawMap && !rawMap.has(v)) {
|
|
740
|
+
rawMap.set(v, mention.raw);
|
|
741
|
+
}
|
|
742
|
+
}
|
|
743
|
+
}
|
|
744
|
+
}
|
|
745
|
+
return out;
|
|
746
|
+
}
|
|
747
|
+
export function formatAnchorSummaryLabel(anchor) {
|
|
748
|
+
const owner = anchor.source ?? anchor.repo ?? "anchor";
|
|
749
|
+
const pagePart = anchor.pageRange ? `#p${anchor.pageRange[0]}-${anchor.pageRange[1]}` : "";
|
|
750
|
+
const symbolPart = anchor.symbol ? `#${anchor.symbol}` : "";
|
|
751
|
+
const extraPart = anchor.assetId
|
|
752
|
+
? ` (${anchor.assetId})`
|
|
753
|
+
: anchor.sectionTitle
|
|
754
|
+
? ` (${anchor.sectionTitle})`
|
|
755
|
+
: "";
|
|
756
|
+
const handlePrefix = anchor.handle ? `[${anchor.handle}] ` : "";
|
|
757
|
+
return `${handlePrefix}${owner}:${toPosixPath(anchor.file)}${pagePart}${symbolPart}${extraPart}`;
|
|
758
|
+
}
|
|
759
|
+
export function toMatchedAnchorSummary(anchor) {
|
|
760
|
+
return {
|
|
761
|
+
label: formatAnchorSummaryLabel(anchor),
|
|
762
|
+
...(anchor.repo ? { repo: anchor.repo } : {}),
|
|
763
|
+
...(anchor.source ? { source: anchor.source } : {}),
|
|
764
|
+
file: anchor.file,
|
|
765
|
+
...(anchor.symbol ? { symbol: anchor.symbol } : {}),
|
|
766
|
+
...(anchor.kind ? { kind: anchor.kind } : {}),
|
|
767
|
+
...(anchor.pageRange
|
|
768
|
+
? { pageRange: [anchor.pageRange[0], anchor.pageRange[1]] }
|
|
769
|
+
: {}),
|
|
770
|
+
...(anchor.sectionTitle ? { sectionTitle: anchor.sectionTitle } : {}),
|
|
771
|
+
...(anchor.assetId ? { assetId: anchor.assetId } : {}),
|
|
772
|
+
...(anchor.handle ? { handle: anchor.handle } : {}),
|
|
773
|
+
...(anchor.scopeNote ? { scopeNote: anchor.scopeNote } : {}),
|
|
774
|
+
};
|
|
775
|
+
}
|
|
776
|
+
function collectAnchorSearchStrings(anchor) {
|
|
777
|
+
const raw = [anchor.file];
|
|
778
|
+
if (anchor.symbol) {
|
|
779
|
+
raw.push(anchor.symbol);
|
|
780
|
+
}
|
|
781
|
+
if (anchor.sectionTitle) {
|
|
782
|
+
raw.push(anchor.sectionTitle);
|
|
783
|
+
}
|
|
784
|
+
if (anchor.assetId) {
|
|
785
|
+
raw.push(anchor.assetId);
|
|
786
|
+
}
|
|
787
|
+
if (anchor.handle) {
|
|
788
|
+
raw.push(anchor.handle);
|
|
789
|
+
}
|
|
790
|
+
if (anchor.scopeNote) {
|
|
791
|
+
raw.push(anchor.scopeNote);
|
|
792
|
+
}
|
|
793
|
+
if (anchor.pageRange) {
|
|
794
|
+
raw.push(`p.${anchor.pageRange[0]}-${anchor.pageRange[1]}`);
|
|
795
|
+
raw.push(`p${anchor.pageRange[0]}-${anchor.pageRange[1]}`);
|
|
796
|
+
}
|
|
797
|
+
return raw;
|
|
798
|
+
}
|
|
799
|
+
const EMPTY_LIST = [];
|
|
800
|
+
const EMPTY_DESIGNATORS = new Set();
|
|
801
|
+
function chainTerms(chain) {
|
|
802
|
+
return chain.entryPoint ? [chain.id, chain.title, chain.entryPoint] : [chain.id, chain.title];
|
|
803
|
+
}
|
|
804
|
+
class SceneSearchRow {
|
|
805
|
+
scene;
|
|
806
|
+
normalize;
|
|
807
|
+
identity;
|
|
808
|
+
structured;
|
|
809
|
+
joined;
|
|
810
|
+
body;
|
|
811
|
+
id;
|
|
812
|
+
shortId;
|
|
813
|
+
title;
|
|
814
|
+
aliases;
|
|
815
|
+
reverse;
|
|
816
|
+
chains;
|
|
817
|
+
paths;
|
|
818
|
+
repoRaw;
|
|
819
|
+
sourceRaw;
|
|
820
|
+
rawSources;
|
|
821
|
+
details;
|
|
822
|
+
hasCode;
|
|
823
|
+
prepared;
|
|
824
|
+
rawSpans;
|
|
825
|
+
spans;
|
|
826
|
+
chartEvidence;
|
|
827
|
+
constructor(scene, normalize) {
|
|
828
|
+
this.scene = scene;
|
|
829
|
+
this.normalize = normalize;
|
|
830
|
+
const meta = scene.frontmatter;
|
|
831
|
+
this.id = scene.id.toLowerCase();
|
|
832
|
+
this.shortId = scene.sceneId.toLowerCase();
|
|
833
|
+
this.title = meta.title.toLowerCase();
|
|
834
|
+
this.aliases = meta.aliases.map((alias) => alias.toLowerCase());
|
|
835
|
+
this.chains =
|
|
836
|
+
scene.chains.length === 1 ? chainTerms(scene.chains[0]) : scene.chains.flatMap(chainTerms);
|
|
837
|
+
const anchors = meta.anchors ?? EMPTY_LIST;
|
|
838
|
+
this.repoRaw = meta.repositories.length
|
|
839
|
+
? meta.repositories.map((repo) => repo.repo)
|
|
840
|
+
: anchors.length
|
|
841
|
+
? []
|
|
842
|
+
: EMPTY_LIST;
|
|
843
|
+
this.sourceRaw =
|
|
844
|
+
meta.sources?.flatMap((source) => source.path ? [source.source, source.path] : [source.source]) ?? (anchors.length ? [] : EMPTY_LIST);
|
|
845
|
+
for (const anchor of anchors) {
|
|
846
|
+
if (anchor.repo)
|
|
847
|
+
this.repoRaw.push(anchor.repo);
|
|
848
|
+
if (anchor.source)
|
|
849
|
+
this.sourceRaw.push(anchor.source);
|
|
850
|
+
}
|
|
851
|
+
this.paths =
|
|
852
|
+
anchors.length || this.repoRaw.length || this.sourceRaw.length
|
|
853
|
+
? [
|
|
854
|
+
anchors.flatMap(collectAnchorSearchStrings).map(toPathTerm),
|
|
855
|
+
[...new Set(this.repoRaw)].map(toPathTerm),
|
|
856
|
+
[...new Set(this.sourceRaw)].map(toPathTerm),
|
|
857
|
+
]
|
|
858
|
+
: EMPTY_LIST;
|
|
859
|
+
const chainLower = this.chains.map((term) => term.toLowerCase());
|
|
860
|
+
this.reverse = [this.shortId, this.title, ...this.aliases].filter((term, idx) => term.length >= (idx ? 2 : 3));
|
|
861
|
+
for (const term of chainLower)
|
|
862
|
+
if (term.length >= 3)
|
|
863
|
+
this.reverse.push(term);
|
|
864
|
+
const identity = [this.id, this.shortId, this.title, ...this.aliases, ...chainLower];
|
|
865
|
+
for (const paths of this.paths)
|
|
866
|
+
for (const path of paths) {
|
|
867
|
+
identity.push(path.lower);
|
|
868
|
+
if (path.base.length >= 3)
|
|
869
|
+
this.reverse.push(path.base);
|
|
870
|
+
}
|
|
871
|
+
this.identity = identity.join("\n");
|
|
872
|
+
this.details = scene.details.length
|
|
873
|
+
? scene.details.map((detail) => detail.content.toLowerCase())
|
|
874
|
+
: EMPTY_LIST;
|
|
875
|
+
this.rawSources = scene.details.length
|
|
876
|
+
? [scene.content, ...scene.details.map((detail) => detail.content)]
|
|
877
|
+
: [scene.content];
|
|
878
|
+
this.hasCode = this.rawSources.some((text) => text.includes("`"));
|
|
879
|
+
const summary = meta.summary === meta.title ? this.title : meta.summary.toLowerCase();
|
|
880
|
+
const other = scene.details.length
|
|
881
|
+
? [...scene.headings, ...scene.details.flatMap((detail) => [detail.name, detail.title])]
|
|
882
|
+
: scene.headings;
|
|
883
|
+
const support = other.length ? `${summary}\n${other.join("\n").toLowerCase()}` : summary;
|
|
884
|
+
this.structured = `${this.identity}\n${support}`;
|
|
885
|
+
this.body = scene.content.toLowerCase();
|
|
886
|
+
}
|
|
887
|
+
get text() {
|
|
888
|
+
this.joined ??= [
|
|
889
|
+
this.structured,
|
|
890
|
+
...this.codeSpans.map((span) => span.lower),
|
|
891
|
+
this.body,
|
|
892
|
+
...this.details,
|
|
893
|
+
].join("\n");
|
|
894
|
+
return this.joined;
|
|
895
|
+
}
|
|
896
|
+
contains(term) {
|
|
897
|
+
return term.includes("\n")
|
|
898
|
+
? this.text.includes(term)
|
|
899
|
+
: this.structured.includes(term) ||
|
|
900
|
+
this.body.includes(term) ||
|
|
901
|
+
this.details.some((text) => text.includes(term)) ||
|
|
902
|
+
(this.hasCode && this.codeSpans.some((span) => span.lower.includes(term)));
|
|
903
|
+
}
|
|
904
|
+
get rawCodeSpans() {
|
|
905
|
+
if (!this.hasCode)
|
|
906
|
+
return EMPTY_LIST;
|
|
907
|
+
this.rawSpans ??= this.rawSources.flatMap(extractInlineCodeSpans);
|
|
908
|
+
return this.rawSpans;
|
|
909
|
+
}
|
|
910
|
+
get codeSpans() {
|
|
911
|
+
if (!this.hasCode)
|
|
912
|
+
return EMPTY_LIST;
|
|
913
|
+
this.spans ??= this.rawCodeSpans.map((span) => {
|
|
914
|
+
const lower = toPosixPath(span).toLowerCase();
|
|
915
|
+
return { lower, parts: lower.split(/[/:.#\s]/).filter(Boolean) };
|
|
916
|
+
});
|
|
917
|
+
return this.spans;
|
|
918
|
+
}
|
|
919
|
+
get entry() {
|
|
920
|
+
this.prepared ??= buildSceneIndexedDoc(this);
|
|
921
|
+
return this.prepared;
|
|
922
|
+
}
|
|
923
|
+
get hasChartEvidence() {
|
|
924
|
+
this.chartEvidence ??=
|
|
925
|
+
!!this.scene.frontmatter.anchors?.some((anchor) => anchor.kind === "figure") ||
|
|
926
|
+
/\b(?:dollars?|units?) in (?:millions?|billions?|thousands?)\b/.test(this.entry.doc.tier34GateLower);
|
|
927
|
+
return this.chartEvidence;
|
|
928
|
+
}
|
|
929
|
+
}
|
|
930
|
+
function buildSceneIndexedDoc(row) {
|
|
931
|
+
const { scene, normalize, id: idLower, shortId: shortIdLower, title: titleLower, aliases: aliasesLower, body: bodyLower, rawSources: rawSnippetSources, details: detailBodySourcesLower, chains: chainTermsRaw, repoRaw: repoTermsRaw, sourceRaw: sourceTermsAllRaw, } = row;
|
|
932
|
+
const repoNames = scene.frontmatter.repositories.map((repo) => repo.repo);
|
|
933
|
+
const sourceNames = scene.frontmatter.sources?.map((source) => source.source) ?? EMPTY_LIST;
|
|
934
|
+
const chainEntries = scene.chains.map((chain) => {
|
|
935
|
+
const terms = chainTerms(chain);
|
|
936
|
+
let keys;
|
|
937
|
+
let body;
|
|
938
|
+
return {
|
|
939
|
+
title: chain.title,
|
|
940
|
+
termsLower: terms.map((term) => term.toLowerCase()),
|
|
941
|
+
get bodyLower() {
|
|
942
|
+
body ??= chain.markdown.toLowerCase();
|
|
943
|
+
return body;
|
|
944
|
+
},
|
|
945
|
+
get designators() {
|
|
946
|
+
keys ??= collectDesignatorsFromStrings([...terms, chain.markdown]);
|
|
947
|
+
return keys;
|
|
948
|
+
},
|
|
949
|
+
};
|
|
950
|
+
});
|
|
951
|
+
const detailEntries = scene.details.map((detail, idx) => {
|
|
952
|
+
let keys;
|
|
953
|
+
return {
|
|
954
|
+
name: detail.name,
|
|
955
|
+
nameLower: detail.name.toLowerCase(),
|
|
956
|
+
titleLower: detail.title.toLowerCase(),
|
|
957
|
+
contentLower: row.details[idx],
|
|
958
|
+
get designators() {
|
|
959
|
+
keys ??= collectDesignatorsFromStrings([detail.content, detail.name, detail.title]);
|
|
960
|
+
return keys;
|
|
961
|
+
},
|
|
962
|
+
};
|
|
963
|
+
});
|
|
964
|
+
const anchorEntries = (scene.frontmatter.anchors ?? EMPTY_LIST).map((anchor) => {
|
|
965
|
+
let keys;
|
|
966
|
+
const raw = collectAnchorSearchStrings(anchor);
|
|
967
|
+
return {
|
|
968
|
+
anchor,
|
|
969
|
+
summary: toMatchedAnchorSummary(anchor),
|
|
970
|
+
terms: raw.map(toPathTerm),
|
|
971
|
+
get designators() {
|
|
972
|
+
keys ??= collectDesignatorsFromStrings(raw);
|
|
973
|
+
return keys;
|
|
974
|
+
},
|
|
975
|
+
};
|
|
976
|
+
});
|
|
977
|
+
const detailTitlesRaw = scene.details.flatMap((detail) => [detail.name, detail.title]);
|
|
978
|
+
const [anchorTerms = EMPTY_LIST, repoTerms = EMPTY_LIST, sourceTerms = EMPTY_LIST] = row.paths;
|
|
979
|
+
let tiers;
|
|
980
|
+
const signatures = new Map();
|
|
981
|
+
function readDesignators(signature) {
|
|
982
|
+
const rawByDesignator = new Map();
|
|
983
|
+
const collect = (strings) => strings.length
|
|
984
|
+
? collectDesignatorsFromStrings(strings, rawByDesignator, normalize, signature)
|
|
985
|
+
: EMPTY_DESIGNATORS;
|
|
986
|
+
const bodyDesig = collect([scene.content]);
|
|
987
|
+
const anchorDesig = anchorEntries.length ? new Set() : EMPTY_DESIGNATORS;
|
|
988
|
+
for (const detail of scene.details) {
|
|
989
|
+
const keys = collect([detail.content]);
|
|
990
|
+
for (const key of keys)
|
|
991
|
+
bodyDesig.add(key);
|
|
992
|
+
collect([detail.name, detail.title]);
|
|
993
|
+
}
|
|
994
|
+
for (const entry of anchorEntries) {
|
|
995
|
+
const keys = collect(collectAnchorSearchStrings(entry.anchor));
|
|
996
|
+
for (const key of keys)
|
|
997
|
+
anchorDesig.add(key);
|
|
998
|
+
}
|
|
999
|
+
const idDesig = collect([scene.id, scene.sceneId]);
|
|
1000
|
+
const titleDesig = collect([scene.frontmatter.title]);
|
|
1001
|
+
const aliasDesig = collect(scene.frontmatter.aliases);
|
|
1002
|
+
const chainDesig = collect(chainTermsRaw);
|
|
1003
|
+
const repoDesig = collect(repoTermsRaw);
|
|
1004
|
+
const sourceDesig = collect(sourceTermsAllRaw);
|
|
1005
|
+
const summaryDesig = scene.frontmatter.title === scene.frontmatter.summary
|
|
1006
|
+
? titleDesig
|
|
1007
|
+
: collect([scene.frontmatter.summary]);
|
|
1008
|
+
const headingDesig = collect(scene.headings);
|
|
1009
|
+
const detailTitleDesig = collect(detailTitlesRaw);
|
|
1010
|
+
const codeDesig = collect(row.rawCodeSpans);
|
|
1011
|
+
const allDesig = new Set([
|
|
1012
|
+
...idDesig,
|
|
1013
|
+
...titleDesig,
|
|
1014
|
+
...aliasDesig,
|
|
1015
|
+
...chainDesig,
|
|
1016
|
+
...anchorDesig,
|
|
1017
|
+
...repoDesig,
|
|
1018
|
+
...sourceDesig,
|
|
1019
|
+
...summaryDesig,
|
|
1020
|
+
...headingDesig,
|
|
1021
|
+
...detailTitleDesig,
|
|
1022
|
+
...codeDesig,
|
|
1023
|
+
...bodyDesig,
|
|
1024
|
+
]);
|
|
1025
|
+
return {
|
|
1026
|
+
id: idDesig,
|
|
1027
|
+
title: titleDesig,
|
|
1028
|
+
alias: aliasDesig,
|
|
1029
|
+
chain: chainDesig,
|
|
1030
|
+
anchor: anchorDesig,
|
|
1031
|
+
repo: repoDesig,
|
|
1032
|
+
source: sourceDesig,
|
|
1033
|
+
summary: summaryDesig,
|
|
1034
|
+
heading: headingDesig,
|
|
1035
|
+
detail: detailTitleDesig,
|
|
1036
|
+
scene: EMPTY_DESIGNATORS,
|
|
1037
|
+
code: codeDesig,
|
|
1038
|
+
body: bodyDesig,
|
|
1039
|
+
all: allDesig,
|
|
1040
|
+
rawByDesignator,
|
|
1041
|
+
};
|
|
1042
|
+
}
|
|
1043
|
+
return {
|
|
1044
|
+
scene,
|
|
1045
|
+
repoNames,
|
|
1046
|
+
sourceNames,
|
|
1047
|
+
chainNames: chainEntries.map((chain) => chain.title),
|
|
1048
|
+
doc: {
|
|
1049
|
+
idLower,
|
|
1050
|
+
idCollapsed: idLower.replace(/[^a-z0-9]+/g, ""),
|
|
1051
|
+
shortIdLower,
|
|
1052
|
+
shortIdCollapsed: shortIdLower.replace(/[^a-z0-9]+/g, ""),
|
|
1053
|
+
titleLower,
|
|
1054
|
+
titleCollapsed: titleLower.replace(/[^a-z0-9]+/g, ""),
|
|
1055
|
+
aliasesLower,
|
|
1056
|
+
chainTermsLower: chainEntries.flatMap((chain) => chain.termsLower),
|
|
1057
|
+
anchorTerms,
|
|
1058
|
+
repoTerms,
|
|
1059
|
+
sourceTerms,
|
|
1060
|
+
summaryLower: scene.frontmatter.summary.toLowerCase(),
|
|
1061
|
+
headingsLower: scene.headings.map((heading) => heading.toLowerCase()),
|
|
1062
|
+
detailTitlesLower: detailTitlesRaw.map((title) => title.toLowerCase()),
|
|
1063
|
+
childHighTermsLower: EMPTY_LIST,
|
|
1064
|
+
childAnchorTerms: EMPTY_LIST,
|
|
1065
|
+
childRepoTerms: EMPTY_LIST,
|
|
1066
|
+
childSourceTerms: EMPTY_LIST,
|
|
1067
|
+
childBodySourcesLower: EMPTY_LIST,
|
|
1068
|
+
get codeSpans() {
|
|
1069
|
+
return row.codeSpans;
|
|
1070
|
+
},
|
|
1071
|
+
bodySourcesLower: [bodyLower],
|
|
1072
|
+
detailBodySourcesLower,
|
|
1073
|
+
tier34GateLower: row.text.slice(row.identity.length + 1),
|
|
1074
|
+
allTextLower: row.text,
|
|
1075
|
+
reverseCandidatesLower: row.reverse,
|
|
1076
|
+
rawSnippetSources,
|
|
1077
|
+
designatorsFor(key) {
|
|
1078
|
+
if (tiers)
|
|
1079
|
+
return tiers;
|
|
1080
|
+
const signature = key.replace(/\D/g, "");
|
|
1081
|
+
const cached = signatures.get(signature);
|
|
1082
|
+
if (cached)
|
|
1083
|
+
return cached;
|
|
1084
|
+
if (signatures.size >= 3)
|
|
1085
|
+
return this.designators;
|
|
1086
|
+
const bucket = readDesignators(signature);
|
|
1087
|
+
signatures.set(signature, bucket);
|
|
1088
|
+
return bucket;
|
|
1089
|
+
},
|
|
1090
|
+
get designators() {
|
|
1091
|
+
tiers ??= readDesignators();
|
|
1092
|
+
signatures.clear();
|
|
1093
|
+
return tiers;
|
|
1094
|
+
},
|
|
1095
|
+
chainEntries,
|
|
1096
|
+
detailEntries,
|
|
1097
|
+
anchorEntries,
|
|
1098
|
+
},
|
|
1099
|
+
};
|
|
1100
|
+
}
|
|
1101
|
+
function buildDomainIndexedDoc(domain, sceneById) {
|
|
1102
|
+
const rawByDesignator = new Map();
|
|
1103
|
+
const childHighTermsLower = [];
|
|
1104
|
+
const childAnchorTerms = [];
|
|
1105
|
+
const childRepoTerms = [];
|
|
1106
|
+
const childSourceTerms = [];
|
|
1107
|
+
const childBodySourcesLower = [];
|
|
1108
|
+
const rawSnippetSources = [domain.content];
|
|
1109
|
+
const domainRawCodeSpans = extractInlineCodeSpans(domain.content);
|
|
1110
|
+
const codeSpans = domainRawCodeSpans.map((span) => {
|
|
1111
|
+
const lower = toPosixPath(span).toLowerCase();
|
|
1112
|
+
return {
|
|
1113
|
+
lower,
|
|
1114
|
+
parts: lower.split(/[/:.#\s]/).filter(Boolean),
|
|
1115
|
+
};
|
|
1116
|
+
});
|
|
1117
|
+
const sceneDesig = new Set();
|
|
1118
|
+
const childAnchorDesig = new Set();
|
|
1119
|
+
const childRepoDesig = new Set();
|
|
1120
|
+
const childSourceDesig = new Set();
|
|
1121
|
+
const childBodyDesig = new Set();
|
|
1122
|
+
const codeDesig = collectDesignatorsFromStrings(domainRawCodeSpans, rawByDesignator);
|
|
1123
|
+
for (const sceneId of domain.sceneIds) {
|
|
1124
|
+
const prepScene = sceneById.get(sceneId);
|
|
1125
|
+
if (!prepScene) {
|
|
1126
|
+
continue;
|
|
1127
|
+
}
|
|
1128
|
+
const sDoc = prepScene.entry.doc;
|
|
1129
|
+
if (sDoc.shortIdLower) {
|
|
1130
|
+
childHighTermsLower.push(sDoc.shortIdLower);
|
|
1131
|
+
}
|
|
1132
|
+
childHighTermsLower.push(sDoc.titleLower, ...sDoc.aliasesLower, sDoc.summaryLower, ...sDoc.headingsLower, ...sDoc.chainTermsLower, ...sDoc.detailTitlesLower);
|
|
1133
|
+
childAnchorTerms.push(...sDoc.anchorTerms);
|
|
1134
|
+
childRepoTerms.push(...sDoc.repoTerms);
|
|
1135
|
+
childSourceTerms.push(...sDoc.sourceTerms);
|
|
1136
|
+
codeSpans.push(...sDoc.codeSpans);
|
|
1137
|
+
childBodySourcesLower.push(...sDoc.bodySourcesLower, ...sDoc.detailBodySourcesLower);
|
|
1138
|
+
rawSnippetSources.push(...sDoc.rawSnippetSources);
|
|
1139
|
+
for (const d of [
|
|
1140
|
+
...sDoc.designators.id,
|
|
1141
|
+
...sDoc.designators.title,
|
|
1142
|
+
...sDoc.designators.alias,
|
|
1143
|
+
...sDoc.designators.summary,
|
|
1144
|
+
...sDoc.designators.heading,
|
|
1145
|
+
...sDoc.designators.chain,
|
|
1146
|
+
...sDoc.designators.detail,
|
|
1147
|
+
]) {
|
|
1148
|
+
sceneDesig.add(d);
|
|
1149
|
+
const raw = sDoc.designators.rawByDesignator.get(d);
|
|
1150
|
+
if (raw && !rawByDesignator.has(d)) {
|
|
1151
|
+
rawByDesignator.set(d, raw);
|
|
1152
|
+
}
|
|
1153
|
+
}
|
|
1154
|
+
for (const d of sDoc.designators.anchor) {
|
|
1155
|
+
childAnchorDesig.add(d);
|
|
1156
|
+
const raw = sDoc.designators.rawByDesignator.get(d);
|
|
1157
|
+
if (raw && !rawByDesignator.has(d)) {
|
|
1158
|
+
rawByDesignator.set(d, raw);
|
|
1159
|
+
}
|
|
1160
|
+
}
|
|
1161
|
+
for (const d of sDoc.designators.repo) {
|
|
1162
|
+
childRepoDesig.add(d);
|
|
1163
|
+
}
|
|
1164
|
+
for (const d of sDoc.designators.source) {
|
|
1165
|
+
childSourceDesig.add(d);
|
|
1166
|
+
}
|
|
1167
|
+
for (const d of sDoc.designators.code) {
|
|
1168
|
+
codeDesig.add(d);
|
|
1169
|
+
const raw = sDoc.designators.rawByDesignator.get(d);
|
|
1170
|
+
if (raw && !rawByDesignator.has(d)) {
|
|
1171
|
+
rawByDesignator.set(d, raw);
|
|
1172
|
+
}
|
|
1173
|
+
}
|
|
1174
|
+
for (const d of sDoc.designators.body) {
|
|
1175
|
+
childBodyDesig.add(d);
|
|
1176
|
+
const raw = sDoc.designators.rawByDesignator.get(d);
|
|
1177
|
+
if (raw && !rawByDesignator.has(d)) {
|
|
1178
|
+
rawByDesignator.set(d, raw);
|
|
1179
|
+
}
|
|
1180
|
+
}
|
|
1181
|
+
}
|
|
1182
|
+
const idLower = domain.domainId.toLowerCase();
|
|
1183
|
+
const titleLower = domain.frontmatter.title.toLowerCase();
|
|
1184
|
+
const aliasesLower = domain.frontmatter.aliases.map((a) => a.toLowerCase());
|
|
1185
|
+
const summaryLower = domain.frontmatter.summary.toLowerCase();
|
|
1186
|
+
const headingsLower = domain.headings.map((h) => h.toLowerCase());
|
|
1187
|
+
const domainBodyLower = domain.content.toLowerCase();
|
|
1188
|
+
const tier34GateLower = [
|
|
1189
|
+
summaryLower,
|
|
1190
|
+
...headingsLower,
|
|
1191
|
+
...codeSpans.map((c) => c.lower),
|
|
1192
|
+
domainBodyLower,
|
|
1193
|
+
...childBodySourcesLower,
|
|
1194
|
+
].join("\n");
|
|
1195
|
+
const allTextLower = [
|
|
1196
|
+
idLower,
|
|
1197
|
+
titleLower,
|
|
1198
|
+
...aliasesLower,
|
|
1199
|
+
...childHighTermsLower,
|
|
1200
|
+
...childAnchorTerms.map((a) => a.lower),
|
|
1201
|
+
...childRepoTerms.map((r) => r.lower),
|
|
1202
|
+
...childSourceTerms.map((s) => s.lower),
|
|
1203
|
+
tier34GateLower,
|
|
1204
|
+
].join("\n");
|
|
1205
|
+
const idDesig = collectDesignatorsFromStrings([domain.domainId], rawByDesignator);
|
|
1206
|
+
const titleDesig = collectDesignatorsFromStrings([domain.frontmatter.title], rawByDesignator);
|
|
1207
|
+
const aliasDesig = collectDesignatorsFromStrings(domain.frontmatter.aliases, rawByDesignator);
|
|
1208
|
+
const summaryDesig = collectDesignatorsFromStrings([domain.frontmatter.summary], rawByDesignator);
|
|
1209
|
+
const headingDesig = collectDesignatorsFromStrings(domain.headings, rawByDesignator);
|
|
1210
|
+
const domainBodyDesig = collectDesignatorsFromStrings([domain.content], rawByDesignator);
|
|
1211
|
+
for (const d of domainBodyDesig) {
|
|
1212
|
+
childBodyDesig.add(d);
|
|
1213
|
+
}
|
|
1214
|
+
const emptySet = new Set();
|
|
1215
|
+
const allDesig = new Set([
|
|
1216
|
+
...idDesig,
|
|
1217
|
+
...titleDesig,
|
|
1218
|
+
...aliasDesig,
|
|
1219
|
+
...summaryDesig,
|
|
1220
|
+
...headingDesig,
|
|
1221
|
+
...sceneDesig,
|
|
1222
|
+
...childAnchorDesig,
|
|
1223
|
+
...childRepoDesig,
|
|
1224
|
+
...childSourceDesig,
|
|
1225
|
+
...codeDesig,
|
|
1226
|
+
...childBodyDesig,
|
|
1227
|
+
]);
|
|
1228
|
+
const reverseCandidatesLower = Array.from(new Set([
|
|
1229
|
+
...(titleLower.length >= 2 ? [titleLower] : []),
|
|
1230
|
+
...aliasesLower.filter((a) => a.length >= 2),
|
|
1231
|
+
...childHighTermsLower.filter((c) => c.length >= 2),
|
|
1232
|
+
]));
|
|
1233
|
+
return {
|
|
1234
|
+
domain,
|
|
1235
|
+
doc: {
|
|
1236
|
+
idLower,
|
|
1237
|
+
idCollapsed: idLower.replace(/[^a-z0-9]+/g, ""),
|
|
1238
|
+
titleLower,
|
|
1239
|
+
titleCollapsed: titleLower.replace(/[^a-z0-9]+/g, ""),
|
|
1240
|
+
aliasesLower,
|
|
1241
|
+
chainTermsLower: [],
|
|
1242
|
+
anchorTerms: [],
|
|
1243
|
+
repoTerms: [],
|
|
1244
|
+
sourceTerms: [],
|
|
1245
|
+
summaryLower,
|
|
1246
|
+
headingsLower,
|
|
1247
|
+
detailTitlesLower: [],
|
|
1248
|
+
childHighTermsLower,
|
|
1249
|
+
childAnchorTerms,
|
|
1250
|
+
childRepoTerms,
|
|
1251
|
+
childSourceTerms,
|
|
1252
|
+
childBodySourcesLower,
|
|
1253
|
+
codeSpans,
|
|
1254
|
+
bodySourcesLower: [domainBodyLower],
|
|
1255
|
+
detailBodySourcesLower: [],
|
|
1256
|
+
tier34GateLower,
|
|
1257
|
+
allTextLower,
|
|
1258
|
+
reverseCandidatesLower,
|
|
1259
|
+
rawSnippetSources,
|
|
1260
|
+
designators: {
|
|
1261
|
+
id: idDesig,
|
|
1262
|
+
title: titleDesig,
|
|
1263
|
+
alias: aliasDesig,
|
|
1264
|
+
chain: emptySet,
|
|
1265
|
+
anchor: childAnchorDesig,
|
|
1266
|
+
repo: childRepoDesig,
|
|
1267
|
+
source: childSourceDesig,
|
|
1268
|
+
summary: summaryDesig,
|
|
1269
|
+
heading: headingDesig,
|
|
1270
|
+
detail: emptySet,
|
|
1271
|
+
scene: sceneDesig,
|
|
1272
|
+
code: codeDesig,
|
|
1273
|
+
body: childBodyDesig,
|
|
1274
|
+
all: allDesig,
|
|
1275
|
+
rawByDesignator,
|
|
1276
|
+
},
|
|
1277
|
+
},
|
|
1278
|
+
};
|
|
1279
|
+
}
|
|
1280
|
+
function post(postings, key, row) {
|
|
1281
|
+
const rows = postings.get(key);
|
|
1282
|
+
if (!rows)
|
|
1283
|
+
postings.set(key, [row]);
|
|
1284
|
+
else if (rows[rows.length - 1] !== row)
|
|
1285
|
+
rows.push(row);
|
|
1286
|
+
}
|
|
1287
|
+
function indexCjk(index, text, row) {
|
|
1288
|
+
if (!CJK_CHAR_REGEX.test(text))
|
|
1289
|
+
return;
|
|
1290
|
+
for (const [run] of text.matchAll(/[\u3400-\u9fff\uf900-\ufaff]+/g)) {
|
|
1291
|
+
for (let offset = 0; offset < run.length; offset++) {
|
|
1292
|
+
post(index.cjkCharacters, run[offset], row);
|
|
1293
|
+
if (offset)
|
|
1294
|
+
post(index.cjkBigramPostings, run.slice(offset - 1, offset + 1), row);
|
|
1295
|
+
}
|
|
1296
|
+
}
|
|
1297
|
+
}
|
|
1298
|
+
function getPrecomputedWikiIndex(wiki) {
|
|
1299
|
+
const cached = WIKI_INDEX_CACHE.get(wiki);
|
|
1300
|
+
if (cached &&
|
|
1301
|
+
cached.domainCount === wiki.domains.size &&
|
|
1302
|
+
cached.sceneCount === wiki.scenes.size) {
|
|
1303
|
+
return cached;
|
|
1304
|
+
}
|
|
1305
|
+
const sceneById = new Map();
|
|
1306
|
+
const scenes = [];
|
|
1307
|
+
const index = {
|
|
1308
|
+
domainCount: wiki.domains.size,
|
|
1309
|
+
sceneCount: wiki.scenes.size,
|
|
1310
|
+
scenes,
|
|
1311
|
+
sceneById,
|
|
1312
|
+
cjkBigramPostings: new Map(),
|
|
1313
|
+
designatorPostings: new Map(),
|
|
1314
|
+
reversePostings: new Map(),
|
|
1315
|
+
collapsedPostings: new Map(),
|
|
1316
|
+
cjkCharacters: new Map(),
|
|
1317
|
+
termPostings: new Map(),
|
|
1318
|
+
reverseLengths: new Map(),
|
|
1319
|
+
fieldBounds: new Map(),
|
|
1320
|
+
};
|
|
1321
|
+
const canonical = new Map();
|
|
1322
|
+
const normalize = (raw) => {
|
|
1323
|
+
if (!canonical.has(raw)) {
|
|
1324
|
+
if (canonical.size >= 8192)
|
|
1325
|
+
canonical.clear();
|
|
1326
|
+
canonical.set(raw, normalizeDesignatorToken(raw));
|
|
1327
|
+
}
|
|
1328
|
+
return canonical.get(raw);
|
|
1329
|
+
};
|
|
1330
|
+
for (const scene of wiki.scenes.values()) {
|
|
1331
|
+
const row = scenes.length;
|
|
1332
|
+
const prep = new SceneSearchRow(scene, normalize);
|
|
1333
|
+
scenes.push(prep);
|
|
1334
|
+
sceneById.set(scene.id, prep);
|
|
1335
|
+
indexCjk(index, prep.structured, row);
|
|
1336
|
+
indexCjk(index, prep.body, row);
|
|
1337
|
+
for (const text of prep.details)
|
|
1338
|
+
indexCjk(index, text, row);
|
|
1339
|
+
for (const key of prep.reverse)
|
|
1340
|
+
post(index.reversePostings, key, row);
|
|
1341
|
+
post(index.collapsedPostings, prep.shortId.replace(/[^a-z0-9]+/g, ""), row);
|
|
1342
|
+
post(index.collapsedPostings, prep.title.replace(/[^a-z0-9]+/g, ""), row);
|
|
1343
|
+
}
|
|
1344
|
+
for (const key of index.reversePostings.keys()) {
|
|
1345
|
+
const first = key.slice(0, 2);
|
|
1346
|
+
let lengths = index.reverseLengths.get(first);
|
|
1347
|
+
if (!lengths) {
|
|
1348
|
+
lengths = new Set();
|
|
1349
|
+
index.reverseLengths.set(first, lengths);
|
|
1350
|
+
}
|
|
1351
|
+
lengths.add(key.length);
|
|
1352
|
+
}
|
|
1353
|
+
WIKI_INDEX_CACHE.set(wiki, index);
|
|
1354
|
+
return index;
|
|
1355
|
+
}
|
|
1356
|
+
function getPrecomputedDomains(wiki, index) {
|
|
1357
|
+
if (index.domains) {
|
|
1358
|
+
return index.domains;
|
|
1359
|
+
}
|
|
1360
|
+
const domains = [];
|
|
1361
|
+
for (const domain of wiki.domains.values()) {
|
|
1362
|
+
domains.push(buildDomainIndexedDoc(domain, index.sceneById));
|
|
1363
|
+
}
|
|
1364
|
+
index.domains = domains;
|
|
1365
|
+
return domains;
|
|
1366
|
+
}
|
|
1367
|
+
function cacheTermRows(index, term, rows) {
|
|
1368
|
+
if (index.termPostings.size >= 8192)
|
|
1369
|
+
index.termPostings.delete(index.termPostings.keys().next().value);
|
|
1370
|
+
index.termPostings.set(term, rows);
|
|
1371
|
+
}
|
|
1372
|
+
function numericProbes(canonical) {
|
|
1373
|
+
const pair = /\d[a-z0-9]/.exec(canonical)?.[0];
|
|
1374
|
+
return pair ? [pair, ...["-", ".", "/"].map((sep) => pair[0] + sep + pair[1])] : [];
|
|
1375
|
+
}
|
|
1376
|
+
function collectQueryPostings(index, groups) {
|
|
1377
|
+
const missing = new Set();
|
|
1378
|
+
for (const group of groups) {
|
|
1379
|
+
for (const term of [group.primary, group.rawToken, ...(group.subTokens ?? EMPTY_LIST)])
|
|
1380
|
+
if (term &&
|
|
1381
|
+
term.length >= 2 &&
|
|
1382
|
+
term.length <= 128 &&
|
|
1383
|
+
!term.includes("\n") &&
|
|
1384
|
+
!CJK_CHAR_REGEX.test(term) &&
|
|
1385
|
+
!index.termPostings.has(term))
|
|
1386
|
+
missing.add(term);
|
|
1387
|
+
for (const canonical of group.designators ?? EMPTY_LIST)
|
|
1388
|
+
if (!index.designatorPostings.has(canonical))
|
|
1389
|
+
for (const probe of numericProbes(canonical))
|
|
1390
|
+
if (!index.termPostings.has(probe))
|
|
1391
|
+
missing.add(probe);
|
|
1392
|
+
}
|
|
1393
|
+
if (missing.size < 4 || missing.size > 32)
|
|
1394
|
+
return;
|
|
1395
|
+
const terms = [...missing];
|
|
1396
|
+
const postings = terms.map(() => []);
|
|
1397
|
+
const frequencies = new Uint16Array(128 * 128);
|
|
1398
|
+
const pairAt = (text, at) => ((text.charCodeAt(at) & 127) << 7) | (text.charCodeAt(at + 1) & 127);
|
|
1399
|
+
const step = Math.max(1, Math.ceil(index.sceneCount / 16));
|
|
1400
|
+
for (let row = 0; row < index.sceneCount; row += step) {
|
|
1401
|
+
const text = index.scenes[row].body;
|
|
1402
|
+
const end = Math.min(1024, text.length - 1);
|
|
1403
|
+
for (let at = 0; at < end; at++)
|
|
1404
|
+
frequencies[pairAt(text, at)]++;
|
|
1405
|
+
}
|
|
1406
|
+
const masks = new Int32Array(frequencies.length);
|
|
1407
|
+
const offsets = terms.map((term, idx) => {
|
|
1408
|
+
let rarest = 0;
|
|
1409
|
+
for (let at = 1; at < term.length - 1; at++) {
|
|
1410
|
+
if (frequencies[pairAt(term, at)] < frequencies[pairAt(term, rarest)])
|
|
1411
|
+
rarest = at;
|
|
1412
|
+
}
|
|
1413
|
+
masks[pairAt(term, rarest)] |= 1 << idx;
|
|
1414
|
+
return rarest;
|
|
1415
|
+
});
|
|
1416
|
+
function scan(text, found) {
|
|
1417
|
+
let previous = text.charCodeAt(0) & 127;
|
|
1418
|
+
for (let at = 1; at < text.length; at++) {
|
|
1419
|
+
const current = text.charCodeAt(at) & 127;
|
|
1420
|
+
let candidates = masks[(previous << 7) | current] & ~found;
|
|
1421
|
+
previous = current;
|
|
1422
|
+
while (candidates) {
|
|
1423
|
+
const bit = candidates & -candidates;
|
|
1424
|
+
const idx = 31 - Math.clz32(bit);
|
|
1425
|
+
const start = at - 1 - offsets[idx];
|
|
1426
|
+
if (start >= 0 && text.startsWith(terms[idx], start))
|
|
1427
|
+
found |= bit;
|
|
1428
|
+
candidates ^= bit;
|
|
1429
|
+
}
|
|
1430
|
+
}
|
|
1431
|
+
return found;
|
|
1432
|
+
}
|
|
1433
|
+
for (let row = 0; row < index.sceneCount; row++) {
|
|
1434
|
+
const scene = index.scenes[row];
|
|
1435
|
+
let found = scan(scene.body, scan(scene.structured, 0));
|
|
1436
|
+
for (const text of scene.details)
|
|
1437
|
+
found = scan(text, found);
|
|
1438
|
+
if (scene.hasCode)
|
|
1439
|
+
for (const span of scene.codeSpans)
|
|
1440
|
+
found = scan(span.lower, found);
|
|
1441
|
+
while (found) {
|
|
1442
|
+
const bit = found & -found;
|
|
1443
|
+
postings[31 - Math.clz32(bit)].push(row);
|
|
1444
|
+
found ^= bit;
|
|
1445
|
+
}
|
|
1446
|
+
}
|
|
1447
|
+
for (const [idx, term] of terms.entries())
|
|
1448
|
+
cacheTermRows(index, term, postings[idx]);
|
|
1449
|
+
}
|
|
1450
|
+
function termRows(index, term) {
|
|
1451
|
+
const cached = index.termPostings.get(term);
|
|
1452
|
+
if (cached)
|
|
1453
|
+
return cached;
|
|
1454
|
+
let candidates;
|
|
1455
|
+
for (const [run] of term.matchAll(/[\u3400-\u9fff\uf900-\ufaff]+/g)) {
|
|
1456
|
+
const chars = index.cjkCharacters.get(run[0]);
|
|
1457
|
+
if (!chars)
|
|
1458
|
+
return [];
|
|
1459
|
+
if (term.length === 1)
|
|
1460
|
+
return chars;
|
|
1461
|
+
if (!candidates || chars.length < candidates.length)
|
|
1462
|
+
candidates = chars;
|
|
1463
|
+
for (let offset = 1; offset < run.length; offset++) {
|
|
1464
|
+
const rows = index.cjkBigramPostings.get(run.slice(offset - 1, offset + 1));
|
|
1465
|
+
if (!rows)
|
|
1466
|
+
return [];
|
|
1467
|
+
if (term.length === 2)
|
|
1468
|
+
return rows;
|
|
1469
|
+
if (!candidates || rows.length < candidates.length)
|
|
1470
|
+
candidates = rows;
|
|
1471
|
+
}
|
|
1472
|
+
}
|
|
1473
|
+
for (const [part] of term.matchAll(/[a-z0-9]{2,}/g)) {
|
|
1474
|
+
const rows = index.termPostings.get(part);
|
|
1475
|
+
if (rows && (!candidates || rows.length < candidates.length))
|
|
1476
|
+
candidates = rows;
|
|
1477
|
+
}
|
|
1478
|
+
const matches = [];
|
|
1479
|
+
if (candidates) {
|
|
1480
|
+
for (const row of candidates)
|
|
1481
|
+
if (index.scenes[row].contains(term))
|
|
1482
|
+
matches.push(row);
|
|
1483
|
+
}
|
|
1484
|
+
else {
|
|
1485
|
+
for (let row = 0; row < index.scenes.length; row++)
|
|
1486
|
+
if (index.scenes[row].contains(term))
|
|
1487
|
+
matches.push(row);
|
|
1488
|
+
}
|
|
1489
|
+
cacheTermRows(index, term, matches);
|
|
1490
|
+
return matches;
|
|
1491
|
+
}
|
|
1492
|
+
function fieldBounds(index, term) {
|
|
1493
|
+
const prior = index.fieldBounds.get(term);
|
|
1494
|
+
if (prior)
|
|
1495
|
+
return prior;
|
|
1496
|
+
const bounds = new Uint8Array(index.sceneCount);
|
|
1497
|
+
for (const row of termRows(index, term)) {
|
|
1498
|
+
const doc = index.scenes[row];
|
|
1499
|
+
bounds[row] =
|
|
1500
|
+
doc.id === term || doc.shortId === term || doc.title === term || doc.aliases.includes(term)
|
|
1501
|
+
? 120
|
|
1502
|
+
: doc.identity.includes(term)
|
|
1503
|
+
? 95
|
|
1504
|
+
: doc.structured.includes(term) || doc.codeSpans.some((span) => span.lower.includes(term))
|
|
1505
|
+
? 62
|
|
1506
|
+
: 16;
|
|
1507
|
+
}
|
|
1508
|
+
if (index.fieldBounds.size >= 128)
|
|
1509
|
+
index.fieldBounds.delete(index.fieldBounds.keys().next().value);
|
|
1510
|
+
index.fieldBounds.set(term, bounds);
|
|
1511
|
+
return bounds;
|
|
1512
|
+
}
|
|
1513
|
+
function getSceneTermDf(index, term) {
|
|
1514
|
+
return termRows(index, term).length;
|
|
1515
|
+
}
|
|
1516
|
+
function designatorRows(index, canonical) {
|
|
1517
|
+
const cached = index.designatorPostings.get(canonical);
|
|
1518
|
+
if (cached)
|
|
1519
|
+
return cached;
|
|
1520
|
+
const possible = new RegExp([...canonical].join("[ \\t./_-]*"));
|
|
1521
|
+
const rows = new Map();
|
|
1522
|
+
const probes = numericProbes(canonical).map((probe) => index.termPostings.get(probe));
|
|
1523
|
+
const candidates = probes.length && probes.every((posting) => posting !== undefined)
|
|
1524
|
+
? new Set(probes.flat())
|
|
1525
|
+
: index.scenes.keys();
|
|
1526
|
+
for (const row of candidates) {
|
|
1527
|
+
const doc = index.scenes[row];
|
|
1528
|
+
if (!possible.test(doc.text)) {
|
|
1529
|
+
const masked = maskRemotes(doc.text);
|
|
1530
|
+
if (masked === doc.text || !possible.test(masked))
|
|
1531
|
+
continue;
|
|
1532
|
+
}
|
|
1533
|
+
const score = scoreDesignatorsAgainstDoc([canonical], doc.entry.doc).hit.bestScore;
|
|
1534
|
+
if (score)
|
|
1535
|
+
rows.set(row, score);
|
|
1536
|
+
}
|
|
1537
|
+
if (index.designatorPostings.size >= 8192)
|
|
1538
|
+
index.designatorPostings.delete(index.designatorPostings.keys().next().value);
|
|
1539
|
+
index.designatorPostings.set(canonical, rows);
|
|
1540
|
+
return rows;
|
|
1541
|
+
}
|
|
1542
|
+
function getSceneDesignatorDf(index, designator) {
|
|
1543
|
+
return designatorRows(index, designator).size;
|
|
1544
|
+
}
|
|
1545
|
+
const IDF_SCALING_MIN_SCENES = 8;
|
|
1546
|
+
function computeIdfProfileForGroup(index, group, scope) {
|
|
1547
|
+
const totalScenes = scope?.size ?? index.sceneCount;
|
|
1548
|
+
if (!scope && totalScenes < IDF_SCALING_MIN_SCENES) {
|
|
1549
|
+
return { multiplier: 1, docRatio: 0 };
|
|
1550
|
+
}
|
|
1551
|
+
const count = (rows) => scope ? rows.filter((row) => scope.has(row)).length : rows.length;
|
|
1552
|
+
let effectiveDf = count(termRows(index, group.primary));
|
|
1553
|
+
if (group.designators && group.designators.length > 0) {
|
|
1554
|
+
let minDesigDf = Number.POSITIVE_INFINITY;
|
|
1555
|
+
for (const d of group.designators) {
|
|
1556
|
+
const posting = designatorRows(index, d);
|
|
1557
|
+
const dDf = scope ? count([...posting.keys()]) : posting.size;
|
|
1558
|
+
if (dDf > 0 && dDf < minDesigDf) {
|
|
1559
|
+
minDesigDf = dDf;
|
|
1560
|
+
}
|
|
1561
|
+
}
|
|
1562
|
+
if (Number.isFinite(minDesigDf)) {
|
|
1563
|
+
effectiveDf = scope
|
|
1564
|
+
? Math.max(effectiveDf, minDesigDf)
|
|
1565
|
+
: effectiveDf > 0
|
|
1566
|
+
? Math.min(effectiveDf, minDesigDf)
|
|
1567
|
+
: minDesigDf;
|
|
1568
|
+
}
|
|
1569
|
+
}
|
|
1570
|
+
else if (effectiveDf === 0 && group.subTokens && group.subTokens.length >= 2) {
|
|
1571
|
+
// Upper-bound co-occurrence DF by the rarest required sub-token
|
|
1572
|
+
let minSubDf = Number.POSITIVE_INFINITY;
|
|
1573
|
+
for (const st of group.subTokens) {
|
|
1574
|
+
const sDf = count(termRows(index, st));
|
|
1575
|
+
if (sDf < minSubDf) {
|
|
1576
|
+
minSubDf = sDf;
|
|
1577
|
+
}
|
|
1578
|
+
}
|
|
1579
|
+
if (Number.isFinite(minSubDf)) {
|
|
1580
|
+
effectiveDf = minSubDf;
|
|
1581
|
+
}
|
|
1582
|
+
}
|
|
1583
|
+
const clampedDf = Math.max(1, effectiveDf);
|
|
1584
|
+
const docRatio = clampedDf / totalScenes;
|
|
1585
|
+
if (scope && (docRatio > 0.55 || docRatio <= 0.2))
|
|
1586
|
+
return { docRatio, multiplier: docRatio > 0.55 ? 0.24 : 2.0 };
|
|
1587
|
+
const normIdf = Math.log((totalScenes + 1) / (clampedDf + 0.5)) / Math.log(totalScenes + 1);
|
|
1588
|
+
let mult;
|
|
1589
|
+
if (docRatio > 0.4) {
|
|
1590
|
+
const t = Math.min(1, (docRatio - 0.4) / 0.6);
|
|
1591
|
+
mult = 0.62 - t * 0.27;
|
|
1592
|
+
}
|
|
1593
|
+
else {
|
|
1594
|
+
const scarcity = 1 - docRatio / 0.4;
|
|
1595
|
+
mult = 0.62 + 0.58 * scarcity + 1.0 * normIdf ** 1.35;
|
|
1596
|
+
}
|
|
1597
|
+
if (group.designators && group.designators.length > 0 && docRatio <= 0.25) {
|
|
1598
|
+
mult = Math.max(mult, 1.45);
|
|
1599
|
+
}
|
|
1600
|
+
return {
|
|
1601
|
+
multiplier: Math.max(0.35, Math.min(2.2, mult)),
|
|
1602
|
+
docRatio,
|
|
1603
|
+
};
|
|
1604
|
+
}
|
|
312
1605
|
const FIELD_DISPLAY_ORDER = [
|
|
313
1606
|
"id",
|
|
314
1607
|
"title",
|
|
@@ -316,6 +1609,7 @@ const FIELD_DISPLAY_ORDER = [
|
|
|
316
1609
|
"chain",
|
|
317
1610
|
"anchor",
|
|
318
1611
|
"repo",
|
|
1612
|
+
"source",
|
|
319
1613
|
"summary",
|
|
320
1614
|
"heading",
|
|
321
1615
|
"detail",
|
|
@@ -323,7 +1617,28 @@ const FIELD_DISPLAY_ORDER = [
|
|
|
323
1617
|
"code",
|
|
324
1618
|
"body",
|
|
325
1619
|
];
|
|
326
|
-
|
|
1620
|
+
const EMPTY_FIELD_SET = new Set();
|
|
1621
|
+
const EMPTY_HIT = {
|
|
1622
|
+
bestScore: 0,
|
|
1623
|
+
fields: EMPTY_FIELD_SET,
|
|
1624
|
+
matchedHigherThanBody: false,
|
|
1625
|
+
matchedCodeOrDetail: false,
|
|
1626
|
+
matchedBodyText: false,
|
|
1627
|
+
};
|
|
1628
|
+
function scoreTermAgainstDoc(term, doc, label) {
|
|
1629
|
+
if ((label && !label.test(doc.allTextLower)) ||
|
|
1630
|
+
(doc.shortIdCollapsed !== term &&
|
|
1631
|
+
doc.titleCollapsed !== term &&
|
|
1632
|
+
!doc.allTextLower.includes(term) &&
|
|
1633
|
+
!doc.reverseCandidatesLower.some((rc) => term.length > rc.length && term.includes(rc)))) {
|
|
1634
|
+
return {
|
|
1635
|
+
bestScore: 0,
|
|
1636
|
+
fields: EMPTY_FIELD_SET,
|
|
1637
|
+
matchedHigherThanBody: false,
|
|
1638
|
+
matchedCodeOrDetail: false,
|
|
1639
|
+
matchedBodyText: false,
|
|
1640
|
+
};
|
|
1641
|
+
}
|
|
327
1642
|
let best = 0;
|
|
328
1643
|
const fields = new Set();
|
|
329
1644
|
let matchedHigherThanBody = false;
|
|
@@ -346,9 +1661,9 @@ function scoreTermAgainstDoc(term, doc) {
|
|
|
346
1661
|
}
|
|
347
1662
|
}
|
|
348
1663
|
// Tier 1: id / shortId, title, aliases
|
|
349
|
-
const idLower = doc.
|
|
350
|
-
const shortIdLower = doc.
|
|
351
|
-
if (idLower === term || shortIdLower === term) {
|
|
1664
|
+
const idLower = doc.idLower;
|
|
1665
|
+
const shortIdLower = doc.shortIdLower;
|
|
1666
|
+
if (idLower === term || shortIdLower === term || doc.shortIdCollapsed === term) {
|
|
352
1667
|
record(120, "id", "high");
|
|
353
1668
|
}
|
|
354
1669
|
else if (idLower.startsWith(term) || shortIdLower?.startsWith(term)) {
|
|
@@ -360,8 +1675,8 @@ function scoreTermAgainstDoc(term, doc) {
|
|
|
360
1675
|
else if (shortIdLower && shortIdLower.length >= 3 && term.includes(shortIdLower)) {
|
|
361
1676
|
record(58, "id", "high");
|
|
362
1677
|
}
|
|
363
|
-
const titleLower = doc.
|
|
364
|
-
if (titleLower === term) {
|
|
1678
|
+
const titleLower = doc.titleLower;
|
|
1679
|
+
if (titleLower === term || doc.titleCollapsed === term) {
|
|
365
1680
|
record(115, "title", "high");
|
|
366
1681
|
}
|
|
367
1682
|
else if (titleLower.startsWith(term)) {
|
|
@@ -373,8 +1688,7 @@ function scoreTermAgainstDoc(term, doc) {
|
|
|
373
1688
|
else if (titleLower.length >= 2 && term.length >= 2 && term.includes(titleLower)) {
|
|
374
1689
|
record(58, "title", "high");
|
|
375
1690
|
}
|
|
376
|
-
for (const
|
|
377
|
-
const aliasLower = alias.toLowerCase();
|
|
1691
|
+
for (const aliasLower of doc.aliasesLower) {
|
|
378
1692
|
if (aliasLower === term) {
|
|
379
1693
|
record(110, "alias", "high");
|
|
380
1694
|
}
|
|
@@ -388,9 +1702,8 @@ function scoreTermAgainstDoc(term, doc) {
|
|
|
388
1702
|
record(56, "alias", "high");
|
|
389
1703
|
}
|
|
390
1704
|
}
|
|
391
|
-
// Tier 2: chainNames, anchors
|
|
392
|
-
for (const
|
|
393
|
-
const cLower = chainTerm.toLowerCase();
|
|
1705
|
+
// Tier 2: chainNames, anchors, repositories, sources
|
|
1706
|
+
for (const cLower of doc.chainTermsLower) {
|
|
394
1707
|
if (cLower === term) {
|
|
395
1708
|
record(95, "chain", "high");
|
|
396
1709
|
}
|
|
@@ -404,9 +1717,9 @@ function scoreTermAgainstDoc(term, doc) {
|
|
|
404
1717
|
record(46, "chain", "high");
|
|
405
1718
|
}
|
|
406
1719
|
}
|
|
407
|
-
for (const anchorTerm of doc.anchorTerms
|
|
408
|
-
const aLower =
|
|
409
|
-
const baseName =
|
|
1720
|
+
for (const anchorTerm of doc.anchorTerms) {
|
|
1721
|
+
const aLower = anchorTerm.lower;
|
|
1722
|
+
const baseName = anchorTerm.base;
|
|
410
1723
|
if (aLower === term || baseName === term) {
|
|
411
1724
|
record(92, "anchor", "high");
|
|
412
1725
|
}
|
|
@@ -420,9 +1733,9 @@ function scoreTermAgainstDoc(term, doc) {
|
|
|
420
1733
|
record(44, "anchor", "high");
|
|
421
1734
|
}
|
|
422
1735
|
}
|
|
423
|
-
for (const repoTerm of doc.repoTerms
|
|
424
|
-
const rLower =
|
|
425
|
-
const repoBase =
|
|
1736
|
+
for (const repoTerm of doc.repoTerms) {
|
|
1737
|
+
const rLower = repoTerm.lower;
|
|
1738
|
+
const repoBase = repoTerm.base;
|
|
426
1739
|
if (rLower === term || repoBase === term) {
|
|
427
1740
|
record(82, "repo", "high");
|
|
428
1741
|
}
|
|
@@ -433,34 +1746,21 @@ function scoreTermAgainstDoc(term, doc) {
|
|
|
433
1746
|
record(38, "repo", "high");
|
|
434
1747
|
}
|
|
435
1748
|
}
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
else if (summaryLower.includes(term)) {
|
|
442
|
-
record(36, "summary", "high");
|
|
443
|
-
}
|
|
444
|
-
for (const heading of doc.headings ?? []) {
|
|
445
|
-
const hLower = heading.toLowerCase();
|
|
446
|
-
if (hLower === term) {
|
|
447
|
-
record(56, "heading", "high");
|
|
448
|
-
}
|
|
449
|
-
else if (hLower.includes(term)) {
|
|
450
|
-
record(34, "heading", "high");
|
|
1749
|
+
for (const srcTerm of doc.sourceTerms) {
|
|
1750
|
+
const sLower = srcTerm.lower;
|
|
1751
|
+
const srcBase = srcTerm.base;
|
|
1752
|
+
if (sLower === term || srcBase === term) {
|
|
1753
|
+
record(82, "source", "high");
|
|
451
1754
|
}
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
const dLower = dTitle.toLowerCase();
|
|
455
|
-
if (dLower === term) {
|
|
456
|
-
record(62, "detail", "high");
|
|
1755
|
+
else if (sLower.includes(term)) {
|
|
1756
|
+
record(44, "source", "high");
|
|
457
1757
|
}
|
|
458
|
-
else if (
|
|
459
|
-
record(38, "
|
|
1758
|
+
else if (srcBase.length >= 3 && term.includes(srcBase)) {
|
|
1759
|
+
record(38, "source", "high");
|
|
460
1760
|
}
|
|
461
1761
|
}
|
|
462
|
-
|
|
463
|
-
|
|
1762
|
+
// Domain child high-tier terms (include reverse substring check)
|
|
1763
|
+
for (const chLower of doc.childHighTermsLower) {
|
|
464
1764
|
if (chLower === term) {
|
|
465
1765
|
record(72, "scene", "high");
|
|
466
1766
|
}
|
|
@@ -474,54 +1774,81 @@ function scoreTermAgainstDoc(term, doc) {
|
|
|
474
1774
|
record(38, "scene", "high");
|
|
475
1775
|
}
|
|
476
1776
|
}
|
|
477
|
-
for (const chAnchor of doc.childAnchorTerms
|
|
478
|
-
|
|
479
|
-
const baseName = aLower.split("/").pop() ?? aLower;
|
|
480
|
-
if (aLower === term || baseName === term) {
|
|
1777
|
+
for (const chAnchor of doc.childAnchorTerms) {
|
|
1778
|
+
if (chAnchor.lower === term || chAnchor.base === term) {
|
|
481
1779
|
record(64, "anchor", "high");
|
|
482
1780
|
}
|
|
483
|
-
else if (
|
|
1781
|
+
else if (chAnchor.lower.includes(term)) {
|
|
484
1782
|
record(38, "anchor", "high");
|
|
485
1783
|
}
|
|
486
1784
|
}
|
|
487
|
-
for (const chRepo of doc.childRepoTerms
|
|
488
|
-
|
|
489
|
-
const repoBase = rLower.split("/").pop() ?? rLower;
|
|
490
|
-
if (rLower === term || repoBase === term) {
|
|
1785
|
+
for (const chRepo of doc.childRepoTerms) {
|
|
1786
|
+
if (chRepo.lower === term || chRepo.base === term) {
|
|
491
1787
|
record(58, "repo", "high");
|
|
492
1788
|
}
|
|
493
|
-
else if (
|
|
1789
|
+
else if (chRepo.lower.includes(term)) {
|
|
494
1790
|
record(34, "repo", "high");
|
|
495
1791
|
}
|
|
496
1792
|
}
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
|
|
1793
|
+
for (const chSrc of doc.childSourceTerms) {
|
|
1794
|
+
if (chSrc.lower === term || chSrc.base === term) {
|
|
1795
|
+
record(58, "source", "high");
|
|
1796
|
+
}
|
|
1797
|
+
else if (chSrc.lower.includes(term)) {
|
|
1798
|
+
record(34, "source", "high");
|
|
1799
|
+
}
|
|
1800
|
+
}
|
|
1801
|
+
// Tier 3 & Tier 4: gated by single O(1) pre-concatenated lowercase check
|
|
1802
|
+
if (doc.tier34GateLower.includes(term)) {
|
|
1803
|
+
const summaryLower = doc.summaryLower;
|
|
1804
|
+
if (summaryLower === term) {
|
|
1805
|
+
record(60, "summary", "high");
|
|
1806
|
+
}
|
|
1807
|
+
else if (summaryLower.includes(term)) {
|
|
1808
|
+
record(36, "summary", "high");
|
|
1809
|
+
}
|
|
1810
|
+
for (const hLower of doc.headingsLower) {
|
|
1811
|
+
if (hLower === term) {
|
|
1812
|
+
record(56, "heading", "high");
|
|
504
1813
|
}
|
|
505
|
-
else if (
|
|
506
|
-
record(
|
|
1814
|
+
else if (hLower.includes(term)) {
|
|
1815
|
+
record(34, "heading", "high");
|
|
507
1816
|
}
|
|
508
1817
|
}
|
|
509
|
-
for (const
|
|
510
|
-
if (
|
|
511
|
-
record(
|
|
512
|
-
break;
|
|
1818
|
+
for (const dLower of doc.detailTitlesLower) {
|
|
1819
|
+
if (dLower === term) {
|
|
1820
|
+
record(62, "detail", "high");
|
|
513
1821
|
}
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
if (dBody.toLowerCase().includes(term)) {
|
|
517
|
-
record(14, "detail", "code");
|
|
518
|
-
break;
|
|
1822
|
+
else if (dLower.includes(term)) {
|
|
1823
|
+
record(38, "detail", "high");
|
|
519
1824
|
}
|
|
520
1825
|
}
|
|
521
|
-
|
|
522
|
-
|
|
523
|
-
|
|
524
|
-
|
|
1826
|
+
if (term.length >= 2) {
|
|
1827
|
+
for (const span of doc.codeSpans) {
|
|
1828
|
+
if (span.lower === term || span.parts.includes(term)) {
|
|
1829
|
+
record(28, "code", "code");
|
|
1830
|
+
}
|
|
1831
|
+
else if (span.lower.includes(term)) {
|
|
1832
|
+
record(22, "code", "code");
|
|
1833
|
+
}
|
|
1834
|
+
}
|
|
1835
|
+
for (const bodyLower of doc.bodySourcesLower) {
|
|
1836
|
+
if (bodyLower.includes(term)) {
|
|
1837
|
+
record(16, "body", "body");
|
|
1838
|
+
break;
|
|
1839
|
+
}
|
|
1840
|
+
}
|
|
1841
|
+
for (const dBodyLower of doc.detailBodySourcesLower) {
|
|
1842
|
+
if (dBodyLower.includes(term)) {
|
|
1843
|
+
record(14, "detail", "code");
|
|
1844
|
+
break;
|
|
1845
|
+
}
|
|
1846
|
+
}
|
|
1847
|
+
for (const cBodyLower of doc.childBodySourcesLower) {
|
|
1848
|
+
if (cBodyLower.includes(term)) {
|
|
1849
|
+
record(12, "body", "body");
|
|
1850
|
+
break;
|
|
1851
|
+
}
|
|
525
1852
|
}
|
|
526
1853
|
}
|
|
527
1854
|
}
|
|
@@ -533,30 +1860,318 @@ function scoreTermAgainstDoc(term, doc) {
|
|
|
533
1860
|
matchedBodyText,
|
|
534
1861
|
};
|
|
535
1862
|
}
|
|
536
|
-
function
|
|
1863
|
+
function scoreDesignatorsAgainstDoc(designators, doc) {
|
|
1864
|
+
let best = 0;
|
|
1865
|
+
const fields = new Set();
|
|
1866
|
+
let matchedHigherThanBody = false;
|
|
1867
|
+
let matchedCodeOrDetail = false;
|
|
1868
|
+
let matchedBodyText = false;
|
|
1869
|
+
let matchedSnippetTerm;
|
|
1870
|
+
let tiers;
|
|
1871
|
+
function record(score, field, tier, d) {
|
|
1872
|
+
best = Math.max(best, score);
|
|
1873
|
+
fields.add(field);
|
|
1874
|
+
if (tier === "high") {
|
|
1875
|
+
matchedHigherThanBody = true;
|
|
1876
|
+
}
|
|
1877
|
+
else if (tier === "code") {
|
|
1878
|
+
matchedCodeOrDetail = true;
|
|
1879
|
+
matchedSnippetTerm ??= tiers.rawByDesignator.get(d);
|
|
1880
|
+
}
|
|
1881
|
+
else {
|
|
1882
|
+
matchedBodyText = true;
|
|
1883
|
+
matchedSnippetTerm ??= tiers.rawByDesignator.get(d);
|
|
1884
|
+
}
|
|
1885
|
+
}
|
|
1886
|
+
for (let idx = 0; idx < designators.length; idx++) {
|
|
1887
|
+
const d = designators[idx];
|
|
1888
|
+
tiers = doc.designatorsFor?.(d) ?? doc.designators;
|
|
1889
|
+
if (!tiers.all.has(d)) {
|
|
1890
|
+
continue;
|
|
1891
|
+
}
|
|
1892
|
+
// Slight discount only when matching a stripped sub-designator (e.g. `r44972` from `CRS-R44972`)
|
|
1893
|
+
const weight = idx === 0 ? 1 : 0.92;
|
|
1894
|
+
if (tiers.id.has(d)) {
|
|
1895
|
+
const idExact = doc.idCollapsed === d || doc.shortIdCollapsed === d;
|
|
1896
|
+
record(Math.round((idExact ? 115 : 66) * weight), "id", "high", d);
|
|
1897
|
+
}
|
|
1898
|
+
if (tiers.title.has(d)) {
|
|
1899
|
+
const titleExact = doc.titleCollapsed === d;
|
|
1900
|
+
record(Math.round((titleExact ? 112 : 78) * weight), "title", "high", d);
|
|
1901
|
+
}
|
|
1902
|
+
if (tiers.alias.has(d)) {
|
|
1903
|
+
record(Math.round(108 * weight), "alias", "high", d);
|
|
1904
|
+
}
|
|
1905
|
+
if (tiers.chain.has(d)) {
|
|
1906
|
+
record(Math.round(94 * weight), "chain", "high", d);
|
|
1907
|
+
}
|
|
1908
|
+
if (tiers.anchor.has(d)) {
|
|
1909
|
+
record(Math.round(92 * weight), "anchor", "high", d);
|
|
1910
|
+
}
|
|
1911
|
+
if (tiers.repo.has(d)) {
|
|
1912
|
+
record(Math.round(80 * weight), "repo", "high", d);
|
|
1913
|
+
}
|
|
1914
|
+
if (tiers.source.has(d)) {
|
|
1915
|
+
record(Math.round(80 * weight), "source", "high", d);
|
|
1916
|
+
}
|
|
1917
|
+
if (tiers.scene.has(d)) {
|
|
1918
|
+
record(Math.round(70 * weight), "scene", "high", d);
|
|
1919
|
+
}
|
|
1920
|
+
if (tiers.detail.has(d)) {
|
|
1921
|
+
record(Math.round(60 * weight), "detail", "high", d);
|
|
1922
|
+
}
|
|
1923
|
+
if (tiers.summary.has(d)) {
|
|
1924
|
+
record(Math.round(56 * weight), "summary", "high", d);
|
|
1925
|
+
}
|
|
1926
|
+
if (tiers.heading.has(d)) {
|
|
1927
|
+
record(Math.round(52 * weight), "heading", "high", d);
|
|
1928
|
+
}
|
|
1929
|
+
if (tiers.code.has(d)) {
|
|
1930
|
+
record(Math.round(48 * weight), "code", "code", d);
|
|
1931
|
+
}
|
|
1932
|
+
if (tiers.body.has(d)) {
|
|
1933
|
+
// Formal model/report designators in body tables/prose carry much stronger identity signal than casual words
|
|
1934
|
+
record(Math.round(46 * weight), "body", "body", d);
|
|
1935
|
+
}
|
|
1936
|
+
}
|
|
1937
|
+
return {
|
|
1938
|
+
hit: {
|
|
1939
|
+
bestScore: best,
|
|
1940
|
+
fields,
|
|
1941
|
+
matchedHigherThanBody,
|
|
1942
|
+
matchedCodeOrDetail,
|
|
1943
|
+
matchedBodyText,
|
|
1944
|
+
},
|
|
1945
|
+
...(matchedSnippetTerm ? { matchedSnippetTerm } : {}),
|
|
1946
|
+
};
|
|
1947
|
+
}
|
|
1948
|
+
function mergeTermHits(a, b) {
|
|
1949
|
+
if (b.bestScore === 0) {
|
|
1950
|
+
return a;
|
|
1951
|
+
}
|
|
1952
|
+
if (a.bestScore === 0) {
|
|
1953
|
+
return b;
|
|
1954
|
+
}
|
|
1955
|
+
const mergedFields = new Set([...a.fields, ...b.fields]);
|
|
1956
|
+
return {
|
|
1957
|
+
bestScore: Math.max(a.bestScore, b.bestScore),
|
|
1958
|
+
fields: mergedFields,
|
|
1959
|
+
matchedHigherThanBody: a.matchedHigherThanBody || b.matchedHigherThanBody,
|
|
1960
|
+
matchedCodeOrDetail: a.matchedCodeOrDetail || b.matchedCodeOrDetail,
|
|
1961
|
+
matchedBodyText: a.matchedBodyText || b.matchedBodyText,
|
|
1962
|
+
};
|
|
1963
|
+
}
|
|
1964
|
+
function pinpointSubSceneMatches(doc, pinpointTerms, pinpointDesignators) {
|
|
1965
|
+
const matchedChains = [];
|
|
1966
|
+
const matchedDetails = [];
|
|
1967
|
+
const matchedAnchors = [];
|
|
1968
|
+
if (pinpointTerms.length === 0 && pinpointDesignators.size === 0) {
|
|
1969
|
+
return { matchedChains, matchedDetails, matchedAnchors };
|
|
1970
|
+
}
|
|
1971
|
+
const usableTerms = pinpointTerms.filter((t) => t.length >= 2);
|
|
1972
|
+
for (const chain of doc.chainEntries ?? []) {
|
|
1973
|
+
let hit = false;
|
|
1974
|
+
for (const d of pinpointDesignators) {
|
|
1975
|
+
if (chain.designators.has(d)) {
|
|
1976
|
+
hit = true;
|
|
1977
|
+
break;
|
|
1978
|
+
}
|
|
1979
|
+
}
|
|
1980
|
+
if (!hit) {
|
|
1981
|
+
for (const term of usableTerms) {
|
|
1982
|
+
if (chain.termsLower.some((ct) => ct.includes(term) || (ct.length >= 3 && term.includes(ct))) ||
|
|
1983
|
+
chain.bodyLower.includes(term)) {
|
|
1984
|
+
hit = true;
|
|
1985
|
+
break;
|
|
1986
|
+
}
|
|
1987
|
+
}
|
|
1988
|
+
}
|
|
1989
|
+
if (hit) {
|
|
1990
|
+
matchedChains.push(chain.title);
|
|
1991
|
+
}
|
|
1992
|
+
}
|
|
1993
|
+
for (const detail of doc.detailEntries ?? []) {
|
|
1994
|
+
let hit = false;
|
|
1995
|
+
for (const d of pinpointDesignators) {
|
|
1996
|
+
if (detail.designators.has(d)) {
|
|
1997
|
+
hit = true;
|
|
1998
|
+
break;
|
|
1999
|
+
}
|
|
2000
|
+
}
|
|
2001
|
+
if (!hit) {
|
|
2002
|
+
for (const term of usableTerms) {
|
|
2003
|
+
if (detail.nameLower.includes(term) ||
|
|
2004
|
+
detail.titleLower.includes(term) ||
|
|
2005
|
+
detail.contentLower.includes(term)) {
|
|
2006
|
+
hit = true;
|
|
2007
|
+
break;
|
|
2008
|
+
}
|
|
2009
|
+
}
|
|
2010
|
+
}
|
|
2011
|
+
if (hit) {
|
|
2012
|
+
matchedDetails.push(detail.name);
|
|
2013
|
+
}
|
|
2014
|
+
}
|
|
2015
|
+
for (const ae of doc.anchorEntries ?? []) {
|
|
2016
|
+
let hit = false;
|
|
2017
|
+
for (const d of pinpointDesignators) {
|
|
2018
|
+
if (ae.designators.has(d)) {
|
|
2019
|
+
hit = true;
|
|
2020
|
+
break;
|
|
2021
|
+
}
|
|
2022
|
+
}
|
|
2023
|
+
if (!hit) {
|
|
2024
|
+
for (const term of usableTerms) {
|
|
2025
|
+
if (ae.terms.some((at) => at.lower.includes(term) ||
|
|
2026
|
+
at.base === term ||
|
|
2027
|
+
(at.base.length >= 3 && term.includes(at.base)))) {
|
|
2028
|
+
hit = true;
|
|
2029
|
+
break;
|
|
2030
|
+
}
|
|
2031
|
+
}
|
|
2032
|
+
}
|
|
2033
|
+
if (hit) {
|
|
2034
|
+
matchedAnchors.push(ae.summary);
|
|
2035
|
+
}
|
|
2036
|
+
}
|
|
2037
|
+
return { matchedChains, matchedDetails, matchedAnchors };
|
|
2038
|
+
}
|
|
2039
|
+
function buildPreparedQueryPlan(query, index, scope) {
|
|
537
2040
|
const tokenized = tokenizeDiscoveryQuery(query);
|
|
2041
|
+
collectQueryPostings(index, tokenized.groups);
|
|
2042
|
+
const corpusSize = scope?.size ?? index.sceneCount;
|
|
2043
|
+
const useCorpusIdf = !!scope || corpusSize >= IDF_SCALING_MIN_SCENES;
|
|
2044
|
+
const df = (term) => scope
|
|
2045
|
+
? termRows(index, term).filter((row) => scope.has(row)).length
|
|
2046
|
+
: getSceneTermDf(index, term);
|
|
2047
|
+
const groupIdf = tokenized.groups.map((g) => computeIdfProfileForGroup(index, g, scope));
|
|
2048
|
+
let phraseIdfMultiplier = 1;
|
|
2049
|
+
const selectiveBigrams = [];
|
|
2050
|
+
if (useCorpusIdf && tokenized.normalizedPhrase) {
|
|
2051
|
+
const phraseDf = Math.max(1, df(tokenized.normalizedPhrase));
|
|
2052
|
+
const phraseRatio = phraseDf / corpusSize;
|
|
2053
|
+
if (phraseRatio > 0.4) {
|
|
2054
|
+
phraseIdfMultiplier =
|
|
2055
|
+
scope && phraseRatio > 0.55
|
|
2056
|
+
? 0.24
|
|
2057
|
+
: Math.max(0.35, 0.62 - ((phraseRatio - 0.4) / 0.6) * 0.27);
|
|
2058
|
+
}
|
|
2059
|
+
else if (tokenized.groups.length === 1 && groupIdf[0]) {
|
|
2060
|
+
phraseIdfMultiplier = groupIdf[0].multiplier;
|
|
2061
|
+
}
|
|
2062
|
+
else {
|
|
2063
|
+
const avgMult = groupIdf.reduce((acc, g) => acc + g.multiplier, 0) / Math.max(1, groupIdf.length);
|
|
2064
|
+
phraseIdfMultiplier = Math.max(0.6, Math.min(2.2, avgMult));
|
|
2065
|
+
}
|
|
2066
|
+
// Extract selective adjacent non-designator 2-word concept phrases (e.g. "program performance", "bar charts")
|
|
2067
|
+
const seenPhrases = new Set();
|
|
2068
|
+
for (let i = 0; i < tokenized.groups.length - 1; i++) {
|
|
2069
|
+
const g1 = tokenized.groups[i];
|
|
2070
|
+
const g2 = tokenized.groups[i + 1];
|
|
2071
|
+
if (scope && groupIdf[i].docRatio > 0.55 && groupIdf[i + 1].docRatio > 0.55)
|
|
2072
|
+
continue;
|
|
2073
|
+
if (g1.designators?.length || g2.designators?.length) {
|
|
2074
|
+
continue;
|
|
2075
|
+
}
|
|
2076
|
+
const w1 = g1.primary;
|
|
2077
|
+
const w2 = g2.primary;
|
|
2078
|
+
if (w1.length < 2 || w2.length < 2 || isPureCjk(w1) || isPureCjk(w2)) {
|
|
2079
|
+
continue;
|
|
2080
|
+
}
|
|
2081
|
+
const phrase = `${w1} ${w2}`;
|
|
2082
|
+
if (seenPhrases.has(phrase)) {
|
|
2083
|
+
continue;
|
|
2084
|
+
}
|
|
2085
|
+
seenPhrases.add(phrase);
|
|
2086
|
+
const biDf = df(phrase);
|
|
2087
|
+
if (biDf > 0 && biDf / corpusSize <= 0.25) {
|
|
2088
|
+
const biScarcity = 1 - biDf / (corpusSize * 0.3);
|
|
2089
|
+
const bodyBoost = Math.max(32, Math.round(78 * biScarcity));
|
|
2090
|
+
selectiveBigrams.push({
|
|
2091
|
+
phrase,
|
|
2092
|
+
rows: new Set(termRows(index, phrase)),
|
|
2093
|
+
bodyBoost,
|
|
2094
|
+
highBoost: bodyBoost + 26,
|
|
2095
|
+
});
|
|
2096
|
+
}
|
|
2097
|
+
}
|
|
2098
|
+
}
|
|
2099
|
+
return {
|
|
2100
|
+
designatorMatches: tokenized.groups.map(({ designators }) => {
|
|
2101
|
+
if (!designators?.length)
|
|
2102
|
+
return undefined;
|
|
2103
|
+
const first = designatorRows(index, designators[0]);
|
|
2104
|
+
if (designators.length === 1)
|
|
2105
|
+
return first;
|
|
2106
|
+
const union = new Map(first);
|
|
2107
|
+
for (const key of designators.slice(1))
|
|
2108
|
+
for (const [row, score] of designatorRows(index, key))
|
|
2109
|
+
union.set(row, Math.max(union.get(row) ?? 0, score));
|
|
2110
|
+
return union;
|
|
2111
|
+
}),
|
|
2112
|
+
labels: new Map([tokenized.normalizedPhrase, ...tokenized.groups.map((group) => group.primary)]
|
|
2113
|
+
.filter((term) => WHOLE_LABEL.test(term))
|
|
2114
|
+
.map((term) => [term, new RegExp(`\\b${term}\\b`)])),
|
|
2115
|
+
tokenized,
|
|
2116
|
+
groupIdf,
|
|
2117
|
+
phraseIdfMultiplier,
|
|
2118
|
+
useCorpusIdf,
|
|
2119
|
+
selectiveBigrams,
|
|
2120
|
+
};
|
|
2121
|
+
}
|
|
2122
|
+
function coordinationBonus(matchedGroupCount, specificMatchedGroupCount, groupCount, useCorpusIdf) {
|
|
2123
|
+
if (!useCorpusIdf) {
|
|
2124
|
+
return matchedGroupCount >= 2
|
|
2125
|
+
? (matchedGroupCount - 1) * 25 + (matchedGroupCount === groupCount ? 15 : 0)
|
|
2126
|
+
: 0;
|
|
2127
|
+
}
|
|
2128
|
+
else {
|
|
2129
|
+
const specificBonus = specificMatchedGroupCount >= 2 ? (specificMatchedGroupCount - 1) * 25 : 0;
|
|
2130
|
+
const crossSupportBonus = specificMatchedGroupCount >= 1 && matchedGroupCount > specificMatchedGroupCount
|
|
2131
|
+
? Math.min(18, (matchedGroupCount - specificMatchedGroupCount) * 6)
|
|
2132
|
+
: 0;
|
|
2133
|
+
const fullMatchBonus = specificMatchedGroupCount >= 1 && matchedGroupCount === groupCount ? 12 : 0;
|
|
2134
|
+
return specificBonus + crossSupportBonus + fullMatchBonus;
|
|
2135
|
+
}
|
|
2136
|
+
}
|
|
2137
|
+
function evaluatePreparedQuery(plan, doc, includePinpoint, relevantGroups, phraseCandidate = true, row) {
|
|
2138
|
+
const { tokenized, groupIdf, phraseIdfMultiplier, useCorpusIdf } = plan;
|
|
538
2139
|
if (!tokenized.normalizedPhrase) {
|
|
539
2140
|
return { score: 1, matchedFields: [] };
|
|
540
2141
|
}
|
|
541
2142
|
const allMatchedFields = new Set();
|
|
542
2143
|
const bodySnippetTerms = [];
|
|
543
|
-
const
|
|
544
|
-
|
|
545
|
-
|
|
2144
|
+
const specificPinpointTerms = [];
|
|
2145
|
+
const fallbackPinpointTerms = [];
|
|
2146
|
+
const specificPinpointDesignators = new Set();
|
|
2147
|
+
const fallbackPinpointDesignators = new Set();
|
|
2148
|
+
function scoreTerm(term) {
|
|
2149
|
+
return scoreTermAgainstDoc(term, doc, plan.labels.get(term));
|
|
2150
|
+
}
|
|
2151
|
+
const rawPhraseHit = phraseCandidate ? scoreTerm(tokenized.normalizedPhrase) : EMPTY_HIT;
|
|
2152
|
+
const weightedPhraseScore = rawPhraseHit.bestScore > 0
|
|
2153
|
+
? Math.max(1, Math.round(rawPhraseHit.bestScore * phraseIdfMultiplier))
|
|
2154
|
+
: 0;
|
|
2155
|
+
if (rawPhraseHit.bestScore > 0) {
|
|
2156
|
+
for (const f of rawPhraseHit.fields) {
|
|
546
2157
|
allMatchedFields.add(f);
|
|
547
2158
|
}
|
|
548
|
-
if (
|
|
2159
|
+
if (rawPhraseHit.matchedBodyText || rawPhraseHit.matchedCodeOrDetail) {
|
|
549
2160
|
bodySnippetTerms.push(tokenized.normalizedPhrase);
|
|
550
2161
|
}
|
|
551
2162
|
}
|
|
552
2163
|
const groupScores = [];
|
|
553
2164
|
let matchedGroupCount = 0;
|
|
554
|
-
|
|
2165
|
+
let specificMatchedGroupCount = 0;
|
|
2166
|
+
for (const gIdx of relevantGroups ?? tokenized.groups.keys()) {
|
|
2167
|
+
const group = tokenized.groups[gIdx];
|
|
2168
|
+
const idfProfile = groupIdf[gIdx] ?? { multiplier: 1, docRatio: 0 };
|
|
2169
|
+
const isSpecificGroup = !useCorpusIdf || idfProfile.docRatio <= 0.35;
|
|
555
2170
|
let primaryHit;
|
|
556
2171
|
let effectivePrimaryTerm = group.primary;
|
|
557
2172
|
if (group.isStrippedStem && group.rawToken) {
|
|
558
|
-
const rawHit =
|
|
559
|
-
const stemHit =
|
|
2173
|
+
const rawHit = scoreTerm(group.rawToken);
|
|
2174
|
+
const stemHit = scoreTerm(group.primary);
|
|
560
2175
|
const discountedStemScore = stemHit.bestScore > 0 ? Math.max(1, Math.round(stemHit.bestScore * 0.45)) : 0;
|
|
561
2176
|
if (rawHit.bestScore >= discountedStemScore && rawHit.bestScore > 0) {
|
|
562
2177
|
primaryHit = rawHit;
|
|
@@ -570,14 +2185,34 @@ function evaluateDiscoveryQuery(query, doc, allowSubTokenFallback = false) {
|
|
|
570
2185
|
}
|
|
571
2186
|
}
|
|
572
2187
|
else {
|
|
573
|
-
primaryHit =
|
|
2188
|
+
primaryHit = scoreTerm(group.primary);
|
|
2189
|
+
}
|
|
2190
|
+
// Match canonical designator variants ("FFG-62" <-> "FFG 62" <-> "FFG62", "CRS-R44972" <-> "R44972") at full tier strength
|
|
2191
|
+
if (group.designators?.length &&
|
|
2192
|
+
(row === undefined || plan.designatorMatches[gIdx]?.has(row))) {
|
|
2193
|
+
const desigEval = scoreDesignatorsAgainstDoc(group.designators, doc);
|
|
2194
|
+
if (desigEval.hit.bestScore > 0) {
|
|
2195
|
+
primaryHit = mergeTermHits(primaryHit, desigEval.hit);
|
|
2196
|
+
if (desigEval.matchedSnippetTerm) {
|
|
2197
|
+
effectivePrimaryTerm = desigEval.matchedSnippetTerm;
|
|
2198
|
+
}
|
|
2199
|
+
}
|
|
2200
|
+
}
|
|
2201
|
+
// Also normalize single-letter hyphenated acronyms ("M-SHORAD" <-> "M SHORAD")
|
|
2202
|
+
if (primaryHit.bestScore === 0 && /^[a-z]-[a-z]{4,}$/.test(group.primary)) {
|
|
2203
|
+
const spacedAcronym = group.primary.replace(/-/g, " ");
|
|
2204
|
+
const spacedHit = scoreTerm(spacedAcronym);
|
|
2205
|
+
if (spacedHit.bestScore > 0) {
|
|
2206
|
+
primaryHit = spacedHit;
|
|
2207
|
+
effectivePrimaryTerm = spacedAcronym;
|
|
2208
|
+
}
|
|
574
2209
|
}
|
|
575
2210
|
let bestTriScore = 0;
|
|
576
2211
|
let secondTriScore = 0;
|
|
577
2212
|
const triFields = new Set();
|
|
578
2213
|
const triBodyTerms = [];
|
|
579
2214
|
for (const tri of group.threeGrams) {
|
|
580
|
-
const h =
|
|
2215
|
+
const h = scoreTerm(tri);
|
|
581
2216
|
if (h.bestScore > 0) {
|
|
582
2217
|
for (const f of h.fields) {
|
|
583
2218
|
triFields.add(f);
|
|
@@ -598,7 +2233,7 @@ function evaluateDiscoveryQuery(query, doc, allowSubTokenFallback = false) {
|
|
|
598
2233
|
const weightedTri = Math.round((bestTriScore * 0.6 + secondTriScore * 0.2) * stemDiscount);
|
|
599
2234
|
const biHits = [];
|
|
600
2235
|
for (const bi of group.twoGrams) {
|
|
601
|
-
const h =
|
|
2236
|
+
const h = scoreTerm(bi);
|
|
602
2237
|
if (h.bestScore > 0) {
|
|
603
2238
|
biHits.push({ term: bi, hit: h });
|
|
604
2239
|
}
|
|
@@ -620,50 +2255,61 @@ function evaluateDiscoveryQuery(query, doc, allowSubTokenFallback = false) {
|
|
|
620
2255
|
const coBiBonus = usableBiHits.length >= 2 ? (usableBiHits.length - 1) * 12 : 0;
|
|
621
2256
|
const rawBi = Math.round((topBiSum * 0.38 + coBiBonus) * stemDiscount);
|
|
622
2257
|
if (usableBiHits.length === 1) {
|
|
623
|
-
// Require raw token or >= 2 CJK bigrams for high-score hits; single bigram is low-weight fallback
|
|
624
2258
|
weightedBi = Math.min(rawBi, 28);
|
|
625
2259
|
}
|
|
626
2260
|
else {
|
|
627
2261
|
weightedBi = rawBi;
|
|
628
2262
|
}
|
|
629
2263
|
}
|
|
630
|
-
//
|
|
2264
|
+
// Per-group identifier sub-token co-occurrence fallback whenever primaryHit.bestScore === 0
|
|
631
2265
|
const subTokHits = [];
|
|
632
|
-
if (
|
|
633
|
-
primaryHit.bestScore === 0 &&
|
|
634
|
-
group.subTokens &&
|
|
635
|
-
group.subTokens.length >= 2) {
|
|
2266
|
+
if (primaryHit.bestScore === 0 && group.subTokens && group.subTokens.length >= 2) {
|
|
636
2267
|
for (const st of group.subTokens) {
|
|
637
|
-
const h =
|
|
2268
|
+
const h = scoreTerm(st);
|
|
638
2269
|
if (h.bestScore > 0) {
|
|
639
|
-
|
|
2270
|
+
// Do not treat a parent domainId prefix match as an 86-pt sceneId prefix during subToken decomposition
|
|
2271
|
+
const onlyDomainPrefixId = Boolean(doc.shortIdLower) &&
|
|
2272
|
+
!st.includes("/") &&
|
|
2273
|
+
!doc.shortIdLower.includes(st) &&
|
|
2274
|
+
h.fields.size === 1 &&
|
|
2275
|
+
h.fields.has("id");
|
|
2276
|
+
const adjustedHit = onlyDomainPrefixId
|
|
2277
|
+
? { ...h, bestScore: Math.min(h.bestScore, 42) }
|
|
2278
|
+
: h;
|
|
2279
|
+
subTokHits.push({ term: st, hit: adjustedHit });
|
|
640
2280
|
}
|
|
641
2281
|
}
|
|
642
2282
|
}
|
|
643
2283
|
let weightedSubTok = 0;
|
|
644
2284
|
if (subTokHits.length >= 2) {
|
|
645
2285
|
subTokHits.sort((a, b) => b.hit.bestScore - a.hit.bestScore);
|
|
646
|
-
const
|
|
647
|
-
const
|
|
648
|
-
|
|
2286
|
+
const leadSub = subTokHits[0]?.hit.bestScore ?? 0;
|
|
2287
|
+
const restSubSum = subTokHits.slice(1, 3).reduce((acc, cur) => acc + cur.hit.bestScore, 0);
|
|
2288
|
+
const allPartsMatched = Boolean(group.subTokens && subTokHits.length === group.subTokens.length);
|
|
2289
|
+
const coSubBonus = (subTokHits.length - 1) * 14 + (allPartsMatched ? 6 : 0);
|
|
2290
|
+
// Cap below verbatim anchor/chain/alias/title/id matches (>= 92) while beating single noisy words
|
|
2291
|
+
weightedSubTok = Math.min(88, Math.round(leadSub * 0.62 + restSubSum * 0.45) + coSubBonus);
|
|
649
2292
|
}
|
|
650
2293
|
const subGramScore = Math.max(weightedTri, weightedBi, weightedSubTok);
|
|
651
|
-
let
|
|
2294
|
+
let rawGroupScore = 0;
|
|
2295
|
+
const matchedTermsForGroup = [];
|
|
652
2296
|
if (primaryHit.bestScore > 0) {
|
|
653
|
-
|
|
2297
|
+
rawGroupScore = primaryHit.bestScore + (subGramScore > primaryHit.bestScore ? 8 : 0);
|
|
654
2298
|
for (const f of primaryHit.fields) {
|
|
655
2299
|
allMatchedFields.add(f);
|
|
656
2300
|
}
|
|
2301
|
+
matchedTermsForGroup.push(effectivePrimaryTerm);
|
|
657
2302
|
if (primaryHit.matchedBodyText || primaryHit.matchedCodeOrDetail) {
|
|
658
2303
|
bodySnippetTerms.push(effectivePrimaryTerm);
|
|
659
2304
|
}
|
|
660
2305
|
}
|
|
661
2306
|
else if (subGramScore > 0) {
|
|
662
|
-
|
|
2307
|
+
rawGroupScore = subGramScore;
|
|
663
2308
|
if (weightedTri >= weightedBi && weightedTri >= weightedSubTok) {
|
|
664
2309
|
for (const f of triFields) {
|
|
665
2310
|
allMatchedFields.add(f);
|
|
666
2311
|
}
|
|
2312
|
+
matchedTermsForGroup.push(...triBodyTerms, ...group.threeGrams);
|
|
667
2313
|
bodySnippetTerms.push(...triBodyTerms);
|
|
668
2314
|
}
|
|
669
2315
|
else if (weightedSubTok > weightedBi) {
|
|
@@ -671,6 +2317,7 @@ function evaluateDiscoveryQuery(query, doc, allowSubTokenFallback = false) {
|
|
|
671
2317
|
for (const f of st.hit.fields) {
|
|
672
2318
|
allMatchedFields.add(f);
|
|
673
2319
|
}
|
|
2320
|
+
matchedTermsForGroup.push(st.term);
|
|
674
2321
|
if (st.hit.matchedBodyText || st.hit.matchedCodeOrDetail) {
|
|
675
2322
|
bodySnippetTerms.push(st.term);
|
|
676
2323
|
}
|
|
@@ -681,115 +2328,159 @@ function evaluateDiscoveryQuery(query, doc, allowSubTokenFallback = false) {
|
|
|
681
2328
|
for (const f of b.hit.fields) {
|
|
682
2329
|
allMatchedFields.add(f);
|
|
683
2330
|
}
|
|
2331
|
+
matchedTermsForGroup.push(b.term);
|
|
684
2332
|
if (b.hit.matchedBodyText || b.hit.matchedCodeOrDetail) {
|
|
685
2333
|
bodySnippetTerms.push(b.term);
|
|
686
2334
|
}
|
|
687
2335
|
}
|
|
688
2336
|
}
|
|
689
2337
|
}
|
|
690
|
-
if (
|
|
2338
|
+
if (rawGroupScore > 0) {
|
|
691
2339
|
matchedGroupCount += 1;
|
|
692
|
-
|
|
2340
|
+
if (isSpecificGroup) {
|
|
2341
|
+
specificMatchedGroupCount += 1;
|
|
2342
|
+
specificPinpointTerms.push(...matchedTermsForGroup);
|
|
2343
|
+
for (const d of group.designators ?? []) {
|
|
2344
|
+
specificPinpointDesignators.add(d);
|
|
2345
|
+
}
|
|
2346
|
+
}
|
|
2347
|
+
else {
|
|
2348
|
+
fallbackPinpointTerms.push(...matchedTermsForGroup);
|
|
2349
|
+
for (const d of group.designators ?? []) {
|
|
2350
|
+
fallbackPinpointDesignators.add(d);
|
|
2351
|
+
}
|
|
2352
|
+
}
|
|
2353
|
+
const scaledScore = Math.max(1, Math.round(rawGroupScore * idfProfile.multiplier));
|
|
2354
|
+
groupScores.push(scaledScore);
|
|
693
2355
|
}
|
|
694
2356
|
}
|
|
695
|
-
if (matchedGroupCount === 0 &&
|
|
2357
|
+
if (matchedGroupCount === 0 && weightedPhraseScore === 0) {
|
|
696
2358
|
return { score: 0, matchedFields: [] };
|
|
697
2359
|
}
|
|
698
|
-
// Sum top-K matched token groups without linear division by tokens.length (no multi-token dilution!)
|
|
699
2360
|
groupScores.sort((a, b) => b - a);
|
|
700
2361
|
const topGroupSum = groupScores.slice(0, 4).reduce((sum, s) => sum + s, 0);
|
|
701
|
-
|
|
702
|
-
|
|
703
|
-
|
|
704
|
-
const
|
|
2362
|
+
// On >= 8 scene wikis, only specific (non-ubiquitous) matched groups earn full +25 coordination bonus
|
|
2363
|
+
const multiTokenBonus = coordinationBonus(matchedGroupCount, specificMatchedGroupCount, tokenized.groups.length, useCorpusIdf);
|
|
2364
|
+
let selectivePhraseBonus = 0;
|
|
2365
|
+
for (const sb of plan.selectiveBigrams) {
|
|
2366
|
+
if (row === undefined ? !doc.allTextLower.includes(sb.phrase) : !sb.rows.has(row)) {
|
|
2367
|
+
continue;
|
|
2368
|
+
}
|
|
2369
|
+
const inHighField = doc.titleLower.includes(sb.phrase) ||
|
|
2370
|
+
doc.summaryLower.includes(sb.phrase) ||
|
|
2371
|
+
doc.headingsLower.some((h) => h.includes(sb.phrase)) ||
|
|
2372
|
+
doc.chainTermsLower.some((c) => c.includes(sb.phrase));
|
|
2373
|
+
selectivePhraseBonus += inHighField ? sb.highBoost : sb.bodyBoost;
|
|
2374
|
+
bodySnippetTerms.push(sb.phrase);
|
|
2375
|
+
}
|
|
2376
|
+
const combinedScore = Math.max(weightedPhraseScore, topGroupSum +
|
|
705
2377
|
multiTokenBonus +
|
|
706
|
-
|
|
2378
|
+
selectivePhraseBonus +
|
|
2379
|
+
(tokenized.groups.length > 1 ? Math.round(weightedPhraseScore * 0.35) : 0));
|
|
707
2380
|
const orderedFields = FIELD_DISPLAY_ORDER.filter((f) => allMatchedFields.has(f));
|
|
708
|
-
|
|
709
|
-
|
|
710
|
-
|
|
711
|
-
|
|
712
|
-
|
|
713
|
-
|
|
714
|
-
|
|
715
|
-
|
|
2381
|
+
let activeTerms;
|
|
2382
|
+
let activeDesigs;
|
|
2383
|
+
if (includePinpoint) {
|
|
2384
|
+
activeTerms =
|
|
2385
|
+
specificPinpointTerms.length > 0 || specificPinpointDesignators.size > 0
|
|
2386
|
+
? specificPinpointTerms
|
|
2387
|
+
: fallbackPinpointTerms;
|
|
2388
|
+
activeDesigs =
|
|
2389
|
+
specificPinpointTerms.length > 0 || specificPinpointDesignators.size > 0
|
|
2390
|
+
? specificPinpointDesignators
|
|
2391
|
+
: fallbackPinpointDesignators;
|
|
2392
|
+
}
|
|
716
2393
|
return {
|
|
717
2394
|
score: combinedScore,
|
|
718
2395
|
matchedFields: orderedFields,
|
|
719
|
-
...(
|
|
2396
|
+
...(bodySnippetTerms.length > 0 ? { bodySnippetTerms } : {}),
|
|
2397
|
+
...(activeTerms && activeTerms.length > 0 ? { pinpointTerms: activeTerms } : {}),
|
|
2398
|
+
...(activeDesigs && activeDesigs.size > 0 ? { pinpointDesignators: activeDesigs } : {}),
|
|
720
2399
|
};
|
|
721
2400
|
}
|
|
2401
|
+
function collectActiveQueries(query, queries) {
|
|
2402
|
+
const active = [];
|
|
2403
|
+
if (query?.trim()) {
|
|
2404
|
+
active.push(query.trim());
|
|
2405
|
+
}
|
|
2406
|
+
for (const q of queries ?? []) {
|
|
2407
|
+
const trimmed = q.trim();
|
|
2408
|
+
if (trimmed && !active.includes(trimmed)) {
|
|
2409
|
+
active.push(trimmed);
|
|
2410
|
+
}
|
|
2411
|
+
}
|
|
2412
|
+
return active;
|
|
2413
|
+
}
|
|
2414
|
+
function filterWeakBodyOnlyHits(items) {
|
|
2415
|
+
if (items.length <= 1) {
|
|
2416
|
+
return items;
|
|
2417
|
+
}
|
|
2418
|
+
let topStructuredScore = 0;
|
|
2419
|
+
for (const item of items) {
|
|
2420
|
+
const hasStructuredField = item.matchedFields?.some((f) => f !== "body") ?? false;
|
|
2421
|
+
if (hasStructuredField && (item.score ?? 0) > topStructuredScore) {
|
|
2422
|
+
topStructuredScore = item.score ?? 0;
|
|
2423
|
+
}
|
|
2424
|
+
}
|
|
2425
|
+
if (topStructuredScore < 65) {
|
|
2426
|
+
return items;
|
|
2427
|
+
}
|
|
2428
|
+
const minBodyOnlyScore = Math.max(25, Math.round(topStructuredScore * 0.25));
|
|
2429
|
+
return items.filter((item) => {
|
|
2430
|
+
const isBodyOnly = item.matchedFields !== undefined &&
|
|
2431
|
+
item.matchedFields.length === 1 &&
|
|
2432
|
+
item.matchedFields[0] === "body";
|
|
2433
|
+
return !isBodyOnly || (item.score ?? 0) >= minBodyOnlyScore;
|
|
2434
|
+
});
|
|
2435
|
+
}
|
|
2436
|
+
function applyLimit(items, limit) {
|
|
2437
|
+
if (limit === undefined) {
|
|
2438
|
+
return items;
|
|
2439
|
+
}
|
|
2440
|
+
if (limit <= 0) {
|
|
2441
|
+
return [];
|
|
2442
|
+
}
|
|
2443
|
+
return items.slice(0, limit);
|
|
2444
|
+
}
|
|
722
2445
|
/**
|
|
723
2446
|
* Level-1 progressive discovery: returns compact 1-entry-per-domain summaries and aliases.
|
|
724
2447
|
*/
|
|
725
2448
|
export function discoverDomains(wiki, options = {}) {
|
|
726
2449
|
const includeInfra = options.includeInfrastructure ?? true;
|
|
727
|
-
const
|
|
728
|
-
|
|
729
|
-
|
|
730
|
-
|
|
731
|
-
|
|
732
|
-
}
|
|
733
|
-
if (!hasQuery || !options.query) {
|
|
734
|
-
prepared.push({ domain });
|
|
735
|
-
continue;
|
|
736
|
-
}
|
|
737
|
-
const childHighTerms = [];
|
|
738
|
-
const childAnchorTerms = [];
|
|
739
|
-
const childRepoTerms = [];
|
|
740
|
-
const childBodySources = [];
|
|
741
|
-
const codeSpans = extractInlineCodeSpans(domain.content);
|
|
742
|
-
for (const sceneId of domain.sceneIds) {
|
|
743
|
-
const scene = wiki.scenes.get(sceneId);
|
|
744
|
-
if (!scene) {
|
|
2450
|
+
const activeQueries = collectActiveQueries(options.query, options.queries);
|
|
2451
|
+
if (activeQueries.length === 0) {
|
|
2452
|
+
const out = [];
|
|
2453
|
+
for (const domain of wiki.domains.values()) {
|
|
2454
|
+
if (!includeInfra && domain.isInfrastructureDomain) {
|
|
745
2455
|
continue;
|
|
746
2456
|
}
|
|
747
|
-
|
|
748
|
-
|
|
749
|
-
childRepoTerms.push(repoRef.repo);
|
|
750
|
-
}
|
|
751
|
-
for (const anchor of scene.frontmatter.anchors ?? []) {
|
|
752
|
-
childAnchorTerms.push(anchor.file);
|
|
753
|
-
if (anchor.symbol) {
|
|
754
|
-
childAnchorTerms.push(anchor.symbol);
|
|
755
|
-
}
|
|
756
|
-
}
|
|
757
|
-
codeSpans.push(...extractInlineCodeSpans(scene.content));
|
|
758
|
-
childBodySources.push(scene.content, ...scene.details.map((d) => d.content));
|
|
759
|
-
}
|
|
760
|
-
prepared.push({
|
|
761
|
-
domain,
|
|
762
|
-
doc: {
|
|
763
|
-
id: domain.domainId,
|
|
2457
|
+
out.push({
|
|
2458
|
+
domainId: domain.domainId,
|
|
764
2459
|
title: domain.frontmatter.title,
|
|
765
2460
|
aliases: domain.frontmatter.aliases,
|
|
766
2461
|
summary: domain.frontmatter.summary,
|
|
767
|
-
|
|
768
|
-
|
|
769
|
-
|
|
770
|
-
|
|
771
|
-
|
|
772
|
-
|
|
773
|
-
|
|
774
|
-
|
|
775
|
-
});
|
|
2462
|
+
maintainers: domain.frontmatter.maintainers,
|
|
2463
|
+
isInfrastructureDomain: domain.isInfrastructureDomain,
|
|
2464
|
+
sceneCount: domain.sceneIds.length,
|
|
2465
|
+
relativePath: domain.relativePath,
|
|
2466
|
+
});
|
|
2467
|
+
}
|
|
2468
|
+
out.sort((a, b) => a.domainId.localeCompare(b.domainId));
|
|
2469
|
+
return applyLimit(out, options.limit);
|
|
776
2470
|
}
|
|
777
|
-
|
|
778
|
-
|
|
779
|
-
|
|
780
|
-
|
|
781
|
-
|
|
782
|
-
|
|
783
|
-
|
|
784
|
-
|
|
785
|
-
|
|
786
|
-
|
|
787
|
-
|
|
788
|
-
score = evalRes.score;
|
|
789
|
-
matchedFields = evalRes.matchedFields;
|
|
790
|
-
matchSnippet = evalRes.matchSnippet;
|
|
2471
|
+
const index = getPrecomputedWikiIndex(wiki);
|
|
2472
|
+
const allDomains = getPrecomputedDomains(wiki, index);
|
|
2473
|
+
const candidateDomains = allDomains.filter((entry) => includeInfra || !entry.domain.isInfrastructureDomain);
|
|
2474
|
+
const domainDocById = new Map(candidateDomains.map((d) => [d.domain.domainId, d.doc]));
|
|
2475
|
+
function runSingleDomainQuery(q) {
|
|
2476
|
+
const plan = buildPreparedQueryPlan(q, index);
|
|
2477
|
+
const hits = [];
|
|
2478
|
+
for (const { domain, doc } of candidateDomains) {
|
|
2479
|
+
const evalRes = evaluatePreparedQuery(plan, doc, false);
|
|
2480
|
+
if (evalRes.score <= 0) {
|
|
2481
|
+
continue;
|
|
791
2482
|
}
|
|
792
|
-
|
|
2483
|
+
const item = {
|
|
793
2484
|
domainId: domain.domainId,
|
|
794
2485
|
title: domain.frontmatter.title,
|
|
795
2486
|
aliases: domain.frontmatter.aliases,
|
|
@@ -798,117 +2489,410 @@ export function discoverDomains(wiki, options = {}) {
|
|
|
798
2489
|
isInfrastructureDomain: domain.isInfrastructureDomain,
|
|
799
2490
|
sceneCount: domain.sceneIds.length,
|
|
800
2491
|
relativePath: domain.relativePath,
|
|
801
|
-
|
|
802
|
-
...(matchedFields
|
|
803
|
-
|
|
2492
|
+
score: evalRes.score,
|
|
2493
|
+
...(evalRes.matchedFields.length > 0 ? { matchedFields: evalRes.matchedFields } : {}),
|
|
2494
|
+
};
|
|
2495
|
+
hits.push({
|
|
2496
|
+
item,
|
|
2497
|
+
score: evalRes.score,
|
|
2498
|
+
matchedFields: item.matchedFields,
|
|
2499
|
+
snippetTerms: evalRes.bodySnippetTerms,
|
|
804
2500
|
});
|
|
805
2501
|
}
|
|
806
|
-
|
|
807
|
-
|
|
808
|
-
|
|
809
|
-
|
|
810
|
-
|
|
811
|
-
options.
|
|
812
|
-
|
|
813
|
-
|
|
814
|
-
|
|
815
|
-
|
|
816
|
-
|
|
817
|
-
|
|
818
|
-
|
|
819
|
-
|
|
820
|
-
|
|
821
|
-
|
|
822
|
-
|
|
823
|
-
|
|
824
|
-
|
|
825
|
-
|
|
826
|
-
|
|
827
|
-
|
|
828
|
-
|
|
829
|
-
|
|
830
|
-
|
|
2502
|
+
const filtered = filterWeakBodyOnlyHits(hits);
|
|
2503
|
+
filtered.sort((a, b) => b.score - a.score || a.item.domainId.localeCompare(b.item.domainId));
|
|
2504
|
+
return filtered;
|
|
2505
|
+
}
|
|
2506
|
+
if (activeQueries.length === 1) {
|
|
2507
|
+
const limited = applyLimit(runSingleDomainQuery(activeQueries[0]), options.limit);
|
|
2508
|
+
return limited.map(({ item, snippetTerms }) => {
|
|
2509
|
+
if (!snippetTerms || snippetTerms.length === 0) {
|
|
2510
|
+
return item;
|
|
2511
|
+
}
|
|
2512
|
+
const doc = domainDocById.get(item.domainId);
|
|
2513
|
+
const snippet = doc
|
|
2514
|
+
? extractMatchSnippet(doc.rawSnippetSources, snippetTerms, 80)
|
|
2515
|
+
: undefined;
|
|
2516
|
+
return snippet ? { ...item, matchSnippet: snippet } : item;
|
|
2517
|
+
});
|
|
2518
|
+
}
|
|
2519
|
+
// Multi-query Reciprocal Rank Fusion (RRF) across sub-queries
|
|
2520
|
+
const fusedById = new Map();
|
|
2521
|
+
for (const q of activeQueries) {
|
|
2522
|
+
const subResults = runSingleDomainQuery(q);
|
|
2523
|
+
const topScore = Math.max(1, subResults[0]?.item.score ?? 1);
|
|
2524
|
+
const rrfWindow = Math.min(subResults.length, 30);
|
|
2525
|
+
for (let idx = 0; idx < rrfWindow; idx++) {
|
|
2526
|
+
const { item, snippetTerms } = subResults[idx];
|
|
2527
|
+
const rank = idx + 1;
|
|
2528
|
+
const rawScore = item.score ?? 0;
|
|
2529
|
+
const rrfContribution = 1200 / (1 + rank) + 40 * (rawScore / topScore);
|
|
2530
|
+
const existing = fusedById.get(item.domainId);
|
|
2531
|
+
if (!existing) {
|
|
2532
|
+
fusedById.set(item.domainId, {
|
|
2533
|
+
base: item,
|
|
2534
|
+
rrfSum: rrfContribution,
|
|
2535
|
+
maxRawScore: rawScore,
|
|
2536
|
+
bestRank: rank,
|
|
2537
|
+
fields: new Set(item.matchedFields ?? []),
|
|
2538
|
+
bestSnippetTerms: snippetTerms,
|
|
831
2539
|
});
|
|
832
2540
|
}
|
|
2541
|
+
else {
|
|
2542
|
+
existing.rrfSum += rrfContribution;
|
|
2543
|
+
existing.maxRawScore = Math.max(existing.maxRawScore, rawScore);
|
|
2544
|
+
for (const f of item.matchedFields ?? []) {
|
|
2545
|
+
existing.fields.add(f);
|
|
2546
|
+
}
|
|
2547
|
+
if (rank < existing.bestRank && snippetTerms?.length) {
|
|
2548
|
+
existing.bestRank = rank;
|
|
2549
|
+
existing.bestSnippetTerms = snippetTerms;
|
|
2550
|
+
}
|
|
2551
|
+
else if (!existing.bestSnippetTerms && snippetTerms?.length) {
|
|
2552
|
+
existing.bestSnippetTerms = snippetTerms;
|
|
2553
|
+
}
|
|
2554
|
+
}
|
|
833
2555
|
}
|
|
834
|
-
results.sort((a, b) => (b.score ?? 0) - (a.score ?? 0) || a.domainId.localeCompare(b.domainId));
|
|
835
2556
|
}
|
|
836
|
-
|
|
837
|
-
|
|
838
|
-
|
|
839
|
-
|
|
2557
|
+
const sortedEntries = Array.from(fusedById.values())
|
|
2558
|
+
.map((entry) => ({
|
|
2559
|
+
entry,
|
|
2560
|
+
fusedScore: Math.round(entry.rrfSum + 0.15 * entry.maxRawScore),
|
|
2561
|
+
}))
|
|
2562
|
+
.sort((a, b) => b.fusedScore - a.fusedScore || a.entry.base.domainId.localeCompare(b.entry.base.domainId));
|
|
2563
|
+
return applyLimit(sortedEntries, options.limit).map(({ entry, fusedScore }) => {
|
|
2564
|
+
const orderedFields = FIELD_DISPLAY_ORDER.filter((f) => entry.fields.has(f));
|
|
2565
|
+
const doc = domainDocById.get(entry.base.domainId);
|
|
2566
|
+
const snippet = doc && entry.bestSnippetTerms?.length
|
|
2567
|
+
? extractMatchSnippet(doc.rawSnippetSources, entry.bestSnippetTerms, 80)
|
|
2568
|
+
: undefined;
|
|
2569
|
+
return {
|
|
2570
|
+
...entry.base,
|
|
2571
|
+
score: fusedScore,
|
|
2572
|
+
...(orderedFields.length > 0 ? { matchedFields: orderedFields } : {}),
|
|
2573
|
+
...(snippet ? { matchSnippet: snippet } : {}),
|
|
2574
|
+
};
|
|
2575
|
+
});
|
|
840
2576
|
}
|
|
841
|
-
|
|
842
|
-
|
|
843
|
-
|
|
844
|
-
|
|
845
|
-
|
|
846
|
-
|
|
847
|
-
|
|
848
|
-
|
|
849
|
-
|
|
2577
|
+
const COMPARISON_GLUE_WORDS = new Set([
|
|
2578
|
+
"compare",
|
|
2579
|
+
"comparing",
|
|
2580
|
+
"comparison",
|
|
2581
|
+
"between",
|
|
2582
|
+
"versus",
|
|
2583
|
+
"vs",
|
|
2584
|
+
"and",
|
|
2585
|
+
"or",
|
|
2586
|
+
"for",
|
|
2587
|
+
"with",
|
|
2588
|
+
"from",
|
|
2589
|
+
"into",
|
|
2590
|
+
"the",
|
|
2591
|
+
"of",
|
|
2592
|
+
"in",
|
|
2593
|
+
"on",
|
|
2594
|
+
"to",
|
|
2595
|
+
"by",
|
|
2596
|
+
]);
|
|
2597
|
+
function expandMultiEntitySingleQuery(rawQuery, plan, index, scope) {
|
|
2598
|
+
if (!plan.useCorpusIdf) {
|
|
2599
|
+
return [rawQuery];
|
|
2600
|
+
}
|
|
2601
|
+
const { tokenized, groupIdf } = plan;
|
|
2602
|
+
if (tokenized.groups.length < 2) {
|
|
2603
|
+
return [rawQuery];
|
|
2604
|
+
}
|
|
2605
|
+
const entityClusters = [];
|
|
2606
|
+
const entityGroupIndices = new Set();
|
|
2607
|
+
for (let i = 0; i < tokenized.groups.length; i++) {
|
|
2608
|
+
if (entityGroupIndices.has(i)) {
|
|
850
2609
|
continue;
|
|
851
2610
|
}
|
|
852
|
-
|
|
2611
|
+
const g = tokenized.groups[i];
|
|
2612
|
+
const idf = groupIdf[i];
|
|
2613
|
+
const isModelOrDesignator = Boolean(g.designators && g.designators.length > 0) ||
|
|
2614
|
+
/^[a-z]{1,6}-[a-z0-9]{2,}(?:-[a-z0-9]+)*$/.test(g.primary);
|
|
2615
|
+
if (!isModelOrDesignator || idf.docRatio > 0.08) {
|
|
853
2616
|
continue;
|
|
854
2617
|
}
|
|
855
|
-
const
|
|
856
|
-
|
|
857
|
-
if (!
|
|
858
|
-
prepared.push({ scene, repoNames, chainNames });
|
|
2618
|
+
const hasCorpusPresence = getSceneTermDf(index, g.primary) > 0 ||
|
|
2619
|
+
(g.designators?.some((d) => getSceneDesignatorDf(index, d) > 0) ?? false);
|
|
2620
|
+
if (!hasCorpusPresence) {
|
|
859
2621
|
continue;
|
|
860
2622
|
}
|
|
861
|
-
|
|
862
|
-
|
|
863
|
-
|
|
864
|
-
|
|
865
|
-
|
|
866
|
-
|
|
867
|
-
a.
|
|
868
|
-
|
|
869
|
-
|
|
870
|
-
|
|
871
|
-
|
|
872
|
-
|
|
873
|
-
|
|
874
|
-
|
|
875
|
-
|
|
876
|
-
|
|
877
|
-
|
|
878
|
-
|
|
879
|
-
|
|
2623
|
+
// Coalesce an immediately following rare model-variant token (e.g. "b-52" + "rmp" -> "b-52 rmp")
|
|
2624
|
+
const nextGroup = tokenized.groups[i + 1];
|
|
2625
|
+
const nextIdf = groupIdf[i + 1];
|
|
2626
|
+
if (nextGroup &&
|
|
2627
|
+
nextIdf &&
|
|
2628
|
+
!nextGroup.designators?.length &&
|
|
2629
|
+
/^[a-z0-9]{2,6}$/.test(nextGroup.primary) &&
|
|
2630
|
+
nextIdf.docRatio <= 0.08 &&
|
|
2631
|
+
getSceneTermDf(index, `${g.primary} ${nextGroup.primary}`) > 0) {
|
|
2632
|
+
entityGroupIndices.add(i);
|
|
2633
|
+
entityGroupIndices.add(i + 1);
|
|
2634
|
+
entityClusters.push({
|
|
2635
|
+
text: `${g.primary} ${nextGroup.primary}`,
|
|
2636
|
+
groupIndices: [i, i + 1],
|
|
2637
|
+
designators: g.designators ?? [],
|
|
2638
|
+
primaryLower: `${g.primary} ${nextGroup.primary}`,
|
|
2639
|
+
});
|
|
2640
|
+
i += 1;
|
|
2641
|
+
continue;
|
|
2642
|
+
}
|
|
2643
|
+
entityGroupIndices.add(i);
|
|
2644
|
+
entityClusters.push({
|
|
2645
|
+
text: g.primary,
|
|
2646
|
+
groupIndices: [i],
|
|
2647
|
+
designators: g.designators ?? [],
|
|
2648
|
+
primaryLower: g.primary,
|
|
2649
|
+
});
|
|
2650
|
+
}
|
|
2651
|
+
if (entityClusters.length < 2) {
|
|
2652
|
+
return [rawQuery];
|
|
2653
|
+
}
|
|
2654
|
+
// Only decompose into per-entity RRF sub-queries when NO single scene contains all entities together
|
|
2655
|
+
const entityRows = entityClusters
|
|
2656
|
+
.map((ent) => {
|
|
2657
|
+
const rows = new Set(termRows(index, ent.primaryLower));
|
|
2658
|
+
for (const key of ent.designators)
|
|
2659
|
+
for (const row of designatorRows(index, key).keys())
|
|
2660
|
+
rows.add(row);
|
|
2661
|
+
return rows;
|
|
2662
|
+
})
|
|
2663
|
+
.sort((left, right) => left.size - right.size);
|
|
2664
|
+
const singleSceneCoversAll = Array.from(entityRows[0]).some((row) => (!scope || scope.has(row)) && entityRows.every((rows) => rows.has(row)));
|
|
2665
|
+
if (singleSceneCoversAll) {
|
|
2666
|
+
return [rawQuery];
|
|
2667
|
+
}
|
|
2668
|
+
const sharedContextTokens = [];
|
|
2669
|
+
for (let i = 0; i < tokenized.groups.length; i++) {
|
|
2670
|
+
if (entityGroupIndices.has(i)) {
|
|
2671
|
+
continue;
|
|
2672
|
+
}
|
|
2673
|
+
const tok = tokenized.groups[i].primary;
|
|
2674
|
+
if (!COMPARISON_GLUE_WORDS.has(tok)) {
|
|
2675
|
+
sharedContextTokens.push(tok);
|
|
2676
|
+
}
|
|
2677
|
+
}
|
|
2678
|
+
const sharedContext = sharedContextTokens.join(" ");
|
|
2679
|
+
return [
|
|
2680
|
+
rawQuery,
|
|
2681
|
+
...entityClusters.map((ent) => (sharedContext ? `${ent.text} ${sharedContext}` : ent.text)),
|
|
2682
|
+
];
|
|
2683
|
+
}
|
|
2684
|
+
/**
|
|
2685
|
+
* Level-2 progressive discovery: lists scenes/infrastructure entries filtered by domain and/or query/queries.
|
|
2686
|
+
*/
|
|
2687
|
+
export function discoverScenes(wiki, options = {}) {
|
|
2688
|
+
const kindFilter = options.kind ?? "all";
|
|
2689
|
+
const rawActiveQueries = collectActiveQueries(options.query, options.queries);
|
|
2690
|
+
if (rawActiveQueries.length === 0) {
|
|
2691
|
+
const out = [];
|
|
2692
|
+
for (const scene of wiki.scenes.values()) {
|
|
2693
|
+
if (options.domainId && scene.domainId !== options.domainId) {
|
|
2694
|
+
continue;
|
|
2695
|
+
}
|
|
2696
|
+
if (kindFilter !== "all" && scene.kind !== kindFilter) {
|
|
2697
|
+
continue;
|
|
2698
|
+
}
|
|
2699
|
+
const repoNames = scene.frontmatter.repositories.map((r) => r.repo);
|
|
2700
|
+
const sourceNames = scene.frontmatter.sources?.map((s) => s.source);
|
|
2701
|
+
const chainNames = scene.chains.map((c) => c.title);
|
|
2702
|
+
out.push({
|
|
880
2703
|
id: scene.id,
|
|
881
|
-
|
|
2704
|
+
domainId: scene.domainId,
|
|
2705
|
+
sceneId: scene.sceneId,
|
|
2706
|
+
kind: scene.kind,
|
|
882
2707
|
title: scene.frontmatter.title,
|
|
883
2708
|
aliases: scene.frontmatter.aliases,
|
|
884
|
-
chainTerms,
|
|
885
|
-
anchorTerms,
|
|
886
|
-
repoTerms: repoNames,
|
|
887
2709
|
summary: scene.frontmatter.summary,
|
|
888
|
-
|
|
889
|
-
|
|
890
|
-
|
|
891
|
-
|
|
892
|
-
|
|
893
|
-
|
|
894
|
-
|
|
2710
|
+
maintainers: scene.frontmatter.maintainers,
|
|
2711
|
+
...(scene.frontmatter.confidence !== undefined
|
|
2712
|
+
? { confidence: scene.frontmatter.confidence }
|
|
2713
|
+
: {}),
|
|
2714
|
+
dependsOn: scene.frontmatter.dependsOn,
|
|
2715
|
+
repositories: repoNames,
|
|
2716
|
+
...(sourceNames && sourceNames.length > 0 ? { sources: sourceNames } : {}),
|
|
2717
|
+
chainNames,
|
|
2718
|
+
hasPendingConfirmations: scene.hasPendingConfirmations,
|
|
2719
|
+
detailCount: scene.details.length,
|
|
2720
|
+
relativePath: scene.relativePath,
|
|
2721
|
+
});
|
|
2722
|
+
}
|
|
2723
|
+
out.sort((a, b) => a.id.localeCompare(b.id));
|
|
2724
|
+
return applyLimit(out, options.limit);
|
|
895
2725
|
}
|
|
896
|
-
|
|
897
|
-
|
|
898
|
-
|
|
899
|
-
|
|
900
|
-
|
|
901
|
-
|
|
902
|
-
|
|
903
|
-
|
|
904
|
-
|
|
2726
|
+
const index = getPrecomputedWikiIndex(wiki);
|
|
2727
|
+
const scope = options.domainId || kindFilter !== "all" ? new Set() : undefined;
|
|
2728
|
+
if (scope)
|
|
2729
|
+
index.scenes.forEach(({ scene }, row) => {
|
|
2730
|
+
if ((!options.domainId || scene.domainId === options.domainId) &&
|
|
2731
|
+
(kindFilter === "all" || scene.kind === kindFilter))
|
|
2732
|
+
scope.add(row);
|
|
2733
|
+
});
|
|
2734
|
+
const localScope = options.domainId && scope && scope.size >= 6 ? scope : undefined;
|
|
2735
|
+
const firstQuery = rawActiveQueries[0];
|
|
2736
|
+
const firstPlan = buildPreparedQueryPlan(firstQuery, index, localScope);
|
|
2737
|
+
const activeQueries = rawActiveQueries.length === 1
|
|
2738
|
+
? expandMultiEntitySingleQuery(firstQuery, firstPlan, index, scope)
|
|
2739
|
+
: rawActiveQueries;
|
|
2740
|
+
const rrfPerQueryCap = options.limit !== undefined ? Math.max(40, options.limit * 4) : 60;
|
|
2741
|
+
function runSingleSceneQuery(q) {
|
|
2742
|
+
const plan = q === firstQuery ? firstPlan : buildPreparedQueryPlan(q, index, localScope);
|
|
2743
|
+
const ordered = [];
|
|
2744
|
+
const groupCounts = new Uint32Array(index.sceneCount);
|
|
2745
|
+
const groupRows = [];
|
|
2746
|
+
const reverse = new Set();
|
|
2747
|
+
const collect = (term, rows, trackReverse = true) => {
|
|
2748
|
+
for (const row of termRows(index, term))
|
|
2749
|
+
rows.add(row);
|
|
2750
|
+
const exact = index.collapsedPostings.get(term);
|
|
2751
|
+
if (exact)
|
|
2752
|
+
for (const row of exact) {
|
|
2753
|
+
rows.add(row);
|
|
2754
|
+
if (trackReverse)
|
|
2755
|
+
reverse.add(row);
|
|
2756
|
+
}
|
|
2757
|
+
for (let start = 0; start + 1 < term.length; start++) {
|
|
2758
|
+
const lengths = index.reverseLengths.get(term.slice(start, start + 2));
|
|
2759
|
+
if (!lengths)
|
|
905
2760
|
continue;
|
|
2761
|
+
for (const length of lengths)
|
|
2762
|
+
if (length < term.length && start + length <= term.length) {
|
|
2763
|
+
const posting = index.reversePostings.get(term.slice(start, start + length));
|
|
2764
|
+
if (posting)
|
|
2765
|
+
for (const row of posting) {
|
|
2766
|
+
rows.add(row);
|
|
2767
|
+
if (trackReverse)
|
|
2768
|
+
reverse.add(row);
|
|
2769
|
+
}
|
|
2770
|
+
}
|
|
2771
|
+
}
|
|
2772
|
+
};
|
|
2773
|
+
const phraseRows = new Set();
|
|
2774
|
+
collect(plan.tokenized.normalizedPhrase, phraseRows);
|
|
2775
|
+
const phraseForward = new Set([
|
|
2776
|
+
...termRows(index, plan.tokenized.normalizedPhrase),
|
|
2777
|
+
...(index.collapsedPostings.get(plan.tokenized.normalizedPhrase) ?? EMPTY_LIST),
|
|
2778
|
+
]);
|
|
2779
|
+
const window = activeQueries.length === 1 ? options.limit : rrfPerQueryCap;
|
|
2780
|
+
const prune = window !== undefined && window > 0 && window < (scope?.size ?? index.sceneCount);
|
|
2781
|
+
const ceilings = new Float64Array(prune ? index.sceneCount : 0);
|
|
2782
|
+
const bestGroups = new Float64Array(ceilings.length * 4);
|
|
2783
|
+
const specific = new Uint32Array(ceilings.length);
|
|
2784
|
+
for (const [groupIndex, group] of plan.tokenized.groups.entries()) {
|
|
2785
|
+
reverse.clear();
|
|
2786
|
+
const rows = new Set();
|
|
2787
|
+
groupRows.push(rows);
|
|
2788
|
+
for (const term of [group.primary, group.rawToken, ...group.threeGrams, ...group.twoGrams])
|
|
2789
|
+
if (term)
|
|
2790
|
+
collect(term, rows);
|
|
2791
|
+
if (/^[a-z]-[a-z]{4,}$/.test(group.primary))
|
|
2792
|
+
collect(group.primary.replace("-", " "), rows);
|
|
2793
|
+
const canonicalHits = plan.designatorMatches[groupIndex];
|
|
2794
|
+
if (canonicalHits)
|
|
2795
|
+
for (const row of canonicalHits.keys())
|
|
2796
|
+
rows.add(row);
|
|
2797
|
+
const cooccurring = new Set();
|
|
2798
|
+
if (group.subTokens && group.subTokens.length >= 2) {
|
|
2799
|
+
const seen = new Set();
|
|
2800
|
+
for (const part of group.subTokens) {
|
|
2801
|
+
const partRows = new Set();
|
|
2802
|
+
collect(part, partRows, false);
|
|
2803
|
+
for (const row of partRows) {
|
|
2804
|
+
if (seen.has(row)) {
|
|
2805
|
+
rows.add(row);
|
|
2806
|
+
cooccurring.add(row);
|
|
2807
|
+
}
|
|
2808
|
+
else
|
|
2809
|
+
seen.add(row);
|
|
2810
|
+
}
|
|
906
2811
|
}
|
|
907
|
-
score = evalRes.score;
|
|
908
|
-
matchedFields = evalRes.matchedFields;
|
|
909
|
-
matchSnippet = evalRes.matchSnippet;
|
|
910
2812
|
}
|
|
911
|
-
|
|
2813
|
+
const gramFallback = group.twoGrams.length ||
|
|
2814
|
+
group.threeGrams.length ||
|
|
2815
|
+
group.isStrippedStem ||
|
|
2816
|
+
/^[a-z]-[a-z]{4,}$/.test(group.primary);
|
|
2817
|
+
const bounds = prune && rows.size && !gramFallback ? fieldBounds(index, group.primary) : undefined;
|
|
2818
|
+
const collapsed = index.collapsedPostings.get(group.primary);
|
|
2819
|
+
for (const row of rows)
|
|
2820
|
+
if (!scope || scope.has(row)) {
|
|
2821
|
+
if (prune) {
|
|
2822
|
+
const canonicalScore = canonicalHits?.get(row) ?? 0;
|
|
2823
|
+
const base = Math.max(bounds?.[row] ?? 0, canonicalScore, reverse.has(row) ? (collapsed?.includes(row) ? 120 : 58) : 0);
|
|
2824
|
+
const maximum = gramFallback
|
|
2825
|
+
? Number.POSITIVE_INFINITY
|
|
2826
|
+
: !canonicalScore && cooccurring.has(row)
|
|
2827
|
+
? Math.max(88, base)
|
|
2828
|
+
: base;
|
|
2829
|
+
let value = Math.max(1, Math.round(maximum * plan.groupIdf[groupIndex].multiplier));
|
|
2830
|
+
const offset = row * 4;
|
|
2831
|
+
for (let slot = offset; slot < offset + 4 && value; slot++) {
|
|
2832
|
+
const prior = bestGroups[slot];
|
|
2833
|
+
if (value > prior) {
|
|
2834
|
+
bestGroups[slot] = value;
|
|
2835
|
+
value = prior;
|
|
2836
|
+
}
|
|
2837
|
+
}
|
|
2838
|
+
if (!plan.useCorpusIdf || plan.groupIdf[groupIndex].docRatio <= 0.35)
|
|
2839
|
+
specific[row]++;
|
|
2840
|
+
}
|
|
2841
|
+
if (groupCounts[row]++ === 0)
|
|
2842
|
+
ordered.push(row);
|
|
2843
|
+
}
|
|
2844
|
+
}
|
|
2845
|
+
const hits = [];
|
|
2846
|
+
const wantsChart = /\b(?:performance|charts?|figures?)\b|原图|图表/i.test(q);
|
|
2847
|
+
for (const row of phraseRows)
|
|
2848
|
+
if (!groupCounts[row] && (!scope || scope.has(row)))
|
|
2849
|
+
ordered.push(row);
|
|
2850
|
+
if (prune) {
|
|
2851
|
+
for (const row of ordered) {
|
|
2852
|
+
const matched = groupCounts[row], count = specific[row];
|
|
2853
|
+
const offset = row * 4;
|
|
2854
|
+
ceilings[row] =
|
|
2855
|
+
bestGroups[offset] +
|
|
2856
|
+
bestGroups[offset + 1] +
|
|
2857
|
+
bestGroups[offset + 2] +
|
|
2858
|
+
bestGroups[offset + 3];
|
|
2859
|
+
ceilings[row] += coordinationBonus(matched, count, plan.tokenized.groups.length, plan.useCorpusIdf);
|
|
2860
|
+
if (phraseRows.has(row))
|
|
2861
|
+
ceilings[row] += Math.round((phraseForward.has(row) ? 120 : 58) * plan.phraseIdfMultiplier);
|
|
2862
|
+
if (wantsChart)
|
|
2863
|
+
ceilings[row] += 24;
|
|
2864
|
+
for (const phrase of plan.selectiveBigrams)
|
|
2865
|
+
if (phrase.rows.has(row))
|
|
2866
|
+
ceilings[row] += phrase.highBoost;
|
|
2867
|
+
}
|
|
2868
|
+
ordered.sort((left, right) => ceilings[right] - ceilings[left]);
|
|
2869
|
+
}
|
|
2870
|
+
const leaders = [];
|
|
2871
|
+
for (const row of ordered) {
|
|
2872
|
+
if (prune && leaders.length === window && ceilings[row] < leaders[0])
|
|
2873
|
+
break;
|
|
2874
|
+
const { scene, repoNames, sourceNames, chainNames, doc } = index.scenes[row].entry;
|
|
2875
|
+
const groups = [];
|
|
2876
|
+
for (let idx = 0; idx < groupRows.length; idx++)
|
|
2877
|
+
if (groupRows[idx].has(row))
|
|
2878
|
+
groups.push(idx);
|
|
2879
|
+
const evalRes = evaluatePreparedQuery(plan, doc, true, groups, phraseRows.has(row), row);
|
|
2880
|
+
if (evalRes.score <= 0) {
|
|
2881
|
+
continue;
|
|
2882
|
+
}
|
|
2883
|
+
if (wantsChart && index.scenes[row].hasChartEvidence)
|
|
2884
|
+
evalRes.score += 24;
|
|
2885
|
+
if (prune &&
|
|
2886
|
+
evalRes.matchedFields.some((field) => field !== "body") &&
|
|
2887
|
+
(leaders.length < window || evalRes.score > leaders[0])) {
|
|
2888
|
+
if (leaders.length === window)
|
|
2889
|
+
leaders.shift();
|
|
2890
|
+
let at = leaders.length;
|
|
2891
|
+
while (at && leaders[at - 1] > evalRes.score)
|
|
2892
|
+
at--;
|
|
2893
|
+
leaders.splice(at, 0, evalRes.score);
|
|
2894
|
+
}
|
|
2895
|
+
const item = {
|
|
912
2896
|
id: scene.id,
|
|
913
2897
|
domainId: scene.domainId,
|
|
914
2898
|
sceneId: scene.sceneId,
|
|
@@ -922,48 +2906,136 @@ export function discoverScenes(wiki, options = {}) {
|
|
|
922
2906
|
: {}),
|
|
923
2907
|
dependsOn: scene.frontmatter.dependsOn,
|
|
924
2908
|
repositories: repoNames,
|
|
2909
|
+
...(sourceNames.length > 0 ? { sources: sourceNames } : {}),
|
|
925
2910
|
chainNames,
|
|
926
2911
|
hasPendingConfirmations: scene.hasPendingConfirmations,
|
|
927
2912
|
detailCount: scene.details.length,
|
|
928
2913
|
relativePath: scene.relativePath,
|
|
929
|
-
|
|
930
|
-
...(matchedFields
|
|
931
|
-
|
|
2914
|
+
score: evalRes.score,
|
|
2915
|
+
...(evalRes.matchedFields.length > 0 ? { matchedFields: evalRes.matchedFields } : {}),
|
|
2916
|
+
};
|
|
2917
|
+
hits.push({
|
|
2918
|
+
item,
|
|
2919
|
+
score: evalRes.score,
|
|
2920
|
+
matchedFields: item.matchedFields,
|
|
2921
|
+
snippetTerms: evalRes.bodySnippetTerms,
|
|
2922
|
+
pinpointTerms: evalRes.pinpointTerms,
|
|
2923
|
+
pinpointDesignators: evalRes.pinpointDesignators,
|
|
932
2924
|
});
|
|
933
2925
|
}
|
|
934
|
-
|
|
935
|
-
|
|
936
|
-
|
|
937
|
-
|
|
938
|
-
|
|
939
|
-
|
|
940
|
-
|
|
941
|
-
|
|
942
|
-
|
|
943
|
-
|
|
944
|
-
|
|
945
|
-
|
|
946
|
-
|
|
947
|
-
|
|
948
|
-
|
|
949
|
-
|
|
950
|
-
|
|
951
|
-
}
|
|
952
|
-
|
|
953
|
-
|
|
954
|
-
|
|
955
|
-
|
|
956
|
-
|
|
957
|
-
|
|
958
|
-
|
|
2926
|
+
const filtered = filterWeakBodyOnlyHits(hits);
|
|
2927
|
+
filtered.sort((a, b) => b.score - a.score || a.item.id.localeCompare(b.item.id));
|
|
2928
|
+
return filtered;
|
|
2929
|
+
}
|
|
2930
|
+
function enrichSceneItem(base, snippetTerms, pTerms, pDesigs) {
|
|
2931
|
+
const doc = index.sceneById.get(base.id)?.entry.doc;
|
|
2932
|
+
if (!doc) {
|
|
2933
|
+
return base;
|
|
2934
|
+
}
|
|
2935
|
+
const snippet = snippetTerms && snippetTerms.length > 0
|
|
2936
|
+
? extractMatchSnippet(doc.rawSnippetSources, [...snippetTerms], 80)
|
|
2937
|
+
: undefined;
|
|
2938
|
+
const pinpoint = pinpointSubSceneMatches(doc, pTerms, pDesigs);
|
|
2939
|
+
return {
|
|
2940
|
+
...base,
|
|
2941
|
+
...(snippet ? { matchSnippet: snippet } : {}),
|
|
2942
|
+
...(pinpoint.matchedChains.length > 0 ? { matchedChains: pinpoint.matchedChains } : {}),
|
|
2943
|
+
...(pinpoint.matchedDetails.length > 0 ? { matchedDetails: pinpoint.matchedDetails } : {}),
|
|
2944
|
+
...(pinpoint.matchedAnchors.length > 0 ? { matchedAnchors: pinpoint.matchedAnchors } : {}),
|
|
2945
|
+
};
|
|
2946
|
+
}
|
|
2947
|
+
if (activeQueries.length === 1) {
|
|
2948
|
+
const emptyDesigs = new Set();
|
|
2949
|
+
const limited = applyLimit(runSingleSceneQuery(activeQueries[0]), options.limit);
|
|
2950
|
+
return limited.map(({ item, snippetTerms, pinpointTerms, pinpointDesignators }) => enrichSceneItem(item, snippetTerms, pinpointTerms ?? [], pinpointDesignators ?? emptyDesigs));
|
|
2951
|
+
}
|
|
2952
|
+
// Multi-query Reciprocal Rank Fusion (RRF) so every queried entity/report gets top-K representation without cannibalization
|
|
2953
|
+
const fusedById = new Map();
|
|
2954
|
+
for (const q of activeQueries) {
|
|
2955
|
+
const subResults = runSingleSceneQuery(q);
|
|
2956
|
+
const topScore = Math.max(1, subResults[0]?.item.score ?? 1);
|
|
2957
|
+
const distinctWinner = subResults[1]?.item.score !== topScore;
|
|
2958
|
+
const windowLen = Math.min(subResults.length, rrfPerQueryCap);
|
|
2959
|
+
for (let idx = 0; idx < windowLen; idx++) {
|
|
2960
|
+
const { item, snippetTerms, pinpointTerms, pinpointDesignators } = subResults[idx];
|
|
2961
|
+
const rank = idx + 1;
|
|
2962
|
+
const rawScore = item.score ?? 0;
|
|
2963
|
+
const rrfContribution = 1200 / (1 + rank) +
|
|
2964
|
+
40 * (rawScore / topScore) +
|
|
2965
|
+
(rank === 1 && rawScore >= 55 && distinctWinner ? 650 * activeQueries.length : 0);
|
|
2966
|
+
const existing = fusedById.get(item.id);
|
|
2967
|
+
if (!existing) {
|
|
2968
|
+
fusedById.set(item.id, {
|
|
2969
|
+
base: item,
|
|
2970
|
+
rrfSum: rrfContribution,
|
|
2971
|
+
maxRawScore: rawScore,
|
|
2972
|
+
bestRank: rank,
|
|
2973
|
+
fields: new Set(item.matchedFields ?? []),
|
|
2974
|
+
pinpointTerms: new Set(pinpointTerms ?? []),
|
|
2975
|
+
pinpointDesignators: new Set(pinpointDesignators ?? []),
|
|
2976
|
+
bestSnippetTerms: snippetTerms,
|
|
959
2977
|
});
|
|
960
2978
|
}
|
|
2979
|
+
else {
|
|
2980
|
+
existing.rrfSum += rrfContribution;
|
|
2981
|
+
existing.maxRawScore = Math.max(existing.maxRawScore, rawScore);
|
|
2982
|
+
for (const f of item.matchedFields ?? []) {
|
|
2983
|
+
existing.fields.add(f);
|
|
2984
|
+
}
|
|
2985
|
+
for (const pt of pinpointTerms ?? []) {
|
|
2986
|
+
existing.pinpointTerms.add(pt);
|
|
2987
|
+
}
|
|
2988
|
+
for (const pd of pinpointDesignators ?? []) {
|
|
2989
|
+
existing.pinpointDesignators.add(pd);
|
|
2990
|
+
}
|
|
2991
|
+
if (rank < existing.bestRank && snippetTerms?.length) {
|
|
2992
|
+
existing.bestRank = rank;
|
|
2993
|
+
existing.bestSnippetTerms = snippetTerms;
|
|
2994
|
+
}
|
|
2995
|
+
else if (!existing.bestSnippetTerms && snippetTerms?.length) {
|
|
2996
|
+
existing.bestSnippetTerms = snippetTerms;
|
|
2997
|
+
}
|
|
2998
|
+
}
|
|
961
2999
|
}
|
|
962
|
-
results.sort((a, b) => (b.score ?? 0) - (a.score ?? 0) || a.id.localeCompare(b.id));
|
|
963
3000
|
}
|
|
964
|
-
|
|
965
|
-
|
|
3001
|
+
const sortedFused = Array.from(fusedById.values())
|
|
3002
|
+
.map((entry) => ({
|
|
3003
|
+
entry,
|
|
3004
|
+
fusedScore: Math.round(entry.rrfSum + 0.15 * entry.maxRawScore),
|
|
3005
|
+
}))
|
|
3006
|
+
.sort((a, b) => b.fusedScore - a.fusedScore || a.entry.base.id.localeCompare(b.entry.base.id));
|
|
3007
|
+
if (!options.domainId && wiki.domains.size > 1) {
|
|
3008
|
+
const domainSeenCount = new Map();
|
|
3009
|
+
for (const hit of sortedFused) {
|
|
3010
|
+
const domain = hit.entry.base.domainId;
|
|
3011
|
+
const seen = domainSeenCount.get(domain) ?? 0;
|
|
3012
|
+
hit.fusedScore = Math.round(hit.fusedScore / (1 + Math.min(seen, 4) * 0.12));
|
|
3013
|
+
domainSeenCount.set(domain, seen + 1);
|
|
3014
|
+
}
|
|
3015
|
+
sortedFused.sort((left, right) => right.fusedScore - left.fusedScore || left.entry.base.id.localeCompare(right.entry.base.id));
|
|
966
3016
|
}
|
|
967
|
-
return
|
|
3017
|
+
return applyLimit(sortedFused, options.limit).map(({ entry, fusedScore }) => {
|
|
3018
|
+
const orderedFields = FIELD_DISPLAY_ORDER.filter((f) => entry.fields.has(f));
|
|
3019
|
+
const baseWithScore = {
|
|
3020
|
+
...entry.base,
|
|
3021
|
+
score: fusedScore,
|
|
3022
|
+
...(orderedFields.length > 0 ? { matchedFields: orderedFields } : {}),
|
|
3023
|
+
};
|
|
3024
|
+
return enrichSceneItem(baseWithScore, entry.bestSnippetTerms, Array.from(entry.pinpointTerms), entry.pinpointDesignators);
|
|
3025
|
+
});
|
|
3026
|
+
}
|
|
3027
|
+
/**
|
|
3028
|
+
* Returns precomputed lowercase corpus text & canonical designator set for a scene in O(N_init) / O(1_cached).
|
|
3029
|
+
*/
|
|
3030
|
+
export function inspectSceneCoverageData(wiki, sceneId) {
|
|
3031
|
+
const index = getPrecomputedWikiIndex(wiki);
|
|
3032
|
+
const found = index.sceneById.get(sceneId);
|
|
3033
|
+
if (!found) {
|
|
3034
|
+
return undefined;
|
|
3035
|
+
}
|
|
3036
|
+
return {
|
|
3037
|
+
allTextLower: found.entry.doc.allTextLower,
|
|
3038
|
+
designators: found.entry.doc.designators.all,
|
|
3039
|
+
};
|
|
968
3040
|
}
|
|
969
3041
|
//# sourceMappingURL=discover.js.map
|