@open-livex-wiki/core 0.2.1 → 0.2.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/browser.d.ts +2 -1
- package/dist/browser.d.ts.map +1 -1
- package/dist/browser.js +1 -0
- package/dist/browser.js.map +1 -1
- package/dist/coverage/handles.d.ts +5 -0
- package/dist/coverage/handles.d.ts.map +1 -0
- package/dist/coverage/handles.js +125 -0
- package/dist/coverage/handles.js.map +1 -0
- package/dist/coverage/targets.d.ts +22 -0
- package/dist/coverage/targets.d.ts.map +1 -0
- package/dist/coverage/targets.js +117 -0
- package/dist/coverage/targets.js.map +1 -0
- package/dist/coverage/units.d.ts +9 -0
- package/dist/coverage/units.d.ts.map +1 -0
- package/dist/coverage/units.js +82 -0
- package/dist/coverage/units.js.map +1 -0
- package/dist/coverage/visuals.d.ts +26 -0
- package/dist/coverage/visuals.d.ts.map +1 -0
- package/dist/coverage/visuals.js +177 -0
- package/dist/coverage/visuals.js.map +1 -0
- package/dist/coverage.d.ts.map +1 -1
- package/dist/coverage.js +61 -243
- package/dist/coverage.js.map +1 -1
- package/dist/discover/designators.d.ts +26 -0
- package/dist/discover/designators.d.ts.map +1 -0
- package/dist/discover/designators.js +361 -0
- package/dist/discover/designators.js.map +1 -0
- package/dist/discover/document-types.d.ts +90 -0
- package/dist/discover/document-types.d.ts.map +1 -0
- package/dist/discover/document-types.js +2 -0
- package/dist/discover/document-types.js.map +1 -0
- package/dist/discover/index-builder.d.ts +28 -0
- package/dist/discover/index-builder.d.ts.map +1 -0
- package/dist/discover/index-builder.js +286 -0
- package/dist/discover/index-builder.js.map +1 -0
- package/dist/discover/postings.d.ts +9 -0
- package/dist/discover/postings.d.ts.map +1 -0
- package/dist/discover/postings.js +183 -0
- package/dist/discover/postings.js.map +1 -0
- package/dist/discover/query-expansion.d.ts +4 -0
- package/dist/discover/query-expansion.d.ts.map +1 -0
- package/dist/discover/query-expansion.js +109 -0
- package/dist/discover/query-expansion.js.map +1 -0
- package/dist/discover/scene-document.d.ts +40 -0
- package/dist/discover/scene-document.d.ts.map +1 -0
- package/dist/discover/scene-document.js +417 -0
- package/dist/discover/scene-document.js.map +1 -0
- package/dist/discover/scene-ranking.d.ts +14 -0
- package/dist/discover/scene-ranking.d.ts.map +1 -0
- package/dist/discover/scene-ranking.js +228 -0
- package/dist/discover/scene-ranking.js.map +1 -0
- package/dist/discover/scoring.d.ts +37 -0
- package/dist/discover/scoring.d.ts.map +1 -0
- package/dist/discover/scoring.js +452 -0
- package/dist/discover/scoring.js.map +1 -0
- package/dist/discover/subscene.d.ts +11 -0
- package/dist/discover/subscene.d.ts.map +1 -0
- package/dist/discover/subscene.js +121 -0
- package/dist/discover/subscene.js.map +1 -0
- package/dist/discover/term-scoring.d.ts +26 -0
- package/dist/discover/term-scoring.d.ts.map +1 -0
- package/dist/discover/term-scoring.js +385 -0
- package/dist/discover/term-scoring.js.map +1 -0
- package/dist/discover/tokenizer.d.ts +36 -0
- package/dist/discover/tokenizer.d.ts.map +1 -0
- package/dist/discover/tokenizer.js +287 -0
- package/dist/discover/tokenizer.js.map +1 -0
- package/dist/discover.d.ts +11 -61
- package/dist/discover.d.ts.map +1 -1
- package/dist/discover.js +123 -2755
- package/dist/discover.js.map +1 -1
- package/dist/index.d.ts +3 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +2 -1
- package/dist/index.js.map +1 -1
- package/dist/loader/config.d.ts +29 -0
- package/dist/loader/config.d.ts.map +1 -0
- package/dist/loader/config.js +80 -0
- package/dist/loader/config.js.map +1 -0
- package/dist/loader/domain.d.ts +19 -0
- package/dist/loader/domain.d.ts.map +1 -0
- package/dist/loader/domain.js +152 -0
- package/dist/loader/domain.js.map +1 -0
- package/dist/loader/paths.d.ts +4 -0
- package/dist/loader/paths.d.ts.map +1 -0
- package/dist/loader/paths.js +29 -0
- package/dist/loader/paths.js.map +1 -0
- package/dist/loader/scene.d.ts +16 -0
- package/dist/loader/scene.d.ts.map +1 -0
- package/dist/loader/scene.js +266 -0
- package/dist/loader/scene.js.map +1 -0
- package/dist/loader.d.ts +2 -2
- package/dist/loader.d.ts.map +1 -1
- package/dist/loader.js +11 -506
- package/dist/loader.js.map +1 -1
- package/dist/reference-linker.d.ts +7 -0
- package/dist/reference-linker.d.ts.map +1 -0
- package/dist/reference-linker.js +155 -0
- package/dist/reference-linker.js.map +1 -0
- package/dist/schemas.d.ts +14 -11
- package/dist/schemas.d.ts.map +1 -1
- package/dist/schemas.js +2 -1
- package/dist/schemas.js.map +1 -1
- package/dist/types.d.ts +34 -0
- package/dist/types.d.ts.map +1 -1
- package/dist/utils/markdown-scanner.d.ts +20 -0
- package/dist/utils/markdown-scanner.d.ts.map +1 -0
- package/dist/utils/markdown-scanner.js +303 -0
- package/dist/utils/markdown-scanner.js.map +1 -0
- package/dist/utils/markdown.d.ts +48 -0
- package/dist/utils/markdown.d.ts.map +1 -0
- package/dist/utils/markdown.js +370 -0
- package/dist/utils/markdown.js.map +1 -0
- package/dist/utils/paths.d.ts +38 -0
- package/dist/utils/paths.d.ts.map +1 -0
- package/dist/utils/paths.js +257 -0
- package/dist/utils/paths.js.map +1 -0
- package/dist/utils/regexp.d.ts +2 -0
- package/dist/utils/regexp.d.ts.map +1 -0
- package/dist/utils/regexp.js +4 -0
- package/dist/utils/regexp.js.map +1 -0
- package/dist/utils/symbols.d.ts +9 -0
- package/dist/utils/symbols.d.ts.map +1 -0
- package/dist/utils/symbols.js +324 -0
- package/dist/utils/symbols.js.map +1 -0
- package/dist/utils.d.ts +4 -96
- package/dist/utils.d.ts.map +1 -1
- package/dist/utils.js +3 -1250
- package/dist/utils.js.map +1 -1
- package/dist/validator/anchor-checker.d.ts +26 -0
- package/dist/validator/anchor-checker.d.ts.map +1 -0
- package/dist/validator/anchor-checker.js +299 -0
- package/dist/validator/anchor-checker.js.map +1 -0
- package/dist/validator/git-remotes.d.ts +12 -0
- package/dist/validator/git-remotes.d.ts.map +1 -0
- package/dist/validator/git-remotes.js +223 -0
- package/dist/validator/git-remotes.js.map +1 -0
- package/dist/validator/source-resolver.d.ts +29 -0
- package/dist/validator/source-resolver.d.ts.map +1 -0
- package/dist/validator/source-resolver.js +315 -0
- package/dist/validator/source-resolver.js.map +1 -0
- package/dist/validator.d.ts +3 -45
- package/dist/validator.d.ts.map +1 -1
- package/dist/validator.js +6 -823
- package/dist/validator.js.map +1 -1
- package/package.json +1 -1
package/dist/discover.js
CHANGED
|
@@ -1,2403 +1,16 @@
|
|
|
1
|
-
import {
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
...CJK_BOUNDARY_PARTICLES,
|
|
15
|
-
]);
|
|
16
|
-
const GENERIC_CJK_SUFFIX_BIGRAMS = new Set([
|
|
17
|
-
"协议",
|
|
18
|
-
"契约",
|
|
19
|
-
"接口",
|
|
20
|
-
"服务",
|
|
21
|
-
"系统",
|
|
22
|
-
"平台",
|
|
23
|
-
"管理",
|
|
24
|
-
"中心",
|
|
25
|
-
"规范",
|
|
26
|
-
"标准",
|
|
27
|
-
"机制",
|
|
28
|
-
"流程",
|
|
29
|
-
"链路",
|
|
30
|
-
"方案",
|
|
31
|
-
"组件",
|
|
32
|
-
"引擎",
|
|
33
|
-
]);
|
|
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;
|
|
35
|
-
const IDENTIFIER_NOISE_SUBTOKENS = new Set([
|
|
36
|
-
"py",
|
|
37
|
-
"ts",
|
|
38
|
-
"tsx",
|
|
39
|
-
"js",
|
|
40
|
-
"jsx",
|
|
41
|
-
"mjs",
|
|
42
|
-
"cjs",
|
|
43
|
-
"go",
|
|
44
|
-
"rs",
|
|
45
|
-
"rb",
|
|
46
|
-
"md",
|
|
47
|
-
"src",
|
|
48
|
-
"lib",
|
|
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
|
-
}
|
|
409
|
-
function isPureCjk(text) {
|
|
410
|
-
return text.length > 0 && /^[\u3400-\u9fff\uf900-\ufaff]+$/.test(text);
|
|
411
|
-
}
|
|
412
|
-
function stripCjkFillers(rawCjk) {
|
|
413
|
-
let cleaned = rawCjk;
|
|
414
|
-
// Iteratively strip prefix/suffix query filler words while remaining length >= 2
|
|
415
|
-
let changed = true;
|
|
416
|
-
while (changed && cleaned.length > 2) {
|
|
417
|
-
changed = false;
|
|
418
|
-
for (const prefix of CJK_PREFIX_FILLERS) {
|
|
419
|
-
if (cleaned.startsWith(prefix) && cleaned.length - prefix.length >= 2) {
|
|
420
|
-
cleaned = cleaned.slice(prefix.length);
|
|
421
|
-
changed = true;
|
|
422
|
-
}
|
|
423
|
-
}
|
|
424
|
-
for (const suffix of CJK_SUFFIX_FILLERS) {
|
|
425
|
-
if (cleaned.endsWith(suffix) && cleaned.length - suffix.length >= 2) {
|
|
426
|
-
cleaned = cleaned.slice(0, -suffix.length);
|
|
427
|
-
changed = true;
|
|
428
|
-
}
|
|
429
|
-
}
|
|
430
|
-
for (const particle of CJK_BOUNDARY_PARTICLES) {
|
|
431
|
-
if (cleaned.startsWith(particle) && cleaned.length - particle.length >= 2) {
|
|
432
|
-
cleaned = cleaned.slice(particle.length);
|
|
433
|
-
changed = true;
|
|
434
|
-
}
|
|
435
|
-
if (cleaned.endsWith(particle) && cleaned.length - particle.length >= 2) {
|
|
436
|
-
cleaned = cleaned.slice(0, -particle.length);
|
|
437
|
-
changed = true;
|
|
438
|
-
}
|
|
439
|
-
}
|
|
440
|
-
}
|
|
441
|
-
// Split conjunctive CJK phrases like "飞书和微信" or "网关的协议" when both sides have >= 2 chars
|
|
442
|
-
const parts = cleaned.split(/[的与和及]/).filter((p) => p.length >= 2);
|
|
443
|
-
if (parts.length >= 2) {
|
|
444
|
-
return parts;
|
|
445
|
-
}
|
|
446
|
-
return [cleaned];
|
|
447
|
-
}
|
|
448
|
-
function buildCjkGroup(cjkToken, rawOriginal) {
|
|
449
|
-
const threeGrams = [];
|
|
450
|
-
const twoGrams = [];
|
|
451
|
-
if (cjkToken.length >= 3) {
|
|
452
|
-
const trailingBigram = cjkToken.length >= 4 ? cjkToken.slice(-2) : "";
|
|
453
|
-
const hasGenericSuffix = cjkToken.length >= 4 &&
|
|
454
|
-
GENERIC_CJK_SUFFIX_BIGRAMS.has(trailingBigram) &&
|
|
455
|
-
cjkToken.length - 2 >= 2;
|
|
456
|
-
if (hasGenericSuffix) {
|
|
457
|
-
// Preserve morpheme boundary `<head><genericSuffix>` (e.g. "中台" + "服务") so cross-boundary
|
|
458
|
-
// phantom n-grams ("台服务", "台服") never false-match unrelated siblings ("前台服务")!
|
|
459
|
-
const head = cjkToken.slice(0, -2);
|
|
460
|
-
if (head.length === 3 && !CJK_STOP_WORDS_SET.has(head)) {
|
|
461
|
-
threeGrams.push(head);
|
|
462
|
-
}
|
|
463
|
-
else if (head.length >= 4) {
|
|
464
|
-
for (let i = 0; i <= head.length - 3; i++) {
|
|
465
|
-
const tri = head.slice(i, i + 3);
|
|
466
|
-
if (!CJK_STOP_WORDS_SET.has(tri)) {
|
|
467
|
-
threeGrams.push(tri);
|
|
468
|
-
}
|
|
469
|
-
}
|
|
470
|
-
}
|
|
471
|
-
for (let i = 0; i <= head.length - 2; i++) {
|
|
472
|
-
const bi = head.slice(i, i + 2);
|
|
473
|
-
if (!CJK_STOP_WORDS_SET.has(bi)) {
|
|
474
|
-
twoGrams.push(bi);
|
|
475
|
-
}
|
|
476
|
-
}
|
|
477
|
-
if (!CJK_STOP_WORDS_SET.has(trailingBigram)) {
|
|
478
|
-
twoGrams.push(trailingBigram);
|
|
479
|
-
}
|
|
480
|
-
}
|
|
481
|
-
else {
|
|
482
|
-
if (cjkToken.length >= 4) {
|
|
483
|
-
for (let i = 0; i <= cjkToken.length - 3; i++) {
|
|
484
|
-
const tri = cjkToken.slice(i, i + 3);
|
|
485
|
-
if (!CJK_STOP_WORDS_SET.has(tri)) {
|
|
486
|
-
threeGrams.push(tri);
|
|
487
|
-
}
|
|
488
|
-
}
|
|
489
|
-
}
|
|
490
|
-
for (let i = 0; i <= cjkToken.length - 2; i++) {
|
|
491
|
-
const bi = cjkToken.slice(i, i + 2);
|
|
492
|
-
if (!CJK_STOP_WORDS_SET.has(bi)) {
|
|
493
|
-
twoGrams.push(bi);
|
|
494
|
-
}
|
|
495
|
-
}
|
|
496
|
-
}
|
|
497
|
-
}
|
|
498
|
-
const isStrippedStem = Boolean(rawOriginal && rawOriginal !== cjkToken);
|
|
499
|
-
return {
|
|
500
|
-
primary: cjkToken,
|
|
501
|
-
...(isStrippedStem && rawOriginal ? { rawToken: rawOriginal, isStrippedStem: true } : {}),
|
|
502
|
-
threeGrams: Array.from(new Set(threeGrams)),
|
|
503
|
-
twoGrams: Array.from(new Set(twoGrams)),
|
|
504
|
-
};
|
|
505
|
-
}
|
|
506
|
-
function extractIdentifierSubTokens(rawAsciiToken, lowerPrimary) {
|
|
507
|
-
const withoutExt = rawAsciiToken.trim().replace(SOURCE_FILE_EXT_REGEX, "");
|
|
508
|
-
// Split camelCase ("AgentAPI" -> "Agent API", "HTMLParser" -> "HTML Parser") and snake/kebab/path separators
|
|
509
|
-
const camelSplit = withoutExt
|
|
510
|
-
.replace(/([a-z0-9])([A-Z])/g, "$1 $2")
|
|
511
|
-
.replace(/([A-Z]+)([A-Z][a-z])/g, "$1 $2");
|
|
512
|
-
const rawParts = camelSplit
|
|
513
|
-
.toLowerCase()
|
|
514
|
-
.split(/[^a-z0-9]+/)
|
|
515
|
-
.map((p) => p.trim())
|
|
516
|
-
.filter((p) => p.length >= 2 && p !== lowerPrimary && !IDENTIFIER_NOISE_SUBTOKENS.has(p));
|
|
517
|
-
const deduped = Array.from(new Set(rawParts));
|
|
518
|
-
return deduped.length >= 2 ? deduped : [];
|
|
519
|
-
}
|
|
520
|
-
function escapeRegExpLiteral(str) {
|
|
521
|
-
return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
522
|
-
}
|
|
523
|
-
/**
|
|
524
|
-
* Smart CJK + Mixed-Script + Designator-Aware tokenizer for progressive discovery queries.
|
|
525
|
-
* - Splits on whitespace and punctuation while preserving `.`, `-`, `_`, `#` inside identifiers/filenames.
|
|
526
|
-
* - Canonicalizes alphanumeric designators (`"FFG-62"` / `"FFG 62"` -> `"ffg62"`, `"CRS-R44972"` -> `["crsr44972", "r44972"]`).
|
|
527
|
-
* - Splits CJK <-> ASCII/number transitions (`"iOS内购"` -> `["ios", "内购"]`, `"LLM网关"` -> `["llm", "网关"]`).
|
|
528
|
-
* - Strips Chinese filler/stop particles when remaining CJK length >= 2.
|
|
529
|
-
* - Emits overlapping CJK 2-grams and 3-grams for CJK compound tokens of length >= 3.
|
|
530
|
-
* - Decomposes compound code/file identifiers (`"settings_api.py"` -> `["settings", "api"]`) for fallback co-occurrence matching.
|
|
531
|
-
*/
|
|
532
|
-
export function tokenizeDiscoveryQuery(query) {
|
|
533
|
-
const trimmedOriginal = query.trim();
|
|
534
|
-
const normalizedPhrase = trimmedOriginal.toLowerCase();
|
|
535
|
-
if (!normalizedPhrase) {
|
|
536
|
-
return { normalizedPhrase: "", groups: [] };
|
|
537
|
-
}
|
|
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);
|
|
542
|
-
const seenPrimary = new Set();
|
|
543
|
-
const groups = [];
|
|
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
|
-
}
|
|
552
|
-
const cleanedOriginal = rawTok.trim().replace(/^[._#-]+|[._#-]+$/g, "");
|
|
553
|
-
const t = cleanedOriginal.toLowerCase();
|
|
554
|
-
if (!t || seenPrimary.has(t)) {
|
|
555
|
-
return;
|
|
556
|
-
}
|
|
557
|
-
if (isPureCjk(t)) {
|
|
558
|
-
if (CJK_STOP_WORDS_SET.has(t) && normalizedPhrase !== t) {
|
|
559
|
-
return;
|
|
560
|
-
}
|
|
561
|
-
seenPrimary.add(t);
|
|
562
|
-
groups.push(buildCjkGroup(t, rawCjkRun?.toLowerCase()));
|
|
563
|
-
return;
|
|
564
|
-
}
|
|
565
|
-
if (t.length < 2 && normalizedPhrase.length >= 2) {
|
|
566
|
-
return;
|
|
567
|
-
}
|
|
568
|
-
seenPrimary.add(t);
|
|
569
|
-
const subTokens = extractIdentifierSubTokens(cleanedOriginal, t);
|
|
570
|
-
const normDesig = normalizeDesignatorToken(cleanedOriginal);
|
|
571
|
-
const designators = normDesig ? buildDesignatorVariants(cleanedOriginal, normDesig) : [];
|
|
572
|
-
groups.push({
|
|
573
|
-
primary: t,
|
|
574
|
-
threeGrams: [],
|
|
575
|
-
twoGrams: [],
|
|
576
|
-
...(subTokens.length > 0 ? { subTokens } : {}),
|
|
577
|
-
...(designators.length > 0 ? { designators } : {}),
|
|
578
|
-
});
|
|
579
|
-
}
|
|
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
|
-
}
|
|
612
|
-
const hasMixedScript = CJK_CHAR_REGEX.test(segment) && /[^\u3400-\u9fff\uf900-\ufaff]/.test(segment);
|
|
613
|
-
if (!hasMixedScript) {
|
|
614
|
-
if (isPureCjk(segment)) {
|
|
615
|
-
for (const stripped of stripCjkFillers(segment)) {
|
|
616
|
-
addToken(stripped, segment);
|
|
617
|
-
}
|
|
618
|
-
}
|
|
619
|
-
else {
|
|
620
|
-
addToken(segment);
|
|
621
|
-
}
|
|
622
|
-
continue;
|
|
623
|
-
}
|
|
624
|
-
// Split CJK <-> ASCII/number runs (e.g. "iOS内购" -> ["ios", "内购"], "LLM网关" -> ["llm", "网关"])
|
|
625
|
-
const runs = segment.match(CJK_RUN_OR_OTHER_REGEX) ?? [segment];
|
|
626
|
-
for (const run of runs) {
|
|
627
|
-
if (isPureCjk(run)) {
|
|
628
|
-
for (const stripped of stripCjkFillers(run)) {
|
|
629
|
-
addToken(stripped, run);
|
|
630
|
-
}
|
|
631
|
-
}
|
|
632
|
-
else {
|
|
633
|
-
addToken(run);
|
|
634
|
-
}
|
|
635
|
-
}
|
|
636
|
-
}
|
|
637
|
-
if (groups.length === 0) {
|
|
638
|
-
groups.push(isPureCjk(normalizedPhrase)
|
|
639
|
-
? buildCjkGroup(normalizedPhrase)
|
|
640
|
-
: { primary: normalizedPhrase, threeGrams: [], twoGrams: [] });
|
|
641
|
-
}
|
|
642
|
-
return { normalizedPhrase, groups };
|
|
643
|
-
}
|
|
644
|
-
function extractInlineCodeSpans(markdown) {
|
|
645
|
-
if (!markdown.includes("`"))
|
|
646
|
-
return [];
|
|
647
|
-
const spans = [];
|
|
648
|
-
const lines = markdown.split(/\r?\n/);
|
|
649
|
-
let inFence = false;
|
|
650
|
-
let fenceChar = "";
|
|
651
|
-
let fenceLen = 0;
|
|
652
|
-
for (const rawLine of lines) {
|
|
653
|
-
if (!inFence) {
|
|
654
|
-
const open = /^ {0,3}(`{3,}|~{3,})(.*)$/.exec(rawLine);
|
|
655
|
-
if (open?.[1] && !(open[1][0] === "`" && (open[2] ?? "").includes("`"))) {
|
|
656
|
-
inFence = true;
|
|
657
|
-
fenceChar = open[1][0] ?? "`";
|
|
658
|
-
fenceLen = open[1].length;
|
|
659
|
-
continue;
|
|
660
|
-
}
|
|
661
|
-
}
|
|
662
|
-
else {
|
|
663
|
-
const close = /^ {0,3}(`{3,}|~{3,})[ \t]*$/.exec(rawLine);
|
|
664
|
-
if (close?.[1] && close[1][0] === fenceChar && close[1].length >= fenceLen) {
|
|
665
|
-
inFence = false;
|
|
666
|
-
}
|
|
667
|
-
continue;
|
|
668
|
-
}
|
|
669
|
-
const matches = rawLine.matchAll(/`([^`\r\n]+)`/g);
|
|
670
|
-
for (const m of matches) {
|
|
671
|
-
const code = m[1]?.trim();
|
|
672
|
-
if (code) {
|
|
673
|
-
spans.push(code);
|
|
674
|
-
}
|
|
675
|
-
}
|
|
676
|
-
}
|
|
677
|
-
return spans;
|
|
678
|
-
}
|
|
679
|
-
function sanitizeMarkdownForSnippet(markdown) {
|
|
680
|
-
const withoutComments = markdown.replace(/<!--[\s\S]*?-->/g, " ");
|
|
681
|
-
let out = "";
|
|
682
|
-
for (let i = 0; i < withoutComments.length; i++) {
|
|
683
|
-
const code = withoutComments.charCodeAt(i);
|
|
684
|
-
out += code <= 0x1f || code === 0x7f ? " " : withoutComments[i];
|
|
685
|
-
}
|
|
686
|
-
return out.replace(/\s+/g, " ").trim();
|
|
687
|
-
}
|
|
688
|
-
function extractMatchSnippet(sources, matchedTerms, targetLength = 80) {
|
|
689
|
-
if (matchedTerms.length === 0 || sources.length === 0) {
|
|
690
|
-
return undefined;
|
|
691
|
-
}
|
|
692
|
-
// Sort matched terms longest first so snippet centers on the most specific term
|
|
693
|
-
const sortedTerms = Array.from(new Set(matchedTerms))
|
|
694
|
-
.filter((t) => t.length > 0)
|
|
695
|
-
.sort((a, b) => b.length - a.length);
|
|
696
|
-
for (const rawSource of sources) {
|
|
697
|
-
const clean = sanitizeMarkdownForSnippet(rawSource);
|
|
698
|
-
if (!clean) {
|
|
699
|
-
continue;
|
|
700
|
-
}
|
|
701
|
-
const cleanLower = clean.toLowerCase();
|
|
702
|
-
for (const term of sortedTerms) {
|
|
703
|
-
const idx = cleanLower.indexOf(term.toLowerCase());
|
|
704
|
-
if (idx === -1) {
|
|
705
|
-
continue;
|
|
706
|
-
}
|
|
707
|
-
if (clean.length <= targetLength) {
|
|
708
|
-
return clean;
|
|
709
|
-
}
|
|
710
|
-
const half = Math.max(10, Math.floor((targetLength - term.length) / 2));
|
|
711
|
-
let start = Math.max(0, idx - half);
|
|
712
|
-
const end = Math.min(clean.length, start + targetLength);
|
|
713
|
-
if (end - start < targetLength) {
|
|
714
|
-
start = Math.max(0, end - targetLength);
|
|
715
|
-
}
|
|
716
|
-
const slice = clean.slice(start, end).trim();
|
|
717
|
-
const prefix = start > 0 ? "..." : "";
|
|
718
|
-
const suffix = end < clean.length ? "..." : "";
|
|
719
|
-
return `${prefix}${slice}${suffix}`;
|
|
720
|
-
}
|
|
721
|
-
}
|
|
722
|
-
return undefined;
|
|
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
|
-
}
|
|
1605
|
-
const FIELD_DISPLAY_ORDER = [
|
|
1606
|
-
"id",
|
|
1607
|
-
"title",
|
|
1608
|
-
"alias",
|
|
1609
|
-
"chain",
|
|
1610
|
-
"anchor",
|
|
1611
|
-
"repo",
|
|
1612
|
-
"source",
|
|
1613
|
-
"summary",
|
|
1614
|
-
"heading",
|
|
1615
|
-
"detail",
|
|
1616
|
-
"scene",
|
|
1617
|
-
"code",
|
|
1618
|
-
"body",
|
|
1619
|
-
];
|
|
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
|
-
}
|
|
1642
|
-
let best = 0;
|
|
1643
|
-
const fields = new Set();
|
|
1644
|
-
let matchedHigherThanBody = false;
|
|
1645
|
-
let matchedCodeOrDetail = false;
|
|
1646
|
-
let matchedBodyText = false;
|
|
1647
|
-
function record(score, field, tier) {
|
|
1648
|
-
if (score <= 0) {
|
|
1649
|
-
return;
|
|
1650
|
-
}
|
|
1651
|
-
best = Math.max(best, score);
|
|
1652
|
-
fields.add(field);
|
|
1653
|
-
if (tier === "high") {
|
|
1654
|
-
matchedHigherThanBody = true;
|
|
1655
|
-
}
|
|
1656
|
-
else if (tier === "code") {
|
|
1657
|
-
matchedCodeOrDetail = true;
|
|
1658
|
-
}
|
|
1659
|
-
else {
|
|
1660
|
-
matchedBodyText = true;
|
|
1661
|
-
}
|
|
1662
|
-
}
|
|
1663
|
-
// Tier 1: id / shortId, title, aliases
|
|
1664
|
-
const idLower = doc.idLower;
|
|
1665
|
-
const shortIdLower = doc.shortIdLower;
|
|
1666
|
-
if (idLower === term || shortIdLower === term || doc.shortIdCollapsed === term) {
|
|
1667
|
-
record(120, "id", "high");
|
|
1668
|
-
}
|
|
1669
|
-
else if (idLower.startsWith(term) || shortIdLower?.startsWith(term)) {
|
|
1670
|
-
record(86, "id", "high");
|
|
1671
|
-
}
|
|
1672
|
-
else if (idLower.includes(term)) {
|
|
1673
|
-
record(66, "id", "high");
|
|
1674
|
-
}
|
|
1675
|
-
else if (shortIdLower && shortIdLower.length >= 3 && term.includes(shortIdLower)) {
|
|
1676
|
-
record(58, "id", "high");
|
|
1677
|
-
}
|
|
1678
|
-
const titleLower = doc.titleLower;
|
|
1679
|
-
if (titleLower === term || doc.titleCollapsed === term) {
|
|
1680
|
-
record(115, "title", "high");
|
|
1681
|
-
}
|
|
1682
|
-
else if (titleLower.startsWith(term)) {
|
|
1683
|
-
record(84, "title", "high");
|
|
1684
|
-
}
|
|
1685
|
-
else if (titleLower.includes(term)) {
|
|
1686
|
-
record(64, "title", "high");
|
|
1687
|
-
}
|
|
1688
|
-
else if (titleLower.length >= 2 && term.length >= 2 && term.includes(titleLower)) {
|
|
1689
|
-
record(58, "title", "high");
|
|
1690
|
-
}
|
|
1691
|
-
for (const aliasLower of doc.aliasesLower) {
|
|
1692
|
-
if (aliasLower === term) {
|
|
1693
|
-
record(110, "alias", "high");
|
|
1694
|
-
}
|
|
1695
|
-
else if (aliasLower.startsWith(term)) {
|
|
1696
|
-
record(80, "alias", "high");
|
|
1697
|
-
}
|
|
1698
|
-
else if (aliasLower.includes(term)) {
|
|
1699
|
-
record(60, "alias", "high");
|
|
1700
|
-
}
|
|
1701
|
-
else if (aliasLower.length >= 2 && term.length >= 2 && term.includes(aliasLower)) {
|
|
1702
|
-
record(56, "alias", "high");
|
|
1703
|
-
}
|
|
1704
|
-
}
|
|
1705
|
-
// Tier 2: chainNames, anchors, repositories, sources
|
|
1706
|
-
for (const cLower of doc.chainTermsLower) {
|
|
1707
|
-
if (cLower === term) {
|
|
1708
|
-
record(95, "chain", "high");
|
|
1709
|
-
}
|
|
1710
|
-
else if (cLower.startsWith(term)) {
|
|
1711
|
-
record(72, "chain", "high");
|
|
1712
|
-
}
|
|
1713
|
-
else if (cLower.includes(term)) {
|
|
1714
|
-
record(52, "chain", "high");
|
|
1715
|
-
}
|
|
1716
|
-
else if (cLower.length >= 3 && term.length >= 3 && term.includes(cLower)) {
|
|
1717
|
-
record(46, "chain", "high");
|
|
1718
|
-
}
|
|
1719
|
-
}
|
|
1720
|
-
for (const anchorTerm of doc.anchorTerms) {
|
|
1721
|
-
const aLower = anchorTerm.lower;
|
|
1722
|
-
const baseName = anchorTerm.base;
|
|
1723
|
-
if (aLower === term || baseName === term) {
|
|
1724
|
-
record(92, "anchor", "high");
|
|
1725
|
-
}
|
|
1726
|
-
else if (baseName.startsWith(term) || aLower.startsWith(term)) {
|
|
1727
|
-
record(68, "anchor", "high");
|
|
1728
|
-
}
|
|
1729
|
-
else if (aLower.includes(term)) {
|
|
1730
|
-
record(50, "anchor", "high");
|
|
1731
|
-
}
|
|
1732
|
-
else if (baseName.length >= 3 && term.includes(baseName)) {
|
|
1733
|
-
record(44, "anchor", "high");
|
|
1734
|
-
}
|
|
1735
|
-
}
|
|
1736
|
-
for (const repoTerm of doc.repoTerms) {
|
|
1737
|
-
const rLower = repoTerm.lower;
|
|
1738
|
-
const repoBase = repoTerm.base;
|
|
1739
|
-
if (rLower === term || repoBase === term) {
|
|
1740
|
-
record(82, "repo", "high");
|
|
1741
|
-
}
|
|
1742
|
-
else if (rLower.includes(term)) {
|
|
1743
|
-
record(44, "repo", "high");
|
|
1744
|
-
}
|
|
1745
|
-
else if (repoBase.length >= 3 && term.includes(repoBase)) {
|
|
1746
|
-
record(38, "repo", "high");
|
|
1747
|
-
}
|
|
1748
|
-
}
|
|
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");
|
|
1754
|
-
}
|
|
1755
|
-
else if (sLower.includes(term)) {
|
|
1756
|
-
record(44, "source", "high");
|
|
1757
|
-
}
|
|
1758
|
-
else if (srcBase.length >= 3 && term.includes(srcBase)) {
|
|
1759
|
-
record(38, "source", "high");
|
|
1760
|
-
}
|
|
1761
|
-
}
|
|
1762
|
-
// Domain child high-tier terms (include reverse substring check)
|
|
1763
|
-
for (const chLower of doc.childHighTermsLower) {
|
|
1764
|
-
if (chLower === term) {
|
|
1765
|
-
record(72, "scene", "high");
|
|
1766
|
-
}
|
|
1767
|
-
else if (chLower.startsWith(term)) {
|
|
1768
|
-
record(52, "scene", "high");
|
|
1769
|
-
}
|
|
1770
|
-
else if (chLower.includes(term)) {
|
|
1771
|
-
record(40, "scene", "high");
|
|
1772
|
-
}
|
|
1773
|
-
else if (chLower.length >= 2 && term.length >= 2 && term.includes(chLower)) {
|
|
1774
|
-
record(38, "scene", "high");
|
|
1775
|
-
}
|
|
1776
|
-
}
|
|
1777
|
-
for (const chAnchor of doc.childAnchorTerms) {
|
|
1778
|
-
if (chAnchor.lower === term || chAnchor.base === term) {
|
|
1779
|
-
record(64, "anchor", "high");
|
|
1780
|
-
}
|
|
1781
|
-
else if (chAnchor.lower.includes(term)) {
|
|
1782
|
-
record(38, "anchor", "high");
|
|
1783
|
-
}
|
|
1784
|
-
}
|
|
1785
|
-
for (const chRepo of doc.childRepoTerms) {
|
|
1786
|
-
if (chRepo.lower === term || chRepo.base === term) {
|
|
1787
|
-
record(58, "repo", "high");
|
|
1788
|
-
}
|
|
1789
|
-
else if (chRepo.lower.includes(term)) {
|
|
1790
|
-
record(34, "repo", "high");
|
|
1791
|
-
}
|
|
1792
|
-
}
|
|
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");
|
|
1813
|
-
}
|
|
1814
|
-
else if (hLower.includes(term)) {
|
|
1815
|
-
record(34, "heading", "high");
|
|
1816
|
-
}
|
|
1817
|
-
}
|
|
1818
|
-
for (const dLower of doc.detailTitlesLower) {
|
|
1819
|
-
if (dLower === term) {
|
|
1820
|
-
record(62, "detail", "high");
|
|
1821
|
-
}
|
|
1822
|
-
else if (dLower.includes(term)) {
|
|
1823
|
-
record(38, "detail", "high");
|
|
1824
|
-
}
|
|
1825
|
-
}
|
|
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
|
-
}
|
|
1852
|
-
}
|
|
1853
|
-
}
|
|
1854
|
-
}
|
|
1855
|
-
return {
|
|
1856
|
-
bestScore: best,
|
|
1857
|
-
fields,
|
|
1858
|
-
matchedHigherThanBody,
|
|
1859
|
-
matchedCodeOrDetail,
|
|
1860
|
-
matchedBodyText,
|
|
1861
|
-
};
|
|
1862
|
-
}
|
|
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) {
|
|
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;
|
|
2139
|
-
if (!tokenized.normalizedPhrase) {
|
|
2140
|
-
return { score: 1, matchedFields: [] };
|
|
2141
|
-
}
|
|
2142
|
-
const allMatchedFields = new Set();
|
|
2143
|
-
const bodySnippetTerms = [];
|
|
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) {
|
|
2157
|
-
allMatchedFields.add(f);
|
|
2158
|
-
}
|
|
2159
|
-
if (rawPhraseHit.matchedBodyText || rawPhraseHit.matchedCodeOrDetail) {
|
|
2160
|
-
bodySnippetTerms.push(tokenized.normalizedPhrase);
|
|
2161
|
-
}
|
|
2162
|
-
}
|
|
2163
|
-
const groupScores = [];
|
|
2164
|
-
let matchedGroupCount = 0;
|
|
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;
|
|
2170
|
-
let primaryHit;
|
|
2171
|
-
let effectivePrimaryTerm = group.primary;
|
|
2172
|
-
if (group.isStrippedStem && group.rawToken) {
|
|
2173
|
-
const rawHit = scoreTerm(group.rawToken);
|
|
2174
|
-
const stemHit = scoreTerm(group.primary);
|
|
2175
|
-
const discountedStemScore = stemHit.bestScore > 0 ? Math.max(1, Math.round(stemHit.bestScore * 0.45)) : 0;
|
|
2176
|
-
if (rawHit.bestScore >= discountedStemScore && rawHit.bestScore > 0) {
|
|
2177
|
-
primaryHit = rawHit;
|
|
2178
|
-
effectivePrimaryTerm = group.rawToken;
|
|
2179
|
-
}
|
|
2180
|
-
else {
|
|
2181
|
-
primaryHit = {
|
|
2182
|
-
...stemHit,
|
|
2183
|
-
bestScore: discountedStemScore,
|
|
2184
|
-
};
|
|
2185
|
-
}
|
|
2186
|
-
}
|
|
2187
|
-
else {
|
|
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
|
-
}
|
|
2209
|
-
}
|
|
2210
|
-
let bestTriScore = 0;
|
|
2211
|
-
let secondTriScore = 0;
|
|
2212
|
-
const triFields = new Set();
|
|
2213
|
-
const triBodyTerms = [];
|
|
2214
|
-
for (const tri of group.threeGrams) {
|
|
2215
|
-
const h = scoreTerm(tri);
|
|
2216
|
-
if (h.bestScore > 0) {
|
|
2217
|
-
for (const f of h.fields) {
|
|
2218
|
-
triFields.add(f);
|
|
2219
|
-
}
|
|
2220
|
-
if (h.matchedBodyText || h.matchedCodeOrDetail) {
|
|
2221
|
-
triBodyTerms.push(tri);
|
|
2222
|
-
}
|
|
2223
|
-
if (h.bestScore >= bestTriScore) {
|
|
2224
|
-
secondTriScore = bestTriScore;
|
|
2225
|
-
bestTriScore = h.bestScore;
|
|
2226
|
-
}
|
|
2227
|
-
else if (h.bestScore > secondTriScore) {
|
|
2228
|
-
secondTriScore = h.bestScore;
|
|
2229
|
-
}
|
|
2230
|
-
}
|
|
2231
|
-
}
|
|
2232
|
-
const stemDiscount = group.isStrippedStem ? 0.45 : 1;
|
|
2233
|
-
const weightedTri = Math.round((bestTriScore * 0.6 + secondTriScore * 0.2) * stemDiscount);
|
|
2234
|
-
const biHits = [];
|
|
2235
|
-
for (const bi of group.twoGrams) {
|
|
2236
|
-
const h = scoreTerm(bi);
|
|
2237
|
-
if (h.bestScore > 0) {
|
|
2238
|
-
biHits.push({ term: bi, hit: h });
|
|
2239
|
-
}
|
|
2240
|
-
}
|
|
2241
|
-
// Precision guard on body-only 2-gram hits: require >= 2 distinct 2-grams if ONLY matching body prose
|
|
2242
|
-
const usableBiHits = biHits.filter((item) => item.hit.matchedHigherThanBody ||
|
|
2243
|
-
item.hit.matchedCodeOrDetail ||
|
|
2244
|
-
primaryHit.bestScore > 0 ||
|
|
2245
|
-
bestTriScore > 0 ||
|
|
2246
|
-
biHits.length >= 2);
|
|
2247
|
-
const hasSpecificHeadBigram = group.twoGrams.some((bi) => !GENERIC_CJK_SUFFIX_BIGRAMS.has(bi));
|
|
2248
|
-
const matchedOnlyGenericSuffix = hasSpecificHeadBigram &&
|
|
2249
|
-
usableBiHits.length > 0 &&
|
|
2250
|
-
usableBiHits.every((item) => GENERIC_CJK_SUFFIX_BIGRAMS.has(item.term));
|
|
2251
|
-
usableBiHits.sort((a, b) => b.hit.bestScore - a.hit.bestScore);
|
|
2252
|
-
let weightedBi = 0;
|
|
2253
|
-
if (usableBiHits.length > 0 && !matchedOnlyGenericSuffix) {
|
|
2254
|
-
const topBiSum = usableBiHits.slice(0, 3).reduce((acc, cur) => acc + cur.hit.bestScore, 0);
|
|
2255
|
-
const coBiBonus = usableBiHits.length >= 2 ? (usableBiHits.length - 1) * 12 : 0;
|
|
2256
|
-
const rawBi = Math.round((topBiSum * 0.38 + coBiBonus) * stemDiscount);
|
|
2257
|
-
if (usableBiHits.length === 1) {
|
|
2258
|
-
weightedBi = Math.min(rawBi, 28);
|
|
2259
|
-
}
|
|
2260
|
-
else {
|
|
2261
|
-
weightedBi = rawBi;
|
|
2262
|
-
}
|
|
2263
|
-
}
|
|
2264
|
-
// Per-group identifier sub-token co-occurrence fallback whenever primaryHit.bestScore === 0
|
|
2265
|
-
const subTokHits = [];
|
|
2266
|
-
if (primaryHit.bestScore === 0 && group.subTokens && group.subTokens.length >= 2) {
|
|
2267
|
-
for (const st of group.subTokens) {
|
|
2268
|
-
const h = scoreTerm(st);
|
|
2269
|
-
if (h.bestScore > 0) {
|
|
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 });
|
|
2280
|
-
}
|
|
2281
|
-
}
|
|
2282
|
-
}
|
|
2283
|
-
let weightedSubTok = 0;
|
|
2284
|
-
if (subTokHits.length >= 2) {
|
|
2285
|
-
subTokHits.sort((a, b) => b.hit.bestScore - a.hit.bestScore);
|
|
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);
|
|
2292
|
-
}
|
|
2293
|
-
const subGramScore = Math.max(weightedTri, weightedBi, weightedSubTok);
|
|
2294
|
-
let rawGroupScore = 0;
|
|
2295
|
-
const matchedTermsForGroup = [];
|
|
2296
|
-
if (primaryHit.bestScore > 0) {
|
|
2297
|
-
rawGroupScore = primaryHit.bestScore + (subGramScore > primaryHit.bestScore ? 8 : 0);
|
|
2298
|
-
for (const f of primaryHit.fields) {
|
|
2299
|
-
allMatchedFields.add(f);
|
|
2300
|
-
}
|
|
2301
|
-
matchedTermsForGroup.push(effectivePrimaryTerm);
|
|
2302
|
-
if (primaryHit.matchedBodyText || primaryHit.matchedCodeOrDetail) {
|
|
2303
|
-
bodySnippetTerms.push(effectivePrimaryTerm);
|
|
2304
|
-
}
|
|
2305
|
-
}
|
|
2306
|
-
else if (subGramScore > 0) {
|
|
2307
|
-
rawGroupScore = subGramScore;
|
|
2308
|
-
if (weightedTri >= weightedBi && weightedTri >= weightedSubTok) {
|
|
2309
|
-
for (const f of triFields) {
|
|
2310
|
-
allMatchedFields.add(f);
|
|
2311
|
-
}
|
|
2312
|
-
matchedTermsForGroup.push(...triBodyTerms, ...group.threeGrams);
|
|
2313
|
-
bodySnippetTerms.push(...triBodyTerms);
|
|
2314
|
-
}
|
|
2315
|
-
else if (weightedSubTok > weightedBi) {
|
|
2316
|
-
for (const st of subTokHits) {
|
|
2317
|
-
for (const f of st.hit.fields) {
|
|
2318
|
-
allMatchedFields.add(f);
|
|
2319
|
-
}
|
|
2320
|
-
matchedTermsForGroup.push(st.term);
|
|
2321
|
-
if (st.hit.matchedBodyText || st.hit.matchedCodeOrDetail) {
|
|
2322
|
-
bodySnippetTerms.push(st.term);
|
|
2323
|
-
}
|
|
2324
|
-
}
|
|
2325
|
-
}
|
|
2326
|
-
else {
|
|
2327
|
-
for (const b of usableBiHits) {
|
|
2328
|
-
for (const f of b.hit.fields) {
|
|
2329
|
-
allMatchedFields.add(f);
|
|
2330
|
-
}
|
|
2331
|
-
matchedTermsForGroup.push(b.term);
|
|
2332
|
-
if (b.hit.matchedBodyText || b.hit.matchedCodeOrDetail) {
|
|
2333
|
-
bodySnippetTerms.push(b.term);
|
|
2334
|
-
}
|
|
2335
|
-
}
|
|
2336
|
-
}
|
|
2337
|
-
}
|
|
2338
|
-
if (rawGroupScore > 0) {
|
|
2339
|
-
matchedGroupCount += 1;
|
|
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);
|
|
2355
|
-
}
|
|
2356
|
-
}
|
|
2357
|
-
if (matchedGroupCount === 0 && weightedPhraseScore === 0) {
|
|
2358
|
-
return { score: 0, matchedFields: [] };
|
|
2359
|
-
}
|
|
2360
|
-
groupScores.sort((a, b) => b - a);
|
|
2361
|
-
const topGroupSum = groupScores.slice(0, 4).reduce((sum, s) => sum + s, 0);
|
|
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 +
|
|
2377
|
-
multiTokenBonus +
|
|
2378
|
-
selectivePhraseBonus +
|
|
2379
|
-
(tokenized.groups.length > 1 ? Math.round(weightedPhraseScore * 0.35) : 0));
|
|
2380
|
-
const orderedFields = FIELD_DISPLAY_ORDER.filter((f) => allMatchedFields.has(f));
|
|
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
|
-
}
|
|
2393
|
-
return {
|
|
2394
|
-
score: combinedScore,
|
|
2395
|
-
matchedFields: orderedFields,
|
|
2396
|
-
...(bodySnippetTerms.length > 0 ? { bodySnippetTerms } : {}),
|
|
2397
|
-
...(activeTerms && activeTerms.length > 0 ? { pinpointTerms: activeTerms } : {}),
|
|
2398
|
-
...(activeDesigs && activeDesigs.size > 0 ? { pinpointDesignators: activeDesigs } : {}),
|
|
2399
|
-
};
|
|
2400
|
-
}
|
|
1
|
+
import { getRelations } from "./relations.js";
|
|
2
|
+
import { escapeRegExp } from "./utils/regexp.js";
|
|
3
|
+
import { getPrecomputedDomains, getPrecomputedWikiIndex, } from "./discover/index-builder.js";
|
|
4
|
+
import { termRows } from "./discover/postings.js";
|
|
5
|
+
import { expandMultiEntitySingleQuery } from "./discover/query-expansion.js";
|
|
6
|
+
import { filterWeakBodyOnlyHits, rankSceneCandidates } from "./discover/scene-ranking.js";
|
|
7
|
+
import { buildPreparedQueryPlan, evaluatePreparedQuery, } from "./discover/scoring.js";
|
|
8
|
+
import { extractMatchSnippet, pinpointSubSceneMatches } from "./discover/subscene.js";
|
|
9
|
+
import { FIELD_DISPLAY_ORDER } from "./discover/term-scoring.js";
|
|
10
|
+
export { extractDesignatorMentions, extractDesignatorTokens, normalizeDesignatorToken, sourceYearMentions, } from "./discover/designators.js";
|
|
11
|
+
export { inspectSceneCoverageData } from "./discover/index-builder.js";
|
|
12
|
+
export { formatAnchorSummaryLabel, toMatchedAnchorSummary } from "./discover/scene-document.js";
|
|
13
|
+
export { tokenizeDiscoveryQuery, } from "./discover/tokenizer.js";
|
|
2401
14
|
function collectActiveQueries(query, queries) {
|
|
2402
15
|
const active = [];
|
|
2403
16
|
if (query?.trim()) {
|
|
@@ -2411,28 +24,6 @@ function collectActiveQueries(query, queries) {
|
|
|
2411
24
|
}
|
|
2412
25
|
return active;
|
|
2413
26
|
}
|
|
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
27
|
function applyLimit(items, limit) {
|
|
2437
28
|
if (limit === undefined) {
|
|
2438
29
|
return items;
|
|
@@ -2574,112 +165,63 @@ export function discoverDomains(wiki, options = {}) {
|
|
|
2574
165
|
};
|
|
2575
166
|
});
|
|
2576
167
|
}
|
|
2577
|
-
|
|
2578
|
-
|
|
2579
|
-
|
|
2580
|
-
|
|
2581
|
-
|
|
2582
|
-
|
|
2583
|
-
|
|
2584
|
-
|
|
2585
|
-
|
|
2586
|
-
|
|
2587
|
-
|
|
2588
|
-
|
|
2589
|
-
|
|
2590
|
-
|
|
2591
|
-
|
|
2592
|
-
|
|
2593
|
-
|
|
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)) {
|
|
2609
|
-
continue;
|
|
2610
|
-
}
|
|
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) {
|
|
2616
|
-
continue;
|
|
2617
|
-
}
|
|
2618
|
-
const hasCorpusPresence = getSceneTermDf(index, g.primary) > 0 ||
|
|
2619
|
-
(g.designators?.some((d) => getSceneDesignatorDf(index, d) > 0) ?? false);
|
|
2620
|
-
if (!hasCorpusPresence) {
|
|
2621
|
-
continue;
|
|
2622
|
-
}
|
|
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;
|
|
168
|
+
/** Weight only the terms that actually occur inside the active search scope. */
|
|
169
|
+
function realizedSpecificity(plan, index, scope) {
|
|
170
|
+
const size = scope?.size ?? index.sceneCount;
|
|
171
|
+
let rarest = 1;
|
|
172
|
+
let found = 0;
|
|
173
|
+
for (const [i, group] of plan.tokenized.groups.entries()) {
|
|
174
|
+
const literal = termRows(index, group.primary);
|
|
175
|
+
const canonical = plan.designatorMatches[i];
|
|
176
|
+
const rows = canonical ? new Set([...canonical.keys(), ...literal]) : literal;
|
|
177
|
+
let hits = 0;
|
|
178
|
+
let canonicalHit = false;
|
|
179
|
+
for (const row of rows) {
|
|
180
|
+
if (scope && !scope.has(row))
|
|
181
|
+
continue;
|
|
182
|
+
hits++;
|
|
183
|
+
if (canonical?.has(row))
|
|
184
|
+
canonicalHit = true;
|
|
2642
185
|
}
|
|
2643
|
-
|
|
2644
|
-
|
|
2645
|
-
|
|
2646
|
-
|
|
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;
|
|
186
|
+
if (canonical && !canonicalHit) {
|
|
187
|
+
const exact = new RegExp(`(?<![a-z0-9])${escapeRegExp(group.primary)}(?![a-z0-9])`);
|
|
188
|
+
if (!literal.some((row) => (!scope || scope.has(row)) && exact.test(index.scenes[row].text)))
|
|
189
|
+
return 0.15;
|
|
2672
190
|
}
|
|
2673
|
-
|
|
2674
|
-
|
|
2675
|
-
|
|
191
|
+
if (hits) {
|
|
192
|
+
found++;
|
|
193
|
+
rarest = Math.min(rarest, hits / size);
|
|
2676
194
|
}
|
|
2677
195
|
}
|
|
2678
|
-
|
|
2679
|
-
|
|
2680
|
-
|
|
2681
|
-
|
|
2682
|
-
|
|
196
|
+
if (rarest > 0.5)
|
|
197
|
+
return 0.2;
|
|
198
|
+
const specificity = Math.min(1, (1 - rarest) / 0.8);
|
|
199
|
+
return specificity * (0.5 + (0.5 * found) / plan.tokenized.groups.length);
|
|
200
|
+
}
|
|
201
|
+
function sceneItem(scene) {
|
|
202
|
+
const repoNames = scene.frontmatter.repositories.map((r) => r.repo);
|
|
203
|
+
const sourceNames = scene.frontmatter.sources?.map((s) => s.source);
|
|
204
|
+
const chainNames = scene.chains.map((c) => c.title);
|
|
205
|
+
return {
|
|
206
|
+
id: scene.id,
|
|
207
|
+
domainId: scene.domainId,
|
|
208
|
+
sceneId: scene.sceneId,
|
|
209
|
+
kind: scene.kind,
|
|
210
|
+
title: scene.frontmatter.title,
|
|
211
|
+
aliases: scene.frontmatter.aliases,
|
|
212
|
+
summary: scene.frontmatter.summary,
|
|
213
|
+
maintainers: scene.frontmatter.maintainers,
|
|
214
|
+
...(scene.frontmatter.confidence !== undefined
|
|
215
|
+
? { confidence: scene.frontmatter.confidence }
|
|
216
|
+
: {}),
|
|
217
|
+
dependsOn: scene.frontmatter.dependsOn,
|
|
218
|
+
repositories: repoNames,
|
|
219
|
+
...(sourceNames && sourceNames.length > 0 ? { sources: sourceNames } : {}),
|
|
220
|
+
chainNames,
|
|
221
|
+
hasPendingConfirmations: scene.hasPendingConfirmations,
|
|
222
|
+
detailCount: scene.details.length,
|
|
223
|
+
relativePath: scene.relativePath,
|
|
224
|
+
};
|
|
2683
225
|
}
|
|
2684
226
|
/**
|
|
2685
227
|
* Level-2 progressive discovery: lists scenes/infrastructure entries filtered by domain and/or query/queries.
|
|
@@ -2687,6 +229,15 @@ function expandMultiEntitySingleQuery(rawQuery, plan, index, scope) {
|
|
|
2687
229
|
export function discoverScenes(wiki, options = {}) {
|
|
2688
230
|
const kindFilter = options.kind ?? "all";
|
|
2689
231
|
const rawActiveQueries = collectActiveQueries(options.query, options.queries);
|
|
232
|
+
if (rawActiveQueries.length && options.expandRelations) {
|
|
233
|
+
const expansion = options.expandRelations === true ? {} : options.expandRelations;
|
|
234
|
+
return discoverScenesWithRelations(wiki, {
|
|
235
|
+
...options,
|
|
236
|
+
seedTopK: expansion.seedTopK,
|
|
237
|
+
relationDepth: expansion.depth,
|
|
238
|
+
direction: expansion.direction,
|
|
239
|
+
});
|
|
240
|
+
}
|
|
2690
241
|
if (rawActiveQueries.length === 0) {
|
|
2691
242
|
const out = [];
|
|
2692
243
|
for (const scene of wiki.scenes.values()) {
|
|
@@ -2696,29 +247,7 @@ export function discoverScenes(wiki, options = {}) {
|
|
|
2696
247
|
if (kindFilter !== "all" && scene.kind !== kindFilter) {
|
|
2697
248
|
continue;
|
|
2698
249
|
}
|
|
2699
|
-
|
|
2700
|
-
const sourceNames = scene.frontmatter.sources?.map((s) => s.source);
|
|
2701
|
-
const chainNames = scene.chains.map((c) => c.title);
|
|
2702
|
-
out.push({
|
|
2703
|
-
id: scene.id,
|
|
2704
|
-
domainId: scene.domainId,
|
|
2705
|
-
sceneId: scene.sceneId,
|
|
2706
|
-
kind: scene.kind,
|
|
2707
|
-
title: scene.frontmatter.title,
|
|
2708
|
-
aliases: scene.frontmatter.aliases,
|
|
2709
|
-
summary: scene.frontmatter.summary,
|
|
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
|
-
});
|
|
250
|
+
out.push(sceneItem(scene));
|
|
2722
251
|
}
|
|
2723
252
|
out.sort((a, b) => a.id.localeCompare(b.id));
|
|
2724
253
|
return applyLimit(out, options.limit);
|
|
@@ -2738,194 +267,8 @@ export function discoverScenes(wiki, options = {}) {
|
|
|
2738
267
|
? expandMultiEntitySingleQuery(firstQuery, firstPlan, index, scope)
|
|
2739
268
|
: rawActiveQueries;
|
|
2740
269
|
const rrfPerQueryCap = options.limit !== undefined ? Math.max(40, options.limit * 4) : 60;
|
|
2741
|
-
function runSingleSceneQuery(q) {
|
|
2742
|
-
|
|
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)
|
|
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
|
-
}
|
|
2811
|
-
}
|
|
2812
|
-
}
|
|
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 = {
|
|
2896
|
-
id: scene.id,
|
|
2897
|
-
domainId: scene.domainId,
|
|
2898
|
-
sceneId: scene.sceneId,
|
|
2899
|
-
kind: scene.kind,
|
|
2900
|
-
title: scene.frontmatter.title,
|
|
2901
|
-
aliases: scene.frontmatter.aliases,
|
|
2902
|
-
summary: scene.frontmatter.summary,
|
|
2903
|
-
maintainers: scene.frontmatter.maintainers,
|
|
2904
|
-
...(scene.frontmatter.confidence !== undefined
|
|
2905
|
-
? { confidence: scene.frontmatter.confidence }
|
|
2906
|
-
: {}),
|
|
2907
|
-
dependsOn: scene.frontmatter.dependsOn,
|
|
2908
|
-
repositories: repoNames,
|
|
2909
|
-
...(sourceNames.length > 0 ? { sources: sourceNames } : {}),
|
|
2910
|
-
chainNames,
|
|
2911
|
-
hasPendingConfirmations: scene.hasPendingConfirmations,
|
|
2912
|
-
detailCount: scene.details.length,
|
|
2913
|
-
relativePath: scene.relativePath,
|
|
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,
|
|
2924
|
-
});
|
|
2925
|
-
}
|
|
2926
|
-
const filtered = filterWeakBodyOnlyHits(hits);
|
|
2927
|
-
filtered.sort((a, b) => b.score - a.score || a.item.id.localeCompare(b.item.id));
|
|
2928
|
-
return filtered;
|
|
270
|
+
function runSingleSceneQuery(q, plan) {
|
|
271
|
+
return rankSceneCandidates(q, plan, index, scope, activeQueries.length === 1 ? options.limit : rrfPerQueryCap);
|
|
2929
272
|
}
|
|
2930
273
|
function enrichSceneItem(base, snippetTerms, pTerms, pDesigs) {
|
|
2931
274
|
const doc = index.sceneById.get(base.id)?.entry.doc;
|
|
@@ -2946,13 +289,15 @@ export function discoverScenes(wiki, options = {}) {
|
|
|
2946
289
|
}
|
|
2947
290
|
if (activeQueries.length === 1) {
|
|
2948
291
|
const emptyDesigs = new Set();
|
|
2949
|
-
const limited = applyLimit(runSingleSceneQuery(activeQueries[0]), options.limit);
|
|
292
|
+
const limited = applyLimit(runSingleSceneQuery(activeQueries[0], firstPlan), options.limit);
|
|
2950
293
|
return limited.map(({ item, snippetTerms, pinpointTerms, pinpointDesignators }) => enrichSceneItem(item, snippetTerms, pinpointTerms ?? [], pinpointDesignators ?? emptyDesigs));
|
|
2951
294
|
}
|
|
2952
295
|
// Multi-query Reciprocal Rank Fusion (RRF) so every queried entity/report gets top-K representation without cannibalization
|
|
2953
296
|
const fusedById = new Map();
|
|
2954
297
|
for (const q of activeQueries) {
|
|
2955
|
-
const
|
|
298
|
+
const plan = q === firstQuery ? firstPlan : buildPreparedQueryPlan(q, index, localScope);
|
|
299
|
+
const subResults = runSingleSceneQuery(q, plan);
|
|
300
|
+
const weight = realizedSpecificity(plan, index, scope);
|
|
2956
301
|
const topScore = Math.max(1, subResults[0]?.item.score ?? 1);
|
|
2957
302
|
const distinctWinner = subResults[1]?.item.score !== topScore;
|
|
2958
303
|
const windowLen = Math.min(subResults.length, rrfPerQueryCap);
|
|
@@ -2960,15 +305,18 @@ export function discoverScenes(wiki, options = {}) {
|
|
|
2960
305
|
const { item, snippetTerms, pinpointTerms, pinpointDesignators } = subResults[idx];
|
|
2961
306
|
const rank = idx + 1;
|
|
2962
307
|
const rawScore = item.score ?? 0;
|
|
2963
|
-
const rrfContribution =
|
|
2964
|
-
|
|
2965
|
-
|
|
308
|
+
const rrfContribution = weight *
|
|
309
|
+
(1200 / (1 + rank) +
|
|
310
|
+
40 * (rawScore / topScore) +
|
|
311
|
+
(weight > 0.2 && rank === 1 && rawScore >= 55 && distinctWinner
|
|
312
|
+
? 650 * activeQueries.length
|
|
313
|
+
: 0));
|
|
2966
314
|
const existing = fusedById.get(item.id);
|
|
2967
315
|
if (!existing) {
|
|
2968
316
|
fusedById.set(item.id, {
|
|
2969
317
|
base: item,
|
|
2970
318
|
rrfSum: rrfContribution,
|
|
2971
|
-
maxRawScore: rawScore,
|
|
319
|
+
maxRawScore: weight * rawScore,
|
|
2972
320
|
bestRank: rank,
|
|
2973
321
|
fields: new Set(item.matchedFields ?? []),
|
|
2974
322
|
pinpointTerms: new Set(pinpointTerms ?? []),
|
|
@@ -2978,7 +326,7 @@ export function discoverScenes(wiki, options = {}) {
|
|
|
2978
326
|
}
|
|
2979
327
|
else {
|
|
2980
328
|
existing.rrfSum += rrfContribution;
|
|
2981
|
-
existing.maxRawScore = Math.max(existing.maxRawScore, rawScore);
|
|
329
|
+
existing.maxRawScore = Math.max(existing.maxRawScore, weight * rawScore);
|
|
2982
330
|
for (const f of item.matchedFields ?? []) {
|
|
2983
331
|
existing.fields.add(f);
|
|
2984
332
|
}
|
|
@@ -3024,18 +372,38 @@ export function discoverScenes(wiki, options = {}) {
|
|
|
3024
372
|
return enrichSceneItem(baseWithScore, entry.bestSnippetTerms, Array.from(entry.pinpointTerms), entry.pinpointDesignators);
|
|
3025
373
|
});
|
|
3026
374
|
}
|
|
3027
|
-
|
|
3028
|
-
|
|
3029
|
-
|
|
3030
|
-
|
|
3031
|
-
|
|
3032
|
-
const
|
|
3033
|
-
|
|
3034
|
-
|
|
3035
|
-
|
|
3036
|
-
|
|
3037
|
-
|
|
3038
|
-
|
|
3039
|
-
|
|
375
|
+
export function discoverScenesWithRelations(wiki, options = {}) {
|
|
376
|
+
const { seedTopK = 2, relationDepth = 2, direction = "both" } = options;
|
|
377
|
+
const limit = options.maxTotal === undefined
|
|
378
|
+
? options.limit
|
|
379
|
+
: Math.min(options.limit ?? Infinity, options.maxTotal);
|
|
380
|
+
const base = discoverScenes(wiki, {
|
|
381
|
+
...options,
|
|
382
|
+
expandRelations: false,
|
|
383
|
+
// A related scene can lie below the output window and still have lexical match evidence.
|
|
384
|
+
limit: limit !== undefined ? Math.max(limit, seedTopK, 32) : undefined,
|
|
385
|
+
});
|
|
386
|
+
if (!collectActiveQueries(options.query, options.queries).length)
|
|
387
|
+
return applyLimit(base, limit);
|
|
388
|
+
const byId = new Map(base.map((item) => [item.id, item]));
|
|
389
|
+
const seeds = base.slice(0, seedTopK);
|
|
390
|
+
const merged = new Map(seeds.map((item) => [item.id, item]));
|
|
391
|
+
const distances = new Map();
|
|
392
|
+
for (const seed of seeds) {
|
|
393
|
+
for (const edge of getRelations(wiki, seed.id, { direction, depth: relationDepth }).edges) {
|
|
394
|
+
const id = edge.direction === "deps" ? edge.to : edge.from;
|
|
395
|
+
if (!edge.missingTarget && !merged.has(id))
|
|
396
|
+
distances.set(id, Math.min(distances.get(id) ?? Infinity, edge.depth));
|
|
397
|
+
}
|
|
398
|
+
}
|
|
399
|
+
for (const [id] of [...distances].sort(([a, x], [b, y]) => x - y || a.localeCompare(b))) {
|
|
400
|
+
const scene = wiki.scenes.get(id);
|
|
401
|
+
if (scene && (!options.kind || options.kind === "all" || options.kind === scene.kind))
|
|
402
|
+
merged.set(id, byId.get(id) ?? { ...sceneItem(scene), matchedFields: ["relation"] });
|
|
403
|
+
}
|
|
404
|
+
for (const item of base)
|
|
405
|
+
if (!merged.has(item.id))
|
|
406
|
+
merged.set(item.id, item);
|
|
407
|
+
return applyLimit([...merged.values()], limit);
|
|
3040
408
|
}
|
|
3041
409
|
//# sourceMappingURL=discover.js.map
|