fix(search): a material's own page outranks the events about it (#242)

* 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>
This commit is contained in:
CatoandClaude Opus 5.5 authored and GitHub committed 2026-10-24 19:08:06 +02:00
1 parent 8e85c7e7b4
commit 71978bd80c
7 files changed
+411 -32

No files matched your search

+23
View File
@@ -22,6 +22,29 @@
"jurisdictions": ["RU"],
"primary": false
},
{
"evidence": "candidate",
"asOf": "2024-12-03",
"source": {
"url": "https://www.mofcom.gov.cn/zcfb/zc/art/2024/art_a362d9e4d4944ff3854b76c572899e7e.html",
"quote": "原则上不予许可镓、锗、锑、超硬材料相关两用物项对美国出口;对石墨两用物项对美国出口,实施更严格的最终用户和最终用途审查。",
"readOn": "2026-10-24"
},
"submittedBy": {
"agent": "data-agent",
"model": "unrecorded",
"runId": "search-rank-2026-10-24"
},
"id": "2024-12-03-mofcom-announcement-46-gallium-germanium-us",
"date": "2024-12-03",
"headline": "MOFCOM Announcement No. 46 of 2024: China in principle denies export licences for gallium and germanium items to the US",
"kind": "policy",
"effect": "tightens",
"bottlenecks": ["Gallium, refined"],
"participants": [],
"jurisdictions": ["CN", "US"],
"primary": true
},
{
"evidence": "candidate",
"asOf": "2025-01-17",
+32 -3
View File
@@ -9,9 +9,14 @@
* the best hit, so the in-process ranking is the database ranking minus
* vectors and tests on a laptop with no DATABASE_URL rank the way the site does.
*
* The word score is then weighted by kind and lifted when a run of the
* question IS an entity's name, by the same rules as the ⌘K search
* (`lib/rank-priority.ts`): a material's own page outranks the events about it.
*
* `rank` is the generic part (chunks in, hits out) and reads no config; only
* `retrieve` binds it to this corpus's chunks.
*/
import { NAMED_TERM_LIFT, kindWeight, nameKeys, namedShare } from '../rank-priority';
import { foldedWords, scoreDocuments, type ResearchDocument } from '../research-index';
import { recency, type Chunk, type Facet } from './chunk';
import { buildChunks } from './build';
@@ -87,6 +92,23 @@ export function queryWords(question: string): string[] {
return [...new Set(words)].filter((w) => w.length > 1 && !STOP.has(w));
}
/** A text's words as `scoreDocuments` reads them, in order, for name runs. */
function orderedWords(text: string): string[] {
return queryWords(text).flatMap((w) => [...foldedWords(w)]);
}
/**
* The word score, weighted by the chunk's kind (an event chunk has none and
* is weighted as `event`), and lifted when it is an entity's own chunk and a
* run of the question is that entity's name. Only `entity` chunks carry a
* name: a derived chunk's title ("Gallium, refined in China") is a label.
*/
export function prioritised(chunk: Chunk, raw: number, question: readonly string[]): number {
const named =
chunk.facet === 'entity' ? namedShare(nameKeys(chunk.title, [], orderedWords), question) : 0;
return raw * kindWeight(chunk.kind ?? chunk.facet) * (1 + NAMED_TERM_LIFT * named);
}
const documentsOf = new WeakMap<readonly Chunk[], ResearchDocument[]>();
function asDocuments(chunks: readonly Chunk[]): ResearchDocument[] {
@@ -120,11 +142,18 @@ export function rank(
const byId = new Map(chunks.map((c) => [c.id, c]));
const words = queryWords(question);
const wanted = [...foldedWords(words.join(' '))];
const scored = scoreDocuments(asDocuments(chunks), words).filter((s) => s.score >= MIN_LEXICAL);
const ordered = orderedWords(question);
const scored = scoreDocuments(asDocuments(chunks), words)
.filter((s) => s.score >= MIN_LEXICAL)
.map((s) => ({
...s,
raw: s.score,
score: prioritised(byId.get(s.document.id)!, s.score, ordered),
}));
const best = Math.max(0, ...scored.map((s) => s.score));
const lexicalWeight = WEIGHTS.lexical + WEIGHTS.cosine;
const hits: Hit[] = [];
for (const { document, score } of scored) {
for (const { document, score, raw } of scored) {
const chunk = byId.get(document.id)!;
if (opts.facets && !opts.facets.includes(chunk.facet)) continue;
const lexical = best > 0 ? score / best : 0;
@@ -132,7 +161,7 @@ export function rank(
hits.push({
chunk,
lexical,
raw: score,
raw,
matched: 0,
score:
lexicalWeight * lexical +
+150
View File
@@ -0,0 +1,150 @@
/**
* What a page IS outranks what merely MENTIONS it. Shared by the ⌘K search
* (`lib/search/score.ts`) and the Ask's retrieval (`lib/index/retrieve.ts`),
* so the two cannot disagree about which kind of record answers a name.
*
* Why this exists: word-match scores grow with every record that repeats a
* material's name. A news event's headline is a sentence, and a sentence
* about gallium in China holds BOTH words of "gallium china" — the bottleneck
* page, named "Gallium, refined", holds one of them in its name. Every event
* filed about a material therefore stood a chance of pushing that material's
* own page down, and adding sourced data made search worse. Three bounded,
* named adjustments fix it at the root:
*
* 1. a kind weight: for an equal word match, the record a reader means by a
* name comes first — bottleneck > country > company > science/policy >
* event > note/article — and a stub company keeps its own 0.6 on top;
* 2. a headline is not a name: an event's title words count half a name's,
* in the search, where a title word is otherwise worth a name's;
* 3. a named-term bonus: when a query word (or a run of them) IS a record's
* name, the head of its name or one of its other spellings, that record
* is the thing itself, not a document about it.
*
* Both are bounded: the weight is a fixed factor per kind, the bonus is at
* most one full step and scales with the share of the query the name covers.
*/
/**
* The factor a kind's word-match score is multiplied by. Reasons per row; the
* order is the point, the gaps are kept small so a much better word match
* (an event's own distinctive words, "MOFCOM announcement 46") still wins.
*/
export const KIND_WEIGHT: Readonly<Record<string, number>> = {
// The site's subject: a named constraint is what a material query means.
bottleneck: 1.15,
// Where it is made or controlled: the other half of "gallium china".
country: 1.1,
// Who makes it. A stub company is further multiplied by STUB_WEIGHT (0.6).
company: 1.05,
// Records that explain or govern a bottleneck: profiled, but secondary to it.
science: 1,
policy: 1,
// Definitions and smaller registers: read through, rarely the destination.
glossary: 0.9,
capital: 0.9,
facility: 0.9,
loop: 0.9,
talent: 0.9,
lab: 0.9,
// One dated fact ABOUT a bottleneck or country, under the page it is about.
event: 0.8,
// Long prose that mentions many things: found by its words, never by a name.
note: 0.75,
article: 0.75,
learn: 0.75,
};
/** The weight of a kind with no row: a profiled record, neither raised nor lowered. */
export function kindWeight(kind: string | undefined): number {
return (kind ? KIND_WEIGHT[kind] : undefined) ?? 1;
}
/**
* Kinds whose title is a HEADLINE (a sentence about things), not a name. A
* word in a headline says the record is about that thing; a word in a name
* says the record IS it. Search counts a headline word at `HEADLINE_SHARE` of
* a name word and never gives a headline the "every word is in the name"
* bonuses: otherwise one event whose sentence holds every query word
* out-points the page named by one of them, and more events mean more of it.
*/
export const HEADLINE_KINDS: ReadonlySet<string> = new Set(['event', 'note', 'article', 'learn']);
/** A headline word's worth, as a share of a name word's: between a body word and another spelling. */
export const HEADLINE_SHARE = 0.5;
/**
* The search's bonus, in its score units, when the WHOLE query is a record's
* name: one name-field step (NAME = 10) for every word, twice — the size of
* the gap between a word in a name and a word in a headline, so a page named
* by the query is not out-pointed by a sentence that happens to hold more of
* the query's words. Scaled by the share of the query the name covers.
*/
export const NAMED_TERM_BONUS = 20;
/**
* The retrieval's equivalent, as a multiplier on the chunk's raw word score:
* up to +50% when the whole question is the record's name. Retrieval scores
* are normalised to the best hit, so a factor, not points.
*/
export const NAMED_TERM_LIFT = 0.5;
/**
* The ways a record is named, as word runs: its full name, the head of its
* name (the part before a comma, a bracket or a dash — "Gallium, refined" is
* named "gallium", "Liquid helium (He-4)" is named "liquid helium"), and each
* other spelling. `tokenize` is the caller's own, so a key matches exactly
* what that caller's index would.
*/
export function nameKeys(
name: string,
aka: readonly string[],
tokenize: (text: string) => string[],
): string[] {
const head = name.split(/\s*[,(]|\s+[—–-]\s+/)[0] ?? name;
const keys = [name, head, ...aka].map((t) => tokenize(t).join(' ')).filter(Boolean);
return [...new Set(keys)];
}
/**
* The query's word positions, grouped into the units a reader means: a run
* that is exactly one of `unitKeys` (a country's name or other spelling,
* "united state america") is ONE unit, every other word its own. Longest run
* first. Without it "gallium United States of America" is four words, three
* of them a country's, and any page that says "United States" out-points the
* page named "Gallium" by sheer word count.
*/
export function queryUnits(query: readonly string[], unitKeys: ReadonlySet<string>): number[][] {
const units: number[][] = [];
for (let i = 0; i < query.length;) {
let end = i + 1;
for (let j = query.length; j > i + 1; j--)
if (unitKeys.has(query.slice(i, j).join(' '))) {
end = j;
break;
}
units.push(Array.from({ length: end - i }, (_, k) => i + k));
i = end;
}
return units;
}
/**
* The share of the query, 0..1, covered by runs that are exactly one of
* `keys`, counted in `units` (each word its own unit when none are given).
* "gallium china" against the Gallium bottleneck is 0.5 (the run "gallium"
* is its head); against China, 0.5; against an event whose headline holds
* both words, 0: no run of the query is its name.
*/
export function namedShare(
keys: readonly string[],
query: readonly string[],
units: readonly (readonly number[])[] = query.map((_, i) => [i]),
): number {
if (!query.length || !keys.length) return 0;
const set = new Set(keys);
const covered = new Array<boolean>(query.length).fill(false);
for (let i = 0; i < query.length; i++)
for (let j = i + 1; j <= query.length; j++)
if (set.has(query.slice(i, j).join(' '))) covered.fill(true, i, j);
return units.filter((u) => u.every((i) => covered[i])).length / units.length;
}
+4 -1
View File
@@ -29,6 +29,7 @@ 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,
@@ -102,10 +103,12 @@ export function search(rawQuery: string, options: SearchOptions = {}): SearchRes
}
});
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) }))
.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) =>
+24 -2
View File
@@ -4,8 +4,9 @@
* from static config and built once per process.
*/
import { createVocabulary, type Vocabulary } from '@bitbaum/searchkit';
import { nameKeys } from '../rank-priority';
import { searchDocuments, type SearchDoc } from './corpus';
import { words } from './text';
import { STOP, words } from './text';
export interface Indexed {
doc: SearchDoc;
@@ -16,6 +17,8 @@ export interface Indexed {
body: Map<string, number>;
normTitle: string;
normAka: string[];
/** Name, head of the name and other spellings, as word runs (`lib/rank-priority.ts`). */
keys: string[];
}
export interface SearchIndex {
@@ -32,6 +35,11 @@ export interface SearchIndex {
rankDocs: number;
/** Every word, counted by documents, so the commoner completion comes first. */
vocab: Vocabulary;
/**
* Country names and other spellings as the query reads them (stop words
* out): a run of the query equal to one is a single unit (`queryUnits`).
*/
unitKeys: Set<string>;
}
function normPhrase(text: string): string {
@@ -62,9 +70,23 @@ export function buildIndex(documents: SearchDoc[]): SearchIndex {
body,
normTitle: nameWords.join(' '),
normAka: doc.aka.map(normPhrase),
keys: nameKeys(doc.title, doc.aka, words),
};
});
return { docs, df, rankDf, rankDocs, vocab: createVocabulary(df) };
const unitKeys = new Set(
docs
.filter((d) => d.doc.type === 'country')
.flatMap((d) =>
d.keys.map((k) =>
k
.split(' ')
.filter((w) => !STOP.has(w))
.join(' '),
),
)
.filter((k) => k.includes(' ')),
);
return { docs, df, rankDf, rankDocs, vocab: createVocabulary(df), unitKeys };
}
let cached: SearchIndex | null = null;
+36 -26
View File
@@ -1,8 +1,15 @@
/**
* Scoring: name beats other spellings beats body, with term frequency, idf,
* phrase-level bonuses and a per-type weight.
* phrase-level bonuses, a bonus when a run of the query IS the name, and a
* per-kind weight — the last two shared with retrieval (`lib/rank-priority.ts`).
*/
import type { SearchType } from '../search-types';
import {
HEADLINE_KINDS,
HEADLINE_SHARE,
NAMED_TERM_BONUS,
kindWeight,
namedShare,
} from '../rank-priority';
import type { Indexed, SearchIndex } from './build';
import type { Expansion } from './expand';
@@ -10,18 +17,6 @@ const NAME = 10;
const AKA = 7;
const BODY = 1.5;
/** How much a type's match is worth, relative to an entity. */
const TYPE_WEIGHT: Partial<Record<SearchType, number>> = {
bottleneck: 1.1,
glossary: 0.9,
note: 0.9,
capital: 0.9,
facility: 0.9,
loop: 0.9,
talent: 0.9,
event: 0.8,
};
export function idf(index: SearchIndex, word: string): number {
return Math.log(1 + index.rankDocs / (index.rankDf.get(word) ?? 1));
}
@@ -38,9 +33,11 @@ function scoreToken(index: SearchIndex, d: Indexed, expansions: Expansion[]) {
let best = 0;
let inName = false;
const matched: string[] = [];
// A headline word is never "in the name": it earns no name bonuses below.
const headline = HEADLINE_KINDS.has(d.doc.type);
for (const { word, weight = 0 } of expansions) {
let field = 0;
if (d.name.has(word)) field = NAME;
if (d.name.has(word)) field = headline ? NAME * HEADLINE_SHARE : NAME;
else if (d.aka.has(word)) field = AKA;
const tf = d.body.get(word) ?? 0;
const body = tf ? BODY * (1 + Math.log(tf)) : 0;
@@ -60,21 +57,32 @@ export function scoreDoc(
tokens: Expansion[][],
phrase: string,
requireAll: boolean,
/** Token positions grouped as the reader means them (`queryUnits`): a country's name is one. */
units: readonly (readonly number[])[] = tokens.map((_, i) => [i]),
): Match | null {
let score = 0;
let inName = 0;
let hitCount = 0;
const matched: string[] = [];
for (const expansions of tokens) {
const t = scoreToken(index, d, expansions);
if (t.score === 0) {
if (requireAll) return null;
continue;
for (const unit of units) {
// A unit weighs as one word: the mean of its words, so a long name cannot outvote a short one.
let unitScore = 0;
let unitHits = 0;
for (const i of unit) {
const t = scoreToken(index, d, tokens[i]);
if (t.score === 0) {
if (requireAll) return null;
continue;
}
unitScore += t.score;
unitHits++;
if (t.inName) inName++;
matched.push(...t.matched);
}
hitCount++;
score += t.score;
if (t.inName) inName++;
matched.push(...t.matched);
if (unitScore === 0) continue;
// Half a country's name is half a match of it.
hitCount += unitHits / unit.length;
score += unitScore / unit.length;
}
if (!hitCount) return null;
// Phrase-level signals: the whole query IS the name, starts it, or sits in it.
@@ -87,8 +95,10 @@ export function scoreDoc(
// Every word in the name, and a name that is mostly those words, reads as "this is it".
if (inName === tokens.length) score += 8;
score += (inName / d.nameLength) * 3;
// A run of the query that IS this record's name: the thing, not a page about it.
if (phrase) score += NAMED_TERM_BONUS * namedShare(d.keys, phrase.split(' '), units);
// A partial match is ranked by how much of the query it covers first.
if (!requireAll) score *= hitCount / tokens.length;
score *= (TYPE_WEIGHT[d.doc.type] ?? 1) * (d.doc.weight ?? 1);
if (!requireAll) score *= hitCount / units.length;
score *= kindWeight(d.doc.type) * (d.doc.weight ?? 1);
return { score, words: matched, inName };
}
+142
View File
@@ -0,0 +1,142 @@
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { EVENTS } from '../config/substrata-events';
import { buildChunks } from '../lib/index/build';
import { makeChunk, type Chunk } from '../lib/index/chunk';
import { countryName } from '../lib/index/chunks/ids';
import { rank } from '../lib/index/retrieve';
import { KIND_WEIGHT, nameKeys, namedShare, queryUnits } from '../lib/rank-priority';
import { plain, search, searchDocuments, type SearchDoc } from '../lib/search';
import { words } from '../lib/search/text';
/**
* A material's own page must not be pushed down by the events filed about it
* (lib/rank-priority.ts). The regression: MOFCOM Announcement 46 of 2024, a
* real sourced event, put "Gallium, refined" fourth for "gallium china".
*/
const GALLIUM = 'Gallium, refined';
const MOFCOM_46 = '2024-12-03-mofcom-announcement-46-gallium-germanium-us';
const at = (q: string, title: string, type: string, docs?: SearchDoc[]) =>
search(q, docs ? { documents: docs, limit: 200 } : { limit: 200 }).hits.findIndex(
(h) => h.type === type && plain(h.title) === title,
);
test('the MOFCOM Announcement 46 event is in the corpus', () => {
assert.ok(EVENTS.some((e) => e.id === MOFCOM_46));
});
test('with the gallium event present, "gallium china" has the Gallium bottleneck first or second', () => {
const i = at('gallium china', GALLIUM, 'bottleneck');
assert.ok(i >= 0 && i < 2, `Gallium, refined is #${i + 1}`);
const firstEvent = search('gallium china').hits.findIndex((h) => h.type === 'event');
assert.ok(firstEvent > i, 'an event outranks the bottleneck it is about');
});
/** N events about gallium in China, each worded to hold every query word, in title and body. */
function syntheticEvents(n: number): SearchDoc[] {
return Array.from({ length: n }, (_, k) => ({
id: `event:synthetic-${k}`,
type: 'event' as const,
title: `China tightens gallium exports again, round ${k}: gallium licences in China cut`,
aka: [],
summary: `Chinese gallium producers in China report gallium shipments ${k} down.`,
body: `${GALLIUM} China CN Policy Tightens`,
href: `/events#synthetic-${k}`,
meta: '2026-01-01 · Tightens',
}));
}
for (const n of [1, 10, 50, 200]) {
test(`${n} synthetic gallium events never push the Gallium bottleneck out of the top 3`, () => {
const docs = [...searchDocuments(), ...syntheticEvents(n)];
const i = at('gallium china', GALLIUM, 'bottleneck', docs);
assert.ok(i >= 0 && i < 3, `Gallium, refined is #${i + 1} with ${n} events`);
});
}
test('the Ask retrieval: the Gallium page outranks every gallium event, even with 50 more', () => {
const extra: Chunk[] = Array.from({ length: 50 }, (_, k) =>
makeChunk({
id: `event:synthetic-${k}`,
facet: 'event',
entityIds: ['bottleneck:gallium-refined', 'country:cn'],
title: `China tightens gallium exports again, round ${k}`,
text: `China tightens gallium exports again — tightens ${GALLIUM} (policy). Jurisdictions: China.`,
href: '/events',
evidence: 'sourced',
asOf: '2026-10-01',
significance: 0.7,
}),
);
const hits = rank([...buildChunks(), ...extra], 'gallium china', { k: 80 });
const page = hits.findIndex((h) => h.chunk.facet === 'entity' && h.chunk.title === GALLIUM);
const event = hits.findIndex((h) => h.chunk.facet === 'event');
assert.ok(page >= 0 && page < 5, `the Gallium page is #${page + 1}`);
assert.ok(event > page, `an event (#${event + 1}) outranks the Gallium page (#${page + 1})`);
});
test('the event’s own words still find the event first', () => {
for (const q of ['MOFCOM announcement 46', 'mofcom 46 gallium']) {
const first = search(q).hits[0];
assert.equal(first?.id, `event:${MOFCOM_46}`, `${q} → ${first && plain(first.title)}`);
}
const hit = rank(buildChunks(), 'MOFCOM announcement 46', { k: 1 })[0];
assert.equal(hit?.chunk.id.startsWith('event:'), true, hit?.chunk.id);
});
test('across the corpus, no event outranks the bottleneck it names for "<material> <country>"', () => {
const seen = new Set<string>();
for (const e of EVENTS)
for (const b of e.bottlenecks)
for (const j of e.jurisdictions) {
const q = `${nameKeys(b, [], words)[1] ?? b} ${countryName(j)}`;
if (seen.has(q)) continue;
seen.add(q);
const hits = search(q, { limit: 200 }).hits;
const page = hits.findIndex((h) => h.type === 'bottleneck' && plain(h.title) === b);
if (page < 0) continue;
const event = hits.findIndex((h) => h.type === 'event');
assert.ok(
event < 0 || event > page,
`"${q}": an event is #${event + 1}, ${b} #${page + 1}`,
);
}
});
test('a name key is the name, the head of the name, or another spelling', () => {
assert.deepEqual(nameKeys('Gallium, refined', [], words), ['gallium refined', 'gallium']);
assert.deepEqual(nameKeys('Liquid helium (He-4)', ['LHe'], words), [
'liquid helium he 4',
'liquid helium',
'lhe',
]);
assert.deepEqual(nameKeys('Shin-Etsu Quartz', [], words), ['shin etsu quartz']);
});
test('the named share counts the query words a name run covers, and nothing a sentence holds', () => {
assert.equal(namedShare(['gallium refined', 'gallium'], ['gallium', 'china']), 0.5);
assert.equal(namedShare(['china', 'cn'], ['gallium', 'china']), 0.5);
assert.equal(namedShare(['liquid helium'], ['liquid', 'helium', 'qatar']), 2 / 3);
assert.equal(namedShare(['china tightens gallium exports'], ['gallium', 'china']), 0);
});
test('kind priority: bottleneck > country > company > science > event > note', () => {
const order = ['bottleneck', 'country', 'company', 'science', 'event', 'note'];
for (let i = 1; i < order.length; i++)
assert.ok(KIND_WEIGHT[order[i - 1]] > KIND_WEIGHT[order[i]], `${order[i - 1]} > ${order[i]}`);
});
test('a country named in several words is one unit of the query, and counts as one', () => {
const q = ['gallium', 'united', 'state', 'america'];
const units = queryUnits(q, new Set(['united state america', 'united state']));
assert.deepEqual(units, [[0], [1, 2, 3]]);
assert.equal(namedShare(['gallium refined', 'gallium'], q, units), 0.5);
const i = at('gallium United States of America', GALLIUM, 'bottleneck');
const firstEvent = search('gallium United States of America').hits.findIndex(
(h) => h.type === 'event',
);
assert.ok(i >= 0 && i < 3, `Gallium, refined is #${i + 1}`);
assert.ok(firstEvent < 0 || firstEvent > i, `an event is #${firstEvent + 1}`);
});