@open-livex-wiki/core 0.2.0 → 0.2.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/coverage.d.ts.map +1 -1
- package/dist/coverage.js +150 -38
- package/dist/coverage.js.map +1 -1
- package/dist/discover.d.ts +1 -0
- package/dist/discover.d.ts.map +1 -1
- package/dist/discover.js +872 -307
- package/dist/discover.js.map +1 -1
- package/package.json +1 -1
package/dist/discover.js
CHANGED
|
@@ -1,5 +1,8 @@
|
|
|
1
1
|
import { toPosixPath } from "./utils.js";
|
|
2
2
|
const QUERY_PUNCT_SPLIT_REGEX = /[\s,;,;、。??!!|/\\()()[\]【】<>::"'`]+/;
|
|
3
|
+
const NUMBERED_LABEL = /\b(?:figures?|fig|tables?|tab|tbl|section|sec|chapter|chap|appendix|part|exhibit|chart)[ \t]+(?:\d{1,4}[a-z]?|[ivxlcdm]{1,5}|[a-d])\b/i;
|
|
4
|
+
const LABEL_SEGMENTS = new RegExp(`(${NUMBERED_LABEL.source})`, "gi");
|
|
5
|
+
const WHOLE_LABEL = new RegExp(`^${NUMBERED_LABEL.source}$`, "i");
|
|
3
6
|
const CJK_CHAR_REGEX = /[\u3400-\u9fff\uf900-\ufaff]/;
|
|
4
7
|
const CJK_RUN_OR_OTHER_REGEX = /[\u3400-\u9fff\uf900-\ufaff]+|[^\u3400-\u9fff\uf900-\ufaff]+/g;
|
|
5
8
|
const CJK_PREFIX_FILLERS = ["关于", "请问", "帮我", "如何", "怎么", "什么", "查询", "查看", "排查"];
|
|
@@ -97,6 +100,7 @@ const NON_DESIGNATOR_PREFIX_WORDS = new Set([
|
|
|
97
100
|
"column",
|
|
98
101
|
"columns",
|
|
99
102
|
"chart",
|
|
103
|
+
"exhibit",
|
|
100
104
|
"charts",
|
|
101
105
|
"graph",
|
|
102
106
|
"diagram",
|
|
@@ -230,6 +234,12 @@ const SPACE_STOP_PREFIXES = new Set([
|
|
|
230
234
|
"us",
|
|
231
235
|
"vs",
|
|
232
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
|
+
}
|
|
233
243
|
/**
|
|
234
244
|
* Normalizes a single alphanumeric model, weapon, report, or standard designator
|
|
235
245
|
* (e.g. `"FFG-62"`, `"FFG 62"`, `"FFG62"` -> `"ffg62"`; `"ATP 7-100.1"` -> `"atp71001"`).
|
|
@@ -243,7 +253,7 @@ export function normalizeDesignatorToken(text) {
|
|
|
243
253
|
.trim()
|
|
244
254
|
.replace(/^[([{"'`]+|[)\]}"'`,.;:!?]+$/g, "")
|
|
245
255
|
.trim();
|
|
246
|
-
if (!cleaned) {
|
|
256
|
+
if (!cleaned || /^[a-z]+\s+(?:19[7-9]\d|20[0-4]\d)$/i.test(cleaned)) {
|
|
247
257
|
return undefined;
|
|
248
258
|
}
|
|
249
259
|
// Must start with 1..10 ASCII letters and contain only ASCII letters, digits, spaces, and ./_- separators
|
|
@@ -310,14 +320,35 @@ function buildDesignatorVariants(rawText, primaryCanonical) {
|
|
|
310
320
|
}
|
|
311
321
|
return variants;
|
|
312
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
|
+
}
|
|
313
345
|
/**
|
|
314
346
|
* Scans arbitrary text and returns structured designator mentions (preserving original span + canonical variants).
|
|
315
347
|
*/
|
|
316
348
|
export function extractDesignatorMentions(text) {
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
// Mask URLs and SCP remotes with spaces only when `://` or `@` is actually present
|
|
349
|
+
return scanDesignators(text, normalizeDesignatorToken);
|
|
350
|
+
}
|
|
351
|
+
function maskRemotes(text) {
|
|
321
352
|
let masked = text;
|
|
322
353
|
if (masked.includes("://")) {
|
|
323
354
|
masked = masked.replace(/(?:git\+)?(?:https?|ssh|git):\/\/[^\s)>\]"']+/gi, " ");
|
|
@@ -325,52 +356,39 @@ export function extractDesignatorMentions(text) {
|
|
|
325
356
|
if (masked.includes("@")) {
|
|
326
357
|
masked = masked.replace(/[A-Za-z0-9._+-]+@[A-Za-z0-9.-]+:[^\s)>\]"']+/g, " ");
|
|
327
358
|
}
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
}
|
|
335
|
-
}
|
|
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);
|
|
336
365
|
const mentions = [];
|
|
337
366
|
const seenPrimary = new Set();
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
if (next && /^[A-Za-z]{1,8}(?:[-/][A-Za-z]{1,8})?$/.test(cur.text)) {
|
|
342
|
-
const between = masked.slice(cur.end, next.start);
|
|
343
|
-
const isSpaceOnly = /^[ \t]+$/.test(between);
|
|
344
|
-
const isSpacedContinuation = /^[0-9][0-9A-Za-z]*(?:[-/.][0-9A-Za-z]+)*$/.test(next.text) ||
|
|
345
|
-
/^[A-Za-z]{1,2}[0-9]{3,}[A-Za-z]?$/.test(next.text);
|
|
346
|
-
if (isSpaceOnly && isSpacedContinuation) {
|
|
347
|
-
const combinedRaw = `${cur.text} ${next.text}`;
|
|
348
|
-
const combinedNorm = normalizeDesignatorToken(combinedRaw);
|
|
349
|
-
if (combinedNorm) {
|
|
350
|
-
if (!seenPrimary.has(combinedNorm)) {
|
|
351
|
-
seenPrimary.add(combinedNorm);
|
|
352
|
-
mentions.push({
|
|
353
|
-
raw: combinedRaw,
|
|
354
|
-
canonical: combinedNorm,
|
|
355
|
-
variants: buildDesignatorVariants(combinedRaw, combinedNorm),
|
|
356
|
-
});
|
|
357
|
-
}
|
|
358
|
-
i += 1;
|
|
359
|
-
continue;
|
|
360
|
-
}
|
|
361
|
-
}
|
|
362
|
-
}
|
|
363
|
-
if (!/[0-9]/.test(cur.text)) {
|
|
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))
|
|
364
370
|
continue;
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
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) });
|
|
374
392
|
}
|
|
375
393
|
}
|
|
376
394
|
return mentions;
|
|
@@ -517,10 +535,20 @@ export function tokenizeDiscoveryQuery(query) {
|
|
|
517
535
|
if (!normalizedPhrase) {
|
|
518
536
|
return { normalizedPhrase: "", groups: [] };
|
|
519
537
|
}
|
|
520
|
-
const rawSegments = trimmedOriginal
|
|
538
|
+
const rawSegments = trimmedOriginal
|
|
539
|
+
.split(LABEL_SEGMENTS)
|
|
540
|
+
.flatMap((part, index) => index % 2 ? [part.trim().replace(/\s+/, " ")] : part.split(QUERY_PUNCT_SPLIT_REGEX))
|
|
541
|
+
.filter(Boolean);
|
|
521
542
|
const seenPrimary = new Set();
|
|
522
543
|
const groups = [];
|
|
523
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
|
+
}
|
|
524
552
|
const cleanedOriginal = rawTok.trim().replace(/^[._#-]+|[._#-]+$/g, "");
|
|
525
553
|
const t = cleanedOriginal.toLowerCase();
|
|
526
554
|
if (!t || seenPrimary.has(t)) {
|
|
@@ -614,6 +642,8 @@ export function tokenizeDiscoveryQuery(query) {
|
|
|
614
642
|
return { normalizedPhrase, groups };
|
|
615
643
|
}
|
|
616
644
|
function extractInlineCodeSpans(markdown) {
|
|
645
|
+
if (!markdown.includes("`"))
|
|
646
|
+
return [];
|
|
617
647
|
const spans = [];
|
|
618
648
|
const lines = markdown.split(/\r?\n/);
|
|
619
649
|
let inFence = false;
|
|
@@ -697,13 +727,13 @@ function toPathTerm(raw) {
|
|
|
697
727
|
const base = lower.split("/").pop() ?? lower;
|
|
698
728
|
return { lower, base };
|
|
699
729
|
}
|
|
700
|
-
function collectDesignatorsFromStrings(strings, rawMap) {
|
|
730
|
+
function collectDesignatorsFromStrings(strings, rawMap, normalize = normalizeDesignatorToken, signature) {
|
|
701
731
|
const out = new Set();
|
|
702
732
|
for (const s of strings) {
|
|
703
|
-
if (!s) {
|
|
733
|
+
if (signature ? !s.includes(signature[0]) : !/\d/.test(s)) {
|
|
704
734
|
continue;
|
|
705
735
|
}
|
|
706
|
-
for (const mention of
|
|
736
|
+
for (const mention of scanDesignators(s, normalize, signature)) {
|
|
707
737
|
for (const v of mention.variants) {
|
|
708
738
|
out.add(v);
|
|
709
739
|
if (rawMap && !rawMap.has(v)) {
|
|
@@ -766,141 +796,255 @@ function collectAnchorSearchStrings(anchor) {
|
|
|
766
796
|
}
|
|
767
797
|
return raw;
|
|
768
798
|
}
|
|
769
|
-
|
|
770
|
-
|
|
771
|
-
|
|
772
|
-
|
|
773
|
-
|
|
774
|
-
|
|
775
|
-
|
|
776
|
-
|
|
777
|
-
|
|
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;
|
|
778
938
|
return {
|
|
779
|
-
title:
|
|
780
|
-
termsLower: terms.map((
|
|
781
|
-
bodyLower
|
|
782
|
-
|
|
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
|
+
},
|
|
783
949
|
};
|
|
784
950
|
});
|
|
785
|
-
const detailEntries = scene.details.map((
|
|
786
|
-
|
|
787
|
-
nameLower: d.name.toLowerCase(),
|
|
788
|
-
titleLower: d.title.toLowerCase(),
|
|
789
|
-
contentLower: d.content.toLowerCase(),
|
|
790
|
-
designators: collectDesignatorsFromStrings([d.name, d.title, d.content], rawByDesignator),
|
|
791
|
-
}));
|
|
792
|
-
const anchorEntries = (scene.frontmatter.anchors ?? []).map((a) => {
|
|
793
|
-
const rawStrings = collectAnchorSearchStrings(a);
|
|
951
|
+
const detailEntries = scene.details.map((detail, idx) => {
|
|
952
|
+
let keys;
|
|
794
953
|
return {
|
|
795
|
-
|
|
796
|
-
|
|
797
|
-
|
|
798
|
-
|
|
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
|
+
},
|
|
799
962
|
};
|
|
800
963
|
});
|
|
801
|
-
const
|
|
802
|
-
|
|
803
|
-
|
|
804
|
-
...(c.entryPoint ? [c.entryPoint] : []),
|
|
805
|
-
]);
|
|
806
|
-
const anchorTerms = anchorEntries.flatMap((ae) => ae.terms);
|
|
807
|
-
const repoTermsRaw = [
|
|
808
|
-
...repoNames,
|
|
809
|
-
...(scene.frontmatter.anchors ?? []).flatMap((a) => (a.repo ? [a.repo] : [])),
|
|
810
|
-
];
|
|
811
|
-
const sourceTermsAllRaw = [
|
|
812
|
-
...sourceSearchRaw,
|
|
813
|
-
...(scene.frontmatter.anchors ?? []).flatMap((a) => (a.source ? [a.source] : [])),
|
|
814
|
-
];
|
|
815
|
-
const repoTerms = Array.from(new Set(repoTermsRaw)).map(toPathTerm);
|
|
816
|
-
const sourceTerms = Array.from(new Set(sourceTermsAllRaw)).map(toPathTerm);
|
|
817
|
-
const detailTitlesRaw = scene.details.flatMap((d) => [d.name, d.title]);
|
|
818
|
-
const rawCodeSpans = [
|
|
819
|
-
...extractInlineCodeSpans(scene.content),
|
|
820
|
-
...scene.details.flatMap((d) => extractInlineCodeSpans(d.content)),
|
|
821
|
-
];
|
|
822
|
-
const codeSpans = rawCodeSpans.map((span) => {
|
|
823
|
-
const lower = toPosixPath(span).toLowerCase();
|
|
964
|
+
const anchorEntries = (scene.frontmatter.anchors ?? EMPTY_LIST).map((anchor) => {
|
|
965
|
+
let keys;
|
|
966
|
+
const raw = collectAnchorSearchStrings(anchor);
|
|
824
967
|
return {
|
|
825
|
-
|
|
826
|
-
|
|
968
|
+
anchor,
|
|
969
|
+
summary: toMatchedAnchorSummary(anchor),
|
|
970
|
+
terms: raw.map(toPathTerm),
|
|
971
|
+
get designators() {
|
|
972
|
+
keys ??= collectDesignatorsFromStrings(raw);
|
|
973
|
+
return keys;
|
|
974
|
+
},
|
|
827
975
|
};
|
|
828
976
|
});
|
|
829
|
-
const
|
|
830
|
-
const
|
|
831
|
-
|
|
832
|
-
const
|
|
833
|
-
|
|
834
|
-
|
|
835
|
-
|
|
836
|
-
|
|
837
|
-
|
|
838
|
-
|
|
839
|
-
|
|
840
|
-
|
|
841
|
-
|
|
842
|
-
|
|
843
|
-
|
|
844
|
-
|
|
845
|
-
|
|
846
|
-
|
|
847
|
-
|
|
848
|
-
|
|
849
|
-
|
|
850
|
-
|
|
851
|
-
|
|
852
|
-
|
|
853
|
-
|
|
854
|
-
|
|
855
|
-
|
|
856
|
-
|
|
857
|
-
|
|
858
|
-
|
|
859
|
-
|
|
860
|
-
|
|
861
|
-
|
|
862
|
-
|
|
863
|
-
|
|
864
|
-
|
|
865
|
-
|
|
866
|
-
|
|
867
|
-
|
|
868
|
-
|
|
869
|
-
|
|
870
|
-
|
|
871
|
-
|
|
872
|
-
|
|
873
|
-
|
|
874
|
-
|
|
875
|
-
|
|
876
|
-
|
|
877
|
-
|
|
878
|
-
|
|
879
|
-
|
|
880
|
-
|
|
881
|
-
|
|
882
|
-
|
|
883
|
-
|
|
884
|
-
|
|
885
|
-
|
|
886
|
-
|
|
887
|
-
|
|
888
|
-
|
|
889
|
-
|
|
890
|
-
|
|
891
|
-
|
|
892
|
-
|
|
893
|
-
|
|
894
|
-
|
|
895
|
-
...anchorTerms.map((a) => a.base).filter((b) => b.length >= 3),
|
|
896
|
-
...repoTerms.map((r) => r.base).filter((b) => b.length >= 3),
|
|
897
|
-
...sourceTerms.map((s) => s.base).filter((b) => b.length >= 3),
|
|
898
|
-
]));
|
|
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
|
+
}
|
|
899
1043
|
return {
|
|
900
1044
|
scene,
|
|
901
1045
|
repoNames,
|
|
902
1046
|
sourceNames,
|
|
903
|
-
chainNames,
|
|
1047
|
+
chainNames: chainEntries.map((chain) => chain.title),
|
|
904
1048
|
doc: {
|
|
905
1049
|
idLower,
|
|
906
1050
|
idCollapsed: idLower.replace(/[^a-z0-9]+/g, ""),
|
|
@@ -909,41 +1053,44 @@ function buildSceneIndexedDoc(scene) {
|
|
|
909
1053
|
titleLower,
|
|
910
1054
|
titleCollapsed: titleLower.replace(/[^a-z0-9]+/g, ""),
|
|
911
1055
|
aliasesLower,
|
|
912
|
-
chainTermsLower,
|
|
1056
|
+
chainTermsLower: chainEntries.flatMap((chain) => chain.termsLower),
|
|
913
1057
|
anchorTerms,
|
|
914
1058
|
repoTerms,
|
|
915
1059
|
sourceTerms,
|
|
916
|
-
summaryLower,
|
|
917
|
-
headingsLower,
|
|
918
|
-
detailTitlesLower,
|
|
919
|
-
childHighTermsLower:
|
|
920
|
-
childAnchorTerms:
|
|
921
|
-
childRepoTerms:
|
|
922
|
-
childSourceTerms:
|
|
923
|
-
childBodySourcesLower:
|
|
924
|
-
codeSpans
|
|
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
|
+
},
|
|
925
1071
|
bodySourcesLower: [bodyLower],
|
|
926
1072
|
detailBodySourcesLower,
|
|
927
|
-
tier34GateLower,
|
|
928
|
-
allTextLower,
|
|
929
|
-
reverseCandidatesLower,
|
|
930
|
-
rawSnippetSources
|
|
931
|
-
|
|
932
|
-
|
|
933
|
-
|
|
934
|
-
|
|
935
|
-
|
|
936
|
-
|
|
937
|
-
|
|
938
|
-
|
|
939
|
-
|
|
940
|
-
|
|
941
|
-
|
|
942
|
-
|
|
943
|
-
|
|
944
|
-
|
|
945
|
-
|
|
946
|
-
|
|
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;
|
|
947
1094
|
},
|
|
948
1095
|
chainEntries,
|
|
949
1096
|
detailEntries,
|
|
@@ -978,7 +1125,7 @@ function buildDomainIndexedDoc(domain, sceneById) {
|
|
|
978
1125
|
if (!prepScene) {
|
|
979
1126
|
continue;
|
|
980
1127
|
}
|
|
981
|
-
const sDoc = prepScene.doc;
|
|
1128
|
+
const sDoc = prepScene.entry.doc;
|
|
982
1129
|
if (sDoc.shortIdLower) {
|
|
983
1130
|
childHighTermsLower.push(sDoc.shortIdLower);
|
|
984
1131
|
}
|
|
@@ -1130,6 +1277,24 @@ function buildDomainIndexedDoc(domain, sceneById) {
|
|
|
1130
1277
|
},
|
|
1131
1278
|
};
|
|
1132
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
|
+
}
|
|
1133
1298
|
function getPrecomputedWikiIndex(wiki) {
|
|
1134
1299
|
const cached = WIKI_INDEX_CACHE.get(wiki);
|
|
1135
1300
|
if (cached &&
|
|
@@ -1139,19 +1304,52 @@ function getPrecomputedWikiIndex(wiki) {
|
|
|
1139
1304
|
}
|
|
1140
1305
|
const sceneById = new Map();
|
|
1141
1306
|
const scenes = [];
|
|
1142
|
-
for (const scene of wiki.scenes.values()) {
|
|
1143
|
-
const prep = buildSceneIndexedDoc(scene);
|
|
1144
|
-
scenes.push(prep);
|
|
1145
|
-
sceneById.set(scene.id, prep);
|
|
1146
|
-
}
|
|
1147
1307
|
const index = {
|
|
1148
1308
|
domainCount: wiki.domains.size,
|
|
1149
1309
|
sceneCount: wiki.scenes.size,
|
|
1150
1310
|
scenes,
|
|
1151
1311
|
sceneById,
|
|
1152
|
-
|
|
1153
|
-
|
|
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(),
|
|
1154
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
|
+
}
|
|
1155
1353
|
WIKI_INDEX_CACHE.set(wiki, index);
|
|
1156
1354
|
return index;
|
|
1157
1355
|
}
|
|
@@ -1166,58 +1364,214 @@ function getPrecomputedDomains(wiki, index) {
|
|
|
1166
1364
|
index.domains = domains;
|
|
1167
1365
|
return domains;
|
|
1168
1366
|
}
|
|
1169
|
-
function
|
|
1170
|
-
|
|
1171
|
-
|
|
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)
|
|
1172
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);
|
|
1173
1483
|
}
|
|
1174
|
-
|
|
1175
|
-
|
|
1176
|
-
|
|
1177
|
-
|
|
1178
|
-
}
|
|
1484
|
+
else {
|
|
1485
|
+
for (let row = 0; row < index.scenes.length; row++)
|
|
1486
|
+
if (index.scenes[row].contains(term))
|
|
1487
|
+
matches.push(row);
|
|
1179
1488
|
}
|
|
1180
|
-
index
|
|
1181
|
-
return
|
|
1489
|
+
cacheTermRows(index, term, matches);
|
|
1490
|
+
return matches;
|
|
1182
1491
|
}
|
|
1183
|
-
function
|
|
1184
|
-
const
|
|
1185
|
-
if (
|
|
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)
|
|
1186
1519
|
return cached;
|
|
1187
|
-
|
|
1188
|
-
|
|
1189
|
-
|
|
1190
|
-
|
|
1191
|
-
|
|
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;
|
|
1192
1532
|
}
|
|
1533
|
+
const score = scoreDesignatorsAgainstDoc([canonical], doc.entry.doc).hit.bestScore;
|
|
1534
|
+
if (score)
|
|
1535
|
+
rows.set(row, score);
|
|
1193
1536
|
}
|
|
1194
|
-
index.
|
|
1195
|
-
|
|
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;
|
|
1196
1544
|
}
|
|
1197
1545
|
const IDF_SCALING_MIN_SCENES = 8;
|
|
1198
|
-
function computeIdfProfileForGroup(index, group) {
|
|
1199
|
-
const totalScenes = index.sceneCount;
|
|
1200
|
-
if (totalScenes < IDF_SCALING_MIN_SCENES) {
|
|
1546
|
+
function computeIdfProfileForGroup(index, group, scope) {
|
|
1547
|
+
const totalScenes = scope?.size ?? index.sceneCount;
|
|
1548
|
+
if (!scope && totalScenes < IDF_SCALING_MIN_SCENES) {
|
|
1201
1549
|
return { multiplier: 1, docRatio: 0 };
|
|
1202
1550
|
}
|
|
1203
|
-
|
|
1551
|
+
const count = (rows) => scope ? rows.filter((row) => scope.has(row)).length : rows.length;
|
|
1552
|
+
let effectiveDf = count(termRows(index, group.primary));
|
|
1204
1553
|
if (group.designators && group.designators.length > 0) {
|
|
1205
1554
|
let minDesigDf = Number.POSITIVE_INFINITY;
|
|
1206
1555
|
for (const d of group.designators) {
|
|
1207
|
-
const
|
|
1556
|
+
const posting = designatorRows(index, d);
|
|
1557
|
+
const dDf = scope ? count([...posting.keys()]) : posting.size;
|
|
1208
1558
|
if (dDf > 0 && dDf < minDesigDf) {
|
|
1209
1559
|
minDesigDf = dDf;
|
|
1210
1560
|
}
|
|
1211
1561
|
}
|
|
1212
1562
|
if (Number.isFinite(minDesigDf)) {
|
|
1213
|
-
effectiveDf =
|
|
1563
|
+
effectiveDf = scope
|
|
1564
|
+
? Math.max(effectiveDf, minDesigDf)
|
|
1565
|
+
: effectiveDf > 0
|
|
1566
|
+
? Math.min(effectiveDf, minDesigDf)
|
|
1567
|
+
: minDesigDf;
|
|
1214
1568
|
}
|
|
1215
1569
|
}
|
|
1216
1570
|
else if (effectiveDf === 0 && group.subTokens && group.subTokens.length >= 2) {
|
|
1217
1571
|
// Upper-bound co-occurrence DF by the rarest required sub-token
|
|
1218
1572
|
let minSubDf = Number.POSITIVE_INFINITY;
|
|
1219
1573
|
for (const st of group.subTokens) {
|
|
1220
|
-
const sDf =
|
|
1574
|
+
const sDf = count(termRows(index, st));
|
|
1221
1575
|
if (sDf < minSubDf) {
|
|
1222
1576
|
minSubDf = sDf;
|
|
1223
1577
|
}
|
|
@@ -1228,6 +1582,8 @@ function computeIdfProfileForGroup(index, group) {
|
|
|
1228
1582
|
}
|
|
1229
1583
|
const clampedDf = Math.max(1, effectiveDf);
|
|
1230
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 };
|
|
1231
1587
|
const normIdf = Math.log((totalScenes + 1) / (clampedDf + 0.5)) / Math.log(totalScenes + 1);
|
|
1232
1588
|
let mult;
|
|
1233
1589
|
if (docRatio > 0.4) {
|
|
@@ -1262,9 +1618,19 @@ const FIELD_DISPLAY_ORDER = [
|
|
|
1262
1618
|
"body",
|
|
1263
1619
|
];
|
|
1264
1620
|
const EMPTY_FIELD_SET = new Set();
|
|
1265
|
-
|
|
1266
|
-
|
|
1267
|
-
|
|
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)))) {
|
|
1268
1634
|
return {
|
|
1269
1635
|
bestScore: 0,
|
|
1270
1636
|
fields: EMPTY_FIELD_SET,
|
|
@@ -1297,7 +1663,7 @@ function scoreTermAgainstDoc(term, doc) {
|
|
|
1297
1663
|
// Tier 1: id / shortId, title, aliases
|
|
1298
1664
|
const idLower = doc.idLower;
|
|
1299
1665
|
const shortIdLower = doc.shortIdLower;
|
|
1300
|
-
if (idLower === term || shortIdLower === term) {
|
|
1666
|
+
if (idLower === term || shortIdLower === term || doc.shortIdCollapsed === term) {
|
|
1301
1667
|
record(120, "id", "high");
|
|
1302
1668
|
}
|
|
1303
1669
|
else if (idLower.startsWith(term) || shortIdLower?.startsWith(term)) {
|
|
@@ -1310,7 +1676,7 @@ function scoreTermAgainstDoc(term, doc) {
|
|
|
1310
1676
|
record(58, "id", "high");
|
|
1311
1677
|
}
|
|
1312
1678
|
const titleLower = doc.titleLower;
|
|
1313
|
-
if (titleLower === term) {
|
|
1679
|
+
if (titleLower === term || doc.titleCollapsed === term) {
|
|
1314
1680
|
record(115, "title", "high");
|
|
1315
1681
|
}
|
|
1316
1682
|
else if (titleLower.startsWith(term)) {
|
|
@@ -1501,6 +1867,7 @@ function scoreDesignatorsAgainstDoc(designators, doc) {
|
|
|
1501
1867
|
let matchedCodeOrDetail = false;
|
|
1502
1868
|
let matchedBodyText = false;
|
|
1503
1869
|
let matchedSnippetTerm;
|
|
1870
|
+
let tiers;
|
|
1504
1871
|
function record(score, field, tier, d) {
|
|
1505
1872
|
best = Math.max(best, score);
|
|
1506
1873
|
fields.add(field);
|
|
@@ -1509,21 +1876,21 @@ function scoreDesignatorsAgainstDoc(designators, doc) {
|
|
|
1509
1876
|
}
|
|
1510
1877
|
else if (tier === "code") {
|
|
1511
1878
|
matchedCodeOrDetail = true;
|
|
1512
|
-
matchedSnippetTerm ??=
|
|
1879
|
+
matchedSnippetTerm ??= tiers.rawByDesignator.get(d);
|
|
1513
1880
|
}
|
|
1514
1881
|
else {
|
|
1515
1882
|
matchedBodyText = true;
|
|
1516
|
-
matchedSnippetTerm ??=
|
|
1883
|
+
matchedSnippetTerm ??= tiers.rawByDesignator.get(d);
|
|
1517
1884
|
}
|
|
1518
1885
|
}
|
|
1519
1886
|
for (let idx = 0; idx < designators.length; idx++) {
|
|
1520
1887
|
const d = designators[idx];
|
|
1521
|
-
|
|
1888
|
+
tiers = doc.designatorsFor?.(d) ?? doc.designators;
|
|
1889
|
+
if (!tiers.all.has(d)) {
|
|
1522
1890
|
continue;
|
|
1523
1891
|
}
|
|
1524
1892
|
// Slight discount only when matching a stripped sub-designator (e.g. `r44972` from `CRS-R44972`)
|
|
1525
1893
|
const weight = idx === 0 ? 1 : 0.92;
|
|
1526
|
-
const tiers = doc.designators;
|
|
1527
1894
|
if (tiers.id.has(d)) {
|
|
1528
1895
|
const idExact = doc.idCollapsed === d || doc.shortIdCollapsed === d;
|
|
1529
1896
|
record(Math.round((idExact ? 115 : 66) * weight), "id", "high", d);
|
|
@@ -1669,17 +2036,25 @@ function pinpointSubSceneMatches(doc, pinpointTerms, pinpointDesignators) {
|
|
|
1669
2036
|
}
|
|
1670
2037
|
return { matchedChains, matchedDetails, matchedAnchors };
|
|
1671
2038
|
}
|
|
1672
|
-
function buildPreparedQueryPlan(query, index) {
|
|
2039
|
+
function buildPreparedQueryPlan(query, index, scope) {
|
|
1673
2040
|
const tokenized = tokenizeDiscoveryQuery(query);
|
|
1674
|
-
|
|
1675
|
-
const
|
|
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));
|
|
1676
2048
|
let phraseIdfMultiplier = 1;
|
|
1677
2049
|
const selectiveBigrams = [];
|
|
1678
2050
|
if (useCorpusIdf && tokenized.normalizedPhrase) {
|
|
1679
|
-
const phraseDf = Math.max(1,
|
|
1680
|
-
const phraseRatio = phraseDf /
|
|
2051
|
+
const phraseDf = Math.max(1, df(tokenized.normalizedPhrase));
|
|
2052
|
+
const phraseRatio = phraseDf / corpusSize;
|
|
1681
2053
|
if (phraseRatio > 0.4) {
|
|
1682
|
-
phraseIdfMultiplier =
|
|
2054
|
+
phraseIdfMultiplier =
|
|
2055
|
+
scope && phraseRatio > 0.55
|
|
2056
|
+
? 0.24
|
|
2057
|
+
: Math.max(0.35, 0.62 - ((phraseRatio - 0.4) / 0.6) * 0.27);
|
|
1683
2058
|
}
|
|
1684
2059
|
else if (tokenized.groups.length === 1 && groupIdf[0]) {
|
|
1685
2060
|
phraseIdfMultiplier = groupIdf[0].multiplier;
|
|
@@ -1693,6 +2068,8 @@ function buildPreparedQueryPlan(query, index) {
|
|
|
1693
2068
|
for (let i = 0; i < tokenized.groups.length - 1; i++) {
|
|
1694
2069
|
const g1 = tokenized.groups[i];
|
|
1695
2070
|
const g2 = tokenized.groups[i + 1];
|
|
2071
|
+
if (scope && groupIdf[i].docRatio > 0.55 && groupIdf[i + 1].docRatio > 0.55)
|
|
2072
|
+
continue;
|
|
1696
2073
|
if (g1.designators?.length || g2.designators?.length) {
|
|
1697
2074
|
continue;
|
|
1698
2075
|
}
|
|
@@ -1706,12 +2083,13 @@ function buildPreparedQueryPlan(query, index) {
|
|
|
1706
2083
|
continue;
|
|
1707
2084
|
}
|
|
1708
2085
|
seenPhrases.add(phrase);
|
|
1709
|
-
const biDf =
|
|
1710
|
-
if (biDf > 0 && biDf /
|
|
1711
|
-
const biScarcity = 1 - biDf / (
|
|
2086
|
+
const biDf = df(phrase);
|
|
2087
|
+
if (biDf > 0 && biDf / corpusSize <= 0.25) {
|
|
2088
|
+
const biScarcity = 1 - biDf / (corpusSize * 0.3);
|
|
1712
2089
|
const bodyBoost = Math.max(32, Math.round(78 * biScarcity));
|
|
1713
2090
|
selectiveBigrams.push({
|
|
1714
2091
|
phrase,
|
|
2092
|
+
rows: new Set(termRows(index, phrase)),
|
|
1715
2093
|
bodyBoost,
|
|
1716
2094
|
highBoost: bodyBoost + 26,
|
|
1717
2095
|
});
|
|
@@ -1719,6 +2097,21 @@ function buildPreparedQueryPlan(query, index) {
|
|
|
1719
2097
|
}
|
|
1720
2098
|
}
|
|
1721
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`)])),
|
|
1722
2115
|
tokenized,
|
|
1723
2116
|
groupIdf,
|
|
1724
2117
|
phraseIdfMultiplier,
|
|
@@ -1726,7 +2119,22 @@ function buildPreparedQueryPlan(query, index) {
|
|
|
1726
2119
|
selectiveBigrams,
|
|
1727
2120
|
};
|
|
1728
2121
|
}
|
|
1729
|
-
function
|
|
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) {
|
|
1730
2138
|
const { tokenized, groupIdf, phraseIdfMultiplier, useCorpusIdf } = plan;
|
|
1731
2139
|
if (!tokenized.normalizedPhrase) {
|
|
1732
2140
|
return { score: 1, matchedFields: [] };
|
|
@@ -1737,7 +2145,10 @@ function evaluatePreparedQuery(plan, doc, includePinpoint) {
|
|
|
1737
2145
|
const fallbackPinpointTerms = [];
|
|
1738
2146
|
const specificPinpointDesignators = new Set();
|
|
1739
2147
|
const fallbackPinpointDesignators = new Set();
|
|
1740
|
-
|
|
2148
|
+
function scoreTerm(term) {
|
|
2149
|
+
return scoreTermAgainstDoc(term, doc, plan.labels.get(term));
|
|
2150
|
+
}
|
|
2151
|
+
const rawPhraseHit = phraseCandidate ? scoreTerm(tokenized.normalizedPhrase) : EMPTY_HIT;
|
|
1741
2152
|
const weightedPhraseScore = rawPhraseHit.bestScore > 0
|
|
1742
2153
|
? Math.max(1, Math.round(rawPhraseHit.bestScore * phraseIdfMultiplier))
|
|
1743
2154
|
: 0;
|
|
@@ -1752,15 +2163,15 @@ function evaluatePreparedQuery(plan, doc, includePinpoint) {
|
|
|
1752
2163
|
const groupScores = [];
|
|
1753
2164
|
let matchedGroupCount = 0;
|
|
1754
2165
|
let specificMatchedGroupCount = 0;
|
|
1755
|
-
for (
|
|
2166
|
+
for (const gIdx of relevantGroups ?? tokenized.groups.keys()) {
|
|
1756
2167
|
const group = tokenized.groups[gIdx];
|
|
1757
2168
|
const idfProfile = groupIdf[gIdx] ?? { multiplier: 1, docRatio: 0 };
|
|
1758
2169
|
const isSpecificGroup = !useCorpusIdf || idfProfile.docRatio <= 0.35;
|
|
1759
2170
|
let primaryHit;
|
|
1760
2171
|
let effectivePrimaryTerm = group.primary;
|
|
1761
2172
|
if (group.isStrippedStem && group.rawToken) {
|
|
1762
|
-
const rawHit =
|
|
1763
|
-
const stemHit =
|
|
2173
|
+
const rawHit = scoreTerm(group.rawToken);
|
|
2174
|
+
const stemHit = scoreTerm(group.primary);
|
|
1764
2175
|
const discountedStemScore = stemHit.bestScore > 0 ? Math.max(1, Math.round(stemHit.bestScore * 0.45)) : 0;
|
|
1765
2176
|
if (rawHit.bestScore >= discountedStemScore && rawHit.bestScore > 0) {
|
|
1766
2177
|
primaryHit = rawHit;
|
|
@@ -1774,10 +2185,11 @@ function evaluatePreparedQuery(plan, doc, includePinpoint) {
|
|
|
1774
2185
|
}
|
|
1775
2186
|
}
|
|
1776
2187
|
else {
|
|
1777
|
-
primaryHit =
|
|
2188
|
+
primaryHit = scoreTerm(group.primary);
|
|
1778
2189
|
}
|
|
1779
2190
|
// Match canonical designator variants ("FFG-62" <-> "FFG 62" <-> "FFG62", "CRS-R44972" <-> "R44972") at full tier strength
|
|
1780
|
-
if (group.designators &&
|
|
2191
|
+
if (group.designators?.length &&
|
|
2192
|
+
(row === undefined || plan.designatorMatches[gIdx]?.has(row))) {
|
|
1781
2193
|
const desigEval = scoreDesignatorsAgainstDoc(group.designators, doc);
|
|
1782
2194
|
if (desigEval.hit.bestScore > 0) {
|
|
1783
2195
|
primaryHit = mergeTermHits(primaryHit, desigEval.hit);
|
|
@@ -1789,7 +2201,7 @@ function evaluatePreparedQuery(plan, doc, includePinpoint) {
|
|
|
1789
2201
|
// Also normalize single-letter hyphenated acronyms ("M-SHORAD" <-> "M SHORAD")
|
|
1790
2202
|
if (primaryHit.bestScore === 0 && /^[a-z]-[a-z]{4,}$/.test(group.primary)) {
|
|
1791
2203
|
const spacedAcronym = group.primary.replace(/-/g, " ");
|
|
1792
|
-
const spacedHit =
|
|
2204
|
+
const spacedHit = scoreTerm(spacedAcronym);
|
|
1793
2205
|
if (spacedHit.bestScore > 0) {
|
|
1794
2206
|
primaryHit = spacedHit;
|
|
1795
2207
|
effectivePrimaryTerm = spacedAcronym;
|
|
@@ -1800,7 +2212,7 @@ function evaluatePreparedQuery(plan, doc, includePinpoint) {
|
|
|
1800
2212
|
const triFields = new Set();
|
|
1801
2213
|
const triBodyTerms = [];
|
|
1802
2214
|
for (const tri of group.threeGrams) {
|
|
1803
|
-
const h =
|
|
2215
|
+
const h = scoreTerm(tri);
|
|
1804
2216
|
if (h.bestScore > 0) {
|
|
1805
2217
|
for (const f of h.fields) {
|
|
1806
2218
|
triFields.add(f);
|
|
@@ -1821,7 +2233,7 @@ function evaluatePreparedQuery(plan, doc, includePinpoint) {
|
|
|
1821
2233
|
const weightedTri = Math.round((bestTriScore * 0.6 + secondTriScore * 0.2) * stemDiscount);
|
|
1822
2234
|
const biHits = [];
|
|
1823
2235
|
for (const bi of group.twoGrams) {
|
|
1824
|
-
const h =
|
|
2236
|
+
const h = scoreTerm(bi);
|
|
1825
2237
|
if (h.bestScore > 0) {
|
|
1826
2238
|
biHits.push({ term: bi, hit: h });
|
|
1827
2239
|
}
|
|
@@ -1853,7 +2265,7 @@ function evaluatePreparedQuery(plan, doc, includePinpoint) {
|
|
|
1853
2265
|
const subTokHits = [];
|
|
1854
2266
|
if (primaryHit.bestScore === 0 && group.subTokens && group.subTokens.length >= 2) {
|
|
1855
2267
|
for (const st of group.subTokens) {
|
|
1856
|
-
const h =
|
|
2268
|
+
const h = scoreTerm(st);
|
|
1857
2269
|
if (h.bestScore > 0) {
|
|
1858
2270
|
// Do not treat a parent domainId prefix match as an 86-pt sceneId prefix during subToken decomposition
|
|
1859
2271
|
const onlyDomainPrefixId = Boolean(doc.shortIdLower) &&
|
|
@@ -1948,24 +2360,10 @@ function evaluatePreparedQuery(plan, doc, includePinpoint) {
|
|
|
1948
2360
|
groupScores.sort((a, b) => b - a);
|
|
1949
2361
|
const topGroupSum = groupScores.slice(0, 4).reduce((sum, s) => sum + s, 0);
|
|
1950
2362
|
// On >= 8 scene wikis, only specific (non-ubiquitous) matched groups earn full +25 coordination bonus
|
|
1951
|
-
|
|
1952
|
-
if (!useCorpusIdf) {
|
|
1953
|
-
multiTokenBonus =
|
|
1954
|
-
matchedGroupCount >= 2
|
|
1955
|
-
? (matchedGroupCount - 1) * 25 + (matchedGroupCount === tokenized.groups.length ? 15 : 0)
|
|
1956
|
-
: 0;
|
|
1957
|
-
}
|
|
1958
|
-
else {
|
|
1959
|
-
const specificBonus = specificMatchedGroupCount >= 2 ? (specificMatchedGroupCount - 1) * 25 : 0;
|
|
1960
|
-
const crossSupportBonus = specificMatchedGroupCount >= 1 && matchedGroupCount > specificMatchedGroupCount
|
|
1961
|
-
? Math.min(18, (matchedGroupCount - specificMatchedGroupCount) * 6)
|
|
1962
|
-
: 0;
|
|
1963
|
-
const fullMatchBonus = specificMatchedGroupCount >= 1 && matchedGroupCount === tokenized.groups.length ? 12 : 0;
|
|
1964
|
-
multiTokenBonus = specificBonus + crossSupportBonus + fullMatchBonus;
|
|
1965
|
-
}
|
|
2363
|
+
const multiTokenBonus = coordinationBonus(matchedGroupCount, specificMatchedGroupCount, tokenized.groups.length, useCorpusIdf);
|
|
1966
2364
|
let selectivePhraseBonus = 0;
|
|
1967
2365
|
for (const sb of plan.selectiveBigrams) {
|
|
1968
|
-
if (!doc.allTextLower.includes(sb.phrase)) {
|
|
2366
|
+
if (row === undefined ? !doc.allTextLower.includes(sb.phrase) : !sb.rows.has(row)) {
|
|
1969
2367
|
continue;
|
|
1970
2368
|
}
|
|
1971
2369
|
const inHighField = doc.titleLower.includes(sb.phrase) ||
|
|
@@ -2196,11 +2594,10 @@ const COMPARISON_GLUE_WORDS = new Set([
|
|
|
2196
2594
|
"to",
|
|
2197
2595
|
"by",
|
|
2198
2596
|
]);
|
|
2199
|
-
function expandMultiEntitySingleQuery(rawQuery, index,
|
|
2200
|
-
if (
|
|
2597
|
+
function expandMultiEntitySingleQuery(rawQuery, plan, index, scope) {
|
|
2598
|
+
if (!plan.useCorpusIdf) {
|
|
2201
2599
|
return [rawQuery];
|
|
2202
2600
|
}
|
|
2203
|
-
const plan = buildPreparedQueryPlan(rawQuery, index);
|
|
2204
2601
|
const { tokenized, groupIdf } = plan;
|
|
2205
2602
|
if (tokenized.groups.length < 2) {
|
|
2206
2603
|
return [rawQuery];
|
|
@@ -2255,8 +2652,16 @@ function expandMultiEntitySingleQuery(rawQuery, index, candidateScenes) {
|
|
|
2255
2652
|
return [rawQuery];
|
|
2256
2653
|
}
|
|
2257
2654
|
// Only decompose into per-entity RRF sub-queries when NO single scene contains all entities together
|
|
2258
|
-
const
|
|
2259
|
-
|
|
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)));
|
|
2260
2665
|
if (singleSceneCoversAll) {
|
|
2261
2666
|
return [rawQuery];
|
|
2262
2667
|
}
|
|
@@ -2319,26 +2724,174 @@ export function discoverScenes(wiki, options = {}) {
|
|
|
2319
2724
|
return applyLimit(out, options.limit);
|
|
2320
2725
|
}
|
|
2321
2726
|
const index = getPrecomputedWikiIndex(wiki);
|
|
2322
|
-
const
|
|
2323
|
-
|
|
2324
|
-
|
|
2325
|
-
|
|
2326
|
-
|
|
2327
|
-
|
|
2328
|
-
}
|
|
2329
|
-
|
|
2330
|
-
|
|
2727
|
+
const scope = options.domainId || kindFilter !== "all" ? new Set() : undefined;
|
|
2728
|
+
if (scope)
|
|
2729
|
+
index.scenes.forEach(({ scene }, row) => {
|
|
2730
|
+
if ((!options.domainId || scene.domainId === options.domainId) &&
|
|
2731
|
+
(kindFilter === "all" || scene.kind === kindFilter))
|
|
2732
|
+
scope.add(row);
|
|
2733
|
+
});
|
|
2734
|
+
const localScope = options.domainId && scope && scope.size >= 6 ? scope : undefined;
|
|
2735
|
+
const firstQuery = rawActiveQueries[0];
|
|
2736
|
+
const firstPlan = buildPreparedQueryPlan(firstQuery, index, localScope);
|
|
2331
2737
|
const activeQueries = rawActiveQueries.length === 1
|
|
2332
|
-
? expandMultiEntitySingleQuery(
|
|
2738
|
+
? expandMultiEntitySingleQuery(firstQuery, firstPlan, index, scope)
|
|
2333
2739
|
: rawActiveQueries;
|
|
2740
|
+
const rrfPerQueryCap = options.limit !== undefined ? Math.max(40, options.limit * 4) : 60;
|
|
2334
2741
|
function runSingleSceneQuery(q) {
|
|
2335
|
-
const plan = buildPreparedQueryPlan(q, index);
|
|
2742
|
+
const plan = q === firstQuery ? firstPlan : buildPreparedQueryPlan(q, index, localScope);
|
|
2743
|
+
const ordered = [];
|
|
2744
|
+
const groupCounts = new Uint32Array(index.sceneCount);
|
|
2745
|
+
const groupRows = [];
|
|
2746
|
+
const reverse = new Set();
|
|
2747
|
+
const collect = (term, rows, trackReverse = true) => {
|
|
2748
|
+
for (const row of termRows(index, term))
|
|
2749
|
+
rows.add(row);
|
|
2750
|
+
const exact = index.collapsedPostings.get(term);
|
|
2751
|
+
if (exact)
|
|
2752
|
+
for (const row of exact) {
|
|
2753
|
+
rows.add(row);
|
|
2754
|
+
if (trackReverse)
|
|
2755
|
+
reverse.add(row);
|
|
2756
|
+
}
|
|
2757
|
+
for (let start = 0; start + 1 < term.length; start++) {
|
|
2758
|
+
const lengths = index.reverseLengths.get(term.slice(start, start + 2));
|
|
2759
|
+
if (!lengths)
|
|
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
|
+
}
|
|
2336
2845
|
const hits = [];
|
|
2337
|
-
|
|
2338
|
-
|
|
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);
|
|
2339
2880
|
if (evalRes.score <= 0) {
|
|
2340
2881
|
continue;
|
|
2341
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
|
+
}
|
|
2342
2895
|
const item = {
|
|
2343
2896
|
id: scene.id,
|
|
2344
2897
|
domainId: scene.domainId,
|
|
@@ -2375,7 +2928,7 @@ export function discoverScenes(wiki, options = {}) {
|
|
|
2375
2928
|
return filtered;
|
|
2376
2929
|
}
|
|
2377
2930
|
function enrichSceneItem(base, snippetTerms, pTerms, pDesigs) {
|
|
2378
|
-
const doc = index.sceneById.get(base.id)?.doc;
|
|
2931
|
+
const doc = index.sceneById.get(base.id)?.entry.doc;
|
|
2379
2932
|
if (!doc) {
|
|
2380
2933
|
return base;
|
|
2381
2934
|
}
|
|
@@ -2398,16 +2951,18 @@ export function discoverScenes(wiki, options = {}) {
|
|
|
2398
2951
|
}
|
|
2399
2952
|
// Multi-query Reciprocal Rank Fusion (RRF) so every queried entity/report gets top-K representation without cannibalization
|
|
2400
2953
|
const fusedById = new Map();
|
|
2401
|
-
const rrfPerQueryCap = options.limit !== undefined ? Math.max(40, options.limit * 4) : 60;
|
|
2402
2954
|
for (const q of activeQueries) {
|
|
2403
2955
|
const subResults = runSingleSceneQuery(q);
|
|
2404
2956
|
const topScore = Math.max(1, subResults[0]?.item.score ?? 1);
|
|
2957
|
+
const distinctWinner = subResults[1]?.item.score !== topScore;
|
|
2405
2958
|
const windowLen = Math.min(subResults.length, rrfPerQueryCap);
|
|
2406
2959
|
for (let idx = 0; idx < windowLen; idx++) {
|
|
2407
2960
|
const { item, snippetTerms, pinpointTerms, pinpointDesignators } = subResults[idx];
|
|
2408
2961
|
const rank = idx + 1;
|
|
2409
2962
|
const rawScore = item.score ?? 0;
|
|
2410
|
-
const rrfContribution = 1200 / (1 + rank) +
|
|
2963
|
+
const rrfContribution = 1200 / (1 + rank) +
|
|
2964
|
+
40 * (rawScore / topScore) +
|
|
2965
|
+
(rank === 1 && rawScore >= 55 && distinctWinner ? 650 * activeQueries.length : 0);
|
|
2411
2966
|
const existing = fusedById.get(item.id);
|
|
2412
2967
|
if (!existing) {
|
|
2413
2968
|
fusedById.set(item.id, {
|
|
@@ -2449,6 +3004,16 @@ export function discoverScenes(wiki, options = {}) {
|
|
|
2449
3004
|
fusedScore: Math.round(entry.rrfSum + 0.15 * entry.maxRawScore),
|
|
2450
3005
|
}))
|
|
2451
3006
|
.sort((a, b) => b.fusedScore - a.fusedScore || a.entry.base.id.localeCompare(b.entry.base.id));
|
|
3007
|
+
if (!options.domainId && wiki.domains.size > 1) {
|
|
3008
|
+
const domainSeenCount = new Map();
|
|
3009
|
+
for (const hit of sortedFused) {
|
|
3010
|
+
const domain = hit.entry.base.domainId;
|
|
3011
|
+
const seen = domainSeenCount.get(domain) ?? 0;
|
|
3012
|
+
hit.fusedScore = Math.round(hit.fusedScore / (1 + Math.min(seen, 4) * 0.12));
|
|
3013
|
+
domainSeenCount.set(domain, seen + 1);
|
|
3014
|
+
}
|
|
3015
|
+
sortedFused.sort((left, right) => right.fusedScore - left.fusedScore || left.entry.base.id.localeCompare(right.entry.base.id));
|
|
3016
|
+
}
|
|
2452
3017
|
return applyLimit(sortedFused, options.limit).map(({ entry, fusedScore }) => {
|
|
2453
3018
|
const orderedFields = FIELD_DISPLAY_ORDER.filter((f) => entry.fields.has(f));
|
|
2454
3019
|
const baseWithScore = {
|
|
@@ -2469,8 +3034,8 @@ export function inspectSceneCoverageData(wiki, sceneId) {
|
|
|
2469
3034
|
return undefined;
|
|
2470
3035
|
}
|
|
2471
3036
|
return {
|
|
2472
|
-
allTextLower: found.doc.allTextLower,
|
|
2473
|
-
designators: found.doc.designators.all,
|
|
3037
|
+
allTextLower: found.entry.doc.allTextLower,
|
|
3038
|
+
designators: found.entry.doc.designators.all,
|
|
2474
3039
|
};
|
|
2475
3040
|
}
|
|
2476
3041
|
//# sourceMappingURL=discover.js.map
|