mirror of
https://github.com/bitbaum/substrata.git
synced 2026-12-04 22:19:07 +01:00
* fix(search): a material's own page outranks the events about it Adding a real, sourced event (MOFCOM Announcement No. 46 of 2024: China in principle denies export licences for gallium, germanium, antimony and superhard-material items to the US) pushed the Gallium bottleneck to #4 for "gallium china". An event headline is a sentence holding every query word, and search scored it as a NAME, so every event filed about a material could push that material's page down. lib/rank-priority.ts, shared by the ⌘K search and the Ask's retrieval: - KIND_WEIGHT: bottleneck 1.15 > country 1.1 > company 1.05 > science and policy 1 > event 0.8 > note/article/learn 0.75 (stubs keep 0.6 on top); - a headline is not a name: event and note title words count half a name word in search and earn no "every word is in the name" bonus; - a named-term bonus: a run of the query that IS a record's name, the head of its name ("Gallium, refined" → "gallium") or an alias adds up to 20 points in search and up to +50% to an entity chunk in retrieval, scaled by the share of the query it covers. Tests: the real event row with "gallium china" (bottleneck #2, behind China); 1/10/50/200 adversarial synthetic events never move it out of the top 3; in retrieval the Gallium page outranks 50 synthetic events; "MOFCOM announcement 46" still finds the event first; across the corpus no event outranks the bottleneck it names for "<material> <country>". No existing expectation was edited. The event row is added as a candidate through scripts/research/add.ts, its quote read verbatim from the MOFCOM notice. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_018WZnBnaLP6RhwFkLxRTKgE * fix(data): keep the events sidecar sorted by key after the merge Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_018WZnBnaLP6RhwFkLxRTKgE * fix(search): a country named in several words is one unit of the query "gallium United States of America" was four words, three of them the country's, so any page that said "United States" out-pointed the page named "Gallium" by word count, and an event ranked above the bottleneck it names (#5 vs #8). A run of the query that is a country's name or other spelling (`queryUnits`, keys from the country documents, stop words out) now scores as ONE unit: the mean of its words, counted once for partial coverage (half a name is half a match) and for the named-term share. Gallium, refined is now #3 behind the USA page and GaN; no event is above it. "gallium china" is unchanged (China, Gallium). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_018WZnBnaLP6RhwFkLxRTKgE --------- Co-authored-by: Claude <noreply@anthropic.com>
177 lines
6.3 KiB
TypeScript
177 lines
6.3 KiB
TypeScript
/**
|
|
* Site search: one index over everything a reader can land on, ranked for a
|
|
* person typing into a box rather than for a model assembling context.
|
|
*
|
|
* `lib/research-index.ts` is the retrieval projection the assistant uses, and
|
|
* its scoring is tuned for that (OR over a question's meaningful words). This
|
|
* module reads the same entity registry — so search can never know about a
|
|
* thing the profile pages do not — and adds the two kinds of record that are
|
|
* not entities but that a reader searches for all the same: accepted events
|
|
* and glossary terms.
|
|
*
|
|
* Ranking, in order of weight:
|
|
* 1. the name (an exact name match beats everything),
|
|
* 2. other spellings (`aka`),
|
|
* 3. the body (summary, long text, topic tags), with term frequency.
|
|
* Each query word may match exactly, as a prefix (so results appear while the
|
|
* reader is still typing) or — only when it is not itself a word of the
|
|
* corpus — within the typo budget, which is what turns "photresist" into
|
|
* "photoresist" instead of into nothing. The matching, folding, marking and
|
|
* snippet cutting are `@bitbaum/searchkit`'s; the ranking is this module's,
|
|
* because this corpus is long documents of several kinds, where how often a
|
|
* rare word recurs says what a page is about (`search/score.ts`).
|
|
*
|
|
* The index is derived from static config and built once per process.
|
|
*/
|
|
import { defaultIndex, buildIndex, type Indexed } from './search/build';
|
|
import type { SearchDoc } from './search/corpus';
|
|
import { PREFIX, expand } from './search/expand';
|
|
import { idf, scoreDoc, type Match } from './search/score';
|
|
import { marks, snippet } from './search/snippets';
|
|
import { STOP, words } from './search/text';
|
|
import { queryUnits } from './rank-priority';
|
|
import {
|
|
SEARCH_TYPES,
|
|
type SearchGroup,
|
|
type SearchHit,
|
|
type SearchResult,
|
|
type SearchType,
|
|
type Segment,
|
|
segments,
|
|
} from './search-types';
|
|
|
|
export * from './search-types';
|
|
export { searchDocuments, type SearchDoc } from './search/corpus';
|
|
|
|
export interface SearchOptions {
|
|
type?: SearchType | null;
|
|
/** Cap on `hits`. */
|
|
limit?: number;
|
|
/** Cap on hits inside each group. */
|
|
perGroup?: number;
|
|
/** Search a given corpus instead of the site's, for tests. */
|
|
documents?: SearchDoc[];
|
|
}
|
|
|
|
export function search(rawQuery: string, options: SearchOptions = {}): SearchResult {
|
|
const query = rawQuery.trim().slice(0, 200);
|
|
const empty: SearchResult = {
|
|
query,
|
|
corrected: null,
|
|
partial: false,
|
|
total: 0,
|
|
counts: {},
|
|
hits: [],
|
|
groups: [],
|
|
};
|
|
const index = options.documents ? buildIndex(options.documents) : defaultIndex();
|
|
let tokens = words(query);
|
|
if (tokens.length > 1) {
|
|
const content = tokens.filter((t) => !STOP.has(t));
|
|
if (content.length) tokens = content;
|
|
}
|
|
tokens = [...new Set(tokens)];
|
|
if (!tokens.length) return empty;
|
|
|
|
// The last word keeps its prefix power only when the query does not end in
|
|
// a space, which is how a reader says "that word is finished".
|
|
const typing = !/\s$/.test(rawQuery);
|
|
const expansions = tokens.map((t, i) => {
|
|
const found = expand(index, t, typing && i === tokens.length - 1);
|
|
// A half-typed word is weighted as its COMMONEST completion, not each
|
|
// completion by its own rarity: otherwise "gallium ch" ranks the rare
|
|
// "Chalco" above the obvious "China" just because fewer documents say it.
|
|
const prefixIdf = Math.min(
|
|
...found.filter((e) => e.quality === PREFIX).map((e) => idf(index, e.word)),
|
|
);
|
|
return found.map((e) => ({
|
|
...e,
|
|
weight: e.quality * (e.quality === PREFIX ? prefixIdf : idf(index, e.word)),
|
|
}));
|
|
});
|
|
const corrections = new Map<string, string>();
|
|
tokens.forEach((t, i) => {
|
|
const e = expansions[i];
|
|
if (e.length && e.every((x) => x.quality < 0.7)) {
|
|
const best = e.reduce((a, b) =>
|
|
b.quality > a.quality ||
|
|
(b.quality === a.quality && (index.df.get(b.word) ?? 0) > (index.df.get(a.word) ?? 0))
|
|
? b
|
|
: a,
|
|
);
|
|
corrections.set(t, best.word);
|
|
}
|
|
});
|
|
const phrase = tokens.map((t) => corrections.get(t) ?? t).join(' ');
|
|
// "united state america" is one country, not three words that outvote "gallium".
|
|
const units = queryUnits(phrase.split(' '), index.unitKeys);
|
|
|
|
const run = (requireAll: boolean) =>
|
|
index.docs
|
|
.map((d) => ({ d, m: scoreDoc(index, d, expansions, phrase, requireAll, units) }))
|
|
.filter((x): x is { d: Indexed; m: Match } => x.m !== null)
|
|
.sort(
|
|
(a, b) =>
|
|
b.m.score - a.m.score ||
|
|
SEARCH_TYPES.indexOf(a.d.doc.type) - SEARCH_TYPES.indexOf(b.d.doc.type) ||
|
|
a.d.doc.title.localeCompare(b.d.doc.title),
|
|
);
|
|
|
|
let ranked = run(true);
|
|
let partial = false;
|
|
if (!ranked.length && expansions.filter((e) => e.length).length > 0 && tokens.length > 1) {
|
|
ranked = run(false);
|
|
partial = ranked.length > 0;
|
|
}
|
|
if (!ranked.length) return { ...empty, corrected: corrections.size ? phrase : null };
|
|
|
|
const toHit = ({ d, m }: { d: Indexed; m: Match }): SearchHit => {
|
|
const matched = new Set(m.words);
|
|
const title = segments(d.doc.title, marks(d.doc.title, matched));
|
|
return {
|
|
id: d.doc.id,
|
|
type: d.doc.type,
|
|
title,
|
|
snippet: snippet(
|
|
d.doc,
|
|
matched,
|
|
title.some((s) => s.hit),
|
|
),
|
|
href: d.doc.href,
|
|
meta: d.doc.meta,
|
|
score: Math.round(m.score * 100) / 100,
|
|
};
|
|
};
|
|
|
|
const counts: Partial<Record<SearchType, number>> = {};
|
|
const byType = new Map<SearchType, typeof ranked>();
|
|
for (const r of ranked) {
|
|
counts[r.d.doc.type] = (counts[r.d.doc.type] ?? 0) + 1;
|
|
const list = byType.get(r.d.doc.type);
|
|
if (list) list.push(r);
|
|
else byType.set(r.d.doc.type, [r]);
|
|
}
|
|
const perGroup = options.perGroup ?? 5;
|
|
const groups: SearchGroup[] = [...byType.entries()].map(([type, rows]) => ({
|
|
type,
|
|
count: rows.length,
|
|
hits: rows.slice(0, perGroup).map(toHit),
|
|
}));
|
|
|
|
const narrowed = options.type ? (byType.get(options.type) ?? []) : ranked;
|
|
return {
|
|
query,
|
|
corrected: corrections.size ? phrase : null,
|
|
partial,
|
|
total: ranked.length,
|
|
counts,
|
|
hits: narrowed.slice(0, options.limit ?? 50).map(toHit),
|
|
groups,
|
|
};
|
|
}
|
|
|
|
/** Plain text of a segment list, for tests and for aria labels. */
|
|
export function plain(parts: Segment[]): string {
|
|
return parts.map((s) => s.text).join('');
|
|
}
|