//! What `search_everything_file` answers: the thought lane, the semantic lane //! inside it, and the engine half of the MCP search tools. //! //! # How the statements were pinned //! //! The TypeScript was handed a RECORDING `SqlDriver` — a stub that answers rows //! and dumps every `{sql, params}` it was asked for, in order — and run under //! `npx tsx` for a spread of options: the whole file, a `kinds` subset, an empty //! `kinds`, `perKind` at its default / 3 / 0, each of the three `lanes`, and //! queries containing `%`, `_`, a backslash, a quote, an emoji and nothing at //! all. The 62 distinct statements that came back are the `sql` module below, //! verbatim, whitespace included; every test here asserts the Rust issues them //! byte for byte, with the same parameters, in the same order. //! //! The row → hit mapping was pinned the same way: canned rows in, the whole //! `EverythingSearchRead` out, read off the running TypeScript rather than //! reasoned about. Three of those readings corrected a guess — a note body //! beginning with a BOM is titled WITHOUT it while one beginning with a NEL //! keeps it, a full stop followed by U+0085 does NOT end a sentence, and the //! message lane alone does not drop a snippet that repeats its title. //! //! # What is NOT here, and whose it is //! //! `mcpSearch.test.ts` and `mcpSearchMeaning.test.ts` are mostly tests of the //! TOOL, not of this engine, and those stay with the server port: the `journal` //! pseudo-kind and its `Journal 2026-08-21` wording, the `detail` field and the //! `[slug]` citation line a memory hit carries into it, the `mode` parameter and //! its refusal naming `text, meaning, both`, the unknown-kind refusal, the //! `meaning: { available: false, reason }` envelope in all four of its shapes //! (`off`, `empty`, `unreachable`, and the provider stub that proves the default //! mode spends no call), and the `_embed_state.active_model` read that decides //! WHICH generation is passed in. What came over is what this engine decides: //! ranking within a kind, the per-kind cap and the totals, `sectionOf`'s folding //! of `thread` into `message` and `email_thread` into `email`, the snippet //! rules, the exact-before-related order, the never-twice rule and //! `matchedBy: "meaning"`. use std::cell::RefCell; use super::*; // ── the statements the running TypeScript issued ───────────────────────────── #[rustfmt::skip] mod sql { pub const TODO: &str = "SELECT t.id AS d_id, -bm25(fts_todos, 2, 1) AS d_rank, snippet(fts_todos, -1, '', '', '…', 12) AS d_snippet , t.title AS d_title, t.status AS d_status, t.due_at AS d_when FROM fts_todos JOIN cotton_todos t ON t.rowid = fts_todos.rowid WHERE fts_todos MATCH ? AND t.trashed_at IS NULL ORDER BY d_rank DESC, t.updated_at DESC LIMIT ?"; pub const EVENT: &str = "SELECT t.id AS d_id, -bm25(fts_events, 2, 1, 1) AS d_rank, snippet(fts_events, -1, '', '', '…', 12) AS d_snippet , t.title AS d_title, t.starts_at AS d_when FROM fts_events JOIN cotton_events t ON t.rowid = fts_events.rowid WHERE fts_events MATCH ? AND t.trashed_at IS NULL ORDER BY d_rank DESC, t.starts_at DESC LIMIT ?"; pub const NOTE: &str = "SELECT t.id AS d_id, -bm25(fts_notes, 2, 1) AS d_rank, snippet(fts_notes, -1, '', '', '…', 12) AS d_snippet , t.title AS d_title, t.body AS d_body, t.kind AS d_kind, COALESCE(t.journal_date, t.updated_at) AS d_when, (t.archived_at IS NOT NULL) AS d_archived FROM fts_notes JOIN cotton_notes t ON t.rowid = fts_notes.rowid WHERE fts_notes MATCH ? AND t.trashed_at IS NULL ORDER BY d_archived ASC, d_rank DESC, t.updated_at DESC LIMIT ?"; pub const PERSON: &str = "SELECT t.id AS d_id, -bm25(fts_people, 2, 1, 1, 1) AS d_rank, snippet(fts_people, -1, '', '', '…', 12) AS d_snippet , t.full_name AS d_title, t.avatar_key AS d_photo_key, (t.archived_at IS NOT NULL) AS d_archived FROM fts_people JOIN cotton_people t ON t.rowid = fts_people.rowid WHERE fts_people MATCH ? ORDER BY d_archived ASC, d_rank DESC, t.updated_at DESC LIMIT ?"; pub const LOCATION: &str = "SELECT t.id AS d_id, -bm25(fts_locations, 2, 1, 1) AS d_rank, snippet(fts_locations, -1, '', '', '…', 12) AS d_snippet , t.name AS d_title, (t.archived_at IS NOT NULL) AS d_archived FROM fts_locations JOIN cotton_locations t ON t.rowid = fts_locations.rowid WHERE fts_locations MATCH ? ORDER BY d_archived ASC, d_rank DESC, t.updated_at DESC LIMIT ?"; pub const MEETING: &str = "SELECT t.id AS d_id, -bm25(fts_meetings, 2, 1) AS d_rank, snippet(fts_meetings, -1, '', '', '…', 12) AS d_snippet , t.title AS d_title, t.started_at AS d_when FROM fts_meetings JOIN cotton_meetings t ON t.rowid = fts_meetings.rowid WHERE fts_meetings MATCH ? AND t.trashed_at IS NULL ORDER BY d_rank DESC, t.started_at DESC LIMIT ?"; pub const PAGE: &str = "SELECT t.id AS d_id, -bm25(fts_pages, 2, 1) AS d_rank, snippet(fts_pages, -1, '', '', '…', 12) AS d_snippet , t.title AS d_title, t.host AS d_host, t.created_at AS d_when, CASE WHEN t.text IS NULL THEN NULL ELSE snippet(fts_pages, 1, '', '', '…', 12) END AS d_excerpt, (t.archived_at IS NOT NULL) AS d_archived FROM fts_pages JOIN cotton_pages t ON t.rowid = fts_pages.rowid WHERE fts_pages MATCH ? ORDER BY d_archived ASC, d_rank DESC, t.created_at DESC LIMIT ?"; pub const MEMORY: &str = "SELECT t.id AS d_id, -bm25(fts_memories, 2, 1) AS d_rank, snippet(fts_memories, -1, '', '', '…', 12) AS d_snippet , t.title AS d_title, (t.status = 'archived') AS d_archived FROM fts_memories JOIN cotton_memories t ON t.rowid = fts_memories.rowid WHERE fts_memories MATCH ? AND t.status IN ('active', 'archived') ORDER BY d_archived ASC, d_rank DESC, t.updated_at DESC LIMIT ?"; pub const MOOD: &str = "SELECT t.id AS d_id, -bm25(fts_moods, 1) AS d_rank, snippet(fts_moods, -1, '', '', '…', 12) AS d_snippet , t.emotions AS d_emotions, t.line AS d_line, t.at AS d_when FROM fts_moods JOIN cotton_moods t ON t.rowid = fts_moods.rowid WHERE fts_moods MATCH ? AND t.trashed_at IS NULL ORDER BY d_rank DESC, t.at DESC LIMIT ?"; pub const THOUGHT: &str = "SELECT t.id AS d_id, -bm25(fts_thoughts, 1) AS d_rank, snippet(fts_thoughts, -1, '', '', '…', 12) AS d_snippet , t.raw_text AS d_body, t.captured_at AS d_when, t.route_status AS d_status FROM fts_thoughts JOIN cotton_inbox_items t ON t.rowid = fts_thoughts.rowid WHERE fts_thoughts MATCH ? AND t.route_status <> 'dismissed' ORDER BY d_rank DESC, t.captured_at DESC LIMIT ?"; pub const SESSION_MESSAGE: &str = "SELECT t.id AS d_id, -bm25(fts_session_messages, 1) AS d_rank, snippet(fts_session_messages, -1, '', '', '…', 12) AS d_snippet , t.body AS d_body, t.kind AS d_kind, t.created_at AS d_when FROM fts_session_messages JOIN cotton_session_messages t ON t.rowid = fts_session_messages.rowid WHERE fts_session_messages MATCH ? AND t.status <> 'withdrawn' ORDER BY d_rank DESC, t.created_at DESC LIMIT ?"; pub const PHOTO: &str = "SELECT t.id AS d_id, -bm25(fts_photos, 2, 1, 1) AS d_rank, snippet(fts_photos, -1, '', '', '…', 12) AS d_snippet , t.caption AS d_title, t.summary AS d_body, t.taken_at AS d_when FROM fts_photos JOIN cotton_photos t ON t.rowid = fts_photos.rowid WHERE fts_photos MATCH ? AND t.trashed_at IS NULL ORDER BY d_rank DESC, t.taken_at DESC LIMIT ?"; pub const VIDEO: &str = "SELECT t.id AS d_id, -bm25(fts_videos, 2, 1) AS d_rank, snippet(fts_videos, -1, '', '', '…', 12) AS d_snippet , t.caption AS d_title, t.summary AS d_body, t.taken_at AS d_when FROM fts_videos JOIN cotton_videos t ON t.rowid = fts_videos.rowid WHERE fts_videos MATCH ? AND t.trashed_at IS NULL ORDER BY d_rank DESC, t.taken_at DESC LIMIT ?"; pub const SECRET: &str = "SELECT t.id AS d_id, -bm25(fts_secrets, 2, 1, 1, 1) AS d_rank, snippet(fts_secrets, -1, '', '', '…', 12) AS d_snippet , t.name AS d_title, t.site AS d_site, t.username AS d_username, t.kind AS d_kind, t.updated_at AS d_when FROM fts_secrets JOIN cotton_secrets t ON t.rowid = fts_secrets.rowid WHERE fts_secrets MATCH ? AND t.trashed_at IS NULL ORDER BY d_rank DESC, t.updated_at DESC LIMIT ?"; pub const DOCUMENT: &str = "WITH hits AS ( SELECT d.id AS d_id, -bm25(fts_documents, 2, 1, 1, 1) AS d_rank, snippet(fts_documents, -1, '', '', '…', 12) AS d_snippet, NULL AS d_page FROM fts_documents JOIN cotton_documents d ON d.rowid = fts_documents.rowid WHERE fts_documents MATCH ? UNION ALL SELECT p.document_id AS d_id, -bm25(fts_document_pages) * 0.8 AS d_rank, snippet(fts_document_pages, -1, '', '', '…', 12) AS d_snippet, p.page AS d_page FROM fts_document_pages JOIN cotton_document_pages p ON p.rowid = fts_document_pages.rowid WHERE fts_document_pages MATCH ? ), best AS ( SELECT d_id, d_rank, d_snippet, d_page, ROW_NUMBER() OVER ( PARTITION BY d_id ORDER BY d_rank DESC, d_page IS NOT NULL, d_page ASC ) AS seat FROM hits ) SELECT b.d_id, b.d_rank, b.d_snippet, b.d_page, COALESCE(NULLIF(trim(d.title), ''), d.original_name) AS d_title FROM best b JOIN cotton_documents d ON d.id = b.d_id WHERE b.seat = 1 AND d.trashed_at IS NULL ORDER BY b.d_rank DESC LIMIT ?"; pub const SESSION: &str = "WITH hits AS ( SELECT p.session_id AS d_id, -bm25(fts_prompts) AS d_rank, snippet(fts_prompts, -1, '', '', '…', 12) AS d_snippet, p.seq AS d_seq FROM fts_prompts JOIN cotton_prompts p ON p.rowid = fts_prompts.rowid WHERE fts_prompts MATCH ? ), best AS ( SELECT d_id, d_rank, d_snippet, ROW_NUMBER() OVER ( PARTITION BY d_id ORDER BY d_rank DESC, d_seq ASC ) AS seat FROM hits ) SELECT b.d_id, b.d_rank, b.d_snippet, s.title AS d_title, s.summary AS d_summary, s.started_at AS d_when FROM best b JOIN cotton_sessions s ON s.id = b.d_id WHERE b.seat = 1 ORDER BY b.d_rank DESC LIMIT ?"; pub const MESSAGE: &str = "SELECT m.id AS d_id, m.thread_id AS d_thread, m.sent_at AS d_when, -bm25(fts_messages) AS d_rank, snippet(fts_messages, -1, '', '', '…', 12) AS d_snippet, COALESCE(NULLIF(trim(th.title), ''), c.display_name, c.phone_e164) AS d_title FROM fts_messages JOIN cotton_msg_messages m ON m.rowid = fts_messages.rowid JOIN cotton_msg_threads th ON th.id = m.thread_id LEFT JOIN cotton_msg_contacts c ON c.id = th.contact_id WHERE fts_messages MATCH ? AND m.deleted_at IS NULL AND m.hidden_at IS NULL AND (th.cleared_before IS NULL OR m.sent_at > th.cleared_before) ORDER BY d_rank DESC, m.sent_at DESC LIMIT ?"; pub const EMAIL: &str = "WITH hit AS ( SELECT e.rowid AS r, e.id, e.thread_id, e.sent_at, e.rowid IN (SELECT rowid FROM fts_emails WHERE fts_emails MATCH ?) AS head FROM fts_emails JOIN cotton_emails e ON e.rowid = fts_emails.rowid WHERE fts_emails MATCH ? AND (e.trashed_at IS NULL)), best AS ( SELECT r, id, thread_id, sent_at, head, row_number() OVER (PARTITION BY thread_id ORDER BY head DESC, sent_at DESC, id DESC) AS n FROM hit), t AS ( SELECT b.r, b.id, b.thread_id, b.sent_at, b.head, th.subject AS thread_subject, th.sender_kind AS stack, NOT EXISTS (SELECT 1 FROM cotton_emails m WHERE m.thread_id = th.id AND m.in_inbox = 1) AS archived FROM best b JOIN cotton_email_threads th ON th.id = b.thread_id WHERE b.n = 1 AND (th.trashed_at IS NULL)), top AS MATERIALIZED ( SELECT * FROM t ORDER BY (t.stack IS 'junk') ASC, t.head DESC, t.sent_at DESC, t.id DESC LIMIT ?), snip AS MATERIALIZED ( SELECT fts_emails.rowid AS r, snippet(fts_emails, -1, '', '', '…', 12) AS s FROM fts_emails WHERE fts_emails MATCH ? AND +fts_emails.rowid IN (SELECT r FROM top)) SELECT t.id AS d_id, t.thread_id AS d_thread, t.sent_at AS d_when, t.head AS d_rank, snip.s AS d_snippet, COALESCE(NULLIF(trim(e.subject), ''), NULLIF(trim(t.thread_subject), '')) AS d_title, t.stack AS d_stack, t.archived AS d_archived FROM top t JOIN cotton_emails e ON e.rowid = t.r LEFT JOIN snip ON snip.r = t.r ORDER BY (t.stack IS 'junk') ASC, t.head DESC, t.sent_at DESC, t.id DESC"; pub const THREAD_SCAN_1: &str = "SELECT th.id AS d_id, COALESCE(NULLIF(trim(th.title), ''), c.display_name, c.phone_e164) AS d_title, th.last_message_at AS d_when, th.archived AS d_archived FROM cotton_msg_threads th LEFT JOIN cotton_msg_contacts c ON c.id = th.contact_id WHERE th.trashed_at IS NULL AND COALESCE(NULLIF(trim(th.title), ''), c.display_name, c.phone_e164, '') || ' ' || COALESCE(th.description, '') LIKE ? ESCAPE '\\' ORDER BY th.archived ASC, th.last_message_at DESC LIMIT ?"; pub const EMAIL_THREAD_SCAN_1: &str = "SELECT th.id AS d_id, NULLIF(trim(th.subject), '') AS d_title, th.last_at AS d_when, NOT EXISTS (SELECT 1 FROM cotton_emails m WHERE m.thread_id = th.id AND m.in_inbox = 1) AS d_archived, th.sender_kind AS d_stack FROM cotton_email_threads th WHERE (th.trashed_at IS NULL) AND COALESCE(th.subject, '') || ' ' || COALESCE((SELECT group_concat(p.email || ' ' || COALESCE(p.display_name, ''), ' ') FROM cotton_email_participants p WHERE p.thread_id = th.id), '') LIKE ? ESCAPE '\\' AND th.id NOT IN (SELECT e.thread_id FROM fts_emails JOIN cotton_emails e ON e.rowid = fts_emails.rowid WHERE fts_emails MATCH ? AND (e.trashed_at IS NULL)) ORDER BY (th.sender_kind IS 'junk') ASC, th.last_at DESC LIMIT ?"; pub const TRANSACTION_SCAN_1: &str = "SELECT t.id AS d_id, NULLIF(trim(t.description), '') AS d_title, t.notes AS d_notes, t.occurred_on AS d_when FROM cotton_money_transactions t WHERE COALESCE(t.description, '') || ' ' || COALESCE(t.notes, '') LIKE ? ESCAPE '\\' ORDER BY t.occurred_on DESC LIMIT ?"; pub const GOAL_SCAN_1: &str = "SELECT t.id AS d_id, t.title AS d_title, t.why AS d_why, t.status AS d_status FROM cotton_goals t WHERE t.trashed_at IS NULL AND t.title || ' ' || COALESCE(t.why, '') LIKE ? ESCAPE '\\' ORDER BY (t.status = 'active') DESC, t.updated_at DESC LIMIT ?"; pub const CALL_SCAN_1: &str = "SELECT t.id AS d_id, t.handle AS d_handle, t.provider AS d_provider, t.direction AS d_direction, t.outcome AS d_outcome, t.started_at AS d_when FROM cotton_call_log t WHERE t.handle IS NOT NULL AND t.handle LIKE ? ESCAPE '\\' ORDER BY t.started_at DESC LIMIT ?"; pub const PULL: &str = "SELECT t.id AS d_id, -bm25(fts_repo_pulls, 2, 1) AS d_rank, snippet(fts_repo_pulls, -1, '', '', '…', 12) AS d_snippet , t.title AS d_title, t.state AS d_state, t.merged AS d_merged, t.number AS d_number, t.repo_id AS d_repo, t.remote_updated_at AS d_when FROM fts_repo_pulls JOIN cotton_repo_pulls t ON t.rowid = fts_repo_pulls.rowid WHERE fts_repo_pulls MATCH ? ORDER BY d_rank DESC, t.remote_updated_at DESC LIMIT ?"; pub const ISSUE: &str = "SELECT t.id AS d_id, -bm25(fts_repo_issues, 2, 1) AS d_rank, snippet(fts_repo_issues, -1, '', '', '…', 12) AS d_snippet , t.title AS d_title, t.state AS d_state, t.number AS d_number, t.repo_id AS d_repo, t.remote_updated_at AS d_when FROM fts_repo_issues JOIN cotton_repo_issues t ON t.rowid = fts_repo_issues.rowid WHERE fts_repo_issues MATCH ? ORDER BY d_rank DESC, t.remote_updated_at DESC LIMIT ?"; pub const DECISION: &str = "SELECT t.id AS d_id, -bm25(fts_decisions, 2, 1) AS d_rank, snippet(fts_decisions, -1, '', '', '…', 12) AS d_snippet , t.title AS d_title, t.updated_at AS d_when FROM fts_decisions JOIN cotton_decisions t ON t.rowid = fts_decisions.rowid WHERE fts_decisions MATCH ? AND t.trashed_at IS NULL ORDER BY d_rank DESC, t.updated_at DESC LIMIT ?"; pub const POST: &str = "SELECT t.id AS d_id, -bm25(fts_posts, 2, 1, 1) AS d_rank, snippet(fts_posts, -1, '', '', '…', 12) AS d_snippet , t.caption AS d_title, t.updated_at AS d_when FROM fts_posts JOIN cotton_posts t ON t.rowid = fts_posts.rowid WHERE fts_posts MATCH ? ORDER BY d_rank DESC, t.updated_at DESC LIMIT ?"; pub const REPOSITORY_SCAN_1: &str = "SELECT t.id AS d_id, t.key AS d_key, t.name AS d_name, t.host AS d_host, t.description AS d_description, t.updated_at AS d_when FROM cotton_repos t WHERE (t.key || ' ' || t.name) LIKE ? ESCAPE '\\' ORDER BY t.updated_at DESC LIMIT ?"; pub const RELEASE_SCAN_1: &str = "SELECT t.id AS d_id, t.tag AS d_tag, t.name AS d_name, t.repo_id AS d_repo, t.draft AS d_draft, t.published_at AS d_when FROM cotton_repo_releases t WHERE (t.tag || ' ' || COALESCE(t.name, '')) LIKE ? ESCAPE '\\' ORDER BY t.published_at DESC LIMIT ?"; pub const REPOSITORY_SCAN_2: &str = "SELECT t.id AS d_id, t.key AS d_key, t.name AS d_name, t.host AS d_host, t.description AS d_description, t.updated_at AS d_when FROM cotton_repos t WHERE (t.key || ' ' || t.name) LIKE ? ESCAPE '\\' AND (t.key || ' ' || t.name) LIKE ? ESCAPE '\\' ORDER BY t.updated_at DESC LIMIT ?"; pub const RELEASE_SCAN_2: &str = "SELECT t.id AS d_id, t.tag AS d_tag, t.name AS d_name, t.repo_id AS d_repo, t.draft AS d_draft, t.published_at AS d_when FROM cotton_repo_releases t WHERE (t.tag || ' ' || COALESCE(t.name, '')) LIKE ? ESCAPE '\\' AND (t.tag || ' ' || COALESCE(t.name, '')) LIKE ? ESCAPE '\\' ORDER BY t.published_at DESC LIMIT ?"; pub const COUNT_PULL: &str = "SELECT COUNT(*) AS n FROM fts_repo_pulls JOIN cotton_repo_pulls t ON t.rowid = fts_repo_pulls.rowid WHERE fts_repo_pulls MATCH ?"; pub const COUNT_ISSUE: &str = "SELECT COUNT(*) AS n FROM fts_repo_issues JOIN cotton_repo_issues t ON t.rowid = fts_repo_issues.rowid WHERE fts_repo_issues MATCH ?"; pub const COUNT_DECISION: &str = "SELECT COUNT(*) AS n FROM fts_decisions JOIN cotton_decisions t ON t.rowid = fts_decisions.rowid WHERE fts_decisions MATCH ? AND t.trashed_at IS NULL"; pub const COUNT_POST: &str = "SELECT COUNT(*) AS n FROM fts_posts JOIN cotton_posts t ON t.rowid = fts_posts.rowid WHERE fts_posts MATCH ?"; pub const THREAD_SCAN_2: &str = "SELECT th.id AS d_id, COALESCE(NULLIF(trim(th.title), ''), c.display_name, c.phone_e164) AS d_title, th.last_message_at AS d_when, th.archived AS d_archived FROM cotton_msg_threads th LEFT JOIN cotton_msg_contacts c ON c.id = th.contact_id WHERE th.trashed_at IS NULL AND COALESCE(NULLIF(trim(th.title), ''), c.display_name, c.phone_e164, '') || ' ' || COALESCE(th.description, '') LIKE ? ESCAPE '\\' AND COALESCE(NULLIF(trim(th.title), ''), c.display_name, c.phone_e164, '') || ' ' || COALESCE(th.description, '') LIKE ? ESCAPE '\\' ORDER BY th.archived ASC, th.last_message_at DESC LIMIT ?"; pub const EMAIL_THREAD_SCAN_2: &str = "SELECT th.id AS d_id, NULLIF(trim(th.subject), '') AS d_title, th.last_at AS d_when, NOT EXISTS (SELECT 1 FROM cotton_emails m WHERE m.thread_id = th.id AND m.in_inbox = 1) AS d_archived, th.sender_kind AS d_stack FROM cotton_email_threads th WHERE (th.trashed_at IS NULL) AND COALESCE(th.subject, '') || ' ' || COALESCE((SELECT group_concat(p.email || ' ' || COALESCE(p.display_name, ''), ' ') FROM cotton_email_participants p WHERE p.thread_id = th.id), '') LIKE ? ESCAPE '\\' AND COALESCE(th.subject, '') || ' ' || COALESCE((SELECT group_concat(p.email || ' ' || COALESCE(p.display_name, ''), ' ') FROM cotton_email_participants p WHERE p.thread_id = th.id), '') LIKE ? ESCAPE '\\' AND th.id NOT IN (SELECT e.thread_id FROM fts_emails JOIN cotton_emails e ON e.rowid = fts_emails.rowid WHERE fts_emails MATCH ? AND (e.trashed_at IS NULL)) ORDER BY (th.sender_kind IS 'junk') ASC, th.last_at DESC LIMIT ?"; pub const TRANSACTION_SCAN_2: &str = "SELECT t.id AS d_id, NULLIF(trim(t.description), '') AS d_title, t.notes AS d_notes, t.occurred_on AS d_when FROM cotton_money_transactions t WHERE COALESCE(t.description, '') || ' ' || COALESCE(t.notes, '') LIKE ? ESCAPE '\\' AND COALESCE(t.description, '') || ' ' || COALESCE(t.notes, '') LIKE ? ESCAPE '\\' ORDER BY t.occurred_on DESC LIMIT ?"; pub const GOAL_SCAN_2: &str = "SELECT t.id AS d_id, t.title AS d_title, t.why AS d_why, t.status AS d_status FROM cotton_goals t WHERE t.trashed_at IS NULL AND t.title || ' ' || COALESCE(t.why, '') LIKE ? ESCAPE '\\' AND t.title || ' ' || COALESCE(t.why, '') LIKE ? ESCAPE '\\' ORDER BY (t.status = 'active') DESC, t.updated_at DESC LIMIT ?"; pub const CALL_SCAN_2: &str = "SELECT t.id AS d_id, t.handle AS d_handle, t.provider AS d_provider, t.direction AS d_direction, t.outcome AS d_outcome, t.started_at AS d_when FROM cotton_call_log t WHERE t.handle IS NOT NULL AND t.handle LIKE ? ESCAPE '\\' AND t.handle LIKE ? ESCAPE '\\' ORDER BY t.started_at DESC LIMIT ?"; pub const EMBEDDINGS_PRESENT: &str = "SELECT name FROM sqlite_master WHERE type = 'table' AND name = '_embeddings'"; pub const EMBEDDINGS_SCAN_8: &str = "SELECT source, row_id, chunk_ix, vec, text_head FROM _embeddings WHERE model = ? AND source IN (?, ?, ?, ?, ?, ?, ?, ?)"; pub const HYDRATE_NOTE_1: &str = "SELECT t.id AS d_key, t.id AS d_id, t.title AS d_title, t.body AS d_body, t.kind AS d_kind, COALESCE(t.journal_date, t.updated_at) AS d_when, (t.archived_at IS NOT NULL) AS d_archived FROM cotton_notes t WHERE t.id IN (?) AND t.trashed_at IS NULL"; pub const HYDRATE_PERSON_1: &str = "SELECT t.id AS d_key, t.id AS d_id, t.full_name AS d_title, t.avatar_key AS d_photo_key, (t.archived_at IS NOT NULL) AS d_archived FROM cotton_people t WHERE t.id IN (?)"; pub const HYDRATE_MEETING_1: &str = "SELECT t.id AS d_key, t.id AS d_id, t.title AS d_title, t.started_at AS d_when FROM cotton_meetings t WHERE t.id IN (?) AND t.trashed_at IS NULL"; pub const HYDRATE_MEMORY_1: &str = "SELECT t.id AS d_key, t.id AS d_id, t.title AS d_title, (t.status = 'archived') AS d_archived FROM cotton_memories t WHERE t.id IN (?) AND t.status IN ('active', 'archived')"; pub const HYDRATE_THOUGHT_1: &str = "SELECT t.id AS d_key, t.id AS d_id, t.raw_text AS d_body, t.captured_at AS d_when, t.route_status AS d_status FROM cotton_inbox_items t WHERE t.id IN (?) AND t.route_status <> 'dismissed'"; pub const HYDRATE_MESSAGE_1: &str = "SELECT t.id AS d_key, t.id AS d_id, t.thread_id AS d_thread, t.sent_at AS d_when, COALESCE(NULLIF(trim(th.title), ''), c.display_name, c.phone_e164) AS d_title FROM cotton_msg_messages t JOIN cotton_msg_threads th ON th.id = t.thread_id LEFT JOIN cotton_msg_contacts c ON c.id = th.contact_id WHERE t.id IN (?) AND t.deleted_at IS NULL AND t.hidden_at IS NULL AND (th.cleared_before IS NULL OR t.sent_at > th.cleared_before)"; pub const HYDRATE_EMAIL_1: &str = "SELECT t.id AS d_key, t.id AS d_id, t.thread_id AS d_thread, t.sent_at AS d_when, COALESCE(NULLIF(trim(t.subject), ''), NULLIF(trim(th.subject), '')) AS d_title, (t.in_inbox = 0) AS d_archived FROM cotton_emails t JOIN cotton_email_threads th ON th.id = t.thread_id WHERE t.id IN (?) AND (t.trashed_at IS NULL)"; pub const HYDRATE_DOCUMENT_PAGE_1: &str = "SELECT t.id AS d_key, t.document_id AS d_id, t.page AS d_page, COALESCE(NULLIF(trim(d.title), ''), d.original_name) AS d_title FROM cotton_document_pages t JOIN cotton_documents d ON d.id = t.document_id WHERE t.id IN (?) AND d.trashed_at IS NULL"; pub const EMBEDDINGS_SCAN_2: &str = "SELECT source, row_id, chunk_ix, vec, text_head FROM _embeddings WHERE model = ? AND source IN (?, ?)"; pub const COUNT_TODO: &str = "SELECT COUNT(*) AS n FROM fts_todos JOIN cotton_todos t ON t.rowid = fts_todos.rowid WHERE fts_todos MATCH ? AND t.trashed_at IS NULL"; pub const COUNT_EVENT: &str = "SELECT COUNT(*) AS n FROM fts_events JOIN cotton_events t ON t.rowid = fts_events.rowid WHERE fts_events MATCH ? AND t.trashed_at IS NULL"; pub const COUNT_NOTE: &str = "SELECT COUNT(*) AS n FROM fts_notes JOIN cotton_notes t ON t.rowid = fts_notes.rowid WHERE fts_notes MATCH ? AND t.trashed_at IS NULL"; pub const COUNT_PERSON: &str = "SELECT COUNT(*) AS n FROM fts_people JOIN cotton_people t ON t.rowid = fts_people.rowid WHERE fts_people MATCH ?"; pub const COUNT_LOCATION: &str = "SELECT COUNT(*) AS n FROM fts_locations JOIN cotton_locations t ON t.rowid = fts_locations.rowid WHERE fts_locations MATCH ?"; pub const COUNT_MEETING: &str = "SELECT COUNT(*) AS n FROM fts_meetings JOIN cotton_meetings t ON t.rowid = fts_meetings.rowid WHERE fts_meetings MATCH ? AND t.trashed_at IS NULL"; pub const COUNT_PAGE: &str = "SELECT COUNT(*) AS n FROM fts_pages JOIN cotton_pages t ON t.rowid = fts_pages.rowid WHERE fts_pages MATCH ?"; pub const COUNT_MEMORY: &str = "SELECT COUNT(*) AS n FROM fts_memories JOIN cotton_memories t ON t.rowid = fts_memories.rowid WHERE fts_memories MATCH ? AND t.status IN ('active', 'archived')"; pub const COUNT_MOOD: &str = "SELECT COUNT(*) AS n FROM fts_moods JOIN cotton_moods t ON t.rowid = fts_moods.rowid WHERE fts_moods MATCH ? AND t.trashed_at IS NULL"; pub const COUNT_THOUGHT: &str = "SELECT COUNT(*) AS n FROM fts_thoughts JOIN cotton_inbox_items t ON t.rowid = fts_thoughts.rowid WHERE fts_thoughts MATCH ? AND t.route_status <> 'dismissed'"; pub const COUNT_SESSION_MESSAGE: &str = "SELECT COUNT(*) AS n FROM fts_session_messages JOIN cotton_session_messages t ON t.rowid = fts_session_messages.rowid WHERE fts_session_messages MATCH ? AND t.status <> 'withdrawn'"; pub const COUNT_PHOTO: &str = "SELECT COUNT(*) AS n FROM fts_photos JOIN cotton_photos t ON t.rowid = fts_photos.rowid WHERE fts_photos MATCH ? AND t.trashed_at IS NULL"; pub const COUNT_VIDEO: &str = "SELECT COUNT(*) AS n FROM fts_videos JOIN cotton_videos t ON t.rowid = fts_videos.rowid WHERE fts_videos MATCH ? AND t.trashed_at IS NULL"; pub const COUNT_SECRET: &str = "SELECT COUNT(*) AS n FROM fts_secrets JOIN cotton_secrets t ON t.rowid = fts_secrets.rowid WHERE fts_secrets MATCH ? AND t.trashed_at IS NULL"; pub const COUNT_DOCUMENT: &str = "SELECT COUNT(*) AS n FROM ( SELECT d.id FROM fts_documents JOIN cotton_documents d ON d.rowid = fts_documents.rowid WHERE fts_documents MATCH ? AND d.trashed_at IS NULL UNION SELECT p.document_id FROM fts_document_pages JOIN cotton_document_pages p ON p.rowid = fts_document_pages.rowid JOIN cotton_documents d ON d.id = p.document_id WHERE fts_document_pages MATCH ? AND d.trashed_at IS NULL )"; pub const COUNT_SESSION: &str = "SELECT COUNT(DISTINCT p.session_id) AS n FROM fts_prompts JOIN cotton_prompts p ON p.rowid = fts_prompts.rowid WHERE fts_prompts MATCH ?"; pub const COUNT_MESSAGE: &str = "SELECT COUNT(*) AS n FROM fts_messages JOIN cotton_msg_messages m ON m.rowid = fts_messages.rowid JOIN cotton_msg_threads th ON th.id = m.thread_id WHERE fts_messages MATCH ? AND m.deleted_at IS NULL AND m.hidden_at IS NULL AND (th.cleared_before IS NULL OR m.sent_at > th.cleared_before)"; pub const COUNT_EMAIL: &str = "SELECT COUNT(DISTINCT e.thread_id) AS n FROM fts_emails JOIN cotton_emails e ON e.rowid = fts_emails.rowid JOIN cotton_email_threads th ON th.id = e.thread_id WHERE fts_emails MATCH ? AND (e.trashed_at IS NULL) AND (th.trashed_at IS NULL)"; pub const COUNT_TRANSACTION_2: &str = "SELECT COUNT(*) AS n FROM cotton_money_transactions t WHERE COALESCE(t.description, '') || ' ' || COALESCE(t.notes, '') LIKE ? ESCAPE '\\' AND COALESCE(t.description, '') || ' ' || COALESCE(t.notes, '') LIKE ? ESCAPE '\\'"; pub const EMBEDDINGS_SCAN_1: &str = "SELECT source, row_id, chunk_ix, vec, text_head FROM _embeddings WHERE model = ? AND source IN (?)"; pub const HYDRATE_NOTE_3: &str = "SELECT t.id AS d_key, t.id AS d_id, t.title AS d_title, t.body AS d_body, t.kind AS d_kind, COALESCE(t.journal_date, t.updated_at) AS d_when, (t.archived_at IS NOT NULL) AS d_archived FROM cotton_notes t WHERE t.id IN (?, ?, ?) AND t.trashed_at IS NULL"; pub const HYDRATE_DOCUMENT_PAGE_2: &str = "SELECT t.id AS d_key, t.document_id AS d_id, t.page AS d_page, COALESCE(NULLIF(trim(d.title), ''), d.original_name) AS d_title FROM cotton_document_pages t JOIN cotton_documents d ON d.id = t.document_id WHERE t.id IN (?, ?) AND d.trashed_at IS NULL"; pub const HYDRATE_NOTE_2: &str = "SELECT t.id AS d_key, t.id AS d_id, t.title AS d_title, t.body AS d_body, t.kind AS d_kind, COALESCE(t.journal_date, t.updated_at) AS d_when, (t.archived_at IS NOT NULL) AS d_archived FROM cotton_notes t WHERE t.id IN (?, ?) AND t.trashed_at IS NULL"; } // ── the recording driver ───────────────────────────────────────────────────── /// A statement as the transcript pins it: the shared mail predicate (MAIL PREDICATE phase 2, `cuts`), which honours /// the cuts in subqueries of its own, read back as the short form each lane wrote before, so the pins below keep /// saying the lane's own SQL. The predicate's text is held by its own tests (cotton-rules mail/cuts.rs); this proves /// each lane asks it, with which prefix. fn pinned(sql: &str) -> String { use crate::rules::mail_predicate as p; let mut out = sql.to_string(); // A conversation's predicate holds a mail's: it is read back first. for on in ["th.", "t."] { out = out.replace(&p::live_thread(on), &format!("({on}trashed_at IS NULL)")); } for on in ["e.", "t.", "m.", ""] { out = out.replace(&p::live(on), &format!("({on}trashed_at IS NULL)")); } out } #[derive(Debug, Clone, PartialEq)] struct Call { method: &'static str, sql: String, params: Vec, } /// What a recorded statement is answered with — the TypeScript stub's /// `respond(sql, params)`. type Respond = dyn Fn(&str, &[SqlParam]) -> Vec; /// The Rust half of the TypeScript's recording `SqlDriver`: it answers whatever /// the responder says and keeps every statement it was asked for, in order. struct Recorder { calls: RefCell>, respond: Box, } impl Recorder { fn empty() -> Recorder { Recorder::with(|_, _| Vec::new()) } fn with(respond: impl Fn(&str, &[SqlParam]) -> Vec + 'static) -> Recorder { Recorder { calls: RefCell::new(Vec::new()), respond: Box::new(respond), } } fn calls(&self) -> Vec { self.calls.borrow().clone() } fn statements(&self) -> Vec { self.calls.borrow().iter().map(|c| c.sql.clone()).collect() } } impl SearchDriver for Recorder { fn all(&self, sql: &str, params: &[SqlParam]) -> Result, SearchError> { self.calls.borrow_mut().push(Call { method: "all", sql: pinned(sql), params: params.to_vec(), }); Ok((self.respond)(sql, params)) } fn get(&self, sql: &str, params: &[SqlParam]) -> Result, SearchError> { self.calls.borrow_mut().push(Call { method: "get", sql: pinned(sql), params: params.to_vec(), }); Ok((self.respond)(sql, params).into_iter().next()) } } fn t(value: &str) -> SqlValue { SqlValue::Text(value.to_string()) } fn n(value: f64) -> SqlValue { SqlValue::Real(value) } const NUL: SqlValue = SqlValue::Null; fn row(columns: Vec<(&str, SqlValue)>) -> SearchRow { SearchRow::new(columns) } fn text_params(values: &[&str]) -> Vec { values.iter().map(|value| t(value)).collect() } fn match_and_limit(match_query: &str, limit: i64) -> Vec { vec![t(match_query), SqlParam::Integer(limit)] } fn ids(read: &EverythingSearchRead) -> Vec<&str> { read.hits.iter().map(|hit| hit.id.as_str()).collect() } fn kinds(read: &EverythingSearchRead) -> Vec { read.hits.iter().map(|hit| hit.kind).collect() } /// One lane in isolation: the first `all` answers these rows, everything after /// it answers nothing — the shape the TypeScript capture used. fn one_lane(wanted: &[EverythingKind], rows: Vec) -> EverythingSearchRead { let served = RefCell::new(false); let driver = Recorder::with(move |_, _| { if *served.borrow() { return Vec::new(); } *served.borrow_mut() = true; rows.clone() }); search_everything_file( &driver, "bali", &EverythingSearchOptions { kinds: Some(wanted), ..EverythingSearchOptions::default() }, ) .expect("the recorder never fails") } // ── the statements, byte for byte ──────────────────────────────────────────── /// The whole file, default options: twenty-nine statements, in this order, /// each bound `[match, perKind]` or `[…tokens, perKind]`. #[test] fn the_whole_file_is_the_twenty_nine_statements_the_file_issues() { let driver = Recorder::empty(); let read = search_everything_file(&driver, "ferry", &EverythingSearchOptions::default()) .expect("no driver failure"); assert!(read.hits.is_empty()); assert!(read.totals.is_empty()); let expected: [(&str, Vec); 29] = [ (sql::TODO, match_and_limit("\"ferry\"", 20)), (sql::EVENT, match_and_limit("\"ferry\"", 20)), (sql::NOTE, match_and_limit("\"ferry\"", 20)), (sql::PERSON, match_and_limit("\"ferry\"", 20)), (sql::LOCATION, match_and_limit("\"ferry\"", 20)), (sql::MEETING, match_and_limit("\"ferry\"", 20)), (sql::PAGE, match_and_limit("\"ferry\"", 20)), (sql::MEMORY, match_and_limit("\"ferry\"", 20)), (sql::MOOD, match_and_limit("\"ferry\"", 20)), (sql::THOUGHT, match_and_limit("\"ferry\"", 20)), (sql::SESSION_MESSAGE, match_and_limit("\"ferry\"", 20)), (sql::PHOTO, match_and_limit("\"ferry\"", 20)), (sql::VIDEO, match_and_limit("\"ferry\"", 20)), (sql::SECRET, match_and_limit("\"ferry\"", 20)), (sql::PULL, match_and_limit("\"ferry\"", 20)), (sql::ISSUE, match_and_limit("\"ferry\"", 20)), (sql::DECISION, match_and_limit("\"ferry\"", 20)), (sql::POST, match_and_limit("\"ferry\"", 20)), ( sql::DOCUMENT, vec![t("\"ferry\""), t("\"ferry\""), SqlParam::Integer(20)], ), (sql::SESSION, match_and_limit("\"ferry\"", 20)), (sql::MESSAGE, match_and_limit("\"ferry\"", 20)), ( sql::EMAIL, vec![t("{subject} : (\"ferry\")"), t("\"ferry\""), SqlParam::Integer(20), t("\"ferry\"")], ), (sql::THREAD_SCAN_1, match_and_limit("%ferry%", 20)), (sql::EMAIL_THREAD_SCAN_1, vec![t("%ferry%"), t("\"ferry\""), SqlParam::Integer(20)]), (sql::TRANSACTION_SCAN_1, match_and_limit("%ferry%", 20)), (sql::GOAL_SCAN_1, match_and_limit("%ferry%", 20)), (sql::CALL_SCAN_1, match_and_limit("%ferry%", 20)), (sql::REPOSITORY_SCAN_1, match_and_limit("%ferry%", 20)), (sql::RELEASE_SCAN_1, match_and_limit("%ferry%", 20)), ]; let calls = driver.calls(); assert_eq!(calls.len(), expected.len()); for (at, (call, (want_sql, want_params))) in calls.iter().zip(expected).enumerate() { assert_eq!(call.method, "all", "statement {at}"); assert_eq!(call.sql, want_sql, "statement {at}"); assert_eq!(call.params, want_params, "statement {at}"); } } /// `lanes: "text"` is the default, spelled — every existing caller gets today's /// answer byte for byte. #[test] fn naming_the_text_lane_changes_nothing() { let implicit = Recorder::empty(); search_everything_file(&implicit, "ferry", &EverythingSearchOptions::default()).expect("ok"); let explicit = Recorder::empty(); search_everything_file( &explicit, "ferry", &EverythingSearchOptions { lanes: Some(EverythingLanes::Text), ..EverythingSearchOptions::default() }, ) .expect("ok"); assert_eq!(implicit.calls(), explicit.calls()); } /// A query that is only whitespace asks the file nothing at all — no statement, /// no hits, no totals. #[test] fn an_empty_query_asks_the_file_nothing() { for query in ["", " ", "\u{feff}", "\n\t "] { let driver = Recorder::empty(); let read = search_everything_file(&driver, query, &EverythingSearchOptions::default()) .expect("ok"); assert!(driver.calls().is_empty(), "{query:?} issued a statement"); assert_eq!(read, EverythingSearchRead::default()); } // U+0085 is NOT ECMAScript whitespace, so a query of one is a REAL query and // every lane runs — `str::trim` would have swallowed it and answered // nothing. Read out of Node: the MATCH expression is a NEL between quotes // and the LIKE pattern is a NEL between percent signs. let driver = Recorder::empty(); search_everything_file(&driver, "\u{85}", &EverythingSearchOptions::default()).expect("ok"); let calls = driver.calls(); assert_eq!(calls.len(), 29, "the whole file still ran"); assert_eq!(calls[0].params, match_and_limit("\"\u{85}\"", 20)); assert_eq!(calls[28].params, match_and_limit("%\u{85}%", 20)); } /// An EMPTY `kinds` is a caller that asked for nothing, not a caller that asked /// for everything. #[test] fn an_empty_kinds_list_asks_the_file_nothing() { let driver = Recorder::empty(); let read = search_everything_file( &driver, "ferry", &EverythingSearchOptions { kinds: Some(&[]), ..EverythingSearchOptions::default() }, ) .expect("ok"); assert!(driver.calls().is_empty()); assert!(read.hits.is_empty()); } #[test] fn a_kinds_subset_runs_only_those_lanes() { let driver = Recorder::empty(); search_everything_file( &driver, "ferry", &EverythingSearchOptions { kinds: Some(&[ EverythingKind::Todo, EverythingKind::Message, EverythingKind::Call, ]), ..EverythingSearchOptions::default() }, ) .expect("ok"); assert_eq!( driver.statements(), vec![sql::TODO, sql::MESSAGE, sql::CALL_SCAN_1] ); } #[test] fn per_kind_binds_the_limit_and_zero_clamps_to_one() { for (per_kind, bound) in [(Some(3), 3), (Some(0), 1), (Some(-5), 1), (None, 20)] { let driver = Recorder::empty(); search_everything_file( &driver, "ferry", &EverythingSearchOptions { per_kind, kinds: Some(&[EverythingKind::Todo]), ..EverythingSearchOptions::default() }, ) .expect("ok"); assert_eq!( driver.calls()[0].params, match_and_limit("\"ferry\"", bound), "perKind {per_kind:?}" ); } } /// Two words are one MATCH expression of two quoted literals and two LIKE /// patterns ANDed — the implicit operator is AND on both lanes, which is what /// somebody typing two words expects. #[test] fn two_words_bind_two_like_patterns_and_one_match_expression() { let driver = Recorder::empty(); search_everything_file( &driver, " bali villa ", &EverythingSearchOptions::default(), ) .expect("ok"); let calls = driver.calls(); assert_eq!(calls[0].sql, sql::TODO); assert_eq!(calls[0].params, match_and_limit("\"bali\" \"villa\"", 20)); assert_eq!(calls[22].sql, sql::THREAD_SCAN_2); assert_eq!(calls[23].sql, sql::EMAIL_THREAD_SCAN_2); assert_eq!(calls[24].sql, sql::TRANSACTION_SCAN_2); assert_eq!(calls[25].sql, sql::GOAL_SCAN_2); assert_eq!(calls[26].sql, sql::CALL_SCAN_2); assert_eq!(calls[27].sql, sql::REPOSITORY_SCAN_2); assert_eq!(calls[28].sql, sql::RELEASE_SCAN_2); assert_eq!( calls[28].params, vec![t("%bali%"), t("%villa%"), SqlParam::Integer(20)] ); } /// `%`, `_` and `\` are escaped for the `ESCAPE '\'` clause; a quote is not one /// of the three and rides through untouched. #[test] fn like_wildcards_are_escaped_and_a_quote_is_not() { let cases: [(&str, Vec<&str>); 4] = [ ("50% off", vec!["%50\\%%", "%off%"]), ("a_b", vec!["%a\\_b%"]), ("c:\\path", vec!["%c:\\\\path%"]), ("say \"hi\"", vec!["%say%", "%\"hi\"%"]), ]; for (query, patterns) in cases { let driver = Recorder::empty(); search_everything_file( &driver, query, &EverythingSearchOptions { kinds: Some(&[EverythingKind::Transaction]), ..EverythingSearchOptions::default() }, ) .expect("ok"); let mut want = text_params(&patterns); want.push(SqlParam::Integer(20)); assert_eq!(driver.calls()[0].params, want, "{query:?}"); } } /// An emoji is a token on both lanes: FTS5 sees it as a quoted literal, the scan /// as a LIKE pattern. #[test] fn an_emoji_is_a_token_on_both_lanes() { let driver = Recorder::empty(); search_everything_file( &driver, "🚢 ferry", &EverythingSearchOptions { kinds: Some(&[EverythingKind::Todo, EverythingKind::Transaction]), ..EverythingSearchOptions::default() }, ) .expect("ok"); let calls = driver.calls(); assert_eq!(calls[0].params, match_and_limit("\"🚢\" \"ferry\"", 20)); assert_eq!( calls[1].params, vec![t("%🚢%"), t("%ferry%"), SqlParam::Integer(20)] ); } /// The COUNT statements fire only when a lane came back FULL — a lane that /// answered fewer than the cap already knows its own total, and asking the file /// again would be a second scan for a number the first one gave. /// /// Twenty-four of them, captured with `perKind: 2` and every lane answering two /// rows. The scan lanes that are NOT here — threads, email threads, goals, /// calls, repositories and releases — never count: their /// tables are small enough that the cap is the answer. /// RULE: Search counts every lane that returned a full page, and only those, so every total is exact and a short lane uses its known total without another query. #[test] fn the_count_statements_fire_only_when_a_lane_came_back_full() { let driver = Recorder::with(|sql, _| { if sql.contains("COUNT(") { return vec![row(vec![("n", SqlValue::Integer(99))])]; } let aliases: Vec = sql .split("AS ") .skip(1) .filter_map(|tail| { let name: String = tail .chars() .take_while(|ch| ch.is_ascii_lowercase() || *ch == '_') .collect(); name.starts_with("d_").then_some(name) }) .collect(); (0..2) .map(|at| { SearchRow::new( aliases .iter() .map(|alias| { let value = match alias.as_str() { "d_rank" | "d_page" | "d_seq" => SqlValue::Integer(at + 1), _ => t(&format!("{alias}-{at}")), }; (alias.clone(), value) }) .collect::>(), ) }) .collect() }); let read = search_everything_file( &driver, "bali villa", &EverythingSearchOptions { per_kind: Some(2), ..EverythingSearchOptions::default() }, ) .expect("ok"); let counts: Vec<(String, Vec)> = driver .calls() .into_iter() .filter(|call| call.method == "get") .map(|call| (call.sql, call.params)) .collect(); let both = text_params(&["\"bali\" \"villa\""]); let expected = [ (sql::COUNT_TODO, both.clone()), (sql::COUNT_EVENT, both.clone()), (sql::COUNT_NOTE, both.clone()), (sql::COUNT_PERSON, both.clone()), (sql::COUNT_LOCATION, both.clone()), (sql::COUNT_MEETING, both.clone()), (sql::COUNT_PAGE, both.clone()), (sql::COUNT_MEMORY, both.clone()), (sql::COUNT_MOOD, both.clone()), (sql::COUNT_THOUGHT, both.clone()), (sql::COUNT_SESSION_MESSAGE, both.clone()), (sql::COUNT_PHOTO, both.clone()), (sql::COUNT_VIDEO, both.clone()), (sql::COUNT_SECRET, both.clone()), (sql::COUNT_PULL, both.clone()), (sql::COUNT_ISSUE, both.clone()), (sql::COUNT_DECISION, both.clone()), (sql::COUNT_POST, both.clone()), ( sql::COUNT_DOCUMENT, text_params(&["\"bali\" \"villa\"", "\"bali\" \"villa\""]), ), (sql::COUNT_SESSION, both.clone()), (sql::COUNT_MESSAGE, both.clone()), (sql::COUNT_EMAIL, both.clone()), ]; // Every scan lane that came back full is counted too: its own statement, // asked with no limit (exact totals, architect 15 Oct 2026). let tokens = scan_tokens("bali villa"); let counted = |query: SearchQuery| (pinned(&format!("SELECT COUNT(*) AS n FROM ({})", query.sql)), query.params); let expected: Vec<(String, Vec)> = expected .into_iter() .map(|(sql, params)| (sql.to_string(), params)) .chain([ counted(thread_scan_query(&tokens, -1)), counted(email_thread_scan_query(&tokens, -1, Some((MAIL_INDEX, "\"bali\" \"villa\"")))), (sql::COUNT_TRANSACTION_2.to_string(), text_params(&["%bali%", "%villa%"])), counted(call_scan_query(&tokens, -1)), counted(repository_scan_query(&tokens, -1)), counted(release_scan_query(&tokens, -1)), ]) .collect(); assert_eq!(counts.len(), expected.len()); for (at, (got, (want_sql, want_params))) in counts.iter().zip(expected).enumerate() { assert_eq!(got.0, want_sql, "count {at}"); assert_eq!(got.1, want_params, "count {at}"); } // Every lane came back full, so every total is its count: `message` and // `email` are 198 because the thread lanes ADD to the section their kind // folds into — 99 counted for each of its two kinds. assert_eq!(read.totals.get(EverythingSection::Todo), Some(99)); assert_eq!(read.totals.get(EverythingSection::Message), Some(198)); assert_eq!(read.totals.get(EverythingSection::Email), Some(198)); assert_eq!(read.totals.get(EverythingSection::Transaction), Some(99)); for section in [ EverythingSection::Call, EverythingSection::Repository, EverythingSection::Release, ] { assert_eq!(read.totals.get(section), Some(99), "{section:?}"); } } /// A lane that came back SHORT is its own total, with no second statement. #[test] fn a_short_lane_counts_itself() { let read = one_lane( &[EverythingKind::Todo], vec![row(vec![ ("d_id", t("t1")), ("d_rank", n(1.5)), ("d_snippet", t("sn")), ("d_title", t("book bali flights")), ("d_status", t("open")), ("d_when", NUL), ])], ); assert_eq!(read.totals.get(EverythingSection::Todo), Some(1)); } // ── the meaning lane's statements ──────────────────────────────────────────── /// 512 bytes of one value — a stand-in vector whose dot product against the /// all-ones query is exactly `512 × value / 127²`, which is how every expected /// score below was arrived at and then read back out of Node. fn vector(value: u8) -> Vec { vec![value; 512] } const SCORE_2: f64 = 0.063_488_126_976_253_96; const SCORE_3: f64 = 0.095_232_190_464_380_93; const SCORE_4: f64 = 0.126_976_253_952_507_92; const SCORE_5: f64 = 0.158_720_317_440_634_9; const SCORE_6: f64 = 0.190_464_380_928_761_86; fn chunk_row(source: &str, row_id: &str, value: u8, head: &str) -> SearchRow { row(vec![ ("source", t(source)), ("row_id", t(row_id)), ("chunk_ix", SqlValue::Integer(0)), ("vec", SqlValue::Blob(vector(value))), ("text_head", t(head)), ]) } /// The eight sources, one chunk each — the fixture the TypeScript capture used. fn every_source_chunk() -> Vec { [ "note", "person", "meeting", "memory", "thought", "message", "email", "document_page", ] .iter() .enumerate() .map(|(at, source)| chunk_row(source, &format!("r{at}"), 3, &format!("head {at}"))) .collect() } fn meaning<'a>(vector: &'a [u8], min_score: Option) -> SemanticQuery<'a> { SemanticQuery { vector, model: "m1", min_score, } } /// Meaning mode: the presence probe FIRST, then the scan, then one hydrate per /// source that scored — and not one text statement. #[test] fn the_meaning_lane_probes_then_scans_then_hydrates() { let driver = Recorder::with(|sql, _| { if sql.contains("sqlite_master") { return vec![row(vec![("name", t("_embeddings"))])]; } if sql.contains("FROM _embeddings") { return every_source_chunk(); } Vec::new() }); let query = vector(1); search_everything_file( &driver, "payment split", &EverythingSearchOptions { lanes: Some(EverythingLanes::Meaning), meaning: Some(meaning(&query, Some(-1.0))), ..EverythingSearchOptions::default() }, ) .expect("ok"); let calls = driver.calls(); assert_eq!(calls.len(), 10); assert_eq!(calls[0].method, "get"); assert_eq!(calls[0].sql, sql::EMBEDDINGS_PRESENT); assert!(calls[0].params.is_empty()); assert_eq!(calls[1].sql, sql::EMBEDDINGS_SCAN_8); assert_eq!( calls[1].params, text_params(&[ "m1", "note", "person", "meeting", "memory", "thought", "message", "email", "document_page", ]) ); let hydrates: [(&str, &str); 8] = [ (sql::HYDRATE_NOTE_1, "r0"), (sql::HYDRATE_PERSON_1, "r1"), (sql::HYDRATE_MEETING_1, "r2"), (sql::HYDRATE_MEMORY_1, "r3"), (sql::HYDRATE_THOUGHT_1, "r4"), (sql::HYDRATE_MESSAGE_1, "r5"), (sql::HYDRATE_EMAIL_1, "r6"), (sql::HYDRATE_DOCUMENT_PAGE_1, "r7"), ]; for (at, (want_sql, want_id)) in hydrates.into_iter().enumerate() { assert_eq!(calls[at + 2].sql, want_sql, "hydrate {at}"); assert_eq!( calls[at + 2].params, text_params(&[want_id]), "hydrate {at}" ); } } /// `both` runs every text lane first and the meaning scan after — the meaning /// half never replaces the text half, it is appended to it. #[test] fn lanes_both_runs_the_text_lanes_then_the_meaning_scan() { let driver = Recorder::with(|sql, _| { if sql.contains("sqlite_master") { return vec![row(vec![("name", t("_embeddings"))])]; } if sql.contains("FROM _embeddings") { return every_source_chunk(); } Vec::new() }); let query = vector(1); search_everything_file( &driver, "payment split", &EverythingSearchOptions { lanes: Some(EverythingLanes::Both), // No floor named: the lane's own 0.28 keeps every one of these // chunks out, which is what leaves the hydrate statements unissued. meaning: Some(meaning(&query, None)), ..EverythingSearchOptions::default() }, ) .expect("ok"); let calls = driver.calls(); assert_eq!( calls.len(), 31, "29 text statements, then the two meaning ones" ); assert_eq!(calls[0].sql, sql::TODO); assert_eq!(calls[29].sql, sql::EMBEDDINGS_PRESENT); assert_eq!(calls[30].sql, sql::EMBEDDINGS_SCAN_8); } /// With `lanes` naming the meaning half and no embedded query, the meaning half /// is simply empty. The CALLER says why — the switch is off, nothing is indexed, /// the provider was unreachable — and the engine does not invent a reason it has /// no way to know. #[test] fn the_meaning_lane_without_a_query_vector_asks_nothing() { let driver = Recorder::empty(); let read = search_everything_file( &driver, "payment split", &EverythingSearchOptions { lanes: Some(EverythingLanes::Meaning), ..EverythingSearchOptions::default() }, ) .expect("ok"); assert!(driver.calls().is_empty()); assert!(read.hits.is_empty()); } /// The `kinds` filter reaches the meaning lane too: the scan binds only the /// sources whose kind was asked for. #[test] fn the_meaning_lane_honours_the_kinds_filter() { let driver = Recorder::with(|sql, _| { if sql.contains("sqlite_master") { return vec![row(vec![("name", t("_embeddings"))])]; } if sql.contains("FROM _embeddings") { return every_source_chunk(); } Vec::new() }); let query = vector(1); search_everything_file( &driver, "who", &EverythingSearchOptions { lanes: Some(EverythingLanes::Meaning), kinds: Some(&[EverythingKind::Person, EverythingKind::Document]), meaning: Some(meaning(&query, Some(-1.0))), ..EverythingSearchOptions::default() }, ) .expect("ok"); let calls = driver.calls(); assert_eq!(calls.len(), 4); assert_eq!(calls[1].sql, sql::EMBEDDINGS_SCAN_2); assert_eq!( calls[1].params, text_params(&["m1", "person", "document_page"]) ); assert_eq!(calls[2].sql, sql::HYDRATE_PERSON_1); assert_eq!(calls[3].sql, sql::HYDRATE_DOCUMENT_PAGE_1); } /// A query vector that is not 512 bytes is refused BEFORE either statement runs: /// a caller that handed over the wrong geometry must not cost two round trips /// before it is told. #[test] fn a_wrong_sized_query_vector_is_refused_before_any_statement() { let driver = Recorder::empty(); let short = vec![1u8; 8]; let error = search_everything_file( &driver, "payment split", &EverythingSearchOptions { lanes: Some(EverythingLanes::Meaning), meaning: Some(meaning(&short, None)), ..EverythingSearchOptions::default() }, ) .expect_err("a refusal"); assert!(driver.calls().is_empty()); assert_eq!( error.to_string(), "semantic query vector is 8 bytes, expected 512" ); } // ── the row → hit mapping, every expected value read out of Node ───────────── fn titles(read: &EverythingSearchRead) -> Vec> { read.hits.iter().map(|hit| hit.title.as_deref()).collect() } fn snippets(read: &EverythingSearchRead) -> Vec> { read.hits.iter().map(|hit| hit.snippet.as_deref()).collect() } fn todo_row(id: &str, rank: f64, snippet: &str, title: SqlValue, status: &str) -> SearchRow { row(vec![ ("d_id", t(id)), ("d_rank", n(rank)), ("d_snippet", t(snippet)), ("d_title", title), ("d_status", t(status)), ("d_when", NUL), ]) } /// A finished life says so instead of hiding: `done` and `dropped` are struck, /// and nothing else is. #[test] fn a_todo_is_struck_by_its_status() { let read = one_lane( &[EverythingKind::Todo], vec![ row(vec![ ("d_id", t("t1")), ("d_rank", n(-1.5)), ("d_snippet", t("book …bali… flights")), ("d_title", t("book bali flights")), ("d_status", t("open")), ("d_when", t("2026-08-20T00:00:00.000Z")), ]), todo_row("t2", -2.0, "visa", t("bali visa forms"), "done"), todo_row("t3", -3.0, "x", t("dropped one"), "dropped"), todo_row("t4", -4.0, "x", t(""), "archived"), ], ); assert_eq!(ids(&read), ["t1", "t2", "t3", "t4"]); assert_eq!( read.hits.iter().map(|hit| hit.struck).collect::>(), [false, true, true, false] ); assert_eq!(read.hits[0].rank, -1.5); assert_eq!( read.hits[0].when.as_deref(), Some("2026-08-20T00:00:00.000Z") ); // `str()` maps an EMPTY title to none — a `NULLIF` that did not fold must // not become a title of nothing. assert_eq!(read.hits[3].title, None); // The snippet that only restates the title is dropped; the two that say // something else are kept. assert_eq!(snippets(&read), [None, None, Some("x"), Some("x")]); assert_eq!(read.totals.get(EverythingSection::Todo), Some(4)); } fn note_row( id: &str, rank: f64, snippet: SqlValue, title: SqlValue, body: &str, kind: &str, ) -> SearchRow { row(vec![ ("d_id", t(id)), ("d_rank", n(rank)), ("d_snippet", snippet), ("d_title", title), ("d_body", t(body)), ("d_kind", t(kind)), ("d_when", NUL), ]) } /// `firstLine` — twelve readings out of Node, including the 79/80/81-unit /// boundary, an emoji, a leading BOM (trimmed) and a leading NEL (NOT trimmed). #[test] fn a_note_is_titled_by_its_first_line_when_it_has_no_title() { let x81 = "x".repeat(81); let x80 = "x".repeat(80); let x79 = "x".repeat(79); let split = format!("{}\u{1f6a2}tail", "y".repeat(78)); let read = one_lane( &[EverythingKind::Note], vec![ note_row( "n1", -1.0, t("the …bali… leg"), t("trip planning"), "b", "note", ), note_row("n2", -2.0, t("dreamt"), NUL, "dreamt about bali", "journal"), note_row("n3", -3.0, t("s"), NUL, " first line \nsecond", "note"), note_row("n4", -4.0, t("s"), NUL, &x81, "note"), note_row("n5", -5.0, t("s"), NUL, &x80, "note"), note_row("n6", -6.0, t("s"), NUL, &x79, "note"), note_row("n7", -7.0, t("s"), NUL, &split, "note"), note_row("n8", -8.0, t("s"), NUL, "\n\nafter blanks", "note"), note_row("n9", -9.0, t("s"), NUL, " ", "note"), note_row("n10", -10.0, t("s"), NUL, "🚢🚢 ferry day", "note"), note_row("n11", -11.0, t("s"), NUL, "\u{feff}bom leading", "note"), note_row("n12", -12.0, t("s"), NUL, "\u{85}nel leading", "note"), ], ); assert_eq!( titles(&read), [ Some("trip planning"), // A journal page has no name of its own — the caller words it by its // date. None, Some("first line"), Some(&format!("{}…", "x".repeat(79))[..]), Some(&x80[..]), Some(&x79[..]), // THE ONE DIVERGENCE: JavaScript's cut lands inside the surrogate // pair and keeps the lone high surrogate (`\ud83d…`); a Rust // `String` cannot hold one, so `from_utf16_lossy` writes U+FFFD. // Both are 80 UTF-16 units long. Some(&format!("{}\u{fffd}…", "y".repeat(78))[..]), None, None, Some("🚢🚢 ferry day"), // JavaScript trims the BOM… Some("bom leading"), // …and does NOT trim the NEL. `str::trim` has both backwards. Some("\u{85}nel leading"), ] ); assert!(read.hits[1].journal, "a journal page says so"); assert!(!read.hits[0].journal); } /// `snippetUnlessTitle` — ten readings out of Node. #[test] fn a_snippet_that_only_restates_its_title_is_dropped() { let read = one_lane( &[EverythingKind::Note], vec![ note_row( "s1", -1.0, t("…trip planning…"), t("Trip Planning today"), "", "note", ), note_row("s2", -2.0, t("………"), t("anything"), "", "note"), note_row("s3", -3.0, t(" "), t("anything"), "", "note"), note_row( "s4", -4.0, t("quite other words"), t("anything"), "", "note", ), // `toLocaleLowerCase` folds the dotted capital İ to `i` + U+0307, // and `str::to_lowercase` agrees — the vector is what proves it. note_row( "s5", -5.0, t("İSTANBUL"), t("the i\u{307}stanbul plan"), "", "note", ), // The sharp s does NOT fold to `ss` in either runtime, so this // snippet is kept. note_row("s6", -6.0, t("STRASSE"), t("die straße"), "", "note"), note_row("s7", -7.0, t("\u{feff}bom"), NUL, "", "note"), note_row("s8", -8.0, t("\u{85}"), t("x"), "", "note"), note_row("s9", -9.0, NUL, t("x"), "", "note"), note_row("s10", -10.0, t(""), t("x"), "", "note"), ], ); assert_eq!( snippets(&read), [ None, // Ellipses and nothing else fold to an empty bare string. None, None, Some("quite other words"), None, Some("STRASSE"), // The BOM is trimmed for the COMPARISON and kept in the answer. Some("\u{feff}bom"), // A NEL is not whitespace in JavaScript, so this bare string is one // character long and the snippet survives. Some("\u{85}"), None, None, ] ); } /// `firstSentence` — twelve readings out of Node. A picture always has SOMETHING /// to be called: the caption, else the first sentence of the description, else /// the plain word. #[test] fn a_photo_is_its_caption_then_its_first_sentence_then_the_plain_word() { let bodies: [SqlValue; 12] = [ t("Two people by a lake. It is raining."), t("Two people by a lake. It is raining."), NUL, t("No punctuation at all"), t("Wow! Really."), t("A.B is one token. Then this."), t("Ends here?"), t(" "), t("Sentence one.\u{a0}Two."), t("Sentence one.\u{feff}Two."), t("Sentence one.\u{85}Two."), t("🚢 sails on. Then rain."), ]; let rows: Vec = bodies .iter() .enumerate() .map(|(at, body)| { row(vec![ ("d_id", t(&format!("ph{}", at + 1))), ("d_rank", n(-(at as f64 + 1.0))), ("d_snippet", t("sn")), ("d_title", if at == 0 { t("At the lake") } else { NUL }), ("d_body", body.clone()), ("d_when", NUL), ]) }) .collect(); let read = one_lane(&[EverythingKind::Photo], rows); assert_eq!( titles(&read), [ Some("At the lake"), Some("Two people by a lake."), Some("A photo"), Some("No punctuation at all"), Some("Wow!"), // A full stop with a letter after it is not a sentence end. Some("A.B is one token."), Some("Ends here?"), Some("A photo"), // NBSP and the BOM are both JavaScript whitespace… Some("Sentence one."), Some("Sentence one."), // …and U+0085 is not, so this whole description is one sentence. Some("Sentence one.\u{85}Two."), Some("🚢 sails on."), ] ); assert_eq!( snippets(&read), [ Some("Two people by a lake. It is raining."), Some("Two people by a lake. It is raining."), None, None, Some("Wow! Really."), Some("A.B is one token. Then this."), None, None, Some("Sentence one.\u{a0}Two."), Some("Sentence one.\u{feff}Two."), None, Some("🚢 sails on. Then rain."), ] ); } /// A video is the photo's lane exactly, over its own index — down to the plain /// word, which is its own. #[test] fn a_video_says_a_video_when_nothing_named_it() { let read = one_lane( &[EverythingKind::Video], vec![ row(vec![ ("d_id", t("v1")), ("d_rank", n(-1.0)), ("d_snippet", t("sn")), ("d_title", NUL), ("d_body", NUL), ("d_when", NUL), ]), row(vec![ ("d_id", t("v2")), ("d_rank", n(-2.0)), ("d_snippet", t("sn")), ("d_title", t("Clip")), ("d_body", t("A clip. Of things.")), ("d_when", t("2026-05-05")), ]), ], ); assert_eq!(titles(&read), [Some("A video"), Some("Clip")]); assert_eq!(snippets(&read), [None, Some("A clip. Of things.")]); } /// A message on the bus is titled by its first line too, and a withdrawn one is /// out of the one search surface while it stays in the queue as the audit trail. #[test] fn a_session_message_is_titled_by_its_first_line() { let read = one_lane( &[EverythingKind::SessionMessage], vec![row(vec![ ("d_id", t("sm1")), ("d_rank", n(-1.0)), ("d_snippet", t("sn")), ("d_body", t("hello there\nmore")), ("d_kind", t("note")), ("d_when", t("2026-09-03T09:00:00.000Z")), ])], ); assert_eq!(titles(&read), [Some("hello there")]); assert!(sql::SESSION_MESSAGE.contains("AND t.status <> 'withdrawn'")); } /// A document hit carries the page the best match was on; a null page means the /// profile matched. #[test] fn a_document_hit_carries_its_best_page() { let read = one_lane( &[EverythingKind::Document], vec![ row(vec![ ("d_id", t("d1")), ("d_rank", n(-1.25)), ("d_snippet", t("…lease…")), ("d_page", SqlValue::Integer(3)), ("d_title", t("The lease")), ]), row(vec![ ("d_id", t("d2")), ("d_rank", n(-2.0)), ("d_snippet", t("sn")), ("d_page", NUL), ("d_title", NUL), ]), ], ); assert_eq!( read.hits.iter().map(|hit| hit.page).collect::>(), [Some(3), None] ); assert_eq!(titles(&read), [Some("The lease"), None]); assert_eq!(snippets(&read), [None, Some("sn")]); assert_eq!(read.hits[0].rank, -1.25); } /// A session is named by its SUMMARY before its title: the title is minted, the /// summary is what the session was about. #[test] fn a_session_is_named_by_its_summary_before_its_title() { let read = one_lane( &[EverythingKind::Session], vec![ row(vec![ ("d_id", t("se1")), ("d_rank", n(-1.0)), ("d_snippet", t("sn")), ("d_title", t("Session one")), ("d_summary", t("what we did\nand then")), ("d_when", t("2026-06-06")), ]), row(vec![ ("d_id", t("se2")), ("d_rank", n(-2.0)), ("d_snippet", t("sn")), ("d_title", t("Session two")), ("d_summary", NUL), ("d_when", NUL), ]), row(vec![ ("d_id", t("se3")), ("d_rank", n(-3.0)), ("d_snippet", t("sn")), ("d_title", NUL), ("d_summary", NUL), ("d_when", NUL), ]), ], ); assert_eq!( titles(&read), [Some("what we did"), Some("Session two"), None] ); assert_eq!(read.hits[0].when.as_deref(), Some("2026-06-06")); } /// A message hit carries its thread and its anchor — where to open the /// conversation, and where in it. And it is the ONE lane that keeps a snippet /// repeating its own title: the matched line of the body is what answered the /// search. #[test] fn a_message_hit_carries_its_thread_and_anchor() { let read = one_lane( &[EverythingKind::Message], vec![ row(vec![ ("d_id", t("ms1")), ("d_thread", t("th1")), ("d_when", t("2026-08-22T10:00:00.000Z")), ("d_rank", n(-1.0)), ("d_snippet", t("the …bali… pool villa")), ("d_title", t("Bali Homestay")), ]), row(vec![ ("d_id", t("ms2")), ("d_thread", t("th2")), ("d_when", NUL), ("d_rank", n(-2.0)), ("d_snippet", t("Bali Homestay")), ("d_title", t("Bali Homestay")), ]), ], ); assert_eq!(read.hits[0].thread_id.as_deref(), Some("th1")); assert_eq!( read.hits[0].sent_at.as_deref(), Some("2026-08-22T10:00:00.000Z") ); assert_eq!(read.hits[0].when, read.hits[0].sent_at); assert_eq!( titles(&read), [Some("Bali Homestay"), Some("Bali Homestay")] ); assert_eq!( snippets(&read), [Some("the …bali… pool villa"), Some("Bali Homestay")] ); assert_eq!(read.totals.get(EverythingSection::Message), Some(2)); } /// An email hit is the message hit's shape — `threadId` + `sentAt` route the /// follow-up to `read_email_thread`, because the reader is addressed by thread /// and never by email id. Its snippet DOES drop a restated subject. #[test] fn an_email_hit_is_addressed_by_its_thread() { let read = one_lane( &[EverythingKind::Email], vec![ row(vec![ ("d_id", t("em1")), ("d_thread", t("et1")), ("d_when", t("2026-08-22T10:00:00.000Z")), ("d_rank", n(-1.0)), ("d_snippet", t("…re: bali…")), ("d_title", t("Re: bali")), ]), row(vec![ ("d_id", t("em2")), ("d_thread", t("et2")), ("d_when", NUL), ("d_rank", n(-2.0)), ("d_snippet", t("re: bali")), ("d_title", t("Re: BALI")), ]), ], ); assert_eq!(read.hits[0].thread_id.as_deref(), Some("et1")); assert_eq!(snippets(&read), [None, None]); assert_eq!(read.totals.get(EverythingSection::Email), Some(2)); } /// A chat matched by NAME answers as a `thread`, ranks 0, and lands in the /// MESSAGE section — the name you typed is usually the conversation you meant. #[test] fn a_thread_answers_in_the_message_section() { let read = one_lane( &[EverythingKind::Thread], vec![ row(vec![ ("d_id", t("t1")), ("d_title", t("Bali Homestay")), ("d_when", t("2026-08-22T10:00:00.000Z")), ]), row(vec![("d_id", t("t2")), ("d_title", NUL), ("d_when", NUL)]), ], ); assert_eq!( kinds(&read), [EverythingKind::Thread, EverythingKind::Thread] ); assert_eq!(read.hits[0].rank, 0.0); assert_eq!(read.hits[0].thread_id.as_deref(), Some("t1")); assert_eq!(read.hits[1].thread_id.as_deref(), Some("t2")); assert_eq!(snippets(&read), [None, None]); assert_eq!(read.totals.get(EverythingSection::Message), Some(2)); assert_eq!(read.totals.get(EverythingSection::Email), None); } #[test] fn an_email_thread_answers_in_the_email_section() { let read = one_lane( &[EverythingKind::EmailThread], vec![row(vec![ ("d_id", t("et1")), ("d_title", t("Bali trip")), ("d_when", t("2026-08-22T10:00:00.000Z")), ])], ); assert_eq!(read.hits[0].kind, EverythingKind::EmailThread); assert_eq!(read.hits[0].thread_id.as_deref(), Some("et1")); assert_eq!(read.totals.get(EverythingSection::Email), Some(1)); } /// A transaction falls back to the first line of its notes for a title, and /// keeps that line as a snippet only when it is not already the title. #[test] fn a_transaction_falls_back_to_its_notes() { let read = one_lane( &[EverythingKind::Transaction], vec![ row(vec![ ("d_id", t("tx1")), ("d_title", t("bali hotel deposit")), ("d_notes", t("paid by card\nsecond")), ("d_when", t("2026-08-18")), ]), row(vec![ ("d_id", t("tx2")), ("d_title", NUL), ("d_notes", t("only notes here")), ("d_when", NUL), ]), row(vec![ ("d_id", t("tx3")), ("d_title", NUL), ("d_notes", NUL), ("d_when", NUL), ]), row(vec![ ("d_id", t("tx4")), ("d_title", t("same words")), ("d_notes", t("same words")), ("d_when", NUL), ]), ], ); assert_eq!( titles(&read), [ Some("bali hotel deposit"), Some("only notes here"), None, Some("same words"), ] ); assert_eq!(snippets(&read), [Some("paid by card"), None, None, None]); assert_eq!(read.hits[0].rank, 0.0); } /// The handle IS the call's title — core mints no English, and a reader that /// knows the person puts their name here instead. A missed call is NOT struck: /// it happened, and striking it would read as "cancelled". #[test] fn the_handle_is_a_calls_title_and_a_missed_call_is_not_struck() { let read = one_lane( &[EverythingKind::Call], vec![ row(vec![ ("d_id", t("c1")), ("d_handle", t("919812345678")), ("d_provider", t("cellular")), ("d_direction", t("out")), ("d_outcome", t("missed")), ("d_when", t("2026-09-01T09:00:00.000Z")), ]), row(vec![ ("d_id", t("c2")), ("d_handle", NUL), ("d_provider", NUL), ("d_direction", t("in")), ("d_outcome", t("answered")), ("d_when", NUL), ]), ], ); assert_eq!(titles(&read), [Some("919812345678"), None]); assert_eq!(snippets(&read), [None, None]); assert!(read.hits.iter().all(|hit| !hit.struck)); // `provider` is deliberately not in the haystack: typing "cellular" would // return a year of calls in no order anybody meant. assert!(!sql::CALL_SCAN_1.contains("t.provider LIKE")); } /// The four lanes whose whole mapping is "the title column, and sometimes a /// moment". #[test] fn the_plain_lanes_map_a_title_and_a_moment() { let event = one_lane( &[EverythingKind::Event], vec![row(vec![ ("d_id", t("e1")), ("d_rank", n(-1.0)), ("d_snippet", t("sn")), ("d_title", t("Bali flight")), ("d_when", t("2026-08-22T10:00:00.000Z")), ])], ); assert_eq!(titles(&event), [Some("Bali flight")]); assert_eq!( event.hits[0].when.as_deref(), Some("2026-08-22T10:00:00.000Z") ); for (kind, id, title) in [ (EverythingKind::Person, "pe1", "Meera"), (EverythingKind::Memory, "mem1", "Bali stays a holiday"), ] { let read = one_lane( &[kind], vec![row(vec![ ("d_id", t(id)), ("d_rank", n(-1.0)), ("d_snippet", t("sn")), ("d_title", t(title)), ])], ); assert_eq!(titles(&read), [Some(title)], "{kind}"); assert!(read.hits[0].when.is_none(), "{kind}"); assert_eq!(snippets(&read), [Some("sn")], "{kind}"); } } // ── the lane inside `searchEverythingFile` ─────────────────────────────────── // // These cases belong here rather than beside the semantic lane: every one of // them is a statement about THIS module. /// A fixture for the meaning lane: text rows keyed by their FTS table, chunk /// rows, and hydrate rows keyed by the domain table. struct Meaning { text: Vec<(&'static str, Vec)>, chunks: Vec, hydrate: Vec<(&'static str, Vec)>, } impl Meaning { fn driver(self) -> Recorder { Recorder::with(move |sql, _| { if sql.contains("sqlite_master") { return vec![row(vec![("name", t("_embeddings"))])]; } if sql.contains("FROM _embeddings") { return self.chunks.clone(); } if sql.contains("AS d_key") { return self .hydrate .iter() .find(|(table, _)| sql.contains(&format!("FROM {table} t"))) .map(|(_, rows)| rows.clone()) .unwrap_or_default(); } self.text .iter() .find(|(fts, _)| sql.contains(&format!("FROM {fts}\n"))) .map(|(_, rows)| rows.clone()) .unwrap_or_default() }) } } fn note_hydrate_row(key: &str, id: &str, title: SqlValue) -> SearchRow { row(vec![ ("d_key", t(key)), ("d_id", t(id)), ("d_title", title), ("d_body", t("")), ("d_kind", t("note")), ("d_when", NUL), ]) } fn run_meaning( fixture: Meaning, query: &str, lanes: EverythingLanes, wanted: &[EverythingKind], min_score: Option, per_kind: Option, ) -> EverythingSearchRead { let driver = fixture.driver(); let vector = vector(1); search_everything_file( &driver, query, &EverythingSearchOptions { per_kind, kinds: Some(wanted), lanes: Some(lanes), meaning: Some(meaning(&vector, min_score)), mail_index: None, offset: 0, as_sections: false, }, ) .expect("ok") } /// Finds a note that shares no word with the query, marked as such. No FTS /// snippet exists for a match that quotes nothing — the stored head stands in, /// and is dropped when it only restates the title. #[test] fn finds_a_note_that_shares_no_word_with_the_query_marked_as_such() { let read = run_meaning( Meaning { text: vec![], chunks: vec![chunk_row("note", "n1", 3, "we agreed on half each")], hydrate: vec![( "cotton_notes", vec![note_hydrate_row("n1", "n1", t("we agreed on half each"))], )], }, "payment split", EverythingLanes::Meaning, &[EverythingKind::Note], Some(-1.0), None, ); assert_eq!(read.hits.len(), 1); assert_eq!(read.hits[0].kind, EverythingKind::Note); assert_eq!(read.hits[0].id, "n1"); assert_eq!( read.hits[0].title.as_deref(), Some("we agreed on half each") ); assert_eq!(read.hits[0].matched_by, Some(MatchedBy::Meaning)); assert_eq!(read.hits[0].snippet, None); assert_eq!(read.hits[0].rank, SCORE_3); // `totals` is deliberately untouched by the meaning lane: a brute-force scan // holds a similarity for EVERY row, so the honest "how many more" is the // whole database, which tells a reader nothing. assert!(read.totals.is_empty()); } /// The stored head is a snippet when it says something the title does not, and /// nothing when it is blank. #[test] fn the_stored_head_stands_in_for_a_snippet() { let says_more = run_meaning( Meaning { text: vec![], chunks: vec![chunk_row("note", "n1", 3, " the tiles arrive tuesday ")], hydrate: vec![( "cotton_notes", vec![note_hydrate_row("n1", "n1", t("half each"))], )], }, "payment split", EverythingLanes::Meaning, &[EverythingKind::Note], Some(-1.0), None, ); assert_eq!( says_more.hits[0].snippet.as_deref(), Some("the tiles arrive tuesday") ); let blank = run_meaning( Meaning { text: vec![], chunks: vec![chunk_row("note", "n1", 3, " ")], hydrate: vec![( "cotton_notes", vec![note_hydrate_row("n1", "n1", t("half each"))], )], }, "payment split", EverythingLanes::Meaning, &[EverythingKind::Note], Some(-1.0), None, ); assert_eq!(blank.hits[0].snippet, None); } /// A row can make several chunks; the best one wins, and its head is the one /// that shows. #[test] fn the_best_chunk_of_a_row_is_the_one_that_answers() { let lower = chunk_row("note", "n1", 2, "lower head"); let higher = row(vec![ ("source", t("note")), ("row_id", t("n1")), ("chunk_ix", SqlValue::Integer(1)), ("vec", SqlValue::Blob(vector(5))), ("text_head", t("higher head")), ]); let read = run_meaning( Meaning { text: vec![], chunks: vec![lower, higher], hydrate: vec![("cotton_notes", vec![note_hydrate_row("n1", "n1", NUL)])], }, "payment split", EverythingLanes::Meaning, &[EverythingKind::Note], Some(-1.0), None, ); assert_eq!(read.hits.len(), 1); assert_eq!(read.hits[0].snippet.as_deref(), Some("higher head")); assert_eq!(read.hits[0].rank, SCORE_5); } /// Ranked best-first and capped at `perKind` — nearest LAST in the fixture, so /// an accidental insertion order cannot pass this. #[test] fn the_meaning_lane_ranks_best_first_and_keeps_the_per_kind_cap() { let fixture = || Meaning { text: vec![], chunks: vec![ chunk_row("note", "a", 2, "a"), chunk_row("note", "b", 6, "b"), chunk_row("note", "c", 4, "c"), ], hydrate: vec![( "cotton_notes", vec![ note_hydrate_row("a", "a", t("A")), note_hydrate_row("b", "b", t("B")), note_hydrate_row("c", "c", t("C")), ], )], }; let all = run_meaning( fixture(), "payment split", EverythingLanes::Meaning, &[EverythingKind::Note], Some(-1.0), None, ); assert_eq!(ids(&all), ["b", "c", "a"]); assert_eq!(all.hits[0].rank, SCORE_6); assert_eq!(all.hits[1].rank, SCORE_4); assert_eq!(all.hits[2].rank, SCORE_2); let capped = run_meaning( fixture(), "payment split", EverythingLanes::Meaning, &[EverythingKind::Note], Some(-1.0), Some(2), ); assert_eq!(ids(&capped), ["b", "c"]); } /// Hides a record the text lane would hide — one visibility rule. /// /// The indexer keeps a vector until its next reconcile pass; the SEARCH is the /// strict one, and that window is exactly why. The filter is in the hydrate /// statement, so an archived note answers no row and therefore no hit. #[test] fn hides_a_record_the_text_lane_would_hide() { let read = run_meaning( Meaning { text: vec![], chunks: vec![chunk_row("note", "gone", 3, "head")], // The statement's `AND t.trashed_at IS NULL` matched nothing. hydrate: vec![("cotton_notes", vec![])], }, "anything", EverythingLanes::Meaning, &[EverythingKind::Note], Some(-1.0), None, ); assert!(read.hits.is_empty()); assert!(sql::HYDRATE_NOTE_1.contains("AND t.trashed_at IS NULL")); // And every derived lane's filter is its text lane's, character for // character — that is what makes drift unspellable. for lane in SEMANTIC_LANES.iter() { if let Some(text) = fts_lane(lane.kind) { if lane.source != "document_page" { assert_eq!(lane.where_clause, text.where_clause, "{}", lane.source); assert_eq!(lane.archived, text.archived, "{}", lane.source); } } } } /// Puts exact hits before related ones inside the same kind, and never lists one /// record twice when both lanes find it. #[test] fn exact_hits_come_before_related_ones_and_no_record_is_listed_twice() { let read = run_meaning( Meaning { text: vec![( "fts_notes", vec![note_row( "exact", 1.5, t("sn"), t("ferry timings"), "", "note", )], )], chunks: vec![ chunk_row("note", "exact", 6, "ferry timings"), chunk_row("note", "related", 3, "the boat leaves at six"), ], hydrate: vec![( "cotton_notes", vec![ note_hydrate_row("exact", "exact", t("ferry timings")), note_hydrate_row("related", "related", t("the boat leaves at six")), ], )], }, "ferry", EverythingLanes::Both, &[EverythingKind::Note], Some(-1.0), None, ); assert_eq!(ids(&read), ["exact", "related"]); assert_eq!(read.hits[0].matched_by, None); assert_eq!(read.hits[1].matched_by, Some(MatchedBy::Meaning)); assert_eq!(read.hits[1].rank, SCORE_3); // The text lane's total stands; the meaning lane adds none. assert_eq!(read.totals.get(EverythingSection::Note), Some(1)); } /// Related hits are spliced after their OWN kind's run, not appended at the end /// — the flat array stays grouped for a caller that renders it in order. #[test] fn related_hits_are_spliced_after_their_own_kinds_run() { let read = run_meaning( Meaning { text: vec![ ( "fts_notes", vec![note_row( "n-exact", 1.5, t("sn"), t("ferry timings"), "", "note", )], ), ( "fts_people", vec![row(vec![ ("d_id", t("p-exact")), ("d_rank", n(2.5)), ("d_snippet", t("sn")), ("d_title", t("Ravi")), ])], ), ], chunks: vec![chunk_row("note", "n-rel", 4, "the boat leaves at six")], hydrate: vec![( "cotton_notes", vec![note_hydrate_row( "n-rel", "n-rel", t("the boat leaves at six"), )], )], }, "ferry", EverythingLanes::Both, &[EverythingKind::Note, EverythingKind::Person], Some(-1.0), None, ); assert_eq!(ids(&read), ["n-exact", "n-rel", "p-exact"]); assert_eq!( kinds(&read), [ EverythingKind::Note, EverythingKind::Note, EverythingKind::Person ] ); assert_eq!(read.hits[1].rank, SCORE_4); } /// A kind the text lane found nothing for answers on its own, after every text /// run. #[test] fn a_meaning_only_kind_lands_after_every_text_run() { let read = run_meaning( Meaning { text: vec![( "fts_notes", vec![note_row( "exact", 1.5, t("sn"), t("ferry timings"), "", "note", )], )], chunks: vec![chunk_row("person", "p1", 4, "Meera runs the yard")], hydrate: vec![( "cotton_people", vec![row(vec![ ("d_key", t("p1")), ("d_id", t("p1")), ("d_title", t("Meera")), ])], )], }, "ferry", EverythingLanes::Both, &[EverythingKind::Note, EverythingKind::Person], Some(-1.0), None, ); assert_eq!(ids(&read), ["exact", "p1"]); assert_eq!(read.hits[1].kind, EverythingKind::Person); assert_eq!(read.hits[1].snippet.as_deref(), Some("Meera runs the yard")); assert_eq!(read.hits[1].matched_by, Some(MatchedBy::Meaning)); } /// Two text hits of one kind, then that kind's related one — the splice looks at /// the END of a run, not at every row. #[test] fn a_related_hit_follows_the_whole_run_of_its_kind() { let read = run_meaning( Meaning { text: vec![( "fts_notes", vec![ note_row("a", 1.5, t("sn"), t("one"), "", "note"), note_row("b", 1.5, t("sn"), t("two"), "", "note"), ], )], chunks: vec![chunk_row("note", "c", 4, "three")], hydrate: vec![("cotton_notes", vec![note_hydrate_row("c", "c", t("three"))])], }, "ferry", EverythingLanes::Both, &[EverythingKind::Note], Some(-1.0), None, ); assert_eq!(ids(&read), ["a", "b", "c"]); assert_eq!(read.hits[2].matched_by, Some(MatchedBy::Meaning)); assert_eq!(read.totals.get(EverythingSection::Note), Some(2)); } /// Folds a document's pages to one hit on its best page. #[test] fn a_documents_pages_fold_to_one_hit_on_its_best_page() { let pages = |best_is_page_two: bool| Meaning { text: vec![], chunks: vec![ chunk_row( "document_page", "pg1", if best_is_page_two { 2 } else { 6 }, "page one", ), chunk_row( "document_page", "pg2", if best_is_page_two { 6 } else { 2 }, "page two", ), ], hydrate: vec![( "cotton_document_pages", vec![ row(vec![ ("d_key", t("pg1")), ("d_id", t("d1")), ("d_page", SqlValue::Integer(1)), ("d_title", t("The lease")), ]), row(vec![ ("d_key", t("pg2")), ("d_id", t("d1")), ("d_page", SqlValue::Integer(2)), ("d_title", t("The lease")), ]), ], )], }; let second = run_meaning( pages(true), "what did we agree", EverythingLanes::Meaning, &[EverythingKind::Document], Some(-1.0), None, ); assert_eq!(second.hits.len(), 1); assert_eq!(second.hits[0].kind, EverythingKind::Document); assert_eq!(second.hits[0].id, "d1"); assert_eq!(second.hits[0].page, Some(2)); assert_eq!(second.hits[0].snippet.as_deref(), Some("page two")); // And the fold does not simply take the LAST row: with page one the closer, // the held hit wins. let first = run_meaning( pages(false), "what did we agree", EverythingLanes::Meaning, &[EverythingKind::Document], Some(-1.0), None, ); assert_eq!(first.hits.len(), 1); assert_eq!(first.hits[0].page, Some(1)); assert_eq!(first.hits[0].snippet.as_deref(), Some("page one")); } /// Answers nothing, and does not fail, when the file holds no vectors — the /// ordinary state of a database whose owner never turned this on. The text lane /// still answers. #[test] fn answers_nothing_and_does_not_fail_when_the_file_holds_no_vectors() { let driver = Recorder::with(|sql, _| { if sql.contains("sqlite_master") { // No row: `_embeddings` is not in this file. Being SEARCHED must not // create it. return Vec::new(); } if sql.contains("FROM fts_notes\n") { return vec![note_row("n1", 1.5, t("sn"), t("ferry timings"), "", "note")]; } Vec::new() }); let vector = vector(1); let read = search_everything_file( &driver, "ferry", &EverythingSearchOptions { kinds: Some(&[EverythingKind::Note]), lanes: Some(EverythingLanes::Both), meaning: Some(meaning(&vector, Some(-1.0))), ..EverythingSearchOptions::default() }, ) .expect("ok"); assert_eq!(ids(&read), ["n1"]); assert_eq!(read.hits[0].matched_by, None); let issued = driver.statements(); assert_eq!(issued.len(), 2, "the note lane, then the presence probe"); assert_eq!(issued[1], sql::EMBEDDINGS_PRESENT); assert!( !issued.iter().any(|sql| sql.contains("FROM _embeddings")), "no scan over a table that is not there" ); } /// Runs no text lane at all in meaning mode: the note says the word and still /// does not answer, because nothing is indexed. #[test] fn runs_no_text_lane_at_all_in_meaning_mode() { let read = run_meaning( Meaning { text: vec![( "fts_notes", vec![note_row("n1", 1.5, t("sn"), t("ferry timings"), "", "note")], )], chunks: vec![], hydrate: vec![], }, "ferry", EverythingLanes::Meaning, &[EverythingKind::Note], Some(-1.0), None, ); assert!(read.hits.is_empty()); } /// The floor keeps a distant chunk out. A brute-force scan ALWAYS returns /// something, so a top-k with no floor answers a query about nothing with twenty /// confident-looking rows. #[test] fn the_floor_keeps_a_distant_chunk_out() { let read = run_meaning( Meaning { text: vec![], chunks: vec![chunk_row("note", "n1", 3, "head")], hydrate: vec![("cotton_notes", vec![note_hydrate_row("n1", "n1", t("x"))])], }, "payment split", EverythingLanes::Meaning, &[EverythingKind::Note], Some(0.28), None, ); assert!(read.hits.is_empty(), "0.095 does not clear 0.28"); } /// A message and a thought hydrate into the same hits their text lanes would /// have made — the whole point of deriving the lane from the text one. #[test] fn the_bespoke_meaning_lanes_hydrate_the_text_lanes_hit() { let message = run_meaning( Meaning { text: vec![], chunks: vec![chunk_row("message", "m1", 3, "the pool villa is free")], hydrate: vec![( "cotton_msg_messages", vec![row(vec![ ("d_key", t("m1")), ("d_id", t("m1")), ("d_thread", t("th1")), ("d_when", t("2026-08-22T10:00:00.000Z")), ("d_title", t("Bali Homestay")), ])], )], }, "payment split", EverythingLanes::Meaning, &[EverythingKind::Message], Some(-1.0), None, ); assert_eq!(message.hits[0].title.as_deref(), Some("Bali Homestay")); assert_eq!(message.hits[0].thread_id.as_deref(), Some("th1")); assert_eq!( message.hits[0].sent_at.as_deref(), Some("2026-08-22T10:00:00.000Z") ); assert_eq!( message.hits[0].snippet.as_deref(), Some("the pool villa is free") ); } // ── the helpers, by Node vector ────────────────────────────────────────────── /// `escapeLikePattern` — twelve readings out of Node. Only `\`, `%` and `_` are /// escaped; a quote, a newline and a tab are not, because LIKE does not treat /// them as anything. #[test] fn escape_like_pattern_escapes_the_three_characters_like_cares_about() { let vectors: [(&str, &str); 12] = [ ("", ""), ("plain", "plain"), ("50%", "50\\%"), ("a_b", "a\\_b"), ("c:\\path", "c:\\\\path"), ("100%_off\\now", "100\\%\\_off\\\\now"), ("\\\\", "\\\\\\\\"), ("%%__", "\\%\\%\\_\\_"), ("say \"hi\"", "say \"hi\""), ("🚢%", "🚢\\%"), ("a\nb", "a\nb"), ("tab\there_", "tab\there\\_"), ]; for (input, want) in vectors { assert_eq!(escape_like_pattern(input), want, "{input:?}"); } } /// `firstLine`, called directly — the same twelve readings the note lane pins /// through the engine, plus the empty and absent cases. #[test] fn first_line_cuts_at_eighty_utf16_units() { assert_eq!(first_line(None), None); assert_eq!(first_line(Some("")), None); assert_eq!(first_line(Some(" ")), None); assert_eq!( first_line(Some(" first line \nsecond")).as_deref(), Some("first line") ); assert_eq!(first_line(Some("\n\nafter blanks")), None); assert_eq!( first_line(Some(&"x".repeat(79))).as_deref(), Some(&"x".repeat(79)[..]) ); assert_eq!( first_line(Some(&"x".repeat(80))).as_deref(), Some(&"x".repeat(80)[..]) ); assert_eq!( first_line(Some(&"x".repeat(81))).as_deref(), Some(&format!("{}…", "x".repeat(79))[..]) ); // 40 astral emoji are 80 UTF-16 units and 40 `chars()`: a port that counted // chars would truncate here, and one that counted bytes would truncate at // twenty. let forty = "🚢".repeat(40); assert_eq!(first_line(Some(&forty)).as_deref(), Some(&forty[..])); let forty_one = "🚢".repeat(41); assert_eq!( first_line(Some(&forty_one)).as_deref(), Some(&format!("{}\u{fffd}…", "🚢".repeat(39))[..]) ); assert_eq!(first_line(Some("\u{feff}bom")).as_deref(), Some("bom")); assert_eq!(first_line(Some("\u{85}nel")).as_deref(), Some("\u{85}nel")); } /// `firstSentence`, called directly. #[test] fn first_sentence_stops_at_the_first_full_stop_that_ends_a_sentence() { let vectors: [(Option<&str>, Option<&str>); 12] = [ (None, None), (Some(" "), None), (Some("No punctuation at all"), Some("No punctuation at all")), ( Some("Two people by a lake. It is raining."), Some("Two people by a lake."), ), (Some("Wow! Really."), Some("Wow!")), ( Some("A.B is one token. Then this."), Some("A.B is one token."), ), (Some("Ends here?"), Some("Ends here?")), (Some("Sentence one.\u{a0}Two."), Some("Sentence one.")), (Some("Sentence one.\u{feff}Two."), Some("Sentence one.")), ( Some("Sentence one.\u{85}Two."), Some("Sentence one.\u{85}Two."), ), (Some("🚢 sails on. Then rain."), Some("🚢 sails on.")), (Some("."), Some(".")), ]; for (input, want) in vectors { assert_eq!(first_sentence(input).as_deref(), want, "{input:?}"); } } /// `snippetUnlessTitle`, called directly. #[test] fn snippet_unless_title_drops_a_snippet_that_restates_its_title() { let vectors: [(Option<&str>, Option<&str>, Option<&str>); 10] = [ (None, Some("x"), None), (Some(""), Some("x"), None), (Some("…trip planning…"), Some("Trip Planning today"), None), (Some("………"), Some("anything"), None), (Some(" "), Some("anything"), None), ( Some("quite other words"), Some("anything"), Some("quite other words"), ), (Some("İSTANBUL"), Some("the i\u{307}stanbul plan"), None), (Some("STRASSE"), Some("die straße"), Some("STRASSE")), (Some("\u{feff}bom"), None, Some("\u{feff}bom")), (Some("\u{85}"), Some("x"), Some("\u{85}")), ]; for (snippet, title, want) in vectors { assert_eq!( snippet_unless_title(snippet, title).as_deref(), want, "{snippet:?} under {title:?}" ); } // An empty title is falsy in JavaScript, so the containment test is skipped // rather than run against nothing. assert_eq!( snippet_unless_title(Some("a"), Some("")).as_deref(), Some("a") ); } // ── the vocabulary's own invariants ────────────────────────────────────────── /// Threads answer as Messages, email threads as Email, and every other kind /// answers as itself. #[test] fn section_of_folds_the_two_conversation_kinds_and_nothing_else() { assert_eq!( section_of(EverythingKind::Thread), EverythingSection::Message ); assert_eq!( section_of(EverythingKind::EmailThread), EverythingSection::Email ); for kind in EVERYTHING_KINDS { if matches!(kind, EverythingKind::Thread | EverythingKind::EmailThread) { continue; } assert_eq!(section_of(kind).as_str(), kind.as_str(), "{kind}"); } assert_eq!(EVERYTHING_KINDS.len(), EVERYTHING_SECTIONS.len() + 2); for section in EVERYTHING_SECTIONS { assert!( EverythingKind::parse(section.as_str()).is_some(), "{section} is not a kind" ); } } /// The wire strings round-trip, and an unknown one answers `None` rather than /// guessing. #[test] fn the_vocabulary_parses_by_its_wire_string() { for kind in EVERYTHING_KINDS { assert_eq!(EverythingKind::parse(kind.as_str()), Some(kind)); assert_eq!( serde_json::to_string(&kind).expect("json"), format!("\"{}\"", kind.as_str()) ); } assert_eq!(EverythingKind::parse("mixtape"), None); assert_eq!(EverythingSection::parse("thread"), None); for lanes in [ EverythingLanes::Text, EverythingLanes::Meaning, EverythingLanes::Both, ] { assert_eq!(EverythingLanes::parse(lanes.as_str()), Some(lanes)); } assert_eq!(EverythingLanes::parse("semantic"), None); assert_eq!(EverythingLanes::default(), EverythingLanes::Text); } /// Every embedded source has a meaning lane, and every lane names a real source. /// /// The TypeScript throws at MODULE LOAD; a source added upstream with no lane /// here would not be an error, it would be vectors the indexer spends money on /// that no search can ever reach — a hole that reads to the person as "there is /// none of that". Rust cannot run that loop at compile time, so it is this. #[test] fn every_embed_source_has_a_meaning_lane() { meaning_lane_totality().expect("the lanes and the sources agree"); assert_eq!(SEMANTIC_LANES.len(), EMBED_SOURCES.len()); } /// Every derived meaning lane names a text lane — the `expect` in /// `from_text_lane` is unreachable, and this is what keeps it so. #[test] fn every_derived_meaning_lane_has_a_text_lane() { for source in ["note", "person", "meeting", "memory", "thought"] { let lane = SEMANTIC_LANES .iter() .find(|lane| lane.source == source) .expect("a lane"); let text = fts_lane(lane.kind).expect("its text lane"); assert_eq!(lane.table, text.table, "{source}"); assert_eq!(Some(lane.select), text.select, "{source}"); assert_eq!(lane.where_clause, text.where_clause, "{source}"); } } /// `weights` must name every fts column, ONE FOR ONE with what the index /// actually declares — bm25 assigns by declaration order, so a lane one weight /// short or one long ranks by the wrong column and nobody sees an error. /// /// This used to assert only that the FIRST weight was 0, for the `row_id` /// column every index led with. Version 3 made the indexes external-content and /// that column is gone, which shifted every weight by one position — the exact /// silent re-ranking the paragraph above warns about. So the guard now reads /// the real column list out of `cotton_store::schema::fts::FTS_SOURCES` and /// counts, which is what it should have done all along: it would have caught /// that shift on its own, rather than being edited to match it. /// RULE: Each search lane weights exactly its index's declared columns, so schema changes cannot silently apply relevance weights to the wrong fields. #[test] fn every_fts_lane_weights_exactly_the_columns_its_index_declares() { for lane in &FTS_LANES { let source = cotton_store::schema::fts::fts_source_named(lane.fts) .unwrap_or_else(|| panic!("{} is not an index cotton-store declares", lane.fts)); assert_eq!( lane.weights.len(), source.columns.len(), "{} weights {} column(s) and the index declares {:?}", lane.fts, lane.weights.len(), source.columns ); assert!(!lane.weights.is_empty(), "{}", lane.fts); assert!(lane.fts.starts_with("fts_"), "{}", lane.fts); assert!(lane.table.starts_with("cotton_"), "{}", lane.table); assert!(lane.recency.starts_with("t."), "{}", lane.recency); } // Every lane is a distinct kind, and every one of them is in the declared // vocabulary. for lane in &FTS_LANES { assert_eq!( FTS_LANES .iter() .filter(|other| other.kind == lane.kind) .count(), 1, "{}", lane.kind ); } } /// The snippet width is the app's number, and it is written into every statement /// that asks for one. #[test] fn the_snippet_carries_twelve_words_of_context() { assert_eq!(SNIPPET_TOKENS, 12); assert_eq!(DEFAULT_PER_KIND, 20); for lane in &FTS_LANES { let query = fts_lane_query(lane, "\"x\"", 20); assert!( query .sql .contains(&format!("'…', {SNIPPET_TOKENS}) AS d_snippet")), "{}", lane.fts ); } } /// Hits are ranked WITHIN a kind and never across kinds: the flat array is one /// contiguous run per kind, in the declared lane order, and a caller that groups /// it by kind gets each lane's own ranking untouched. #[test] fn hits_are_grouped_by_kind_in_lane_order_and_never_re_ranked() { let driver = Recorder::with(|sql, _| { if sql.contains("FROM fts_todos\n") { return vec![ todo_row("t1", 9.0, "a", t("A"), "open"), todo_row("t2", 1.0, "b", t("B"), "open"), ]; } if sql.contains("FROM fts_notes\n") { return vec![note_row("n1", 50.0, t("a"), t("N"), "", "note")]; } Vec::new() }); let read = search_everything_file( &driver, "bali", &EverythingSearchOptions { kinds: Some(&[EverythingKind::Note, EverythingKind::Todo]), ..EverythingSearchOptions::default() }, ) .expect("ok"); // The todo lane runs FIRST because that is the declared order — not because // its ranks are bigger, which they are not. assert_eq!(ids(&read), ["t1", "t2", "n1"]); assert_eq!( read.hits.iter().map(|hit| hit.rank).collect::>(), [9.0, 1.0, 50.0] ); } /// `totals` serialises as an object keyed by SECTION, in the order the lanes /// wrote it — a hasher's seed must not decide what an assistant reads first. #[test] fn totals_serialise_in_the_order_the_lanes_wrote_them() { let driver = Recorder::with(|sql, _| { if sql.contains("FROM cotton_msg_threads th") { return vec![row(vec![ ("d_id", t("th1")), ("d_title", t("Bali Homestay")), ("d_when", NUL), ])]; } if sql.contains("FROM fts_messages\n") { return vec![row(vec![ ("d_id", t("ms1")), ("d_thread", t("th1")), ("d_when", NUL), ("d_rank", n(1.0)), ("d_snippet", t("sn")), ("d_title", t("Bali Homestay")), ])]; } if sql.contains("FROM fts_todos\n") { return vec![todo_row("t1", 1.0, "a", t("A"), "open")]; } Vec::new() }); let read = search_everything_file(&driver, "bali", &EverythingSearchOptions::default()).expect("ok"); // One message + one thread, both under `message`. assert_eq!(read.totals.get(EverythingSection::Message), Some(2)); assert_eq!(read.totals.get(EverythingSection::Todo), Some(1)); assert_eq!( serde_json::to_string(&read.totals).expect("json"), "{\"todo\":1,\"message\":2}" ); } /// A hit found by no meaning lane emits no `matchedBy` — a caller written /// before it existed sees exactly what it saw before — and no `storeId`, /// which went with the product lane (Stores, 11 Oct 2026). #[test] fn a_plain_hit_carries_neither_store_id_nor_matched_by() { let read = one_lane( &[EverythingKind::Todo], vec![todo_row("t1", 1.0, "a", t("A"), "open")], ); let json = serde_json::to_value(&read.hits[0]).expect("json"); let object = json.as_object().expect("an object"); assert!(!object.contains_key("storeId")); assert!(!object.contains_key("matchedBy")); // AND NOT THE REPOSITORY ADDRESS EITHER. `repoId`, `number` and `tag` are // a pull's, an issue's and a release's, and a todo carries no key for them // — so the exhaustive list below is unchanged by their arrival, which is // the promise this case makes to every caller written before them. for key in ["repoId", "number", "tag"] { assert!(!object.contains_key(key), "{key}"); } assert_eq!( object.keys().map(String::as_str).collect::>(), [ "kind", "id", "title", "snippet", "rank", "when", "struck", "journal", "threadId", "sentAt", "page" ] ); } /// **A PULL, AN ISSUE AND A RELEASE CARRY THE ADDRESS THEY ARE OPENED AT.** /// /// They are the only kinds in Find that are not reached by their row id: /// `/repos/[id]/pulls/[number]`, `…/issues/[number]`, `…/releases/[tag]`. The /// SQL had `d_repo` and `d_number` selected all along and the mapping dropped /// them, so all three RANKED and READ — the title, the snippet and the moment /// were right there — and then went nowhere at all. #[test] fn a_pull_and_an_issue_carry_their_repository_and_their_number() { for kind in [EverythingKind::Pull, EverythingKind::Issue] { let read = one_lane( &[kind], vec![row(vec![ ("d_id", t("pull-row-1")), ("d_rank", n(1.5)), ("d_snippet", t("the forward")), ("d_title", t("Forward the moved refs")), ("d_state", t("open")), ("d_number", SqlValue::Integer(852)), ("d_repo", t("repo-1")), ("d_when", t("2026-09-20T10:00:00.000Z")), ])], ); let hit = &read.hits[0]; assert_eq!(hit.kind, kind); // The ROW id is still the id — nothing about it changes. assert_eq!(hit.id, "pull-row-1"); assert_eq!(hit.repo_id.as_deref(), Some("repo-1"), "{kind:?}"); assert_eq!(hit.number, Some(852), "{kind:?}"); // A release's field is not a pull's. assert_eq!(hit.tag, None, "{kind:?}"); let json = serde_json::to_value(hit).expect("json"); assert_eq!(json["repoId"], serde_json::json!("repo-1")); assert_eq!(json["number"], serde_json::json!(852)); assert!(json.get("tag").is_none(), "{json}"); } } #[test] fn a_release_carries_its_repository_and_its_tag_rather_than_its_display_title() { let read = one_lane( &[EverythingKind::Release], vec![row(vec![ ("d_id", t("release-row-1")), ("d_tag", t("mac-v0.8.0")), ("d_name", t("CottonDB for Mac 0.8.0")), ("d_repo", t("repo-1")), ("d_draft", n(0.0)), ("d_when", t("2026-09-20T10:00:00.000Z")), ])], ); let hit = &read.hits[0]; assert_eq!(hit.repo_id.as_deref(), Some("repo-1")); assert_eq!(hit.tag.as_deref(), Some("mac-v0.8.0")); // **THE ADDRESS IS NOT READ OFF THE TITLE.** It happens to be the same // string today, and the title is a DISPLAY string somebody may one day // resolve to the release's name — at which point an address read off it // would open nothing. assert_eq!(hit.title.as_deref(), Some("mac-v0.8.0")); assert_eq!(hit.number, None); } #[test] fn a_repository_child_with_no_address_carries_none_rather_than_a_number_that_opens_nothing() { // A row whose `repo_id` or `number` is NULL — a shape the file should not // hold, and the honest answer is a hit that does not open rather than // `/repos//pulls/0`. `SearchRow::number` answers `0.0` for a missing // column, which is why `number_opt` exists. let read = one_lane( &[EverythingKind::Pull], vec![row(vec![ ("d_id", t("pull-row-2")), ("d_rank", n(1.0)), ("d_snippet", t("x")), ("d_title", t("Untethered")), ("d_state", t("open")), ("d_number", NUL), ("d_repo", NUL), ("d_when", NUL), ])], ); let hit = &read.hits[0]; assert_eq!(hit.repo_id, None); assert_eq!(hit.number, None); let json = serde_json::to_value(hit).expect("json"); assert!(json.get("repoId").is_none(), "{json}"); assert!(json.get("number").is_none(), "{json}"); } /// A driver failure is the caller's to shape, and it comes back with the /// driver's own sentence rather than a panic. #[test] fn a_driver_failure_comes_back_as_the_drivers_own_sentence() { struct Broken; impl SearchDriver for Broken { fn all(&self, _: &str, _: &[SqlParam]) -> Result, SearchError> { Err(SearchError::Driver("no such table: fts_todos".to_string())) } } let error = search_everything_file(&Broken, "bali", &EverythingSearchOptions::default()) .expect_err("a failure"); assert_eq!(error.to_string(), "no such table: fts_todos"); } /// `String(row.d_id)` — SQLite hands back an INTEGER for a numeric-looking id, /// and the coercion is not decoration. #[test] fn a_numeric_id_is_coerced_the_way_javascript_coerces_it() { let read = one_lane( &[EverythingKind::Todo], vec![row(vec![ ("d_id", SqlValue::Integer(17)), ("d_rank", SqlValue::Integer(3)), ("d_snippet", t("sn")), ("d_title", t("A")), ("d_status", t("open")), ("d_when", NUL), ])], ); assert_eq!(ids(&read), ["17"]); assert_eq!(read.hits[0].rank, 3.0); // And `num()` answers 0 for anything that is not a number. let text_rank = one_lane( &[EverythingKind::Todo], vec![todo_row("t1", 0.0, "sn", t("A"), "open")], ); assert_eq!(text_rank.hits[0].rank, 0.0); } /// The hydrate statement grows one placeholder per scored row, and the scan /// binds one per source — both captured off the running TypeScript at one, two /// and three. #[test] fn the_id_list_grows_one_placeholder_at_a_time() { let three = Meaning { text: vec![], chunks: vec![ chunk_row("note", "a", 2, "a"), chunk_row("note", "b", 6, "b"), chunk_row("note", "c", 4, "c"), ], hydrate: vec![( "cotton_notes", vec![ note_hydrate_row("a", "a", t("A")), note_hydrate_row("b", "b", t("B")), note_hydrate_row("c", "c", t("C")), ], )], }; let driver = three.driver(); let vector = vector(1); search_everything_file( &driver, "payment split", &EverythingSearchOptions { kinds: Some(&[EverythingKind::Note]), lanes: Some(EverythingLanes::Meaning), meaning: Some(meaning(&vector, Some(-1.0))), ..EverythingSearchOptions::default() }, ) .expect("ok"); let calls = driver.calls(); assert_eq!(calls[1].sql, sql::EMBEDDINGS_SCAN_1); assert_eq!(calls[1].params, text_params(&["m1", "note"])); assert_eq!(calls[2].sql, sql::HYDRATE_NOTE_3); // In the order the SCAN RANKED them — the lane hands its chunks back // best-first per source, and the `IN` list binds them as it met them there. assert_eq!(calls[2].params, text_params(&["b", "c", "a"])); let two = Meaning { text: vec![], chunks: vec![ chunk_row("note", "exact", 6, "ferry timings"), chunk_row("note", "related", 3, "the boat leaves at six"), ], hydrate: vec![( "cotton_notes", vec![ note_hydrate_row("exact", "exact", t("ferry timings")), note_hydrate_row("related", "related", t("the boat leaves at six")), ], )], }; let driver = two.driver(); search_everything_file( &driver, "ferry", &EverythingSearchOptions { kinds: Some(&[EverythingKind::Note]), lanes: Some(EverythingLanes::Meaning), meaning: Some(meaning(&vector, Some(-1.0))), ..EverythingSearchOptions::default() }, ) .expect("ok"); assert_eq!(driver.calls()[2].sql, sql::HYDRATE_NOTE_2); let pages = Meaning { text: vec![], chunks: vec![ chunk_row("document_page", "pg1", 2, "page one"), chunk_row("document_page", "pg2", 6, "page two"), ], hydrate: vec![( "cotton_document_pages", vec![ row(vec![ ("d_key", t("pg1")), ("d_id", t("d1")), ("d_page", SqlValue::Integer(1)), ("d_title", t("The lease")), ]), row(vec![ ("d_key", t("pg2")), ("d_id", t("d1")), ("d_page", SqlValue::Integer(2)), ("d_title", t("The lease")), ]), ], )], }; let driver = pages.driver(); search_everything_file( &driver, "what did we agree", &EverythingSearchOptions { kinds: Some(&[EverythingKind::Document]), lanes: Some(EverythingLanes::Meaning), meaning: Some(meaning(&vector, Some(-1.0))), ..EverythingSearchOptions::default() }, ) .expect("ok"); let calls = driver.calls(); assert_eq!(calls[2].sql, sql::HYDRATE_DOCUMENT_PAGE_2); assert_eq!(calls[2].params, text_params(&["pg2", "pg1"])); } // A search result must use this record's current canonical image, including a clear; // matching another person's name or fetching an avatar later can display the wrong person. #[test] fn person_search_photo_key_is_current_by_id_and_null_when_cleared() { use cotton_store::driver::Driver; use rusqlite::types::Value as StoreValue; use std::rc::Rc; let db = Rc::new(Driver::open_in_memory().unwrap()); for statement in cotton_store::schema::ddl::SCHEMA_DDL { db.exec(statement).unwrap(); } db.exec("INSERT INTO cotton_workspaces (id, name, owner_user_id, created_at) VALUES ('search-fixture', 'Tidewell fixture', 'invented-owner', '2026-10-07'); INSERT INTO cotton_people (id, workspace_id, full_name, avatar_key, created_at, updated_at) VALUES ('person-a', 'search-fixture', 'Mira Tidewell', 'synthetic/mira-a.jpg', '2026-10-07', '2026-10-07'), ('person-b', 'search-fixture', 'Mira Tidewell', 'synthetic/mira-b.jpg', '2026-10-07', '2026-10-07'); INSERT INTO cotton_notes (id, workspace_id, title, created_at, updated_at) VALUES ('note-a', 'search-fixture', 'Mira Tidewell', '2026-10-07', '2026-10-07');").unwrap(); let read_db = Rc::clone(&db); let driver = Recorder::with(move |sql, params| { let params: Vec = params .iter() .map(|value| match value { SqlValue::Null => StoreValue::Null, SqlValue::Text(value) => StoreValue::Text(value.clone()), SqlValue::Integer(value) => StoreValue::Integer(*value), SqlValue::Real(value) => StoreValue::Real(*value), SqlValue::Blob(value) => StoreValue::Blob(value.clone()), }) .collect(); read_db .all(sql, ¶ms) .unwrap() .iter() .map(|row| { SearchRow::new(row.columns().iter().map(|(name, value)| { ( name.clone(), match value { StoreValue::Null => SqlValue::Null, StoreValue::Text(value) => SqlValue::Text(value.clone()), StoreValue::Integer(value) => SqlValue::Integer(*value), StoreValue::Real(value) => SqlValue::Real(*value), StoreValue::Blob(value) => SqlValue::Blob(value.clone()), }, ) })) }) .collect() }); let wanted = [EverythingKind::Person, EverythingKind::Note]; let options = EverythingSearchOptions { kinds: Some(&wanted), ..Default::default() }; let search = || search_everything_file(&driver, "Mira", &options).unwrap(); let key = |read: &EverythingSearchRead, id: &str| { let hit = read.hits.iter().find(|hit| hit.id == id).unwrap(); serde_json::to_value(hit).unwrap().get("photoKey").cloned() }; let read = search(); assert_eq!( key(&read, "person-a"), Some(serde_json::json!("synthetic/mira-a.jpg")) ); assert_eq!( key(&read, "person-b"), Some(serde_json::json!("synthetic/mira-b.jpg")) ); assert_eq!(key(&read, "note-a"), None); let statements = driver.statements(); assert_eq!( statements.len(), 2, "one query per uncapped lane; no avatar lookup" ); assert!( !serde_json::to_value(read.hits.iter().find(|hit| hit.id == "person-a").unwrap()) .unwrap() .as_object() .unwrap() .contains_key("photo_key") ); db.exec("UPDATE cotton_people SET avatar_key = 'synthetic/mira-new.jpg' WHERE id = 'person-a'") .unwrap(); assert_eq!( key(&search(), "person-a"), Some(serde_json::json!("synthetic/mira-new.jpg")) ); db.exec("UPDATE cotton_people SET avatar_key = NULL WHERE id = 'person-a'") .unwrap(); let cleared = search(); assert_eq!(key(&cleared, "person-a"), Some(serde_json::Value::Null)); assert_eq!( key(&cleared, "person-b"), Some(serde_json::json!("synthetic/mira-b.jpg")) ); assert_eq!(key(&cleared, "note-a"), None); } // Meaning hits need the same current canonical image, rather than a stale embedding snapshot. #[test] fn person_meaning_hits_carry_the_hydrated_photo_key_including_null() { for photo_key in [t("synthetic/mira-current.jpg"), NUL] { let expected = photo_key.text().map(str::to_string); let read = run_meaning( Meaning { text: vec![], chunks: vec![chunk_row( "person", "person-a", 4, "Invented lighthouse keeper", )], hydrate: vec![( "cotton_people", vec![row(vec![ ("d_key", t("person-a")), ("d_id", t("person-a")), ("d_title", t("Mira Tidewell")), ("d_photo_key", photo_key), ])], )], }, "lighthouse", EverythingLanes::Meaning, &[EverythingKind::Person], Some(-1.0), None, ); assert_eq!(read.hits.len(), 1); let wire = serde_json::to_value(&read.hits[0]).unwrap(); assert_eq!(wire.get("photoKey"), Some(&serde_json::json!(expected))); } } /// RULE: an imported data-only table's record is found by search — the table /// is searched through its DEFINITION (title, text columns), never a lane /// hand-written for its name, so a tool imported today is findable today /// (lane T7, 22 Oct 2026: search stops hand-listing tables). The file is a /// real one: its storage is what `package_tables::from_definition` derives. #[test] fn an_imported_data_only_tables_record_is_found_by_its_definition() { use cotton_store::driver::Driver; use rusqlite::types::Value as StoreValue; let json = include_str!("../../kits/kitchen/tables/kitchen_dish.json"); let raw: serde_json::Value = serde_json::from_str(json).unwrap(); let definition = crate::definitions::TableDefinition::from_json(json).unwrap(); assert!(definition.engine.is_none(), "the fixture is a data-only table"); let db = Driver::open_in_memory().unwrap(); let tables = cotton_store::schema::package_tables::from_definition(&raw).unwrap(); for statement in cotton_store::schema::package_tables::generate(&tables, false).unwrap() { db.exec(&statement).unwrap(); } db.exec("INSERT INTO cotton_kitchen_dish (id, workspace_id, created_at, updated_at, name, notes) VALUES ('dish-a', 'synthetic', '2026-10-22', '2026-10-22', 'Saffron rice', 'Soaked overnight'), ('dish-b', 'synthetic', '2026-10-22', '2026-10-22', 'Lemon dal', 'Finished with saffron butter'), ('dish-c', 'synthetic', '2026-10-22', '2026-10-22', 'Plain toast', NULL); INSERT INTO cotton_kitchen_dish (id, workspace_id, created_at, updated_at, deleted_at, name) VALUES ('dish-d', 'synthetic', '2026-10-22', '2026-10-22', '2026-10-22', 'Saffron gone');").unwrap(); let driver = Recorder::with(move |sql, params| { let params: Vec = params .iter() .map(|value| match value { SqlValue::Null => StoreValue::Null, SqlValue::Text(value) => StoreValue::Text(value.clone()), SqlValue::Integer(value) => StoreValue::Integer(*value), SqlValue::Real(value) => StoreValue::Real(*value), SqlValue::Blob(value) => StoreValue::Blob(value.clone()), }) .collect(); db.all(sql, ¶ms) .unwrap() .iter() .map(|row| { SearchRow::new(row.columns().iter().map(|(name, value)| { ( name.clone(), match value { StoreValue::Null => SqlValue::Null, StoreValue::Text(value) => SqlValue::Text(value.clone()), StoreValue::Integer(value) => SqlValue::Integer(*value), StoreValue::Real(value) => SqlValue::Real(*value), StoreValue::Blob(value) => SqlValue::Blob(value.clone()), }, ) })) }) .collect() }); let read = search_defined_table(&driver, &definition, "synthetic", "saffron", 20, 0).unwrap(); let found: Vec<(&str, &str)> = read.hits.iter().map(|hit| (hit.id.as_str(), hit.title.as_str())).collect(); // The title match ranks first; a match only in the notes still comes back, // with the stretch that matched; a deleted record never does. assert_eq!(found, [("dish-a", "Saffron rice"), ("dish-b", "Lemon dal")]); assert_eq!(read.total, 2); assert!(read.hits[1].snippet.contains("saffron butter")); assert!(read.hits.iter().all(|hit| hit.table == "kitchen_dish" && !hit.archived)); // A section's next page starts after the hits it holds and keeps the total. let next = search_defined_table(&driver, &definition, "synthetic", "saffron", 1, 1).unwrap(); assert_eq!(next.hits.iter().map(|hit| hit.id.as_str()).collect::>(), ["dish-b"]); assert_eq!(next.total, 2); }