Open History to see the last commit
1/** Shared ranking keeps command palettes and MCP thread search consistent across surfaces. */
2
3import type { OrchestrationV2ThreadOpens } from "@t3tools/contracts";
4
5import { WORKTREE_BRANCH_PREFIX } from "./git.ts";
6
7const ALPHANUMERIC = /[\p{L}\p{N}]/u;
8const LOWERCASE = /\p{Ll}/u;
9const UPPERCASE = /\p{Lu}/u;
10const DIGIT = /\p{N}/u;
11const LETTER = /\p{L}/u;
12const COMBINING_MARKS = /\p{M}/gu;
13// Emoji and other symbols can be searched for, so they start words too.
14const SYMBOL = /\p{So}/u;
15const APOSTROPHE = /['’]/;
16const CURLY_APOSTROPHES = /[\u2018\u2019]/g;
17
18interface SearchField {
19 /** Case- and accent-folded text, one UTF-16 unit per source unit. */
20 readonly text: string;
21 /** 1 where a word starts in `text`. */
22 readonly wordStarts: Uint8Array;
23}
24
25export interface SearchRange {
26 readonly start: number;
27 readonly end: number;
28}
29
30// Thread titles, branches, and project names repeat across keystrokes; folding
31// them once keeps a keystroke to plain string scans. Each keystroke reads every
32// field, so the limit must hold all of them or the cache clears every time; a
33// field is a few bytes per character.
34const fieldCache = new Map<string, SearchField>();
35const FIELD_CACHE_LIMIT = 100_000;
36
37function foldCharacter(character: string): string {
38 // A typed straight apostrophe finds a curly one: iOS keyboards type "’".
39 return character
40 .normalize("NFKD")
41 .replace(COMBINING_MARKS, "")
42 .toLowerCase()
43 .replace("ς", "σ")
44 .replace(/[‘’]/, "'");
45}
46
47/**
48 * `text` with case and accents folded one UTF-16 unit at a time, so offsets
49 * and word starts still read from `text` and highlights need no mapping. A
50 * letter that folds to more or less than one unit ("ß", "fi") stays as it is.
51 */
52function foldInPlace(text: string): string {
53 return text
54 .replace(/[\u0080-\uffff]/g, (character) => {
55 const folded = foldCharacter(character);
56 return folded.length === 1 ? folded : character;
57 })
58 .toLowerCase();
59}
60
61// Chinese and Japanese text has no spaces, so each ideograph or kana starts a word.
62function isCjk(character: string): boolean {
63 const code = character.codePointAt(0)!;
64 return (
65 (code >= 0x3040 && code <= 0x30ff) ||
66 (code >= 0x3400 && code <= 0x4dbf) ||
67 (code >= 0x4e00 && code <= 0x9fff) ||
68 (code >= 0xf900 && code <= 0xfaff)
69 );
70}
71
72// Two Chinese, Japanese, or Korean characters already make a common word.
73function hasCjkWord(token: string): boolean {
74 return Array.from(token).some((character) => {
75 const code = character.codePointAt(0)!;
76 return isCjk(character) || (code >= 0xac00 && code <= 0xd7af);
77 });
78}
79
80/**
81 * Whether `character` starts a word after `previous` and `beforePrevious`
82 * ("" at the start): after a non-letter, at a camelCase or digit boundary, or
83 * at any Chinese or Japanese character. The one rule for titles and messages.
84 */
85function isWordStart(
86 beforePrevious: string,
87 previous: string,
88 character: string,
89 next: string,
90): boolean {
91 // "Julius’s": a possessive or contraction does not start a word.
92 const afterApostrophe = APOSTROPHE.test(previous) && ALPHANUMERIC.test(beforePrevious);
93 return (
94 (ALPHANUMERIC.test(character) || SYMBOL.test(character)) &&
95 !afterApostrophe &&
96 (previous === "" ||
97 !ALPHANUMERIC.test(previous) ||
98 (LOWERCASE.test(previous) && UPPERCASE.test(character)) ||
99 // The last capital of an acronym starts the next word: "JSONSchema".
100 (UPPERCASE.test(previous) && UPPERCASE.test(character) && LOWERCASE.test(next)) ||
101 DIGIT.test(previous) !== DIGIT.test(character) ||
102 isCjk(character))
103 );
104}
105
106function foldSearchField(source: string): SearchField {
107 const wordStarts = new Uint8Array(source.length);
108 const characters = Array.from(source);
109 let index = 0;
110 for (const [position, character] of characters.entries()) {
111 const previous = characters[position - 1] ?? "";
112 const next = characters[position + 1] ?? "";
113 if (isWordStart(characters[position - 2] ?? "", previous, character, next)) {
114 wordStarts[index] = 1;
115 }
116 index += character.length;
117 }
118 return { text: foldInPlace(source), wordStarts };
119}
120
121function prepareSearchField(source: string): SearchField {
122 const cached = fieldCache.get(source);
123 if (cached) return cached;
124 // Oldest first out. A read does not re-insert: that would cost more than the
125 // fold it saves, and the limit holds far more fields than a keystroke reads.
126 if (fieldCache.size >= FIELD_CACHE_LIMIT) {
127 fieldCache.delete(fieldCache.keys().next().value!);
128 }
129 const field = foldSearchField(source);
130 fieldCache.set(source, field);
131 return field;
132}
133
134// Quotes around a pasted query: "fix sidebar".
135const WRAPPING_QUOTES = /^\s*["'`“”‘’]+|["'`“”‘’]+\s*$/g;
136
137/** Folded, whitespace-collapsed query; empty when there is nothing to match. */
138export function foldSearchQuery(query: string): string {
139 return foldInPlace(query.replace(WRAPPING_QUOTES, "").normalize("NFC"))
140 .split(/\s+/)
141 .filter((token) => token.length > 0)
142 .join(" ");
143}
144
145function wordEnd(field: SearchField, index: number): number {
146 let end = index + 1;
147 while (end < field.text.length && !field.wordStarts[end] && ALPHANUMERIC.test(field.text[end]!)) {
148 end++;
149 }
150 return end;
151}
152
153// One substitution, insertion, deletion, or swap of neighbours; with
154// `swapOnly`, only a swap.
155function withinOneEdit(left: string, right: string, swapOnly: boolean): boolean {
156 if (Math.abs(left.length - right.length) > (swapOnly ? 0 : 1)) return false;
157 let index = 0;
158 while (index < left.length && index < right.length && left[index] === right[index]) index++;
159 const restLeft = left.slice(index);
160 const restRight = right.slice(index);
161 const swapped =
162 restLeft.length > 1 &&
163 restLeft[0] === restRight[1] &&
164 restLeft[1] === restRight[0] &&
165 restLeft.slice(2) === restRight.slice(2);
166 if (swapOnly) return swapped;
167 return (
168 swapped ||
169 restLeft === restRight ||
170 restLeft.slice(1) === restRight.slice(1) ||
171 restLeft.slice(1) === restRight ||
172 restLeft === restRight.slice(1)
173 );
174}
175
176const WHOLE_WORD = 1;
177// The bonus for a field equal to the whole query lifts a whole word to this.
178const WHOLE_NAME = 1.5;
179const MID_WORD = 0.3;
180const TYPO = 0.45;
181// Whole words typed together are exact, so they rank with typos and above
182// mid-word hits, though below a match at a word start.
183const JOINED_WORDS = 0.6;
184
185interface TokenMatch extends SearchRange {
186 readonly score: number;
187 /** Separate ranges, for words typed together. */
188 readonly letters?: ReadonlyArray<SearchRange>;
189}
190
191/**
192 * Mid-word hits need four or more characters and `midWord`, so "del" does not find "model".
193 * Typos preserve the first letter except for swaps; short tokens allow fewer edits to limit noise.
194 * Numbers never match with a typo because different pull request numbers must stay distinct.
195 */
196function matchToken(
197 field: SearchField,
198 token: string,
199 typos: boolean,
200 isPrimary: boolean,
201 midWord: boolean,
202): TokenMatch | null {
203 if (token.length === 0) return null;
204 let best: TokenMatch | null = null;
205 const ownBoundary = !ALPHANUMERIC.test(token[0]!) && !SYMBOL.test(token[0]!);
206 for (
207 let index = field.text.indexOf(token);
208 index !== -1;
209 index = field.text.indexOf(token, index + 1)
210 ) {
211 // A token that opens with punctuation (".ts") brings its own boundary, as in messages.
212 if (field.wordStarts[index] || ownBoundary) {
213 // Whole when the match ends where a word ends: "t3c" is a prefix of
214 // "t3code", ".ts" whole in "index.ts" but a prefix in "parser.tsx".
215 const end = index + token.length;
216 const whole =
217 end >= field.text.length ||
218 field.wordStarts[end] === 1 ||
219 !ALPHANUMERIC.test(field.text[end]!);
220 let runEnd = end;
221 while (runEnd < field.text.length && ALPHANUMERIC.test(field.text[runEnd]!)) runEnd++;
222 const score = whole ? WHOLE_WORD : 0.7 + (0.2 * token.length) / (runEnd - index);
223 if (best === null || score > best.score) {
224 best = { score, start: index, end: index + token.length };
225 }
226 if (score === WHOLE_WORD) return best;
227 } else if (midWord && token.length >= 4 && best === null) {
228 best = { score: MID_WORD, start: index, end: index + token.length };
229 }
230 }
231 // Joined words are exact, so they count without the typo pass: a strong
232 // match elsewhere must not hide "VS Code" for "vscode".
233 if ((best === null || best.score <= MID_WORD) && isPrimary) {
234 const joined = matchJoinedWords(field, token);
235 if (joined) return joined;
236 }
237 if ((best !== null && best.score > MID_WORD) || !typos || token.length < 3) return best;
238 // Numbers skip typos to keep pull requests distinct. Words with digits ("t3code") do not.
239 if (LETTER.test(token)) {
240 for (let index = 0; index < field.text.length; index++) {
241 if (!field.wordStarts[index]) continue;
242 // People rarely mistype the first letter, so a typo keeps it, unless it
243 // swaps the first two of a longer word ("ing" is not "nig…").
244 const first = field.text[index];
245 const firstLetterKept =
246 first === token[0] ||
247 (token.length > 3 && first === token[1] && field.text[index + 1] === token[0]);
248 if (!firstLetterKept) continue;
249 // The whole run, across camelCase joins: "githbu" is "GitHub".
250 let runEnd = index + 1;
251 while (runEnd < field.text.length && ALPHANUMERIC.test(field.text[runEnd]!)) runEnd++;
252 const word = field.text.slice(index, runEnd);
253 // Short tokens forgive a swapped pair or one missing letter ("srv" for
254 // "serv…"); any other edit of a three- or four-letter word matches too
255 // much ("cron" would find every "con…").
256 const short = token.length <= 4;
257 // The same length first, so "githbu" highlights all of "GitHub".
258 const lengths = short
259 ? [token.length, token.length + 1]
260 : [token.length, token.length - 1, token.length + 1];
261 for (const length of lengths) {
262 if (length > word.length) continue;
263 const prefix = word.slice(0, length);
264 if (withinOneEdit(token, prefix, short && length === token.length)) {
265 return { score: TYPO, start: index, end: index + length };
266 }
267 }
268 }
269 }
270 return best;
271}
272
273/**
274 * Short words followed by a short prefix are noise inside a title ("inth" in "in thread").
275 * Allow them at its start ("t3co"), before three letters ("gomod"), or a whole word ("vscode").
276 */
277function matchJoinedWords(field: SearchField, token: string): TokenMatch | null {
278 const firstWord = field.wordStarts.indexOf(1);
279 for (let start = 0; start < field.text.length; start++) {
280 if (!field.wordStarts[start] || field.text[start] !== token[0]) continue;
281 const runs: SearchRange[] = [];
282 let at = start;
283 let rest = token;
284 while (rest.length > 0 && at < field.text.length) {
285 const end = wordEnd(field, at);
286 if (rest.length <= end - at && field.text.startsWith(rest, at)) {
287 runs.push({ start: at, end: at + rest.length });
288 rest = "";
289 } else if (rest.startsWith(field.text.slice(at, end))) {
290 runs.push({ start: at, end });
291 rest = rest.slice(end - at);
292 at = end;
293 while (at < field.text.length && !field.wordStarts[at]) at++;
294 } else {
295 break;
296 }
297 }
298 const last = runs.at(-1);
299 if (rest.length > 0 || last === undefined || runs.length < 2) continue;
300 if (
301 last.end === wordEnd(field, last.start) ||
302 last.end - last.start >= 3 ||
303 start === firstWord ||
304 runs.slice(0, -1).every((run) => run.end - run.start >= 3)
305 ) {
306 return { score: JOINED_WORDS, start, end: last.end, letters: runs };
307 }
308 }
309 return null;
310}
311
312interface WeightedSearchField {
313 readonly value: string;
314 readonly weight: number;
315 /** Only a whole-word match counts, as for a short query against keywords. */
316 readonly wholeWords?: boolean;
317 /**
318 * Only a match at a word start counts, without typos: hidden keywords that
319 * matched loosely would list results the user cannot see why for.
320 */
321 readonly keyword?: boolean;
322 /**
323 * Where the thread lives (project, environment): it helps a match, but a
324 * word start there does not make the match strong, so it never turns off
325 * joined words or typos for the titles.
326 */
327 readonly context?: boolean;
328 /**
329 * A token of four or more letters may match inside a word here. Only thread
330 * titles allow it: inside a command name or a branch it reads as junk
331 * ("arch" in "Search").
332 */
333 readonly midWord?: boolean;
334}
335
336interface SearchFieldsMatch {
337 /** Roughly 0.3 (inside a word) to 1.5 (exact title). */
338 readonly quality: number;
339 /** Every token matched at a word start, without a typo. */
340 readonly strong: boolean;
341 /** Source ranges matched in the first field, for highlighting. */
342 readonly primaryRanges: ReadonlyArray<SearchRange>;
343}
344
345const FILLER_WORDS = new Set(["a", "an", "and", "for", "in", "of", "on", "the", "to", "with"]);
346
347// Sorted, with overlapping ranges joined.
348function mergeRanges(ranges: ReadonlyArray<SearchRange>): SearchRange[] {
349 const merged: SearchRange[] = [];
350 for (const range of [...ranges].sort((left, right) => left.start - right.start)) {
351 const last = merged.at(-1);
352 if (last && range.start <= last.end) {
353 merged[merged.length - 1] = { start: last.start, end: Math.max(last.end, range.end) };
354 } else {
355 merged.push({ start: range.start, end: range.end });
356 }
357 }
358 return merged;
359}
360
361/**
362 * Every query token must match some field. Quality is the mean of each token's
363 * best weighted match, plus a bonus when the first field holds the whole query
364 * as a phrase or equals it.
365 */
366function matchSearchFields(
367 normalizedQuery: string,
368 fields: ReadonlyArray<WeightedSearchField>,
369 options?: { readonly typos?: boolean },
370): SearchFieldsMatch | null {
371 if (normalizedQuery.length === 0) return null;
372 const prepared = fields
373 .filter((field) => field.value.length > 0)
374 .map((field) => ({
375 field: prepareSearchField(field.value),
376 weight: field.weight,
377 wholeWords: field.wholeWords ?? false,
378 keyword: field.keyword ?? false,
379 context: field.context ?? false,
380 allowMidWord: field.midWord ?? false,
381 }));
382 const primary = fields[0]?.value ? prepared[0]?.field : undefined;
383 // An empty token would match everywhere, and loop forever in `matchToken`.
384 const tokens = normalizedQuery.split(" ").filter((token) => token.length > 0);
385 if (tokens.length === 0) return null;
386 // A phrase-style query ("fix the sidebar") carries filler words a name may
387 // leave out; they count where they match but are not required.
388 const fillerOptional = tokens.some((token) => !FILLER_WORDS.has(token));
389 const primaryRanges: SearchRange[] = [];
390 let total = 0;
391 let counted = 0;
392 let strong = true;
393 for (const token of tokens) {
394 let best = 0;
395 let bestPrimary: TokenMatch | null = null;
396 let atWordStart = false;
397 for (const { field, weight, wholeWords, keyword, context, allowMidWord } of prepared) {
398 if (best >= weight && field !== primary && atWordStart) continue;
399 const typos = (options?.typos ?? false) && !keyword;
400 // Joined words only count in the name.
401 const match = matchToken(field, token, typos, field === primary, allowMidWord);
402 if (match === null || match.score < (wholeWords ? WHOLE_WORD : keyword ? 0.7 : 0)) continue;
403 if (field === primary) bestPrimary = match;
404 if (match.score >= 0.7 && !context) atWordStart = true;
405 if (match.score * weight > best) best = match.score * weight;
406 }
407 if (best === 0) {
408 if (fillerOptional && FILLER_WORDS.has(token)) continue;
409 return null;
410 }
411 strong &&= atWordStart;
412 if (bestPrimary) primaryRanges.push(...(bestPrimary.letters ?? [bestPrimary]));
413 total += best;
414 counted += 1;
415 }
416 let quality = total / counted;
417 if (primary) {
418 if (primary.text === normalizedQuery) quality += WHOLE_NAME - WHOLE_WORD;
419 else if (tokens.length > 1 && primary.text.includes(normalizedQuery)) quality += 0.25;
420 }
421 return {
422 quality,
423 strong,
424 primaryRanges: mergeRanges(primaryRanges),
425 };
426}
427
428// A two-letter Latin substring of a message is noise rather than a match.
429const MESSAGE_TOKEN_MIN_LENGTH = 3;
430
431/**
432 * Keep accents: the server index folds Latin accents, and stripping marks breaks Korean/Japanese.
433 * Every `long` token must match; `short` tokens only narrow hits. No long tokens means no search.
434 * Two CJK characters count as long.
435 */
436export function messageSearchTokens(query: string): {
437 readonly long: ReadonlyArray<string>;
438 readonly short: ReadonlyArray<string>;
439 /** Every token, in the order typed. */
440 readonly words: ReadonlyArray<string>;
441} {
442 const tokens = query
443 .replace(WRAPPING_QUOTES, "")
444 // The index stores apostrophes straight, as `indexedMessageText` writes them.
445 .replace(CURLY_APOSTROPHES, "'")
446 .normalize("NFC")
447 .toLowerCase()
448 .split(/\s+/)
449 .filter((token) => token.length > 0);
450 const searchable = (token: string) => {
451 const length = Array.from(token).length;
452 return length >= MESSAGE_TOKEN_MIN_LENGTH || (length === 2 && hasCjkWord(token));
453 };
454 return {
455 long: tokens.filter(searchable),
456 short: tokens.filter((token) => !searchable(token)),
457 words: tokens,
458 };
459}
460
461/**
462 * Matches the query's words side by side as whole words, as typed, whatever
463 * whitespace is between them and ignoring case; null for a single word.
464 */
465export function messagePhrase(query: string): RegExp | null {
466 const { words } = messageSearchTokens(query);
467 return words.length > 1
468 ? new RegExp(
469 `(?<![\\p{L}\\p{N}])${words
470 .map((word) => word.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"))
471 .join("\\s+")}(?![\\p{L}\\p{N}])`,
472 "iu",
473 )
474 : null;
475}
476
477// Words written together, as typed, rank above the same words apart, as in
478// titles; words near each other rank above words far apart.
479const MESSAGE_PHRASE_BONUS = 0.25;
480const MESSAGE_NEAR_BONUS = 0.1;
481// About what a result row shows.
482const MESSAGE_NEAR_SPAN = 60;
483
484const NON_ASCII = /[\u0080-\uffff]/;
485// A message token shorter than this must start a word: "fts" is not in "drafts".
486const MESSAGE_WORD_START_LENGTH = 4;
487const MESSAGE_PREFIX = 0.8;
488
489function startsWordAt(text: string, index: number): boolean {
490 const character = text[index]!;
491 // A token that opens with punctuation (such as ".ts") brings its own boundary.
492 if (!ALPHANUMERIC.test(character) && !SYMBOL.test(character)) return true;
493 return isWordStart(
494 text[index - 2] ?? "",
495 text[index - 1] ?? "",
496 character,
497 text[index + 1] ?? "",
498 );
499}
500
501// Whether a word ends right before `end` in `text`.
502function endsWordAt(text: string, end: number): boolean {
503 return end >= text.length || !ALPHANUMERIC.test(text[end]!) || startsWordAt(text, end);
504}
505
506// A commit SHA or UUID part: seven or more hex characters with a digit.
507const HEX_ID = /^(?=[a-f]*\d)[0-9a-f]{7,}$/i;
508
509// Where `token` best sits in `folded`, a fold of `text`: every place it is a
510// whole word, else a word start, else inside a word. Hits past the start of a
511// hex ID do not count ("cafe" in "7cafe52bb8"), though a pasted SHA prefix
512// does.
513function findMessageToken(
514 text: string,
515 folded: string,
516 token: string,
517): { readonly at: ReadonlyArray<number>; readonly quality: number } | null {
518 let quality = 0;
519 let at: number[] = [];
520 // The letters-and-digits run around the hit, kept for later hits in the
521 // same run: rescanning it per hit is quadratic in a long run ("0000" in a
522 // hex dump).
523 let run = { start: 0, end: -1, hex: false };
524 for (let index = folded.indexOf(token); index !== -1; index = folded.indexOf(token, index + 1)) {
525 if (index + token.length > run.end) {
526 let start = index;
527 while (start > 0 && ALPHANUMERIC.test(text[start - 1]!)) start--;
528 let end = index + token.length;
529 while (end < text.length && ALPHANUMERIC.test(text[end]!)) end++;
530 run = { start, end, hex: HEX_ID.test(text.slice(start, end)) };
531 }
532 if (run.hex && run.start < index) continue;
533 const found = !startsWordAt(text, index)
534 ? MID_WORD
535 : endsWordAt(text, index + token.length)
536 ? 1
537 : MESSAGE_PREFIX;
538 if (found > quality) {
539 quality = found;
540 at = [index];
541 } else if (found === quality) {
542 at.push(index);
543 }
544 }
545 return at.length === 0 ? null : { at, quality };
546}
547
548export interface MessageMatch {
549 /**
550 * 1 when every searched word is a whole word, MESSAGE_PREFIX when one only
551 * starts a word ("mode" in "model"), MID_WORD when one only appears inside
552 * words, plus MESSAGE_PHRASE_BONUS when the words are written together as
553 * typed, else MESSAGE_NEAR_BONUS when they sit within a row's width.
554 */
555 readonly quality: number;
556 /** Where a snippet should start to show the match. */
557 readonly offset: number;
558}
559
560/**
561 * Grades messages against a query, so message hits rank like titles: null
562 * when a token is missing or a short one never starts a word ("fts" in
563 * "drafts"). Case and accents are ignored, as in the server's index. The
564 * query is prepared once, since the server grades thousands of hits for it.
565 */
566export function messageMatcher(query: string): (text: string) => MessageMatch | null {
567 const { long, short, words } = messageSearchTokens(query);
568 const tokens = [...long, ...short].map((token) => ({
569 token,
570 // Marks go from the folded token: lowercasing "İ" adds one.
571 folded: foldInPlace(token).replace(COMBINING_MARKS, ""),
572 nonAscii: NON_ASCII.test(token),
573 mustStartWord: Array.from(token).length < MESSAGE_WORD_START_LENGTH,
574 // Too short to search, so it only narrows: grading by it would reorder
575 // results on each keystroke while the next word is typed ("nvme s").
576 grades: long.includes(token),
577 }));
578 const phrase = messagePhrase(query);
579 // Accents typed or left out still read as written together: "cafe open"
580 // in "Café open".
581 const foldedPhrase = messagePhrase(
582 words.map((word) => foldInPlace(word).replace(COMBINING_MARKS, "")).join(" "),
583 );
584 const queryNonAscii = NON_ASCII.test(query);
585 return (text) => {
586 const lower = text.toLowerCase();
587 // "İ" lowercases to two units, which would shift every offset after it.
588 const plain = lower.length === text.length ? lower : foldInPlace(text);
589 let folded: string | null = null;
590 let quality = 1;
591 const positions: Array<ReadonlyArray<number>> = [];
592 for (const { token, folded: foldedToken, nonAscii, mustStartWord, grades } of tokens) {
593 let found = findMessageToken(text, plain, token);
594 // Accents typed or left out: "cafe" finds "Café", also after "cafeteria".
595 if (found?.quality !== 1 && foldedToken.length > 0 && (nonAscii || NON_ASCII.test(text))) {
596 found = findMessageToken(text, (folded ??= foldInPlace(text)), foldedToken);
597 }
598 if (found === null) return null;
599 if (found.quality === MID_WORD && mustStartWord) return null;
600 if (grades) quality = Math.min(quality, found.quality);
601 positions.push(found.at);
602 }
603 // Written together as typed: the snippet starts there. Apostrophes are
604 // straight in the query, and straightening keeps offsets.
605 const straight = (value: string) => value.replace(CURLY_APOSTROPHES, "'");
606 const together =
607 phrase?.exec(straight(plain)) ??
608 (queryNonAscii || NON_ASCII.test(text)
609 ? foldedPhrase?.exec(straight((folded ??= foldInPlace(text))))
610 : null);
611 if (together) return { quality: quality + MESSAGE_PHRASE_BONUS, offset: together.index };
612 // Else the shortest stretch that holds every word: the snippet starts
613 // there, so it shows them all, and words close together rank above words
614 // far apart ("lakebed perf").
615 const near = shortestSpan(positions);
616 return {
617 quality:
618 long.length > 1 && near.length <= MESSAGE_NEAR_SPAN
619 ? quality + MESSAGE_NEAR_BONUS
620 : quality,
621 offset: near.start,
622 };
623 };
624}
625
626// The shortest stretch of text holding one place of each word, from each
627// word's places in order.
628function shortestSpan(places: ReadonlyArray<ReadonlyArray<number>>): {
629 readonly start: number;
630 readonly length: number;
631} {
632 const hits = places
633 .flatMap((at, word) => at.map((index) => ({ index, word })))
634 .sort((left, right) => left.index - right.index);
635 const counts = places.map(() => 0);
636 let covered = 0;
637 let best = { start: hits[0]?.index ?? 0, length: Number.POSITIVE_INFINITY };
638 let left = 0;
639 for (const hit of hits) {
640 counts[hit.word] = (counts[hit.word] ?? 0) + 1;
641 if (counts[hit.word] === 1) covered++;
642 while (covered === places.length) {
643 const first = hits[left]!;
644 if (hit.index - first.index < best.length) {
645 best = { start: first.index, length: hit.index - first.index };
646 }
647 counts[first.word] = (counts[first.word] ?? 1) - 1;
648 if (counts[first.word] === 0) covered--;
649 left++;
650 }
651 }
652 return best;
653}
654
655/**
656 * Ranges of `text` that contain a long message search token, for message
657 * snippets, ignoring case and accents. Shorter tokens would light up half the
658 * snippet, and a short long token only counts where it starts a word.
659 * Snippets vary per query, so they skip the field cache.
660 */
661export function findSearchTokenRanges(text: string, query: string): SearchRange[] {
662 const tokens = new Map(
663 messageSearchTokens(query)
664 .long.map(
665 (token) =>
666 [foldSearchQuery(token), Array.from(token).length < MESSAGE_WORD_START_LENGTH] as const,
667 )
668 // Some tokens fold to nothing ("´´´"), which would match everywhere.
669 .filter(([token]) => token.length > 0),
670 );
671 if (tokens.size === 0) return [];
672 const field = foldSearchField(text);
673 const ranges: SearchRange[] = [];
674 for (const [token, needsWordStart] of tokens) {
675 // A token that opens with punctuation brings its own boundary, as in scoring.
676 const ownBoundary = !ALPHANUMERIC.test(token[0]!) && !SYMBOL.test(token[0]!);
677 for (let index = field.text.indexOf(token); index !== -1;) {
678 if (needsWordStart && !ownBoundary && !field.wordStarts[index]) {
679 index = field.text.indexOf(token, index + 1);
680 continue;
681 }
682 ranges.push({ start: index, end: index + token.length });
683 index = field.text.indexOf(token, index + token.length);
684 }
685 }
686 return mergeRanges(ranges);
687}
688
689export interface SearchTextPart {
690 readonly text: string;
691 readonly highlighted: boolean;
692 readonly start: number;
693}
694
695/** `text` cut into plain and highlighted parts at sorted, non-overlapping `ranges`. */
696export function splitSearchText(
697 text: string,
698 ranges: ReadonlyArray<SearchRange>,
699): SearchTextPart[] {
700 const parts: SearchTextPart[] = [];
701 let cursor = 0;
702 for (const range of ranges) {
703 if (range.start > cursor) {
704 parts.push({ text: text.slice(cursor, range.start), highlighted: false, start: cursor });
705 }
706 parts.push({ text: text.slice(range.start, range.end), highlighted: true, start: range.start });
707 cursor = range.end;
708 }
709 if (cursor < text.length || parts.length === 0) {
710 parts.push({ text: text.slice(cursor), highlighted: false, start: cursor });
711 }
712 return parts;
713}
714
715const DAY_MS = 24 * 60 * 60 * 1000;
716/** Both activity recency and open counts halve every two weeks. */
717export const SEARCH_RECENCY_HALF_LIFE_MS = 14 * DAY_MS;
718/**
719 * Opens closer together than this count once, so flipping between threads is
720 * not frequency. Clients skip sending them.
721 */
722export const THREAD_OPEN_DEDUPE_MS = 10 * 60 * 1000;
723const THREAD_SEARCH_PICK_LIMIT = 3;
724/** Picked queries are stored this long; clients send no more. */
725const THREAD_SEARCH_PICK_MAX_LENGTH = 32;
726
727/**
728 * `query` as a pick is stored and compared: folded, then cut to the stored
729 * length without splitting an emoji in two. Clients and the server both use
730 * it, so a long pick matches its query again.
731 */
732export function pickedQuery(query: string): string {
733 const cut = foldSearchQuery(query).slice(0, THREAD_SEARCH_PICK_MAX_LENGTH);
734 return (/[\ud800-\udbff]$/.test(cut) ? cut.slice(0, -1) : cut).trim();
735}
736
737function decay(ageMs: number): number {
738 return 2 ** (-Math.max(0, ageMs) / SEARCH_RECENCY_HALF_LIFE_MS);
739}
740
741/** Server-stored open history; see `OrchestrationV2ThreadOpens`. */
742export type ThreadOpenStats = OrchestrationV2ThreadOpens;
743
744/**
745 * Next open stats after an open at `at`. `query` is the palette query that
746 * picked the thread, when it was opened from search.
747 */
748export function recordThreadOpen(
749 previous: ThreadOpenStats | null,
750 at: number,
751 query: string | undefined,
752): ThreadOpenStats {
753 const pick = pickedQuery(query ?? "");
754 // Picks that no longer count are not kept or synced.
755 const earlier = (previous?.picks ?? []).filter((entry) => at - entry.at <= PICK_WINDOW_MS);
756 const picks = pick
757 ? [{ query: pick, at }, ...earlier.filter((entry) => entry.query !== pick)].slice(
758 0,
759 THREAD_SEARCH_PICK_LIMIT,
760 )
761 : earlier;
762 if (previous !== null && at - previous.openedAt < THREAD_OPEN_DEDUPE_MS) {
763 return { ...previous, picks };
764 }
765 const score = previous === null ? 1 : previous.score * decay(at - previous.openedAt) + 1;
766 return { openedAt: at, score, picks };
767}
768
769export interface ThreadSearchSubject {
770 /** Matched only by the whole query, like references. */
771 readonly id?: string;
772 readonly title: string;
773 readonly branch?: string | null;
774 readonly projectTitle?: string | null;
775 /** Only set with two or more environments; it tells same-named threads apart. */
776 readonly environmentLabel?: string | null;
777 readonly pullRequests?: ReadonlyArray<{
778 readonly number: number;
779 readonly title?: string | null;
780 /** Values such as URLs, matched only by the whole query. */
781 readonly references?: ReadonlyArray<string>;
782 }>;
783 /** Latest user activity, in epoch ms. */
784 readonly activityAt: number | null;
785 readonly opens?: ThreadOpenStats | null;
786}
787
788// Use reorders matches of about the same quality but never turns a mid-word
789// hit on a busy thread into a better result than a whole word on a quiet one.
790const USE_BOOST_LIMIT = 2.5;
791
792/**
793 * How much use lifts a thread: 1 for a stale, never-opened thread, about 2 for
794 * one active today, and up to 2.5 for threads opened often.
795 */
796function threadUsageBoost(thread: ThreadSearchSubject, now: number): number {
797 const recency = thread.activityAt === null ? 0 : decay(now - thread.activityAt);
798 const opens = thread.opens ? thread.opens.score * decay(now - thread.opens.openedAt) : 0;
799 return Math.min(USE_BOOST_LIMIT, 1 + recency + 0.5 * Math.log2(1 + opens));
800}
801
802const REFERENCE_PREFIX_MIN = 8;
803
804// IDs and URLs have many word starts, so field matching would let short queries hit every thread.
805// Require a long prefix, or any long part containing a digit. Both are ASCII; lowercasing suffices.
806function matchReference(
807 normalizedQuery: string,
808 thread: ThreadSearchSubject,
809): SearchFieldsMatch | null {
810 if (normalizedQuery.length < REFERENCE_PREFIX_MIN) return null;
811 const references = [
812 ...(thread.id ? [thread.id] : []),
813 ...(thread.pullRequests ?? []).flatMap((pullRequest) => pullRequest.references ?? []),
814 ];
815 const anywhere = DIGIT.test(normalizedQuery);
816 // A number is never cut short: ".../pull/2288" is not pull request 22889.
817 const notCut = (text: string, end: number) => !DIGIT.test(text[end] ?? "");
818 return references.some((reference) => {
819 const folded = reference.toLowerCase();
820 const at = folded.indexOf(normalizedQuery);
821 // A pasted link may go on past the reference: ".../pull/22889/files".
822 return anywhere
823 ? (at !== -1 && notCut(folded, at + normalizedQuery.length)) ||
824 (normalizedQuery.startsWith(folded) && notCut(normalizedQuery, folded.length))
825 : at === 0;
826 })
827 ? { quality: 0.6, strong: true, primaryRanges: [] }
828 : null;
829}
830
831// Picks expire from the pick time; opening a thread another way must not extend their priority.
832// They reorder word matches within a group, never the groups themselves.
833const PICK_WINDOW_MS = 21 * DAY_MS;
834// The start of a picked query counts from three letters: "n" is too little to
835// go on.
836const PICK_PREFIX_MIN_LENGTH = 3;
837
838/** The latest pick of the thread for this query, while it lasts. */
839function activePick(
840 thread: ThreadSearchSubject,
841 normalizedQuery: string,
842 now: number,
843): ThreadOpenStats["picks"][number] | undefined {
844 // Stored picks are cut to a length, so compare the query cut the same way.
845 const query = pickedQuery(normalizedQuery);
846 const prefix = query.length >= PICK_PREFIX_MIN_LENGTH;
847 // The latest exact pick, else the latest pick the query starts.
848 let exact: ThreadOpenStats["picks"][number] | undefined;
849 let latest: ThreadOpenStats["picks"][number] | undefined;
850 for (const pick of thread.opens?.picks ?? []) {
851 if (now - pick.at > PICK_WINDOW_MS) continue;
852 if (pick.query === query && (exact === undefined || pick.at > exact.at)) exact = pick;
853 const matches = pick.query === query || (prefix && pick.query.startsWith(query));
854 if (matches && (latest === undefined || pick.at > latest.at)) latest = pick;
855 }
856 return exact ?? latest;
857}
858
859export interface ThreadSearchMatch {
860 /** Match quality times use; what results sort by. */
861 readonly score: number;
862 /** Match quality alone; see `rankSearchGroups`. */
863 readonly quality: number;
864 /** Every token matched at a word start; see `rankSearchGroups`. */
865 readonly strong: boolean;
866 /** Matched ranges in the title. */
867 readonly ranges: ReadonlyArray<SearchRange>;
868 /**
869 * Why the thread matched when its title shows no match, for the result row.
870 * Built on demand, so only the rows shown pay for it.
871 */
872 readonly explain?: () => SearchMatchHint | undefined;
873 /** When the thread was picked for this query, while that pick lasts; see `rankSearchGroups`. */
874 readonly pickedAt?: number;
875 /** Picked for exactly this query, before newer picks for longer ones; see `rankSearchGroups`. */
876 readonly pickedExactly?: boolean;
877 /** Below the whole-name class; see `scoreThreadSearch`. */
878 readonly groupQuality: number;
879}
880
881export interface SearchMatchHint {
882 readonly label: string;
883 readonly text: string;
884 readonly ranges: ReadonlyArray<SearchRange>;
885}
886
887// Most threads' branches start with the app's own worktree prefix ("t3/", and
888// "t3code/" before it), so "t3 connect" would match nearly every thread.
889// Only before more text, so typing "t3/" does not empty the list for a keystroke.
890const WORKTREE_BRANCH_PREFIX_PATTERN = new RegExp(`^(?:${WORKTREE_BRANCH_PREFIX}|t3code)/(?=\\S)`);
891
892function searchableBranch(branch: string | null | undefined): string | null {
893 return branch ? branch.replace(WORKTREE_BRANCH_PREFIX_PATTERN, "") : null;
894}
895
896/**
897 * The field that explains a match whose title shows none: the first that holds
898 * the whole query, else, past the words the project or environment holds, the
899 * first that holds the rest ("lakebed perf" in project "lakebed" with the PR
900 * title "perf: …").
901 */
902function matchHint(
903 normalizedQuery: string,
904 thread: ThreadSearchSubject,
905 typos: boolean,
906): SearchMatchHint | undefined {
907 const candidates: Array<{ readonly label: string; readonly text: string | null | undefined }> = [
908 ...(thread.pullRequests ?? []).map((pullRequest) => ({
909 label: "PR",
910 text: `#${pullRequest.number}${pullRequest.title ? ` ${pullRequest.title}` : ""}`,
911 })),
912 { label: "Branch", text: searchableBranch(thread.branch) },
913 { label: "Project", text: thread.projectTitle },
914 { label: "Environment", text: thread.environmentLabel },
915 ];
916 const holds = (text: string, query: string) =>
917 matchSearchFields(query, [{ value: text, weight: 1 }], { typos })?.primaryRanges;
918 const hintFor = (query: string) => {
919 for (const { label, text } of candidates) {
920 const ranges = text ? holds(text, query) : undefined;
921 if (text && ranges) return { label, text, ranges };
922 }
923 return undefined;
924 };
925 const whole = hintFor(normalizedQuery);
926 if (whole) return whole;
927 const contexts = [thread.projectTitle, thread.environmentLabel].filter(
928 (text): text is string => !!text,
929 );
930 const rest = normalizedQuery
931 .split(" ")
932 .filter((token) => !contexts.some((text) => holds(text, token)))
933 .join(" ");
934 return rest && rest !== normalizedQuery ? hintFor(rest) : undefined;
935}
936
937/**
938 * Scores a thread for a normalized query, or null when it does not match.
939 * Titles and pull request numbers count fully, pull request titles and
940 * branches less, project and environment names least.
941 */
942export function scoreThreadSearch(
943 normalizedQuery: string,
944 thread: ThreadSearchSubject,
945 now: number,
946 options?: {
947 readonly typos?: boolean;
948 /**
949 * Palette picks; off where a pick would show up unexplained, such as a
950 * sidebar filter or an agent's search.
951 */
952 readonly picks?: boolean;
953 },
954): ThreadSearchMatch | null {
955 const fields: WeightedSearchField[] = [{ value: thread.title, weight: 1, midWord: true }];
956 for (const pullRequest of thread.pullRequests ?? []) {
957 fields.push({ value: `#${pullRequest.number}`, weight: 1 });
958 if (pullRequest.title) fields.push({ value: pullRequest.title, weight: 0.5 });
959 }
960 const branch = searchableBranch(thread.branch);
961 if (branch) fields.push({ value: branch, weight: 0.6 });
962 if (thread.projectTitle) {
963 fields.push({ value: thread.projectTitle, weight: 0.25, context: true });
964 }
965 if (thread.environmentLabel) {
966 fields.push({ value: thread.environmentLabel, weight: 0.25, context: true });
967 }
968 // Strip pull request prefixes and the worktree prefix so queries match the stored fields.
969 const fieldQuery = normalizedQuery
970 .replace(/^(?:pr|pull request|pull)\s*(?=#?\d)/, "")
971 .replace(/^#\s*/, "")
972 .replace(WORKTREE_BRANCH_PREFIX_PATTERN, "");
973 const fieldMatch = matchSearchFields(fieldQuery, fields, options);
974 const referenceMatch = fieldMatch ? null : matchReference(normalizedQuery, thread);
975 const match = fieldMatch ?? referenceMatch;
976 if (match === null) return null;
977 // A row whose title shows no match must say why. With several words, one
978 // that cannot (its words spread over unrelated fields) is a coincidence and
979 // is left out; a single word always sits in the field that matched it, so
980 // its hint waits until the row is shown.
981 const typos = options?.typos ?? false;
982 const titleShowsMatch = match.primaryRanges.length > 0;
983 const checkHint = !titleShowsMatch && referenceMatch === null && fieldQuery.includes(" ");
984 const checkedHint = checkHint ? matchHint(fieldQuery, thread, typos) : undefined;
985 if (checkHint && checkedHint === undefined) return null;
986 const explain = titleShowsMatch
987 ? undefined
988 : (): SearchMatchHint | undefined =>
989 referenceMatch
990 ? { label: "ID or link", text: normalizedQuery, ranges: [] }
991 : (checkedHint ?? matchHint(fieldQuery, thread, typos));
992 const pick = options?.picks === false ? undefined : activePick(thread, normalizedQuery, now);
993 return {
994 score: match.quality * threadUsageBoost(thread, now),
995 quality: match.quality,
996 // A thread's whole title never lifts its group over a command or project
997 // of that name: every new thread is titled "New thread" for a while.
998 groupQuality: Math.min(match.quality, WHOLE_NAME - 0.01),
999 strong: match.strong,
1000 ranges: match.primaryRanges,
1001 ...(explain ? { explain } : {}),
1002 ...(pick ? { pickedAt: pick.at } : {}),
1003 ...(pick?.query === pickedQuery(normalizedQuery) ? { pickedExactly: true } : {}),
1004 };
1005}
1006
1007/** When the user last used a thread: their last message or their last open. */
1008export function threadRecentUse(thread: ThreadSearchSubject): number {
1009 return Math.max(thread.activityAt ?? 0, thread.opens?.openedAt ?? 0);
1010}
1011
1012/**
1013 * How strongly a thread's messages match among matches of one quality: a
1014 * thread that keeps using the word outweighs a recent passing mention, as
1015 * hits count for more than recency or use (21 hits about 5.5, one hit 2).
1016 */
1017function messageMatchWeight(hits: number): number {
1018 return 1 + Math.log2(1 + hits);
1019}
1020
1021/** `withoutTitleMatches` reserves message rows for threads the palette has not already listed. */
1022export function rankMessageMatches<
1023 T extends {
1024 readonly quality?: number;
1025 readonly hits?: number;
1026 readonly messageCreatedAt?: string | null;
1027 },
1028>(
1029 matches: ReadonlyArray<T>,
1030 subjectOf: (match: T) => ThreadSearchSubject | undefined,
1031 normalizedQuery: string,
1032 now: number,
1033 options?: { readonly picks?: boolean; readonly withoutTitleMatches?: boolean },
1034): T[] {
1035 return matches
1036 .flatMap((match) => {
1037 const subject = subjectOf(match);
1038 if (!subject) return [];
1039 if (
1040 options?.withoutTitleMatches &&
1041 scoreThreadSearch(normalizedQuery, subject, now, { picks: false }) !== null
1042 ) {
1043 return [];
1044 }
1045 // Older servers send no quality; their matches count as words.
1046 const quality = match.quality ?? 1;
1047 return [
1048 {
1049 match,
1050 quality,
1051 pickedAt:
1052 options?.picks === false ? 0 : (activePick(subject, normalizedQuery, now)?.at ?? 0),
1053 score: messageMatchWeight(match.hits ?? 1) * threadUsageBoost(subject, now),
1054 },
1055 ];
1056 })
1057 .sort(
1058 (left, right) =>
1059 // Word matches first; among them a pick, then the closer match.
1060 Number(right.quality >= MESSAGE_PREFIX) - Number(left.quality >= MESSAGE_PREFIX) ||
1061 right.pickedAt - left.pickedAt ||
1062 right.quality - left.quality ||
1063 right.score - left.score ||
1064 (right.match.messageCreatedAt ?? "").localeCompare(left.match.messageCreatedAt ?? ""),
1065 )
1066 .map(({ match }) => match);
1067}
1068
1069/** Palette limits shared by web and mobile. */
1070export const PALETTE_THREAD_LIMIT = 20;
1071export const PALETTE_MESSAGE_LIMIT = 10;
1072/** Next to matching threads, other groups show only their best few rows. */
1073export const PALETTE_SECONDARY_LIMIT = 3;
1074
1075// Whole words and prefixes share a class so "Compact" does not lift settings over "Compaction".
1076function matchClass(quality: number): number {
1077 return quality >= WHOLE_NAME ? 3 : quality >= 0.7 ? 2 : quality >= 0.4 ? 1 : 0;
1078}
1079
1080export interface RankedSearchItem<T, M> {
1081 readonly item: T;
1082 readonly match: M;
1083}
1084
1085/**
1086 * Rank groups by match class to keep typing stable and thread use from outweighing equal commands.
1087 * Try typos only without word-start matches: they add noise beside real matches and cost per key.
1088 */
1089export function rankSearchGroups<
1090 G,
1091 T,
1092 M extends {
1093 readonly score: number;
1094 readonly quality: number;
1095 readonly strong: boolean;
1096 readonly pickedAt?: number;
1097 readonly pickedExactly?: boolean;
1098 readonly groupQuality?: number;
1099 },
1100>(
1101 groups: ReadonlyArray<{ readonly group: G; readonly items: ReadonlyArray<T> }>,
1102 score: (item: T, options: { readonly typos: boolean }, group: G) => M | null,
1103): Array<{ readonly group: G; readonly ranked: ReadonlyArray<RankedSearchItem<T, M>> }> {
1104 const rank = (typos: boolean) =>
1105 groups.map(({ group, items }) => ({
1106 group,
1107 ranked: items.flatMap((item) => {
1108 const match = score(item, { typos }, group);
1109 return match === null ? [] : [{ item, match }];
1110 }),
1111 }));
1112 let ranked = rank(false);
1113 if (!ranked.some((entry) => entry.ranked.some(({ match }) => match.strong))) {
1114 ranked = rank(true);
1115 }
1116 return ranked
1117 .flatMap(({ group, ranked: items }, order) => {
1118 if (items.length === 0) return [];
1119 // Use cannot lift a project-only match above a title match or cross match classes.
1120 // Picks reorder word matches, keeping typos and mid-word hits below them.
1121 // A longer-query pick must not pass a whole-name match for the current query.
1122 const wordMatch = (match: M) => Math.min(matchClass(match.quality), 2);
1123 const exactPickAt = (match: M) => (match.pickedExactly ? (match.pickedAt ?? 0) : 0);
1124 const sorted = [...items].sort(
1125 (left, right) =>
1126 wordMatch(right.match) - wordMatch(left.match) ||
1127 exactPickAt(right.match) - exactPickAt(left.match) ||
1128 matchClass(right.match.quality) - matchClass(left.match.quality) ||
1129 (right.match.pickedAt ?? 0) - (left.match.pickedAt ?? 0) ||
1130 right.match.score - left.match.score,
1131 );
1132 const best = Math.max(
1133 ...items.map(({ match }) => matchClass(match.groupQuality ?? match.quality)),
1134 );
1135 return [{ group, ranked: sorted, best, order }];
1136 })
1137 .sort((left, right) => right.best - left.best || left.order - right.order)
1138 .map(({ group, ranked: items }) => ({ group, ranked: items }));
1139}
1140
1141/** `rankSearchGroups` for a single list. */
1142export function rankSearchItems<
1143 T,
1144 M extends { readonly score: number; readonly quality: number; readonly strong: boolean },
1145>(
1146 items: ReadonlyArray<T>,
1147 score: (item: T, options: { readonly typos: boolean }) => M | null,
1148): ReadonlyArray<RankedSearchItem<T, M>> {
1149 return rankSearchGroups([{ group: null, items }], score)[0]?.ranked ?? [];
1150}
1151
1152export interface SearchTermsMatch {
1153 readonly score: number;
1154 readonly quality: number;
1155 /** The quality its group ranks by, when lower; see `scoreSearchTerms`. */
1156 readonly groupQuality?: number;
1157 readonly strong: boolean;
1158 readonly ranges: ReadonlyArray<SearchRange>;
1159}
1160
1161const KEYWORD_QUALITY = 0.65;
1162// Below this, keyword prefixes match too much: "co" or "pro" would list most
1163// settings. A short query still matches a keyword it equals ("pr").
1164const KEYWORD_QUERY_MIN_LENGTH = 4;
1165
1166/**
1167 * Keywords count less so hidden terms cannot lift a group above a matching name.
1168 * Short queries need whole keywords to avoid listing most settings for common prefixes.
1169 */
1170export function scoreSearchTerms(
1171 normalizedQuery: string,
1172 terms: ReadonlyArray<string>,
1173 options?: { readonly typos?: boolean },
1174): SearchTermsMatch | null {
1175 // Filler words ("the ci") do not make a short query long.
1176 const meaningful = normalizedQuery
1177 .split(" ")
1178 .filter((token) => !FILLER_WORDS.has(token))
1179 .join(" ");
1180 const short = (meaningful || normalizedQuery).length < KEYWORD_QUERY_MIN_LENGTH;
1181 const match = matchSearchFields(
1182 normalizedQuery,
1183 terms.map((value, index) =>
1184 index === 0
1185 ? { value, weight: 1 }
1186 : // An alias typed in full ("pr") is deliberate, above a mere name prefix.
1187 { value, weight: short ? 0.8 : 0.6, wholeWords: short, keyword: true },
1188 ),
1189 options,
1190 );
1191 return (
1192 match && {
1193 score: match.quality,
1194 quality: match.quality,
1195 // Below the word-start class: a match only in hidden keywords must not put
1196 // its group above a result whose name matches. Inside the group an exact
1197 // alias still beats a name prefix ("pr" lists "Open pull requests" first).
1198 ...(match.primaryRanges.length > 0
1199 ? {}
1200 : { groupQuality: Math.min(match.quality, KEYWORD_QUALITY) }),
1201 strong: match.strong,
1202 ranges: match.primaryRanges,
1203 }
1204 );
1205}