/** * The memory full-text search, approximated honestly. The Rust server asks * SQLite FTS5 (`fts_memories`, tokenize `unicode61 remove_diacritics 2`, * `title MATCH ?`, ranked by `bm25()`); the object's rows live in one JSON * table with no FTS index, so this computes the same thing in memory: * * - the tokenizer approximates unicode61: NFKD with the marks dropped (the * diacritics), lowercase, and runs of letters, numbers and private-use * characters as tokens; * - a query is a list of phrases (FTS5's quoted literals), ANDed for * `recall`'s `to_match_query` and ORed for `remember`'s candidate scan; a * phrase matches where its tokens stand consecutively in the title; * - the rank is FTS5's own bm25 formula (k1 1.2, b 0.75, idf * `ln((N − n + 0.5)/(n + 0.5))` floored at 1e-6, negated so lower is better) * over the title column, with N and the average length taken over every * memory row, as the index holds every row. * * Where unicode61 and this tokenizer split a word differently the two can * disagree on a match or a tie; the order of clear winners is the same. */ export type Phrase = string[]; export function ftsTokens(text: string): string[] { return text .normalize("NFKD") .replace(/\p{M}/gu, "") .toLowerCase() .split(/[^\p{L}\p{N}\p{Co}]+/u) .filter(Boolean); } /** The characters FTS5 treats as syntax, which a search box must not (cotton-store search.rs). */ const STRIPPED = /["'^*:()-]/g; /** `to_match_query`: each whitespace-separated word a quoted literal, ANDed; null when there is no word. */ export function matchQuery(input: string): Phrase[] | null { const words = input.replace(STRIPPED, " ").split(/\s+/).filter(Boolean); return words.length ? words.map(ftsTokens) : null; } function hits(tokens: string[], phrase: Phrase): number { if (!phrase.length) return 0; let n = 0; for (let i = 0; i + phrase.length <= tokens.length; i++) if (phrase.every((t, k) => tokens[i + k] === t)) n++; return n; } export interface Ranked { row: T; rank: number; } /** * The rows the query matches among those `keep` admits, each with its bm25 * rank, in one pass over `corpus` — every row the index holds, read as a * stream: N, the average length and each phrase's document count come from * every row, and only the matching candidates are held. */ export function ftsSearch(corpus: Iterable, titleOf: (row: T) => string, keep: (row: T) => boolean, phrases: Phrase[], mode: "and" | "or"): Ranked[] { let total = 0; let length = 0; const holding = phrases.map(() => 0); const candidates: { row: T; counts: number[]; tokens: number }[] = []; for (const row of corpus) { const tokens = ftsTokens(titleOf(row)); total += 1; length += tokens.length; const counts = phrases.map((p) => hits(tokens, p)); counts.forEach((c, i) => { if (c > 0) holding[i]! += 1; }); const matched = mode === "and" ? counts.every((c) => c > 0) : counts.some((c) => c > 0); if (matched && keep(row)) candidates.push({ row, counts, tokens: tokens.length }); } const avg = total ? length / total : 0; const idf = holding.map((n) => { const v = Math.log((total - n + 0.5) / (n + 0.5)); return v <= 0 ? 1e-6 : v; }); const k1 = 1.2; const b = 0.75; return candidates.map(({ row, counts, tokens }) => { let score = 0; counts.forEach((f, i) => { if (!f) return; score += (idf[i]! * (f * (k1 + 1))) / (f + k1 * (1 - b + (b * tokens) / (avg || 1))); }); return { row, rank: -score }; }); }