Cotton code
175 lines · 6.5 KB · TypeScriptRaw
/** * `list_sessions { q }` — the Rust tool asks SQLite FTS5 (`fts_prompts`, * `tokenize='unicode61 remove_diacritics 2'`) with `to_match_query(q)`, ranks * by `bm25`, then `seq`, and cuts `snippet(…, '', '', '…', 12)`. The object * keeps rows as JSON with no FTS table, so this is the same match, rank and * snippet worked in TypeScript over the prompt rows: every word a quoted * phrase, the phrases ANDed, BM25 with k1 1.2 and b 0.75, and FTS5's own * snippet window choice (fts5_aux.c). */import type { StoredRow } from "../../../store.ts";import { int, text } from "./common.ts";const STRIPPED = new Set(['"', "'", "^", "*", ":", "(", ")", "-"]);const SNIPPET_TOKENS = 12;const K1 = 1.2;const B = 0.75;interface Token {  term: string;  start: number;  end: number;}const TOKEN = /[\p{L}\p{N}\p{Co}\p{Mn}]+/gu;/** unicode61 with remove_diacritics: runs of letters and numbers, folded to lower case without their marks. */export function tokenize(value: string): Token[] {  const out: Token[] = [];  for (const m of value.matchAll(TOKEN)) {    const term = m[0].normalize("NFD").replace(/\p{Mn}/gu, "").toLowerCase();    if (term) out.push({ term, start: m.index, end: m.index + m[0].length });  }  return out;}/** `to_match_query`: each whitespace-separated word, syntax characters breaking it, as a phrase; null when nothing is left. */export function matchPhrases(q: string): string[][] | null {  const spaced = [...q].map((ch) => (STRIPPED.has(ch) ? " " : ch)).join("");  const words = spaced.split(/\s+/).filter(Boolean);  if (!words.length) return null;  return words.map((w) => tokenize(w).map((t) => t.term));}/** Where a phrase starts in a token list. */function instances(tokens: Token[], phrase: string[]): number[] {  const out: number[] = [];  if (!phrase.length) return out;  for (let i = 0; i + phrase.length <= tokens.length; i++) if (phrase.every((term, k) => tokens[i + k]!.term === term)) out.push(i);  return out;}export interface Hit {  sessionId: string;  seq: number;  snippet: string;}/** * The prompt rows matching every phrase, best first, at most `limit`, in one * pass over `prompts` — every prompt the index holds, read as a stream: N, * the average length and each phrase's document count come from every row, * and only a match's place is kept (its id, seq and counts, never its text). * The winners' text is read again for their snippets. *//** * With `stats` (a big prompt table, src/mcp/tools/sessions/list.ts) `prompts` is only the rows that can match, and N * and the average length are the whole table's as given; each phrase's document count is still counted here, exactly, * since a row that cannot match holds none of them. */export function searchPrompts(prompts: Iterable<StoredRow>, phrases: string[][], limit: number, reread: (id: string) => StoredRow | null, stats?: { n: number; avgdl: number }): Hit[] {  if (phrases.some((p) => !p.length)) return [];  let n = 0;  let length = 0;  const holding = phrases.map(() => 0);  const matched: { id: string; order: number; seq: number; tf: number[]; tokens: number }[] = [];  for (const row of prompts) {    const tokens = tokenize(text(row.data, "text") ?? "");    const at = phrases.map((p) => instances(tokens, p).length);    at.forEach((c, i) => {      if (c) holding[i]! += 1;    });    if (at.every((c) => c > 0)) matched.push({ id: row.id, order: n, seq: int(row.data, "seq"), tf: at, tokens: tokens.length });    n += 1;    length += tokens.length;  }  if (stats) {    n = stats.n;    length = stats.avgdl * stats.n;  }  if (!n) return [];  const avgdl = length / n;  const idf = holding.map((h) => {    const v = Math.log((n - h + 0.5) / (h + 0.5));    return v <= 0 ? 1e-6 : v;  });  const ranked = matched    .map((m) => {      let score = 0;      m.tf.forEach((tf, i) => {        score += (idf[i]! * (tf * (K1 + 1))) / (tf + K1 * (1 - B + (B * m.tokens) / (avgdl || 1)));      });      return { ...m, rank: -score };    })    .sort((a, b) => a.rank - b.rank || a.seq - b.seq || a.order - b.order)    .slice(0, limit);  const out: Hit[] = [];  for (const m of ranked) {    const row = reread(m.id);    if (!row) continue;    const body = text(row.data, "text") ?? "";    const tokens = tokenize(body);    const at = phrases.map((p) => instances(tokens, p));    out.push({ sessionId: text(row.data, "session") ?? "", seq: m.seq, snippet: snippet(body, tokens, at, phrases) });  }  return out;}/** FTS5's snippet: the 12-token window scoring the most distinct phrases, nudged to centre them or to start a sentence. */function snippet(body: string, tokens: Token[], at: number[][], phrases: string[][]): string {  const size = tokens.length;  const inst = at.flatMap((offsets, phrase) => offsets.map((offset) => ({ phrase, offset }))).sort((a, b) => a.offset - b.offset || a.phrase - b.phrase);  const firsts: number[] = [];  tokens.forEach((t, i) => {    if (i === 0) {      firsts.push(0);      return;    }    let j = t.start - 1;    while (j >= 0 && " \t\n\r".includes(body[j]!)) j--;    if (j !== t.start - 1 && (body[j] === "." || body[j] === ":")) firsts.push(i);  });  const score = (pos: number): { score: number; adj: number } => {    const seen = new Set<number>();    let total = 0;    let first = -1;    let last = 0;    for (const h of inst) {      if (h.offset < pos || h.offset >= pos + SNIPPET_TOKENS) continue;      total += seen.has(h.phrase) ? 1 : 1000;      seen.add(h.phrase);      if (first < 0) first = h.offset;      last = h.offset + phrases[h.phrase]!.length;    }    let adj = first - Math.trunc((SNIPPET_TOKENS - (last - first)) / 2);    if (adj + SNIPPET_TOKENS > size) adj = size - SNIPPET_TOKENS;    if (adj < 0) adj = 0;    return { score: total, adj };  };  let best = 0;  let start = 0;  for (const h of inst) {    const s = score(h.offset);    if (s.score > best) {      best = s.score;      start = s.adj;    }    if (firsts.length && size > SNIPPET_TOKENS) {      let jj = 0;      for (; jj < firsts.length - 1; jj++) if (firsts[jj + 1]! > h.offset) break;      if (firsts[jj]! < h.offset) {        const f = score(firsts[jj]!).score + (firsts[jj] === 0 ? 120 : 100);        if (f > best) {          best = f;          start = firsts[jj]!;        }      }    }  }  if (!size) return "";  const end = Math.min(start + SNIPPET_TOKENS, size) - 1;  let out = start > 0 ? "…" : "";  out += body.slice(start > 0 ? tokens[start]!.start : 0, tokens[end]!.end);  out += end >= size - 1 ? body.slice(tokens[end]!.end) : "…";  return out;}