/** * `search_records`: the records whose words hold `q`, across one table, a * few, or every table the record tools read — newest first, each hit the row * it came from, the column it matched in and a few words around the match. It * is how a session finds the messages, emails, people and notes about a name, * a company or a word without paging a whole table. * * It reads the object's own SQLite: `LIKE` over the text columns each * definition names (`Table.searchable`, the columns `list_records`' `query` * looks in), a table at a time, each table's hits newest first by its time, * merged. A raw `data LIKE` comes first where the words are stored as written * (no quote, backslash or control letter in `q`): every row it lets by is one * whose JSON holds `q`, so the column test runs only on those. */ import { boundedLimit, fail, optionalString, type Data, type ToolContext } from "../../context.ts"; import { col, typeOf, type Cond, type StoredRow } from "../../../store.ts"; import { blindSql, blindVerified, likePattern } from "./list.ts"; import { cellTexts } from "../../../seal.ts"; import { outsideOf } from "../../outside.ts"; import { isSealedTable, needWindow, openStored, READ_REASON } from "../window.ts"; import type { TableKeys } from "../../../window.ts"; import { resolveTable, visibleTables, type Table } from "./table.ts"; import { newestSql, readWindow, timeOf, windowSql, type Window } from "./window.ts"; const DEFAULT_HITS = 25; const MAX_HITS = 200; /** Letters of context kept each side of a match. */ const AROUND = 60; const TITLE_LENGTH = 80; /** Rows a page of a big table's search reads (Store.pageBack): each statement stays bounded. */ const SEARCH_STEP = 5_000; /** A search of the open tables reads pages until this long has gone, then answers what it found and how far back it read. */ export const SEARCH_BUDGET_MS = 2_500; /** At most this many hits a table are gathered before they are ordered: past it the answer says there are more. */ const GATHER_MOST = 2_000; /** SQLite's LIKE folds ASCII letters only; the excerpt finds the match the same way. */ const fold = (s: string): string => s.replace(/[A-Z]/g, (c) => c.toLowerCase()); /** Whether JSON.stringify writes `q` other than as it is: a quote, a backslash, a control letter or half a pair. */ function escaped(q: string): boolean { for (let i = 0; i < q.length; i++) { const c = q.charCodeAt(i); if (c === 0x22 || c === 0x5c || c < 0x20 || (c >= 0xd800 && c <= 0xdfff)) return true; } return false; } function tablesOf(ctx: ToolContext, args: Data): { tables: Table[]; named: boolean } { const one = args.table; const some = args.tables; const hasOne = one !== undefined && one !== null; const hasSome = some !== undefined && some !== null; if (hasOne && hasSome) fail("say table or tables, not both"); if (hasOne) { if (typeof one !== "string" || !one.trim()) fail('table is a table\'s id, e.g. "message"'); return { tables: [resolveTable(ctx, one.trim(), one)], named: true }; } if (hasSome) { if (!Array.isArray(some) || !some.length || some.length > 50) fail('tables is a list of 1 to 50 table ids, e.g. ["message", "email"]'); const seen = new Map(); for (const id of some) { if (typeof id !== "string" || !id.trim()) fail("each of tables is one table's id"); const t = resolveTable(ctx, id.trim(), id); seen.set(t.id, t); } return { tables: [...seen.values()], named: true }; } return { tables: visibleTables(ctx), named: false }; } /** * The rows of one table whose searchable words hold `q`, newest first, at most `limit`. The table is read a page at a * time, newest made first (on a million-row object one whole read of an open table took over a second, and his * answered 502 through the proxy), every hit gathered and then ordered by the table's time; once `deadline` passes * the rest is left, and `back_to` says where the read stopped. */ function hitsIn(ctx: ToolContext, t: Table, q: string, window: Window, limit: number, deadline: number): { rows: StoredRow[]; back_to: string | null } { const conds = hitConds(t, q, window); const gathered: StoredRow[] = []; let before: { created_at: string; id: string } | null = null; for (;;) { const page = ctx.store.pageBack(t.id, conds, before, SEARCH_STEP); gathered.push(...page.rows); if (!page.next) break; before = page.next; if (gathered.length >= GATHER_MOST || Date.now() > deadline) { return { rows: orderHits(t, gathered).slice(0, limit), back_to: before.created_at }; } } return { rows: orderHits(t, gathered).slice(0, limit), back_to: null }; } /** Hits in the order hitsIn's one statement gave them: the table's newest first (src/mcp/tools/records/window.ts newestSql). */ function orderHits(t: Table, rows: StoredRow[]): StoredRow[] { const keyed = rows.map((row) => ({ row, ms: timeOf(t, row).ms })); keyed.sort((a, b) => (a.ms === null ? 1 : 0) - (b.ms === null ? 1 : 0) || (b.ms ?? 0) - (a.ms ?? 0) || b.row.updated_at.localeCompare(a.row.updated_at) || a.row.id.localeCompare(b.row.id)); return keyed.map((k) => k.row); } function hitConds(t: Table, q: string, window: Window): Cond[] { const columns = t.searchable; const pattern = likePattern(q); const conds: Cond[] = []; if (!escaped(q)) conds.push({ sql: "data LIKE ? ESCAPE '\\'", args: [pattern] }); conds.push({ sql: columns.map((k) => `(${typeOf(k)} = 'text' AND ${col(k)} LIKE ? ESCAPE '\\')`).join(" OR "), args: columns.map(() => pattern) }); const bin = t.binColumn; if (bin) conds.push({ sql: `NOT (${typeOf(bin)} = 'text' AND ${col(bin)} <> '')`, args: [] }); conds.push(...windowSql(t, window)); return conds; } /** A few words either side of the match, on one line; an ellipsis where the value goes on. */ export function excerpt(value: string, q: string): string { const at = fold(value).indexOf(fold(q)); if (at < 0) return ""; let start = Math.max(0, at - AROUND); let end = Math.min(value.length, at + q.length + AROUND); // Never split a letter written as two UTF-16 units. if (start > 0 && /[\udc00-\udfff]/.test(value[start]!)) start--; if (end < value.length && /[\udc00-\udfff]/.test(value[end]!)) end++; const words = value.slice(start, end).replace(/\s+/g, " "); return `${start > 0 ? "…" : ""}${start > 0 ? words.trimStart() : words}${end < value.length ? "…" : ""}`.trim(); } function titleOf(t: Table, row: StoredRow): string | null { const v = t.title ? row.data[t.title] : undefined; if (typeof v !== "string") return null; const line = v.trim().split("\n")[0]!.trim(); if (!line) return null; return line.length > TITLE_LENGTH ? `${line.slice(0, TITLE_LENGTH)}…` : line; } interface Hit { table: string; id: string; column: string; excerpt: string; at: string | null; title?: string; archived?: true; ms: number | null; outside?: Data; } /** AUDIT C 4: a hit whose excerpt or title is another person's text says so (src/mcp/outside.ts). */ function markOutside(hit: Hit, data: Data): void { const mark = outsideOf(hit.table, data); if (mark && (mark.columns as string[]).some((c) => c === hit.column || hit.title !== undefined)) hit.outside = mark; } /** In a window, a sealed table's hits: the rows whose blind tokens hold `q`'s words, opened and held to them in plaintext, newest first. */ async function sealedHits(ctx: ToolContext, t: Table, keys: TableKeys, q: string, window: Window, limit: number): Promise<{ hits: Hit[]; more: boolean }> { const conds: Cond[] = [await blindSql(ctx, t, keys, q)]; const bin = t.binColumn; if (bin) conds.push({ sql: `NOT (${typeOf(bin)} = 'text' AND ${col(bin)} <> '')`, args: [] }); conds.push(...windowSql(t, window)); const hits: Hit[] = []; let more = false; // Candidates are read a page at a time until the hits are full: the plaintext check may drop many (a common prefix's longer words). const step = limit * 4; for (let page = 0; !more; page += step) { const batch = ctx.store.select(t.id, conds, newestSql(t), step, page); for (const stored of batch) { const { row, parked } = await openStored(ctx, t, keys, stored); if (parked) continue; const column = blindVerified(t, q, row.data); if (column === null) continue; if (hits.length === limit) { more = true; break; } const value = cellTexts(row.data[column]).join("\n"); const word = [q, ...q.split(/\s+/)].find((w) => w && fold(value).includes(fold(w))) ?? q; const { at, ms } = timeOf(t, row); const hit: Hit = { table: t.id, id: row.id, column, excerpt: excerpt(value, word), at, ms }; const title = column === t.title ? null : titleOf(t, row); if (title) hit.title = title; if (t.archived(row)) hit.archived = true; markOutside(hit, row.data); hits.push(hit); } if (batch.length < step) break; } return { hits, more }; } export async function searchRecords(ctx: ToolContext, args: Data): Promise { const q = optionalString(args, "q") ?? fail("q is required: the words to find — a name, a company, a word"); if (q.length < 2) fail("q is at least two letters"); const limit = boundedLimit(args, DEFAULT_HITS, MAX_HITS); const window = readWindow(ctx, args); const { tables, named } = tablesOf(ctx, args); const foldedQ = fold(q); const hits: Hit[] = []; let more = false; const unopened: string[] = []; const deadline = Date.now() + SEARCH_BUDGET_MS; const cut: { table: string; back_to: string }[] = []; for (const t of tables) { // A sealed table is searched by its blind tokens in a window; named without one it asks for one, else it is said as not searched. if (isSealedTable(t)) { const keys = await ctx.window.keys(t.id); if (!keys) { if (named) await needWindow(ctx, [t], READ_REASON); unopened.push(t.id); continue; } const found = await sealedHits(ctx, t, keys, q, window, limit); if (found.more) more = true; hits.push(...found.hits); continue; } if (!t.searchable.length) { if (named) fail(`${t.plural} have no words to search`); continue; } const found = hitsIn(ctx, t, q, window, limit + 1, deadline); const rows = found.rows; if (found.back_to !== null) cut.push({ table: t.id, back_to: found.back_to }); if (rows.length > limit) more = true; for (const row of rows.slice(0, limit)) { const column = t.searchable.find((k) => typeof row.data[k] === "string" && fold(row.data[k] as string).includes(foldedQ))!; const { at, ms } = timeOf(t, row); const hit: Hit = { table: t.id, id: row.id, column, excerpt: excerpt(row.data[column] as string, q), at, ms }; const title = column === t.title ? null : titleOf(t, row); if (title) hit.title = title; if (t.archived(row)) hit.archived = true; markOutside(hit, row.data); hits.push(hit); } } // Newest first across the tables; a record with no time after every timed one. hits.sort((a, b) => (a.ms === null ? 1 : 0) - (b.ms === null ? 1 : 0) || (b.ms ?? 0) - (a.ms ?? 0) || a.table.localeCompare(b.table) || a.id.localeCompare(b.id)); if (hits.length > limit) more = true; // A table read only back to a point (the time ran out): what was read, and where to ask from for older (`until`). const partly = cut.length ? { searched_back_to: cut } : {}; return { q, hits: hits.slice(0, limit).map(({ ms: _ms, ...hit }) => hit), more: more || cut.length > 0, ...partly, ...(unopened.length ? { sealed_not_searched: unopened } : {}) }; }