//! Search everything — the whole file from one call.//!//! The port of `packages/core/src/engine/searchEverything.ts` (spec//! `2026-08-27-cotton-search-everything-design.md`). It is the app's Find//! screen and the MCP `search_records` tool at once: one implementation, so the//! phone and the server rank one file one way — the same reason "who wins" has//! one implementation.//!//! Most kinds ride FTS5 tables (weighted bm25, title counted double); the small//! per-conversation and per-goal kinds ride an indexed LIKE scan until their row//! counts earn an index of their own.//!//! The rule this engine keeps: **hits are ranked WITHIN a kind and never across//! kinds.** Each section is the tool's own answer; a single mixed ranking would//! claim a comparison bm25 cannot make between different tables.//!//! # What changed in the port, and why//!//! The TypeScript is driver-in: `searchEverythingFile(db, query, options)` runs//! two dozen statements against a `SqlDriver`. This crate opens no database, so//! the module splits three ways and the seam is a trait the server implements://!//! 1. **The query plan is pure data.** Every statement is built by a pure//! function into a [`SearchQuery`] — SQL text plus bound parameters — so a//! statement can be asserted as a value. `search_everything_tests.rs` pins//! all 62 of them byte for byte against what the running TypeScript issued to//! a recording `SqlDriver`, whitespace included, because a query re-derived//! at each call site is how a visibility filter silently goes missing.//! 2. **The driver is a trait.** [`SearchDriver`] speaks in [`SqlParam`] and//! [`SearchRow`], both declared here as plain values, so the crate depends on//! no SQLite binding and the server writes a ten-line bridge.//! 3. **Row → hit mapping stays pure**, exactly as the TypeScript's per-lane//! `map` closures are — a `match` over [`EverythingKind`] rather than a//! closure stored in a const, which is also what makes a kind with no mapping//! fail the BUILD.//!//! [`search_everything_file`] issues the SAME statements in the SAME order with//! the SAME parameters as the TypeScript.//!//! # The traps, written down//!//! * **UTF-16 everywhere a length or a cut is observable.** [`first_line`] caps//! at 80 UTF-16 code units and cuts at 79, because `String.prototype.slice`//! and `.length` count code units. Ported with `encode_utf16`, never bytes and//! never `chars()`.//! * **JavaScript's whitespace class, not Rust's.** Every trim here is//! [`cotton_store::protocol::js::is_js_whitespace`] — ECMAScript trims U+FEFF//! and does NOT trim U+0085, and Rust's `str::trim` has it exactly the other//! way round. Both directions are pinned by Node vector: a note body starting//! with a BOM is titled without it, one starting with a NEL keeps it.//! * **`toLocaleLowerCase` is a Unicode case fold**, and [`snippet_unless_title`]//! leans on `str::to_lowercase` agreeing with it. They do agree for every//! locale but Turkish, Azeri and Lithuanian, whose dotted/dotless I rules ICU//! applies only when the locale asks; the host here is English-only by//! decision. The dotted capital İ is pinned by vector (both sides fold it to//! `i` + U+0307) so a change in either runtime's tables goes red.//! * **Floats never reach a partial comparator.** bm25 ranks come back negative//! and are negated by the SQL; a scan lane's rank is 0; a meaning hit's rank is//! a cosine. Rust's `slice::sort_by` may PANIC when it detects a comparator//! that is not a total order, and a pure library in a server may not panic on//! rows a caller handed it — so the meaning lane's ranking sorts with//! `f64::total_cmp`, which is total and stable and agrees with the//! TypeScript's `b.score - a.score` on every score the scan can produce (a//! dot product over `i64` divided by a positive constant: never NaN, never a//! negative zero).use std::collections::HashSet;use std::sync::LazyLock;use serde::ser::SerializeMap;use serde::{Deserialize, Serialize};use cotton_store::protocol::js::{is_js_whitespace, number_to_string};usecrate::rules::chunk::EMBED_SOURCES;usecrate::rules::mail_predicate;usecrate::rules::semantic_lane::{ embeddings_scan_query, semantic_chunk_scan, EmbeddingChunkRow, SemanticChunkHit,SemanticLaneError, SemanticScanOptions, EMBEDDINGS_PRESENT_SQL,};// ── the vocabulary ───────────────────────────────────────────────────────────/// Every kind a hit can be.////// `Thread` folds into the `message` SECTION and `EmailThread` into `email`, the/// same way: the name you typed is usually the conversation you meant.////// Declared by hand rather than through `constants.rs`'s `string_enum!` macro,/// which is module-scoped there: the union lives in `searchEverything.ts` and/// not in `constants.ts`, so this is the same four things that macro gives —/// the wire strings, the declared ORDER (which the lane loop depends on), a/// `parse` that answers `None` rather than guessing, and a `Display` that cannot/// drift from the serde representation.#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]pubenumEverythingKind { #[serde(rename = "todo")]Todo, #[serde(rename = "event")]Event, #[serde(rename = "note")]Note, #[serde(rename = "person")]Person, #[serde(rename = "message")]Message, #[serde(rename = "thread")]Thread, #[serde(rename = "email")]Email, #[serde(rename = "email_thread")]EmailThread, #[serde(rename = "memory")]Memory, #[serde(rename = "document")]Document, #[serde(rename = "session")]Session, #[serde(rename = "transaction")]Transaction, #[serde(rename = "session_message")]SessionMessage,/// A photo and a video (schema v31). A picture is unfindable until something/// has said what is in it, which is exactly what the caption and the describe/// worker's description are for. #[serde(rename = "photo")]Photo, #[serde(rename = "video")]Video,/// A call the phone recorded (schema v36). On the LIKE lane, not FTS: a call/// has no prose to rank — the searchable thing is the HANDLE, so "did I ever/// ring that number" is answerable even before anybody has named them. #[serde(rename = "call")]Call,/// A secret (v6 of the Rust ladder). On the FTS lane over the PLAIN/// columns only — a person types "gmail" and expects the login. The sealed/// payload is not indexed and never reaches a hit: what a result carries is/// the name, the site and the username, which is what the Passwords list/// shows anyway. #[serde(rename = "secret")]Secret,/// A repository, a pull request, an issue and a release (schema v19)./// The pull request and the issue are on the FTS lane — a title and a body/// are prose a person half-remembers ("the pull that fixed the launch/// crash"); the repository and the release are on the LIKE lane, because/// "where is that repo" and "which release was 0.6.6" are lookups over a/// handful of rows rather than rankings. A `repo_comment` is in NEITHER: it/// is read in the timeline of the thing it is on, and a workspace-wide/// index over review chatter would answer every search with "looks good to/// me". #[serde(rename = "repository")]Repository, #[serde(rename = "pull")]Pull, #[serde(rename = "issue")]Issue, #[serde(rename = "release")]Release,// gen-kind: everything-kind}implEverythingKind {pubconstfn as_str(self) -> &'static str {matchself {EverythingKind::Todo => "todo",EverythingKind::Event => "event",EverythingKind::Note => "note",EverythingKind::Person => "person",EverythingKind::Message => "message",EverythingKind::Thread => "thread",EverythingKind::Email => "email",EverythingKind::EmailThread => "email_thread",EverythingKind::Memory => "memory",EverythingKind::Document => "document",EverythingKind::Session => "session",EverythingKind::Transaction => "transaction",EverythingKind::SessionMessage => "session_message",EverythingKind::Photo => "photo",EverythingKind::Video => "video",EverythingKind::Call => "call",EverythingKind::Secret => "secret",EverythingKind::Repository => "repository",EverythingKind::Pull => "pull",EverythingKind::Issue => "issue",EverythingKind::Release => "release",// gen-kind: everything-kind-str } }pubfn parse(value: &str) -> Option<Self> { EVERYTHING_KINDS .into_iter() .find(|kind| kind.as_str() == value) }/// The section this kind answers under.pubconstfn section(self) -> EverythingSection { section_of(self) }}impl std::fmt::DisplayforEverythingKind {fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.write_str(self.as_str()) }}/// `EVERYTHING_KINDS` — in the TypeScript's declared order, which IS the order/// the lanes run in and therefore the order the flat `hits` array is grouped by.pubconst EVERYTHING_KINDS: [EverythingKind; 21] = [EverythingKind::Todo,EverythingKind::Event,EverythingKind::Note,EverythingKind::Person,EverythingKind::Message,EverythingKind::Thread,EverythingKind::Email,EverythingKind::EmailThread,EverythingKind::Memory,EverythingKind::Document,EverythingKind::Session,EverythingKind::Transaction,EverythingKind::SessionMessage,EverythingKind::Photo,EverythingKind::Video,EverythingKind::Call,EverythingKind::Secret,EverythingKind::Repository,EverythingKind::Pull,EverythingKind::Issue,EverythingKind::Release,// gen-kind: everything-kinds];/// The section a kind answers under — the TypeScript's/// `Exclude<EverythingKind, "thread" | "email_thread">`.////// A separate enum rather than a re-used [`EverythingKind`] with two variants/// declared unreachable: `totals` is keyed by SECTION, and a total filed under/// `thread` would be a count no reader ever looks up.#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]pubenumEverythingSection { #[serde(rename = "todo")]Todo, #[serde(rename = "event")]Event, #[serde(rename = "note")]Note, #[serde(rename = "person")]Person, #[serde(rename = "message")]Message, #[serde(rename = "email")]Email, #[serde(rename = "memory")]Memory, #[serde(rename = "document")]Document, #[serde(rename = "session")]Session, #[serde(rename = "transaction")]Transaction, #[serde(rename = "session_message")]SessionMessage, #[serde(rename = "photo")]Photo, #[serde(rename = "video")]Video, #[serde(rename = "call")]Call, #[serde(rename = "secret")]Secret,/// Four sections, not one "Code" (schema v19): a repository, a pull/// request, an issue and a release are read differently and a merged list/// would make "is anything waiting on me" a question about reading titles. #[serde(rename = "repository")]Repository, #[serde(rename = "pull")]Pull, #[serde(rename = "issue")]Issue, #[serde(rename = "release")]Release,// gen-kind: everything-section}implEverythingSection {pubconstfn as_str(self) -> &'static str {matchself {EverythingSection::Todo => "todo",EverythingSection::Event => "event",EverythingSection::Note => "note",EverythingSection::Person => "person",EverythingSection::Message => "message",EverythingSection::Email => "email",EverythingSection::Memory => "memory",EverythingSection::Document => "document",EverythingSection::Session => "session",EverythingSection::Transaction => "transaction",EverythingSection::SessionMessage => "session_message",EverythingSection::Photo => "photo",EverythingSection::Video => "video",EverythingSection::Call => "call",EverythingSection::Secret => "secret",EverythingSection::Repository => "repository",EverythingSection::Pull => "pull",EverythingSection::Issue => "issue",EverythingSection::Release => "release",// gen-kind: everything-section-str } }pubfn parse(value: &str) -> Option<Self> { EVERYTHING_SECTIONS .into_iter() .find(|section| section.as_str() == value) }}impl std::fmt::DisplayforEverythingSection {fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.write_str(self.as_str()) }}pubconst EVERYTHING_SECTIONS: [EverythingSection; 19] = [EverythingSection::Todo,EverythingSection::Event,EverythingSection::Note,EverythingSection::Person,EverythingSection::Message,EverythingSection::Email,EverythingSection::Memory,EverythingSection::Document,EverythingSection::Session,EverythingSection::Transaction,EverythingSection::SessionMessage,EverythingSection::Photo,EverythingSection::Video,EverythingSection::Call,EverythingSection::Secret,EverythingSection::Repository,EverythingSection::Pull,EverythingSection::Issue,EverythingSection::Release,// gen-kind: everything-sections];/// Threads answer as Messages, email threads as Email.////// A `const fn` over the enum rather than a lookup table: Rust's exhaustiveness/// is the gate the TypeScript needs a `switch` fallthrough for.pubconstfn section_of(kind: EverythingKind) -> EverythingSection {match kind {EverythingKind::Thread | EverythingKind::Message => EverythingSection::Message,EverythingKind::EmailThread | EverythingKind::Email => EverythingSection::Email,EverythingKind::Todo => EverythingSection::Todo,EverythingKind::Event => EverythingSection::Event,EverythingKind::Note => EverythingSection::Note,EverythingKind::Person => EverythingSection::Person,EverythingKind::Memory => EverythingSection::Memory,EverythingKind::Document => EverythingSection::Document,EverythingKind::Session => EverythingSection::Session,EverythingKind::Transaction => EverythingSection::Transaction,EverythingKind::SessionMessage => EverythingSection::SessionMessage,EverythingKind::Photo => EverythingSection::Photo,EverythingKind::Video => EverythingSection::Video,EverythingKind::Call => EverythingSection::Call,EverythingKind::Secret => EverythingSection::Secret,EverythingKind::Repository => EverythingSection::Repository,EverythingKind::Pull => EverythingSection::Pull,EverythingKind::Issue => EverythingSection::Issue,EverythingKind::Release => EverythingSection::Release,// gen-kind: section-of }}// ── the driver seam ──────────────────────────────────────────────────────────/// One SQLite value — a bound parameter, or a cell of a returned row.////// The two are the same value space in SQLite and the TypeScript's/// `StorageValue` (`string | number | null`) is the row half of it; `Blob` is/// here because the meaning lane reads a `vec` column, and `Real` because a bm25/// rank is one. Declared HERE rather than borrowed from a SQLite binding so this/// crate keeps its rule — no I/O, no database, no native dependency — and the/// server writes the bridge.#[derive(Debug, Clone, PartialEq)]pubenumSqlValue {Text(String),Integer(i64),Real(f64),Blob(Vec<u8>),Null,}/// A bound parameter. The same value space as a returned cell, spelled twice so/// a signature reads the way the call site means it.pubtypeSqlParam = SqlValue;implSqlValue {/// The TypeScript's `str(value)`: a NON-EMPTY string, or nothing.////// An empty string answers `None` because `value.length > 0` is the/// TypeScript's guard, and that is load-bearing — a `NULLIF(trim(…), '')`/// that came back as `''` from a driver that does not fold empties must read/// as "this record has no title", not as a title of nothing.pubfn text(&self) -> Option<&str> {matchself {SqlValue::Text(value) if !value.is_empty() => Some(value), _ => None, } }/// The TypeScript's `num(value)`: a number, or 0 for anything else.pubfn number(&self) -> f64 {matchself {SqlValue::Integer(value) => *value as f64,SqlValue::Real(value) => *value, _ => 0.0, } }/// ECMAScript `String(value)` — what `String(row.d_id)` does to whatever a/// driver handed back.////// SQLite will return an INTEGER for a numeric-looking id, so the coercion/// is not decoration; and `String(null)` really is `"null"` in JavaScript,/// which is what a row with a null id would land as on both sides. A BLOB/// id is not reachable from any of these statements; it decodes as UTF-8 the/// way a Node `Buffer`'s own `toString()` would.pubfn to_js_string(&self) -> String {matchself {SqlValue::Text(value) => value.clone(),SqlValue::Integer(value) => number_to_string(*value as f64),SqlValue::Real(value) => number_to_string(*value),SqlValue::Blob(bytes) => String::from_utf8_lossy(bytes).into_owned(),SqlValue::Null => "null".to_string(), } }/// The TypeScript's `typeof row.d_page === "number" ? row.d_page : null`,/// narrowed to an integer.////// `cotton_document_pages.page` is an INTEGER column and a page number that/// is not a whole number is a malformed row, so a `Real` answers `None`/// rather than being truncated into a page that is not the one the text was/// on. The TypeScript would carry the fraction through to the hit, where the/// app would render it as a page nobody can turn to.pubfn integer(&self) -> Option<i64> {matchself {SqlValue::Integer(value) => Some(*value), _ => None, } }/// The stored bytes of a BLOB column, or an empty slice — the shape/// [`EmbeddingChunkRow`] wants for a `vec` that is NULL or is not bytes at/// all, both of which the scan skips rather than scoring.pubfn blob(&self) -> &[u8] {matchself {SqlValue::Blob(bytes) => bytes, _ => &[], } }}/// One row a driver handed back, by column name, in the SELECT list's order.////// A `Vec` rather than a hash map: a statement here selects at most six columns,/// a linear scan over six `&str` beats hashing them, and the insertion order/// stays readable in a test failure.#[derive(Debug, Clone, Default, PartialEq)]pubstructSearchRow { columns: Vec<(String, SqlValue)>,}implSearchRow {pubfn new<K: Into<String>, I: IntoIterator<Item = (K, SqlValue)>>(columns: I) -> Self {SearchRow { columns: columns .into_iter() .map(|(name, value)| (name.into(), value)) .collect(), } }/// The cell, or `None` where the statement selected no such column — which/// is the TypeScript's `undefined`, and reads the same way through/// [`SqlValue::text`] and friends.pubfn get(&self, column: &str) -> Option<&SqlValue> {self.columns .iter() .find(|(name, _)| name == column) .map(|(_, value)| value) }/// `str(row[column])` — a non-empty string, or nothing.pubfn text(&self, column: &str) -> Option<&str> {self.get(column).and_then(SqlValue::text) }/// `num(row[column])` — a number, or 0.pubfn number(&self, column: &str) -> f64 {self.get(column).map_or(0.0, SqlValue::number) }/// The column as a whole number, or nothing — a missing column, a `NULL`/// and a non-number are all nothing.////// Distinct from [`SearchRow::number`], which answers `0.0` for all three:/// a pull request numbered `0` does not exist, so a `0` there would be an/// address that looks real and opens nothing.pubfn number_opt(&self, column: &str) -> Option<i64> {matchself.get(column) {Some(SqlValue::Integer(value)) => Some(*value),// A REAL that is a whole number is one too: SQLite answers a// column's affinity, and a number bound through the driver comes// back as one on some paths.Some(SqlValue::Real(value)) if value.fract() == 0.0 => Some(*value as i64), _ => None, } }/// `String(row[column])`, with a missing column reading as `"undefined"`,/// exactly as `String(undefined)` does.pubfn js_string(&self, column: &str) -> String {self.get(column) .map_or_else(|| "undefined".to_string(), SqlValue::to_js_string) }/// Is this cell equal to this string? The TypeScript's `row.d_kind ===/// "journal"` — false for a number, a null and a missing column alike.pubfn is(&self, column: &str, value: &str) -> bool { matches!(self.get(column), Some(SqlValue::Text(text)) if text == value) }pubfn columns(&self) -> &[(String, SqlValue)] { &self.columns }}/// One statement, ready to run — the whole query plan as a value.#[derive(Debug, Clone, PartialEq)]pubstructSearchQuery {pub sql: String,pub params: Vec<SqlParam>,}implSearchQuery {fn new(sql: String, params: Vec<SqlParam>) -> Self {SearchQuery { sql, params } }}/// What the engine asks of the file.////// Two methods, which is all the engine uses. `get` has a default that takes/// the first row of `all`, so a bridge may implement one method — but a driver/// that can fetch a single row without materialising the rest of the result/// set should override it, which is why it is on the trait rather than folded/// away.////// Fallible, because a driver is: the failure travels out as a `Result` for/// the caller to shape, and a pure library never panics on a row a stranger's/// database handed it.pubtraitSearchDriver {fn all(&self, sql: &str, params: &[SqlParam]) -> Result<Vec<SearchRow>, SearchError>;fn get(&self, sql: &str, params: &[SqlParam]) -> Result<Option<SearchRow>, SearchError> {Ok(self.all(sql, params)?.into_iter().next()) }}/// Why the search could not answer.#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]pubenumSearchError {/// Whatever the driver said. The TypeScript lets the exception through/// untouched; this carries its message so a handler can do the same. #[error("{0}")]Driver(String),/// The meaning lane refused the query vector. `Display` is the TypeScript's/// thrown sentence verbatim. #[error("{0}")]SemanticLane(#[from] SemanticLaneError),}// ── the string helpers ───────────────────────────────────────────────────────/// Escape `%`/`_`/`\` for a LIKE pattern used with `ESCAPE '\'`.////// LIKE has no default escape character, so a backslash without the clause is/// matched literally and the `%`/`_` in the input stay wildcards. Lives here —/// the lowest layer that scans — and the service layer re-exports it.pubfn escape_like_pattern(value: &str) -> String {letmut out = String::with_capacity(value.len());for ch in value.chars() {if matches!(ch, '\\' | '%' | '_') { out.push('\\'); } out.push(ch); } out}/// Words of context a snippet carries around the match (the app's number).const SNIPPET_TOKENS: i64 = 12;/// Per-kind cap. Three render collapsed; the rest are the inline "See all".pubconst DEFAULT_PER_KIND: i64 = 20;/// The title cap, in UTF-16 code units — a line longer than this is cut at 79/// and given an ellipsis, so the result is exactly 80 units either way.const FIRST_LINE_MAX_UNITS: usize = 80;/// `String.prototype.trim()` — the ECMAScript whitespace class.////// Not `str::trim`. JavaScript trims U+FEFF and Rust does not; Rust trims U+0085/// and JavaScript does not, and this trim decides whether a note has a title at/// all. Both directions are pinned by Node vector.fn js_trim(value: &str) -> &str { value.trim_matches(is_js_whitespace)}/// `String.prototype.length` — UTF-16 code units.fn utf16_len(value: &str) -> usize { value.encode_utf16().count()}/// First line of a body, trimmed to a title-sized fragment.////// The cut is at 79 UTF-16 code units, which can land INSIDE a surrogate pair./// JavaScript keeps the lone high surrogate there; a Rust `String` cannot hold/// one, so `from_utf16_lossy` writes U+FFFD in its place. Both sides are 80/// units long and the divergence is one replacement character at the end of a/// truncated line containing an astral character — the same trade/// `rules::feedback` already made, and matching it exactly would mean carrying/// every title through the app as a `Vec<u16>`.pubfn first_line(body: Option<&str>) -> Option<String> {let line = js_trim(body.unwrap_or("").split('\n').next().unwrap_or(""));if line.is_empty() {returnNone; }if utf16_len(line) > FIRST_LINE_MAX_UNITS {let units: Vec<u16> = line.encode_utf16().collect();letmut cut = String::from_utf16_lossy(&units[..FIRST_LINE_MAX_UNITS - 1]); cut.push('…');returnSome(cut); }Some(line.to_string())}/// The first SENTENCE of a description — what a picture is called when nobody/// captioned it.////// A description is one or two sentences on ONE line, so [`first_line`] would/// hand back both of them; the first is the one that says what the picture is.////// The TypeScript's `text.search(/[.!?](\s|$)/)` answers a UTF-16 INDEX and its/// `\s` is JavaScript's, not Rust's — a full stop followed by U+FEFF ends the/// sentence and one followed by U+0085 does not. Both are pinned by vector.pubfn first_sentence(body: Option<&str>) -> Option<String> {let text = js_trim(body.unwrap_or(""));if text.is_empty() {returnNone; }let units: Vec<u16> = text.encode_utf16().collect();// The pattern is two units wide, so a candidate is only a sentence end when// what FOLLOWS it is whitespace or nothing — otherwise the first full stop// of "A.B is one token." would end the sentence, and it does not.let end = units.iter().enumerate().find_map(|(at, unit)| {let ch = char::from_u32(u32::from(*unit))?;if !matches!(ch, '.' | '!' | '?') {returnNone; }let follows_ok = match units.get(at + 1) {None => true,Some(next) => char::from_u32(u32::from(*next)).is_some_and(is_js_whitespace), }; follows_ok.then_some(at) });let sentence = match end {None => text.to_string(),Some(at) => String::from_utf16_lossy(&units[..at + 1]), }; first_line(Some(&sentence))}/// Drop a snippet that only restates the title under itself.////// The ellipses FTS5 puts around a fragment are stripped before the comparison,/// so `…trip planning…` under the title `Trip Planning today` is recognised as/// the title said twice. The fold is `to_lowercase`, which stands in for/// `toLocaleLowerCase()` — see the module doc for where that substitution is/// exact and where it is not.pubfn snippet_unless_title(snippet: Option<&str>, title: Option<&str>) -> Option<String> {let snippet = match snippet {// `if (!snippet)` — an EMPTY snippet is falsy in JavaScript, so it is// dropped here rather than surviving as a blank line under the title.Some(value) if !value.is_empty() => value, _ => returnNone, };let bare = js_trim(&snippet.replace('…', "")).to_lowercase();if bare.is_empty() {returnNone; }// `title &&` — an empty title is falsy, so the containment test is skipped// rather than asking whether "" contains the snippet (which is false anyway,// but the TypeScript's shape is what is being ported).ifletSome(title) = title {if !title.is_empty() && title.to_lowercase().contains(&bare) {returnNone; } }Some(snippet.to_string())}// ── the hit ──────────────────────────────────────────────────────────────────/// Why this record came back, when the answer is not "it says what you typed".#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]pubenumMatchedBy { #[serde(rename = "meaning")]Meaning,}/// One hit, in the shape the app's Find screen and the `search_records` tool/// both read.#[derive(Debug, Clone, PartialEq, Serialize)]#[serde(rename_all = "camelCase")]pubstructEverythingHit {pub kind: EverythingKind,/// The record's own id — for `message` the MESSAGE id, for `thread` the/// thread id.pub id: String,/// The display title, resolved as far as the file can take it (a page falls/// back to its host, a note to its first line). `None` when only the caller/// can word it — a journal page, an untitled meeting or session.pub title: Option<String>,/// The person's current canonical image. Person hits emit null when cleared;/// other kinds omit this field. #[serde(default, skip_serializing_if = "Option::is_none")]pub photo_key: Option<Option<String>>,/// The matched line, when it says something the title does not.pub snippet: Option<String>,/// Bigger is better within a kind (bm25 negated; 0 for the scan lanes).pub rank: f64,/// The record's own moment (due / starts / sent / occurred …).pub when: Option<String>,/// A finished life: done or dropped todo, achieved or dropped goal.pub struck: bool,/// A notes hit that is a journal page.pub journal: bool,/// Message and email hits: the thread the row lives in — where to anchor a/// message, and the only address an EMAIL hit can be opened at (the reader/// is addressed by thread, never by email id).pub thread_id: Option<String>,pub sent_at: Option<String>,/// Document hits: the page the best match was on (`None`: the profile/// matched).pub page: Option<i64>,/// Absent on every hit the text lane found — which is every hit this engine/// has ever returned, so a caller written before the meaning lane existed/// sees exactly what it saw before. `meaning` marks a record that shares no/// word with the query and was found by what it is about (spec D20). #[serde(default, skip_serializing_if = "Option::is_none")]pub matched_by: Option<MatchedBy>,/// **A PULL, AN ISSUE OR A RELEASE'S REPOSITORY — WITHOUT WHICH THE HIT/// CANNOT BE OPENED.** Those three are addressed by their repository and/// their own number or tag (`/repos/[id]/pulls/[number]`, `…/issues/[n]`,/// `…/releases/[tag]`), never by the row id every other kind is reached/// by. Until this field existed they RANKED and READ in Find and then went/// nowhere: the SQL had `d_repo` and `d_number` selected and the mapping/// dropped them on the floor.////// Absent on every other kind, which is what the `skip_serializing_if`/// keeps true — a caller written before this saw no key and still sees/// none. #[serde(default, skip_serializing_if = "Option::is_none")]pub repo_id: Option<String>,/// A pull request's or an issue's number within its repository. #[serde(default, skip_serializing_if = "Option::is_none")]pub number: Option<i64>,/// A release's tag — its address, and the host's own key for it.////// Carried beside [`EverythingHit::title`] rather than read back out of/// it: the title is a DISPLAY string the lane may one day resolve to the/// release's name, and an address read off a display string is an address/// that breaks the day somebody improves the label. #[serde(default, skip_serializing_if = "Option::is_none")]pub tag: Option<String>,/// An archived record: found, so it can be brought back, and drawn as/// archived. Absent on every live hit. #[serde(default, skip_serializing_if = "std::ops::Not::not")]pub archived: bool,/// Mail hits: the stack the conversation is drawn in — `people`,/// `records` or `junk` ([`mail_stack`]) — so a slip can say a hit is junk/// rather than hide it. Absent on every other kind. #[serde(default, skip_serializing_if = "Option::is_none")]pub stack: Option<&'static str>,}implEverythingHit {/// `EMPTY_HIT` with a kind and an id — every lane starts here and overwrites/// what it knows.fn empty(kind: EverythingKind, id: String) -> Self {EverythingHit { kind, id, title: None, photo_key: None, snippet: None, rank: 0.0, when: None, struck: false, journal: false, thread_id: None, sent_at: None, page: None, matched_by: None, repo_id: None, number: None, tag: None, archived: false, stack: None, } }}/// The TypeScript's `Partial<IEverythingHit>` — what one lane's `map` decides,/// spread over `EMPTY_HIT`.////// `snippet` and `photo_key` need the doubled option: for every other field/// "the lane said nothing" and "the lane said null" land on the same value, and/// only for these is the difference observable (an unset `snippet` falls/// through to the FTS one; an unset `photo_key` emits no JSON key).#[derive(Debug, Clone, Default, PartialEq)]structHitExtra { title: Option<String>, photo_key: Option<Option<String>>, snippet: Option<Option<String>>, when: Option<String>, struck: bool, journal: bool, thread_id: Option<String>, sent_at: Option<String>, page: Option<i64>, repo_id: Option<String>, number: Option<i64>, tag: Option<String>,}/// Per SECTION: how many the file holds, beyond what the cap let through.////// Insertion-ordered, because the TypeScript's `totals` is a plain object and/// its key order is the order the lanes wrote it — which reaches an assistant as/// JSON. A `HashMap` would put a hasher's seed in charge of that.#[derive(Debug, Clone, Default, PartialEq)]pubstructSectionTotals(Vec<(EverythingSection, i64)>);implSectionTotals {pubfn get(&self, section: EverythingSection) -> Option<i64> {self.0 .iter() .find(|(key, _)| *key == section) .map(|(_, total)| *total) }pubfn iter(&self) -> implIterator<Item = (EverythingSection, i64)> + '_ {self.0.iter().copied() }pubfn is_empty(&self) -> bool {self.0.is_empty() }pubfn len(&self) -> usize {self.0.len() }/// `totals[section] = (totals[section] ?? 0) + total` — the message section/// really is written twice (once by the message lane, once by the thread/// lane), which is why this adds rather than sets.fn add(&mutself, section: EverythingSection, total: i64) {matchself.0.iter_mut().find(|(key, _)| *key == section) {Some(entry) => entry.1 += total,None => self.0.push((section, total)), } }}implSerializeforSectionTotals {fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {letmut map = serializer.serialize_map(Some(self.0.len()))?;for (section, total) in &self.0 { map.serialize_entry(section.as_str(), total)?; } map.end() }}/// What one call answers.#[derive(Debug, Clone, Default, PartialEq, Serialize)]pubstructEverythingSearchRead {/// Ranked within each kind, kinds in lane order; the caller groups and/// orders sections.pub hits: Vec<EverythingHit>,pub totals: SectionTotals,}// ── what the caller asks for ─────────────────────────────────────────────────/// The already-embedded query, as the meaning lane needs it.////// The vector arrives ready rather than being made here, and that is the seam/// this whole design turns on: embedding a query is a network round-trip to a/// third party, and this engine is pure, synchronous and driver-in like every/// engine beside it. Keeping the call outside also keeps D17's rule —/// model-seconds never inside the workspace write lock — a property of the/// server's wiring rather than a hope about this function.#[derive(Debug, Clone)]pubstructSemanticQuery<'a> {/// The query vector, quantised exactly as the stored ones were.pub vector: &'a [u8],/// `_embed_state.active_model` — the generation the vectors in the file are.pub model: &'a str,/// Minimum cosine similarity; the lane's own floor when omitted.pub min_score: Option<f64>,}/// Which lanes answer. `Text` is what this engine has always done.#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]pubenumEverythingLanes { #[default] #[serde(rename = "text")]Text, #[serde(rename = "meaning")]Meaning, #[serde(rename = "both")]Both,}implEverythingLanes {pubconstfn as_str(self) -> &'static str {matchself {EverythingLanes::Text => "text",EverythingLanes::Meaning => "meaning",EverythingLanes::Both => "both", } }pubfn parse(value: &str) -> Option<Self> { [EverythingLanes::Text,EverythingLanes::Meaning,EverythingLanes::Both, ] .into_iter() .find(|lanes| lanes.as_str() == value) }}/// The options, with the TypeScript's defaults spelled as `None`.#[derive(Debug, Clone, Default)]pubstructEverythingSearchOptions<'a> {/// Per-kind cap (default [`DEFAULT_PER_KIND`], floor 1).pub per_kind: Option<i64>,/// Run only these kinds' lanes. `None` for the whole file. An EMPTY slice is/// a caller that asked for nothing and gets nothing — not the whole file.pub kinds: Option<&'a [EverythingKind]>,/// Which lanes run. Default `Text`: every existing caller gets today's/// answer byte for byte, and a caller that never heard of the meaning lane/// cannot accidentally spend a provider call.pub lanes: Option<EverythingLanes>,/// The embedded query. Required for the meaning lane to answer at all — with/// `lanes` naming it and this absent, the meaning half is simply empty,/// which is the honest shape when the switch is off, nothing is indexed yet,/// or the server could not reach the provider. The CALLER says why; the/// engine does not invent a reason it has no way to know.pub meaning: Option<SemanticQuery<'a>>,/// The index mail is searched through ([`mail_index`]); `None` reads/// [`MAIL_INDEX`], the one every file holds whole.pub mail_index: Option<MailIndex>,/// The hits each kind skips before its page: an expanded section pages/// through its kind from here. Every total stays the kind's whole count.pub offset: i64,/// The kinds asked are pages of the sections the whole search draws: a/// kind leaves out what another kind of its section answers (a/// conversation the mail text lane finds is an Email, never also an/// EmailThread), as it does when the whole section is read together.pub as_sections: bool,}// ── the FTS lanes ────────────────────────────────────────────────────────────/// One FTS lane: match, join the domain row, rank with the title column counted/// double.////// `weights` must name every fts column, in the index's own declaration order —/// bm25 assigns by that order, so a lane one weight short or one weight long/// ranks by the wrong column and nobody sees an error. There is no leading/// weight for a `row_id` column: an external-content index has none, because it/// finds its row by rowid.#[derive(Debug, Clone, Copy, PartialEq)]pubstructFtsLane {pub kind: EverythingKind,pub fts: &'static str,pub table: &'static str,pub weights: &'static [i64],/// Extra SELECT columns off the joined domain row `t`.pub select: Option<&'static str>,/// Extra WHERE (the bin, …) against `t`.pub where_clause: Option<&'static str>,/// A test on `t` true of an ARCHIVED record: it is still found, marked/// `archived`, and ranked after every live hit of its kind. What is/// archived can be found again; what is binned stays out (`where_clause`).pub archived: Option<&'static str>,/// Recency tiebreak column on `t`.pub recency: &'static str,}/// The eleven lanes, in the order they run.////// The TypeScript carries a `map` closure on each entry; here the mapping is/// [`map_fts_row`], a `match` over the kind — a closure cannot live in a `const`,/// and the `match` is the better half of the trade anyway: a lane added without/// a mapping fails the BUILD.pubconst FTS_LANES: [FtsLane; 11] = [// Hand path: the todos engine's compiled storage and FTS index (columns, bm25 weights) are not what a definition declares.FtsLane { kind: EverythingKind::Todo, fts: "fts_todos", table: "cotton_todos", weights: &[2, 1], select: Some("t.title AS d_title, t.status AS d_status, t.due_at AS d_when"), where_clause: Some("t.trashed_at IS NULL"), archived: None, recency: "t.updated_at", },// Hand path: the calendar engine's compiled storage and FTS index (columns, bm25 weights) are not what a definition declares.FtsLane { kind: EverythingKind::Event, fts: "fts_events", table: "cotton_events", weights: &[2, 1, 1], select: Some("t.title AS d_title, t.starts_at AS d_when"),// An event in the bin is deleted, waiting: no search finds it. where_clause: Some("t.trashed_at IS NULL"), archived: None, recency: "t.starts_at", },// Hand path: a journal page shares the table and is worded by its day, which no definition says.FtsLane { kind: EverythingKind::Note, fts: "fts_notes", table: "cotton_notes", weights: &[2, 1], select: Some("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", ), where_clause: Some("t.trashed_at IS NULL"), archived: Some("t.archived_at IS NOT NULL"), recency: "t.updated_at", },// Hand path: the people engine's compiled storage and FTS index (columns, bm25 weights) are not what a definition declares.FtsLane { kind: EverythingKind::Person, fts: "fts_people", table: "cotton_people", weights: &[2, 1, 1, 1], select: Some("t.full_name AS d_title, t.avatar_key AS d_photo_key"), where_clause: None, archived: Some("t.archived_at IS NOT NULL"), recency: "t.updated_at", },// Hand path: the memory engine's compiled storage and FTS index (columns, bm25 weights) are not what a definition declares.FtsLane { kind: EverythingKind::Memory, fts: "fts_memories", table: "cotton_memories", weights: &[2, 1], select: Some("t.title AS d_title"), where_clause: Some("t.status IN ('active', 'archived')"), archived: Some("t.status = 'archived'"), recency: "t.updated_at", },// A message on the bus (v29). One indexed column again.// Hand path: the sessions engine's compiled storage and FTS index (columns, bm25 weights) are not what a definition declares.FtsLane { kind: EverythingKind::SessionMessage, fts: "fts_session_messages", table: "cotton_session_messages", weights: &[1], select: Some("t.body AS d_body, t.kind AS d_kind, t.created_at AS d_when"),// A withdrawn message is one the sender took back; it stays in the queue// as the audit trail and stays out of the one search surface. where_clause: Some("t.status <> 'withdrawn'"), archived: None, recency: "t.created_at", },// A photo (v31). Two indexed columns: the person's own caption first (the// title, counted double) and the describe worker's description after it.//// A picture always has SOMETHING to be called, unlike a note or a meeting —// so this lane never answers a null title. The caption if there is one, else// the first sentence of the description, else the plain word, because a row// in a list of hits with no name at all is a row nobody can act on.// Hand path: a picture with no caption is titled by the describe worker's first sentence.FtsLane { kind: EverythingKind::Photo,// Three indexed columns, and all three are weighted here. Before// version 3 this lane declared two (plus the `row_id` zero), leaving// `ocr_text` to bm25's own default of 1.0 — which is the number it// wanted, so the ranking was right by accident and the declaration was// short. `every_fts_lane_weights_exactly_the_columns_its_index_declares`// is what found it. fts: "fts_photos", table: "cotton_photos", weights: &[2, 1, 1], select: Some("t.caption AS d_title, t.summary AS d_body, t.taken_at AS d_when"),// No archive column; a photo in the bin is deleted, waiting: no// search finds it. where_clause: Some("t.trashed_at IS NULL"), archived: None, recency: "t.taken_at", },// A video (v31) — the photo's lane exactly, over its own index.// Hand path: a picture with no caption is titled by the describe worker's first sentence.FtsLane { kind: EverythingKind::Video, fts: "fts_videos", table: "cotton_videos", weights: &[2, 1], select: Some("t.caption AS d_title, t.summary AS d_body, t.taken_at AS d_when"),// A video in the bin, likewise. where_clause: Some("t.trashed_at IS NULL"), archived: None, recency: "t.taken_at", },// A secret (v6 of the Rust ladder). The SELECT names the PLAIN columns and// nothing else: `value_enc` is the sealed payload, it is not in the index,// and it must never be in a hit either — a search result carrying a secret// would be the leak this whole design exists to close. Rows in the bin stay// out, the same line every other lane draws at its own soft delete.// Hand path: the sealed value must never reach a hit, and only this SELECT can promise that.FtsLane { kind: EverythingKind::Secret, fts: "fts_secrets", table: "cotton_secrets", weights: &[2, 1, 1, 1], select: Some("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", ), where_clause: Some("t.trashed_at IS NULL"), archived: None, recency: "t.updated_at", },// A pull request and an issue (schema v19). The title carries twice the// weight of the body for the reason every other two-column lane does: a// word in the title is what the thing IS ABOUT, and a word in the body may// be one line of a checklist.// Hand path: the repos engine's compiled storage and FTS index (columns, bm25 weights) are not what a definition declares.FtsLane { kind: EverythingKind::Pull, fts: "fts_repo_pulls", table: "cotton_repo_pulls", weights: &[2, 1], select: Some("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", ), where_clause: None, archived: None, recency: "t.remote_updated_at", },// Hand path: the repos engine's compiled storage and FTS index (columns, bm25 weights) are not what a definition declares.FtsLane { kind: EverythingKind::Issue, fts: "fts_repo_issues", table: "cotton_repo_issues", weights: &[2, 1], select: Some("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", ), where_clause: None, archived: None, recency: "t.remote_updated_at", },// gen-kind: fts-lanes];/// The text lane for a kind, so a meaning lane never restates its rules.pubfn fts_lane(kind: EverythingKind) -> Option<&'staticFtsLane> { FTS_LANES.iter().find(|lane| lane.kind == kind)}/// The TypeScript's per-lane `map` closures, as one exhaustive `match`.////// Only the fourteen FTS kinds reach this; every other kind's mapping is inline/// beside its bespoke statement, exactly as it is in the TypeScript. A kind with/// no FTS lane answers the empty extra rather than panicking: this is a pure/// library and the caller supplies the row.fn map_fts_row(kind: EverythingKind, row: &SearchRow) -> HitExtra {match kind {EverythingKind::Todo => HitExtra { title: row.text("d_title").map(str::to_string), when: row.text("d_when").map(str::to_string), struck: row.is("d_status", "done") || row.is("d_status", "dropped") || row.is("d_status", "missed"), ..HitExtra::default() },EverythingKind::Event => HitExtra { title: row.text("d_title").map(str::to_string), when: row.text("d_when").map(str::to_string), ..HitExtra::default() },EverythingKind::Note => HitExtra {// A journal page has no name of its own — the caller words it by its// date. title: if row.is("d_kind", "journal") {None } else { row.text("d_title") .map(str::to_string) .or_else(|| first_line(row.text("d_body"))) }, when: row.text("d_when").map(str::to_string), journal: row.is("d_kind", "journal"), ..HitExtra::default() },EverythingKind::Person => HitExtra { title: row.text("d_title").map(str::to_string), photo_key: Some(row.text("d_photo_key").map(str::to_string)), ..HitExtra::default() },EverythingKind::Memory => HitExtra { title: row.text("d_title").map(str::to_string), ..HitExtra::default() },EverythingKind::SessionMessage => HitExtra { title: first_line(row.text("d_body")), when: row.text("d_when").map(str::to_string), ..HitExtra::default() },EverythingKind::Photo | EverythingKind::Video => HitExtra { title: Some( row.text("d_title") .map(str::to_string) .or_else(|| first_sentence(row.text("d_body"))) .unwrap_or_else(|| {if kind == EverythingKind::Photo {"A photo".to_string() } else {"A video".to_string() } }), ), snippet: Some(first_line(row.text("d_body"))), when: row.text("d_when").map(str::to_string), ..HitExtra::default() },// A secret (v6 of the Rust ladder). The name is the title and the site// or the username is the second line — the SAME two things the// Passwords list shows. There is deliberately no snippet: a snippet is// a window onto matched TEXT, and the only text a secret has is the// three plain columns already here.EverythingKind::Secret => HitExtra { title: row.text("d_title").map(str::to_string), snippet: Some( row.text("d_site") .or_else(|| row.text("d_username")) .map(str::to_string), ), when: row.text("d_when").map(str::to_string), ..HitExtra::default() },// A pull request and an issue (schema v19). `struck` is the CLOSED// reading and nothing else: a merged pull request is closed and reads// as done, and an open one never strikes through.EverythingKind::Pull | EverythingKind::Issue => HitExtra { title: row.text("d_title").map(str::to_string), when: row.text("d_when").map(str::to_string), struck: row.is("d_state", "closed"),// **THE ADDRESS, and it is not the row id.** A pull and an issue// are reached at `/repos/[id]/pulls/[number]`, so a hit that named// neither ranked and read and then went nowhere. Both columns were// already in this lane's `select` and were dropped here. repo_id: row.text("d_repo").map(str::to_string), number: row.number_opt("d_number"), ..HitExtra::default() },// gen-kind: map-fts-rowEverythingKind::Message | EverythingKind::Thread | EverythingKind::Email | EverythingKind::EmailThread | EverythingKind::Document | EverythingKind::Session | EverythingKind::Transaction | EverythingKind::Call | EverythingKind::Repository | EverythingKind::Release => HitExtra::default(), }}// ── the query plan, as values ────────────────────────────────────────────────//// Every statement below is pinned byte for byte in `search_everything_tests.rs`// against what the running TypeScript issued to a recording `SqlDriver`. The// literals carry the TypeScript template's own indentation because that is what// a query log, an `EXPLAIN` and a `diff` against the other implementation see.fn weights_list(weights: &[i64]) -> String { weights .iter() .map(|weight| weight.to_string()) .collect::<Vec<_>>() .join(", ")}fn placeholders(count: usize) -> String { vec!["?"; count].join(", ")}/// One FTS lane's statement: `[match, per_kind]`.pubfn fts_lane_query(lane: &FtsLane, match_query: &str, per_kind: i64) -> SearchQuery {let rank = format!("-bm25({}, {})", lane.fts, weights_list(lane.weights));letmut select = lane .select .map_or_else(String::new, |select| format!(", {select}"));// An archived hit comes after every live one of its kind.letmut order = String::new();ifletSome(archived) = lane.archived { select.push_str(&format!(", ({archived}) AS d_archived")); order.push_str("d_archived ASC, "); }let filter = lane .where_clause .map_or_else(String::new, |clause| format!(" AND {clause}"));let fts = lane.fts;let table = lane.table;let recency = lane.recency;let sql = format!("SELECT t.id AS d_id, {rank} AS d_rank, snippet({fts}, -1, '', '', '…', {SNIPPET_TOKENS}) AS d_snippet {select} FROM {fts} JOIN {table} t ON t.rowid = {fts}.rowid WHERE {fts} MATCH ?{filter} ORDER BY {order}d_rank DESC, {recency} DESC LIMIT ?" );SearchQuery::new( sql, vec![SqlParam::Text(match_query.to_string()),SqlParam::Integer(per_kind), ], )}/// How many the file holds for one FTS lane, past the cap.pubfn fts_lane_count_query(lane: &FtsLane, match_query: &str) -> SearchQuery {let filter = lane .where_clause .map_or_else(String::new, |clause| format!(" AND {clause}"));let fts = lane.fts;let table = lane.table;let sql = format!("SELECT COUNT(*) AS n FROM {fts} JOIN {table} t ON t.rowid = {fts}.rowid WHERE {fts} MATCH ?{filter}" );SearchQuery::new(sql, vec![SqlParam::Text(match_query.to_string())])}/// Documents: the profile and every extracted page, folded to one row per/// document on its best rank (the documents-service shape, kept here so one call/// answers the whole file). Bound `[match, match, per_kind]`./// Hand path: a document is found by its pages (`cotton_document_pages`), a second table its definition does not describe.pubfn document_lane_query(match_query: &str, per_kind: i64) -> SearchQuery {let sql = format!("WITH hits AS ( SELECT d.id AS d_id, -bm25(fts_documents, 2, 1, 1, 1) AS d_rank, snippet(fts_documents, -1, '', '', '…', {SNIPPET_TOKENS}) 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, '', '', '…', {SNIPPET_TOKENS}) 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 ?" );SearchQuery::new( sql, vec![SqlParam::Text(match_query.to_string()),SqlParam::Text(match_query.to_string()),SqlParam::Integer(per_kind), ], )}/// A UNION, not a UNION ALL: a document that matched on its profile AND on a/// page is one document, and counting it twice would promise a second hit that/// does not exist.pubfn document_count_query(match_query: &str) -> SearchQuery {let sql = "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 )" .to_string();SearchQuery::new( sql, vec![SqlParam::Text(match_query.to_string()),SqlParam::Text(match_query.to_string()), ], )}/// Sessions: every prompt the owner ever typed, folded to the session that said/// it (the sessions-service fold). Bound `[match, per_kind]`./// Hand path: a session's words live in its tasks and jobs, tables beside the one its definition draws.pubfn session_lane_query(match_query: &str, per_kind: i64) -> SearchQuery {let sql = format!("WITH hits AS ( SELECT p.session_id AS d_id, -bm25(fts_prompts) AS d_rank, snippet(fts_prompts, -1, '', '', '…', {SNIPPET_TOKENS}) 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 ?" );SearchQuery::new( sql, vec![SqlParam::Text(match_query.to_string()),SqlParam::Integer(per_kind), ], )}/// `COUNT(DISTINCT session_id)`, because the fold is by session and twenty/// prompts in one are one hit.pubfn session_count_query(match_query: &str) -> SearchQuery {let sql = "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 ?" .to_string();SearchQuery::new(sql, vec![SqlParam::Text(match_query.to_string())])}/// Messages: body full-text, ranked — a hit lands its thread anchored at the/// message, so the row carries the anchor. Deleted, hidden and cleared-away rows/// never answer./// Hand path: a message is found through its conversation's visibility, which the messages engine keeps.pubfn message_lane_query(match_query: &str, per_kind: i64) -> SearchQuery {let sql = format!("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, '', '', '…', {SNIPPET_TOKENS}) 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 ?" );SearchQuery::new( sql, vec![SqlParam::Text(match_query.to_string()),SqlParam::Integer(per_kind), ], )}pubfn message_count_query(match_query: &str) -> SearchQuery {let sql = "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)" .to_string();SearchQuery::new(sql, vec![SqlParam::Text(match_query.to_string())])}/// The full-text index mail is searched through, and the columns that count/// as its HEADERS — what a match ranks higher for.////// One value rather than a name spelled inside each statement: the index is/// re-declared wider (subject, body, sender name and address) and filled in/// the background beside the one that answers today, and the lane swaps to it/// in one step when the fill is done — so the index is an argument, and the/// swap is choosing the other value.#[derive(Debug, Clone, Copy, PartialEq, Eq)]pubstructMailIndex {pub fts: &'static str,/// An FTS5 column filter (`{subject}`) the header tier matches through.pub headers: &'static str,}/// `fts_emails(subject, body)` — the index that answers while the wide one/// fills.pubconst MAIL_INDEX: MailIndex = MailIndex { fts: "fts_emails", headers: "{subject}" };/// `fts_mail(subject, body, from_name, from_email)` (v122) — the index that/// answers once it is whole: a sender's name or address is a header match.pubconst MAIL_INDEX_WIDE: MailIndex =MailIndex { fts: "fts_mail", headers: "{subject from_name from_email}" };/// The index a search reads, by whether the wide one is still filling/// (`cotton_store::fts_fill`). The swap is this one choice: while the fill row/// stands, [`MAIL_INDEX`] answers; the moment the fill deletes it, the next/// search reads [`MAIL_INDEX_WIDE`]. The CALLER reads the fill row — this/// engine opens no file — and passes the answer as/// [`EverythingSearchOptions::mail_index`].pubfn mail_index(filling: bool) -> MailIndex {if filling { MAIL_INDEX } else { MAIL_INDEX_WIDE }}/// The most conversations one mail search hands back. Twelve years of mail/// match a common word thousands of times; a person reads the newest few/// hundred and narrows the words, and the total still says how many there/// are. The phone's Find asks for every hit of every kind (`WHOLE_SET_LIMIT`)/// — for mail that would be the whole mailbox shipped to a screen per/// keystroke.pubconst MAIL_CEILING: i64 = 500;/// The header tier's match expression: every word, in the header columns.pubfn mail_header_query(index: MailIndex, match_query: &str) -> String { format!("{} : ({match_query})", index.headers)}/// Emails: ONE HIT PER CONVERSATION, anchored at its best-matching message.////// RANKED FOR MAIL, not by bm25 (mailsearch brief, 12 Oct 2026): a thread whose/// subject or sender says the words comes before one whose bodies alone do,/// and within each tier the NEWEST comes first — twelve years ranked by bm25/// put a 2014 newsletter over last week's letter. A JUNK conversation is found/// and labelled (`d_stack`) but comes after every other; the bin is never found./// Within a conversation the anchor is the newest message of the best tier,/// and the row carries it (`d_id`, `d_when`) so the hit opens the thread there.////// The snippet is taken for the rows handed back only — a common word matches/// tens of thousands of emails, and each snippet re-reads its row's text — in/// ONE pass over the match (`+rowid` keeps the page's rows from becoming one/// index constraint each): a lookup per row re-walked the whole match once per/// row, 60 of the 100 ms "a" took over 3,800 emails.////// Bound `[header_query, match_query, limit, match_query]`./// Hand path: mail rides its own header index ([`MailIndex`]) and stack rules, which no definition declares.pubfn email_lane_query_in(index: MailIndex, match_query: &str, per_kind: i64) -> SearchQuery {let fts = index.fts;let order = "(t.stack IS 'junk') ASC, t.head DESC, t.sent_at DESC, t.id DESC";let sql = format!("WITH hit AS ( SELECT e.rowid AS r, e.id, e.thread_id, e.sent_at, e.rowid IN (SELECT rowid FROM {fts} WHERE {fts} MATCH ?) AS head FROM {fts} JOIN cotton_emails e ON e.rowid = {fts}.rowid WHERE {fts} MATCH ? AND {live_mail}), 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 {live_thread}), top AS MATERIALIZED ( SELECT * FROM t ORDER BY {order} LIMIT ?), snip AS MATERIALIZED ( SELECT {fts}.rowid AS r, snippet({fts}, -1, '', '', '…', {SNIPPET_TOKENS}) AS s FROM {fts} WHERE {fts} MATCH ? AND +{fts}.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 {order}", live_thread = mail_predicate::live_thread("th."), live_mail = mail_predicate::live("e."));SearchQuery::new( sql, vec![SqlParam::Text(mail_header_query(index, match_query)),SqlParam::Text(match_query.to_string()),SqlParam::Integer(per_kind),SqlParam::Text(match_query.to_string()), ], )}/// [`email_lane_query_in`] over [`MAIL_INDEX`].pubfn email_lane_query(match_query: &str, per_kind: i64) -> SearchQuery { email_lane_query_in(MAIL_INDEX, match_query, per_kind)}/// How many CONVERSATIONS the words match — the unit the lane hands back.pubfn email_count_query_in(index: MailIndex, match_query: &str) -> SearchQuery {let fts = index.fts;let sql = format!("SELECT COUNT(DISTINCT e.thread_id) AS n FROM {fts} JOIN cotton_emails e ON e.rowid = {fts}.rowid JOIN cotton_email_threads th ON th.id = e.thread_id WHERE {fts} MATCH ? AND {live_mail} AND {live_thread}", live_thread = mail_predicate::live_thread("th."), live_mail = mail_predicate::live("e."));SearchQuery::new(sql, vec![SqlParam::Text(match_query.to_string())])}pubfn email_count_query(match_query: &str) -> SearchQuery { email_count_query_in(MAIL_INDEX, match_query)}/// The stack a conversation is drawn in, by the sender kind the list keys on/// (`email_views`: person → People, service → Records, junk → Junk). `None`/// while the reader has not yet said who the sender is.pubfn mail_stack(sender_kind: Option<&str>) -> Option<&'static str> {match sender_kind? {"person" => Some("people"),"service" => Some("records"),"junk" => Some("junk"), _ => None, }}// ── the scan lanes — small tables, matched whole-query token by token ─────────/// One `LIKE ? ESCAPE '\'` per token, ANDed: every token must appear somewhere/// in the haystack, which is what a person typing two words means.fn like_predicate(haystack: &str, tokens: usize) -> String { (0..tokens) .map(|_| format!("{haystack} LIKE ? ESCAPE '\\'")) .collect::<Vec<_>>() .join(" AND ")}const THREAD_HAY: &str = "COALESCE(NULLIF(trim(th.title), ''), c.display_name, c.phone_e164, '') \|| ' ' || COALESCE(th.description, '')";const EMAIL_THREAD_HAY: &str = "COALESCE(th.subject, '') || ' ' || COALESCE((\SELECT group_concat(p.email || ' ' || COALESCE(p.display_name, ''), ' ') \FROM cotton_email_participants p WHERE p.thread_id = th.id), '')";const MONEY_HAY: &str = "COALESCE(t.description, '') || ' ' || COALESCE(t.notes, '')";/// Chat threads by their resolved name — the chat a typed NAME means, beside the/// messages its body matches. Bound `[...tokens, per_kind]`./// Hand path: a conversation's name falls back to its contact's, a join the messages engine keeps.pubfn thread_scan_query(tokens: &[String], per_kind: i64) -> SearchQuery {let predicate = like_predicate(THREAD_HAY, tokens.len());let sql = format!("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 {predicate} ORDER BY th.archived ASC, th.last_message_at DESC LIMIT ?" );SearchQuery::new(sql, token_params(tokens, Some(per_kind)))}/// Email threads by subject or participant — the conversation a typed NAME or/// ADDRESS means, beside the emails its bodies match. One row per conversation/// keeps the scan honest at archive size.////// A conversation with no email left in the inbox is ARCHIVED — the OR over/// its messages `email_state::fold_thread_state` folds — found and marked./// Mail is ranked newest first with Junk last, as the text lane ranks it/// (mailsearch brief, 12 Oct 2026): twelve years of mail are mostly archived,/// and archived-last buried last week's letter under a decade of inbox.////// A conversation the mail text lane answers (`answered`: its index and match/// expression) is that lane's ONE result, so the scan leaves it out in the/// statement itself — the pages and the count then agree with the text lane./// Hand path: a mail conversation is found by its messages' words, a second table.pubfn email_thread_scan_query(tokens: &[String], per_kind: i64, answered: Option<(MailIndex, &str)>) -> SearchQuery {let predicate = like_predicate(EMAIL_THREAD_HAY, tokens.len());let (exclude, matched) = match answered {Some((index, match_query)) => ( format!("\n AND th.id NOT IN (SELECT e.thread_id FROM {fts} JOIN cotton_emails e ON e.rowid = {fts}.rowid WHERE {fts} MATCH ? AND {live_mail})", fts = index.fts, live_mail = mail_predicate::live("e.")),Some(match_query.to_string()), ),None => (String::new(), None), };let sql = format!("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 {live_thread} AND {predicate}{exclude} ORDER BY (th.sender_kind IS 'junk') ASC, th.last_at DESC LIMIT ?", live_thread = mail_predicate::live_thread("th."));letmut params = token_params(tokens, None); params.extend(matched.map(SqlParam::Text)); params.push(SqlParam::Integer(per_kind));SearchQuery::new(sql, params)}/// Money: the words on a transaction. Small enough to scan; promoted to FTS the/// day the books outgrow it (spec §5)./// Hand path: a money row's visibility (the bin, its sides) is the money engine's.pubfn transaction_scan_query(tokens: &[String], per_kind: i64) -> SearchQuery {let predicate = like_predicate(MONEY_HAY, tokens.len());let sql = format!("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 {predicate} ORDER BY t.occurred_on DESC LIMIT ?" );SearchQuery::new(sql, token_params(tokens, Some(per_kind)))}/// The one scan lane that counts: money is the only one of the five whose table/// can outgrow the cap in a life anybody actually lives.pubfn transaction_count_query(tokens: &[String]) -> SearchQuery {let predicate = like_predicate(MONEY_HAY, tokens.len());let sql = format!("SELECT COUNT(*) AS n FROM cotton_money_transactions t WHERE {predicate}" );SearchQuery::new(sql, token_params(tokens, None))}/// Calls: the HANDLE, and nothing else, because nothing else on the row is/// words. A named counterpart is found through their person page; this lane is/// for the number nobody has named yet — "who was that 98… I keep missing" —/// which is the one question about a call log a search box can answer./// `provider` is deliberately not in the haystack: typing "cellular" would/// return a year of calls in no order anybody meant./// Hand path: a call is named by the contact it reached, a join the calls engine keeps.pubfn call_scan_query(tokens: &[String], per_kind: i64) -> SearchQuery {let predicate = like_predicate("t.handle", tokens.len());let sql = format!("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 {predicate} ORDER BY t.started_at DESC LIMIT ?" );SearchQuery::new(sql, token_params(tokens, Some(per_kind)))}/// A repository's LIKE scan (schema v19) — over the KEY and the NAME.////// The key is `owner/name`, which is what a person types: "field-notes" finds/// it and so does "alpaca/". The description is not scanned — it is the host's/// sentence rather than the owner's, and a word in it would rank a repository/// above the one whose name is the word./// Hand path: a repository's storage is the repos engine's, several tables under one record.pubfn repository_scan_query(tokens: &[String], per_kind: i64) -> SearchQuery {let predicate = like_predicate("(t.key || ' ' || t.name)", tokens.len());let sql = format!("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 {predicate} ORDER BY t.updated_at DESC LIMIT ?" );SearchQuery::new(sql, token_params(tokens, Some(per_kind)))}/// A release's LIKE scan (schema v19) — over the TAG and the NAME.////// The notes are not scanned: a changelog names every pull request it carried,/// so a word in one would answer "which release" with every release since./// Hand path: a release is addressed by its repository and tag, never its row id.pubfn release_scan_query(tokens: &[String], per_kind: i64) -> SearchQuery {let predicate = like_predicate("(t.tag || ' ' || COALESCE(t.name, ''))", tokens.len());let sql = format!("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 {predicate} ORDER BY t.published_at DESC LIMIT ?" );SearchQuery::new(sql, token_params(tokens, Some(per_kind)))}fn token_params(tokens: &[String], per_kind: Option<i64>) -> Vec<SqlParam> {letmut params: Vec<SqlParam> = tokens .iter() .map(|token| SqlParam::Text(token.clone())) .collect();ifletSome(per_kind) = per_kind { params.push(SqlParam::Integer(per_kind)); } params}/// The LIKE patterns one query becomes — `%token%`, escaped, one per whitespace/// -separated word.////// The split is JavaScript's `/\s+/` over the ALREADY-TRIMMED query, so there is/// no leading empty token to drop; the filter is ported anyway because the/// TypeScript has one.pubfn scan_tokens(trimmed_query: &str) -> Vec<String> { trimmed_query .split(is_js_whitespace) .filter(|token| !token.is_empty()) .map(|token| format!("%{}%", escape_like_pattern(token))) .collect()}// ── the meaning lanes ────────────────────────────────────────────────────────/// One MEANING lane: which `_embeddings.source` it drains, and how a scored row/// id becomes the same hit the text lane would have produced for that record.////// The rule these specs keep, and the reason they are not simply "SELECT the/// row": **a record the text lane would hide, the meaning lane hides too.** A/// binned note, a deleted or cleared-away message, a proposed memory — one/// visibility rule for both lanes, because a person who cannot find something by/// its own words must not find it by what it is about. The five kinds that/// already have an FTS lane read their filter and their title straight off it/// ([`SemanticLaneSpec::from_text_lane`]) rather than restating it, so the two/// can never drift; the three whose text lane is bespoke SQL state theirs here,/// copied from the same statements above.////// This is a STRICTER contract than the indexer's own indexable set (`EMBED_SCAN`/// on the server): the indexer keeps a vector for a moment after a row is/// archived, until its next reconcile pass. That window is exactly where a/// search must be the strict one.#[derive(Debug, Clone, Copy, PartialEq)]pubstructSemanticLaneSpec {/// The `_embeddings.source` value.pub source: &'static str,/// The kind the hit answers as — `document_page` answers as `document`.pub kind: EverythingKind,/// The domain table the vector's `row_id` names.pub table: &'static str,/// The HIT's id, when it is not the embedded row's own.pub id_expr: Option<&'static str>,/// Extra joins, aliased so `select`/`where` can reach them.pub join: Option<&'static str>,/// SELECT columns off `t` (and any join), in the `d_*` convention.pub select: &'static str,/// The visibility filter — the text lane's own.pub where_clause: Option<&'static str>,/// The text lane's archive test: an archived record is found, marked/// and ranked after the live ones.pub archived: Option<&'static str>,}implSemanticLaneSpec {/// The text lane for a kind, restated as a meaning lane.////// Panics only if a lane below names a kind with no FTS lane, which is this/// module's own data and not a caller's — the TypeScript throws in the same/// place, for the same reason, and `every_derived_meaning_lane_has_a_text_lane`/// is the test that keeps it unreachable.fn from_text_lane(source: &'static str, kind: EverythingKind) -> SemanticLaneSpec {let lane = fts_lane(kind).expect("every derived meaning lane names a text lane");SemanticLaneSpec { source, kind, table: lane.table, id_expr: None, join: None, select: lane.select.unwrap_or("t.id AS d_ignored"), where_clause: lane.where_clause, archived: lane.archived, } }}/// The six lanes, in the order they hydrate./// The email lane's live mail, on its `t` (MAIL PREDICATE): a `&'static str` for [`SemanticLaneSpec::where_clause`].static LIVE_MAIL_ON_T: LazyLock<String> = LazyLock::new(|| mail_predicate::live("t."));pubstatic SEMANTIC_LANES: LazyLock<[SemanticLaneSpec; 6]> = LazyLock::new(|| { [SemanticLaneSpec::from_text_lane("note", EverythingKind::Note),SemanticLaneSpec::from_text_lane("person", EverythingKind::Person),SemanticLaneSpec::from_text_lane("memory", EverythingKind::Memory),SemanticLaneSpec { source: "message", kind: EverythingKind::Message, table: "cotton_msg_messages", id_expr: None, join: Some("JOIN cotton_msg_threads th ON th.id = t.thread_id \LEFT JOIN cotton_msg_contacts c ON c.id = th.contact_id", ), select: "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",// The text lane's three, verbatim: a deleted message, one the owner// hid, and one behind a cleared marker are all gone from search// either way. where_clause: Some("t.deleted_at IS NULL AND t.hidden_at IS NULL \AND (th.cleared_before IS NULL OR t.sent_at > th.cleared_before)", ), archived: None, },SemanticLaneSpec { source: "email", kind: EverythingKind::Email, table: "cotton_emails", id_expr: None, join: Some("JOIN cotton_email_threads th ON th.id = t.thread_id"), select: "t.thread_id AS d_thread, t.sent_at AS d_when, \COALESCE(NULLIF(trim(t.subject), ''), NULLIF(trim(th.subject), '')) AS d_title",// In the bin is out of search (schema v33) — the text lane's own// filter, restated here because this lane's SQL is bespoke. where_clause: Some(LIVE_MAIL_ON_T.as_str()),// Out of the inbox is archived, as on the text lane. archived: Some("t.in_inbox = 0"), },// The vectors sit on the PAGES and the hit is the DOCUMENT — the text// lane's own fold, one row per document on its best page.SemanticLaneSpec { source: "document_page", kind: EverythingKind::Document, table: "cotton_document_pages", id_expr: Some("t.document_id"), join: Some("JOIN cotton_documents d ON d.id = t.document_id"), select: "t.page AS d_page, \COALESCE(NULLIF(trim(d.title), ''), d.original_name) AS d_title",// A document in the bin is deleted, waiting: no search finds it. where_clause: Some("d.trashed_at IS NULL"), archived: None, }, ]});/// The rows one meaning lane's scored ids hydrate from.pubfn semantic_hydrate_query(lane: &SemanticLaneSpec, ids: &[String]) -> SearchQuery {let id_expr = lane.id_expr.unwrap_or("t.id");let select = match lane.archived {Some(archived) => format!("{}, ({archived}) AS d_archived", lane.select),None => lane.select.to_string(), };let table = lane.table;let join = lane.join.unwrap_or("");let holes = placeholders(ids.len());let filter = lane .where_clause .map_or_else(String::new, |clause| format!(" AND {clause}"));let sql = format!("SELECT t.id AS d_key, {id_expr} AS d_id, {select} FROM {table} t {join} WHERE t.id IN ({holes}){filter}" );SearchQuery::new( sql, ids.iter().map(|id| SqlParam::Text(id.clone())).collect(), )}/// The TypeScript's per-lane `map`, for the three lanes whose text lane is/// bespoke; the derived five hand straight back to [`map_fts_row`].fn map_semantic_row(lane: &SemanticLaneSpec, row: &SearchRow) -> HitExtra {match lane.source {"message" | "email" => HitExtra { title: row.text("d_title").map(str::to_string), when: row.text("d_when").map(str::to_string), thread_id: row.text("d_thread").map(str::to_string), sent_at: row.text("d_when").map(str::to_string), ..HitExtra::default() },"document_page" => HitExtra { title: row.text("d_title").map(str::to_string), page: row.get("d_page").and_then(SqlValue::integer), ..HitExtra::default() }, _ => map_fts_row(lane.kind, row), }}/// The best chunk score per row, and the head of that chunk.////// Insertion-ordered: the ids become the `IN (…)` list, and a hasher's seed must/// not decide the order parameters bind in.fn best_per_row(chunks: &[SemanticChunkHit]) -> Vec<(String, &SemanticChunkHit)> {letmut best: Vec<(String, &SemanticChunkHit)> = Vec::new();for chunk in chunks {match best.iter_mut().find(|(row_id, _)| *row_id == chunk.row_id) {Some(held) => {if chunk.score > held.1.score { held.1 = chunk; } }None => best.push((chunk.row_id.clone(), chunk)), } } best}/// One meaning lane's scored rows, as hits.////// `rank` carries the cosine similarity — the same "bigger is better within a/// kind" contract the text lane's negated bm25 keeps, and deliberately NOT on a/// scale anybody can compare with a bm25 rank. There is no such scale; inventing/// one would be the mixed ranking this engine exists to refuse.fn hydrate_semantic_lane( driver: &dynSearchDriver, lane: &SemanticLaneSpec, chunks: &[SemanticChunkHit], per_kind: i64,) -> Result<Vec<EverythingHit>, SearchError> {let best = best_per_row(chunks);let ids: Vec<String> = best.iter().map(|(row_id, _)| row_id.clone()).collect();if ids.is_empty() {returnOk(Vec::new()); }let query = semantic_hydrate_query(lane, &ids);let rows = driver.all(&query.sql, &query.params)?;// A document's pages fold to one hit on the best page (`id_expr`); every// other lane's key IS its id, so the fold is a no-op there.letmut folded: Vec<(String, f64, EverythingHit)> = Vec::new();for row in &rows {let key = row.js_string("d_key");letSome((_, chunk)) = best.iter().find(|(row_id, _)| *row_id == key) else {continue; };let extra = map_semantic_row(lane, row);let title = extra.title.clone();let id = row.js_string("d_id");ifletSome(held) = folded.iter().find(|(held_id, _, _)| *held_id == id) {if held.1 >= chunk.score {continue; } }letmut hit = EverythingHit::empty(lane.kind, id.clone()); hit.rank = chunk.score; apply_extra(&mut hit, &extra); hit.title = title.clone();// No FTS `snippet()` exists here — nothing matched literally. The head// of the chunk that scored is the honest stand-in, and it is stored// beside the vector precisely so this needs no second read per hit.let head = js_trim(&chunk.text_head).to_string(); hit.snippet = snippet_unless_title(if head.is_empty() { None } else { Some(&head) }, title.as_deref(), ); hit.matched_by = Some(MatchedBy::Meaning); hit.archived = row.number("d_archived") != 0.0;match folded.iter_mut().find(|(held_id, _, _)| *held_id == id) {Some(held) => { held.1 = chunk.score; held.2 = hit; }None => folded.push((id, chunk.score, hit)), } }// `total_cmp` rather than `partial_cmp().unwrap()`: a partial comparator can// make `sort_by` PANIC, and a pure library in a server may not panic on rows// a caller handed it. Every score here is an `i64` dot product over a// positive constant — never NaN, never a negative zero — so the total order// and the TypeScript's `b.score - a.score` agree element for element, and// both sorts are stable.// Live before archived, then by score. folded.sort_by(|a, b| a.2.archived.cmp(&b.2.archived).then(b.1.total_cmp(&a.1)));Ok(folded .into_iter() .take(per_kind.max(0) as usize) .map(|(_, _, hit)| hit) .collect())}/// `{ ...EMPTY_HIT, ...extra }` — the fields a lane's `map` set.fn apply_extra(hit: &mutEverythingHit, extra: &HitExtra) { hit.title.clone_from(&extra.title); hit.photo_key.clone_from(&extra.photo_key);ifletSome(snippet) = &extra.snippet { hit.snippet.clone_from(snippet); } hit.when.clone_from(&extra.when); hit.struck = extra.struck; hit.journal = extra.journal; hit.thread_id.clone_from(&extra.thread_id); hit.sent_at.clone_from(&extra.sent_at); hit.page = extra.page; hit.repo_id.clone_from(&extra.repo_id); hit.number = extra.number; hit.tag.clone_from(&extra.tag);}// ── the entry point ──────────────────────────────────────────────────────────/// Everything in the file that says what was typed — every kind, one call.////// Answers whatever the driver answers; the callers own their error shapes/// (`ApiResponse` in the app service, `ToolFailure` on the server). The/// TypeScript's `(db, query, options)` signature is kept: the query is not one of/// the options, it is the question.pubfn search_everything_file( driver: &dynSearchDriver, query: &str, options: &EverythingSearchOptions<'_>,) -> Result<EverythingSearchRead, SearchError> {let trimmed = js_trim(query);if trimmed.is_empty() {returnOk(EverythingSearchRead::default()); }let per_kind = options.per_kind.unwrap_or(DEFAULT_PER_KIND).max(1);// A page from `offset` is the statement asked for `offset + per_kind`// rows, read past the first `offset` (`from_offset`).let offset = options.offset.max(0);let reach = per_kind.saturating_add(offset);let wanted: HashSet<EverythingKind> = match options.kinds {Some(kinds) => kinds.iter().copied().collect(),None => EVERYTHING_KINDS.into_iter().collect(), };let lanes = options.lanes.unwrap_or_default();let run_text = lanes != EverythingLanes::Meaning;let match_query = if run_text { cotton_store::search::to_match_query(trimmed) } else {None };letmut read = EverythingSearchRead::default();ifletSome(match_query) = match_query.as_deref() {for lane in &FTS_LANES {if !wanted.contains(&lane.kind) {continue; }let query = fts_lane_query(lane, match_query, reach);let query = from_offset(query, offset);let rows = driver.all(&query.sql, &query.params)?;let lane_hits: Vec<EverythingHit> = rows .iter() .map(|row| {let extra = map_fts_row(lane.kind, row);let title = extra.title.clone();letmut hit = EverythingHit::empty(lane.kind, row.js_string("d_id")); hit.rank = row.number("d_rank"); apply_extra(&mut hit, &extra); hit.title.clone_from(&title);// `extra.snippet !== undefined ? extra.snippet : str(row.d_snippet)`// — an unset snippet falls through to the FTS fragment, and a// lane that set one to null means it.let from_lane = extra .snippet .clone() .unwrap_or_else(|| row.text("d_snippet").map(str::to_string)); hit.snippet = snippet_unless_title(from_lane.as_deref(), title.as_deref()); hit.archived = row.number("d_archived") != 0.0; hit }) .collect();let total = if (lane_hits.len() as i64) < per_kind { offset + lane_hits.len() as i64 } else {let count = fts_lane_count_query(lane, match_query); count_scalar(driver, &count)? }; record(&mut read, section_of(lane.kind), lane_hits, total); }if wanted.contains(&EverythingKind::Document) {let query = document_lane_query(match_query, reach);let query = from_offset(query, offset);let rows = driver.all(&query.sql, &query.params)?;let document_hits: Vec<EverythingHit> = rows .iter() .map(|row| {let title = row.text("d_title").map(str::to_string);letmut hit =EverythingHit::empty(EverythingKind::Document, row.js_string("d_id")); hit.title.clone_from(&title); hit.snippet = snippet_unless_title(row.text("d_snippet"), title.as_deref()); hit.rank = row.number("d_rank"); hit.page = row.get("d_page").and_then(SqlValue::integer); hit }) .collect();let total = if (document_hits.len() as i64) < per_kind { offset + document_hits.len() as i64 } else { count_scalar(driver, &document_count_query(match_query))? }; record(&mut read, EverythingSection::Document, document_hits, total); }if wanted.contains(&EverythingKind::Session) {let query = session_lane_query(match_query, reach);let query = from_offset(query, offset);let rows = driver.all(&query.sql, &query.params)?;let session_hits: Vec<EverythingHit> = rows .iter() .map(|row| {// The SUMMARY names a session before its title does: the// title is minted, the summary is what the session was// about.let title = first_line(row.text("d_summary")) .or_else(|| row.text("d_title").map(str::to_string));letmut hit =EverythingHit::empty(EverythingKind::Session, row.js_string("d_id")); hit.title.clone_from(&title); hit.snippet = snippet_unless_title(row.text("d_snippet"), title.as_deref()); hit.rank = row.number("d_rank"); hit.when = row.text("d_when").map(str::to_string); hit }) .collect();let total = if (session_hits.len() as i64) < per_kind { offset + session_hits.len() as i64 } else { count_scalar(driver, &session_count_query(match_query))? }; record(&mut read, EverythingSection::Session, session_hits, total); }if wanted.contains(&EverythingKind::Message) {let query = message_lane_query(match_query, reach);let query = from_offset(query, offset);let rows = driver.all(&query.sql, &query.params)?;let message_hits: Vec<EverythingHit> = rows .iter() .map(|row| {letmut hit =EverythingHit::empty(EverythingKind::Message, row.js_string("d_id")); hit.title = row.text("d_title").map(str::to_string);// The ONE lane that does not ask `snippetUnlessTitle`: a// message's snippet is the matched line of the body, and a// body that happens to repeat the contact's name is still// the line that answered the search. hit.snippet = row.text("d_snippet").map(str::to_string); hit.rank = row.number("d_rank"); hit.when = row.text("d_when").map(str::to_string); hit.thread_id = row.text("d_thread").map(str::to_string); hit.sent_at = row.text("d_when").map(str::to_string); hit }) .collect();let total = if (message_hits.len() as i64) < per_kind { offset + message_hits.len() as i64 } else { count_scalar(driver, &message_count_query(match_query))? }; record(&mut read, EverythingSection::Message, message_hits, total); }if wanted.contains(&EverythingKind::Email) {let index = options.mail_index.unwrap_or(MAIL_INDEX);let mail_page = per_kind.min(MAIL_CEILING);let query = email_lane_query_in(index, match_query, offset + mail_page);let query = from_offset(query, offset);let rows = driver.all(&query.sql, &query.params)?;let email_hits: Vec<EverythingHit> = rows .iter() .map(|row| {let title = row.text("d_title").map(str::to_string);letmut hit =EverythingHit::empty(EverythingKind::Email, row.js_string("d_id")); hit.title.clone_from(&title); hit.snippet = snippet_unless_title(row.text("d_snippet"), title.as_deref()); hit.rank = row.number("d_rank"); hit.when = row.text("d_when").map(str::to_string); hit.thread_id = row.text("d_thread").map(str::to_string); hit.sent_at = row.text("d_when").map(str::to_string); hit.archived = row.number("d_archived") != 0.0; hit.stack = mail_stack(row.text("d_stack")); hit }) .collect();let total = if (email_hits.len() as i64) < mail_page { offset + email_hits.len() as i64 } else { count_scalar(driver, &email_count_query_in(index, match_query))? }; record(&mut read, EverythingSection::Email, email_hits, total); } }let tokens = if run_text { scan_tokens(trimmed) } else {Vec::new() };if !tokens.is_empty() {if wanted.contains(&EverythingKind::Thread) {let query = thread_scan_query(&tokens, reach);let query = from_offset(query, offset);let rows = driver.all(&query.sql, &query.params)?;let total = lane_total(rows.len(), per_kind, offset, || count_all(driver, thread_scan_query(&tokens, -1)))?;let thread_hits: Vec<EverythingHit> = rows .iter() .map(|row| {let id = row.js_string("d_id");letmut hit = EverythingHit::empty(EverythingKind::Thread, id); hit.title = row.text("d_title").map(str::to_string); hit.when = row.text("d_when").map(str::to_string); hit.thread_id = row.text("d_id").map(str::to_string); hit.archived = row.number("d_archived") != 0.0; hit }) .collect(); record(&mut read, EverythingSection::Message, thread_hits, total); }if wanted.contains(&EverythingKind::EmailThread) {// A conversation the text lane answers is ONE result, an Email:// the scan leaves it out (its subject or a participant said the// words too) — also when this kind is paged alone as its section// (`as_sections`), so its pages and count agree with the first page.let answered = match_query .as_deref() .filter(|_| wanted.contains(&EverythingKind::Email) || options.as_sections) .map(|match_query| (options.mail_index.unwrap_or(MAIL_INDEX), match_query));let query = email_thread_scan_query(&tokens, reach, answered);let query = from_offset(query, offset);let rows = driver.all(&query.sql, &query.params)?;let total = lane_total(rows.len(), per_kind, offset, || { count_all(driver, email_thread_scan_query(&tokens, -1, answered)) })?;let thread_hits: Vec<EverythingHit> = rows .iter() .map(|row| {let id = row.js_string("d_id");letmut hit = EverythingHit::empty(EverythingKind::EmailThread, id); hit.title = row.text("d_title").map(str::to_string); hit.when = row.text("d_when").map(str::to_string); hit.thread_id = row.text("d_id").map(str::to_string); hit.archived = row.number("d_archived") != 0.0; hit.stack = mail_stack(row.text("d_stack")); hit }) .collect(); record(&mut read, EverythingSection::Email, thread_hits, total); }if wanted.contains(&EverythingKind::Transaction) {let query = transaction_scan_query(&tokens, reach);let query = from_offset(query, offset);let rows = driver.all(&query.sql, &query.params)?;let money_hits: Vec<EverythingHit> = rows .iter() .map(|row| {let notes_line = first_line(row.text("d_notes"));let title = row .text("d_title") .map(str::to_string) .or_else(|| notes_line.clone());letmut hit =EverythingHit::empty(EverythingKind::Transaction, row.js_string("d_id")); hit.title.clone_from(&title); hit.snippet = snippet_unless_title(notes_line.as_deref(), title.as_deref()); hit.when = row.text("d_when").map(str::to_string); hit }) .collect();let total = if (rows.len() as i64) < per_kind { offset + rows.len() as i64 } else { count_scalar(driver, &transaction_count_query(&tokens))? }; record(&mut read, EverythingSection::Transaction, money_hits, total); }if wanted.contains(&EverythingKind::Call) {let query = call_scan_query(&tokens, reach);let query = from_offset(query, offset);let rows = driver.all(&query.sql, &query.params)?;let total = lane_total(rows.len(), per_kind, offset, || count_all(driver, call_scan_query(&tokens, -1)))?;let call_hits: Vec<EverythingHit> = rows .iter() .map(|row| {letmut hit = EverythingHit::empty(EverythingKind::Call, row.js_string("d_id"));// The handle IS the title: core mints no English, and a// reader that knows the person puts their name here instead. hit.title = row.text("d_handle").map(str::to_string); hit.when = row.text("d_when").map(str::to_string);// A missed call is not struck through — it HAPPENED, and// striking it would read as "cancelled" to anyone scanning// the list. hit.struck = false; hit }) .collect(); record(&mut read, EverythingSection::Call, call_hits, total); }if wanted.contains(&EverythingKind::Repository) {let query = repository_scan_query(&tokens, reach);let query = from_offset(query, offset);let rows = driver.all(&query.sql, &query.params)?;let total = lane_total(rows.len(), per_kind, offset, || count_all(driver, repository_scan_query(&tokens, -1)))?;let repo_hits: Vec<EverythingHit> = rows .iter() .map(|row| {letmut hit =EverythingHit::empty(EverythingKind::Repository, row.js_string("d_id"));// The KEY is the title — `owner/name` is how a person// names a repository, and the bare name would collide// across hosts. hit.title = row.text("d_key").map(str::to_string); hit.snippet = row.text("d_description").map(str::to_string); hit.when = row.text("d_when").map(str::to_string); hit }) .collect(); record(&mut read, EverythingSection::Repository, repo_hits, total); }if wanted.contains(&EverythingKind::Release) {let query = release_scan_query(&tokens, reach);let query = from_offset(query, offset);let rows = driver.all(&query.sql, &query.params)?;let total = lane_total(rows.len(), per_kind, offset, || count_all(driver, release_scan_query(&tokens, -1)))?;let release_hits: Vec<EverythingHit> = rows .iter() .map(|row| {letmut hit =EverythingHit::empty(EverythingKind::Release, row.js_string("d_id"));// The TAG is the title and the name is the subtitle: a// person asks for `v0.6.6`, not for "the pictures are// back". hit.title = row.text("d_tag").map(str::to_string); hit.snippet = row.text("d_name").map(str::to_string); hit.when = row.text("d_when").map(str::to_string);// A DRAFT is struck through — it has not shipped, and a// list that drew it like a release would say it had. hit.struck = row.number("d_draft") != 0.0;// **THE ADDRESS.** A release is reached at// `/repos/[id]/releases/[tag]`, and `d_repo` was already// selected and thrown away. The tag is carried on its own// field rather than read back out of `title`, which is a// DISPLAY string somebody may improve. hit.repo_id = row.text("d_repo").map(str::to_string); hit.tag = row.text("d_tag").map(str::to_string); hit }) .collect(); record(&mut read, EverythingSection::Release, release_hits, total); } }// ── the meaning lane — the same file, asked what these rows are ABOUT ──//// Runs last and folds INTO the sections that already exist, appended after// that kind's exact hits (D19's "Related"). Never a section of its own and// never interleaved by a blended score: there is no scale on which a bm25// rank and a cosine similarity are comparable, and inventing one would be// exactly the mixed ranking this engine refuses.if lanes != EverythingLanes::Text {ifletSome(meaning) = &options.meaning {let active: Vec<&SemanticLaneSpec> = SEMANTIC_LANES .iter() .filter(|lane| wanted.contains(&lane.kind)) .collect();let chunks = if active.is_empty() {Vec::new() } else {let sources: Vec<String> = active.iter().map(|lane| lane.source.to_string()).collect();let scan = SemanticScanOptions { vector: meaning.vector, model: meaning.model, sources: Some(&sources),// A row can make several chunks and several chunks fold to// one hit, so the scan keeps a little more than the caller's// cap and the fold trims back to it. per_source: Some((per_kind * 2).max(0) as usize), min_score: meaning.min_score, }; semantic_chunks(driver, &scan)? };if !chunks.is_empty() {// Already found by its own words ⇒ already in the answer. A// record listed twice, once as an exact hit and once as a// related one, reads as two records to anyone scanning a// section.let already_found: HashSet<(EverythingKind, String)> = read .hits .iter() .map(|hit| (hit.kind, hit.id.clone())) .collect();letmut by_kind: Vec<(EverythingKind, Vec<EverythingHit>)> = Vec::new();for lane in &active {let lane_chunks: Vec<SemanticChunkHit> = chunks .iter() .filter(|chunk| chunk.source == lane.source) .cloned() .collect();if lane_chunks.is_empty() {continue; }let lane_hits: Vec<EverythingHit> = hydrate_semantic_lane(driver, lane, &lane_chunks, per_kind)? .into_iter() .filter(|hit| !already_found.contains(&(hit.kind, hit.id.clone()))) .collect();if lane_hits.is_empty() {continue; }match by_kind.iter_mut().find(|(kind, _)| *kind == lane.kind) {Some(held) => held.1.extend(lane_hits),None => by_kind.push((lane.kind, lane_hits)), } }if !by_kind.is_empty() {// Each kind occupies one contiguous run of `hits` (one lane// pushes it, once), so its meaning hits are spliced in// directly after that run and the flat array stays grouped// for a caller that renders it in order.letmut merged: Vec<EverythingHit> = Vec::new();for at in0..read.hits.len() { merged.push(read.hits[at].clone());let kind = read.hits[at].kind;if read.hits.get(at + 1).map(|next| next.kind) != Some(kind) {ifletSome(position) = by_kind.iter().position(|(held, _)| *held == kind) { merged.extend(by_kind.remove(position).1); } } }// Kinds the text lane found nothing for answer on their own.for (_, related) in by_kind { merged.extend(related); } read.hits = merged; } } } }// `totals` is deliberately untouched by the meaning lane. It answers "how// many more does the file hold", and a brute-force scan holds a similarity// for EVERY row — the honest number is the whole database, which tells a// reader nothing and would read as a promise of thousands more good hits.Ok(read)}fn record( read: &mutEverythingSearchRead, section: EverythingSection, lane: Vec<EverythingHit>, total: i64,) { read.hits.extend(lane);if total > 0 { read.totals.add(section, total); }}/// A lane's page from `offset`: its statement, asked for `offset` more rows/// than the page, read past them. The first page is the statement itself.fn from_offset(query: SearchQuery, offset: i64) -> SearchQuery {if offset == 0 {return query; }SearchQuery::new(format!("SELECT * FROM ({}) LIMIT -1 OFFSET {offset}", query.sql), query.params)}/// Every row a lane's statement answers, counted: the statement asked with no/// limit (`LIMIT -1`), so the count can never disagree with the pages.fn count_all(driver: &dynSearchDriver, query: SearchQuery) -> Result<i64, SearchError> { count_scalar(driver, &SearchQuery::new(format!("SELECT COUNT(*) AS n FROM ({})", query.sql), query.params))}/// A kind's exact total: a page that came back short is the rest of the kind;/// a full one is counted.fn lane_total( len: usize, page: i64, offset: i64, count: implFnOnce() -> Result<i64, SearchError>,) -> Result<i64, SearchError> {if (len as i64) < page { Ok(offset + len as i64) } else { count() }}fn count_scalar(driver: &dynSearchDriver, query: &SearchQuery) -> Result<i64, SearchError> {let row = driver.get(&query.sql, &query.params)?;// The TypeScript reads `num(row.n)`, which is a JavaScript number; a count// is a whole one, and rounding toward zero is what any reader of this does// with it anyway.Ok(row.map_or(0, |row| row.number("n") as i64))}/// The meaning lane's two statements, run through the driver, scanned in memory.////// [`semantic_chunk_scan`] is rows-in — the semantic-lane port's own seam — so/// this is where the two statements it DECLARES are actually issued, in the/// TypeScript's order: the query vector is checked FIRST (a wrong-sized one must/// not cost two round trips before it is refused), then `sqlite_master`, then the/// scan.fn semantic_chunks( driver: &dynSearchDriver, scan: &SemanticScanOptions<'_>,) -> Result<Vec<SemanticChunkHit>, SearchError> {ifcrate::rules::semantic_lane::as_stored_vector(scan.vector).is_none() {returnErr(SemanticLaneError::QueryVectorBytes(scan.vector.len()).into()); }letSome((sql, params)) = embeddings_scan_query(scan) else {returnOk(Vec::new()); };// Looking at a database must never be what brings a table into being: a// workspace whose owner never turned the switch on has no `_embeddings`, and// the lane answers empty rather than creating one.if driver.get(EMBEDDINGS_PRESENT_SQL, &[])?.is_none() {returnOk(Vec::new()); }let params: Vec<SqlParam> = params.into_iter().map(SqlParam::Text).collect();let rows = driver.all(&sql, ¶ms)?;let rows: Vec<EmbeddingChunkRow> = rows .iter() .map(|row| EmbeddingChunkRow { source: row.js_string("source"), row_id: row.js_string("row_id"), chunk_ix: row.get("chunk_ix").and_then(SqlValue::integer).unwrap_or(0), vec: row .get("vec") .map(SqlValue::blob) .unwrap_or_default() .to_vec(), text_head: row.text("text_head").map(str::to_string), }) .collect();Ok(semantic_chunk_scan(&rows, scan)?)}/// Every embedded source has a lane here, and every lane names a real source.////// The TypeScript asserts this at MODULE LOAD, and the reason is worth keeping:/// a source added to `EMBED_SOURCES` 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 a loop over a `LazyLock` at compile time, so the boot failure/// becomes a test: `every_embed_source_has_a_meaning_lane`./// Which way the lanes and the embedded sources disagree — read only by the/// developer whose test fails, so a typed fact and never words.#[derive(Debug, Clone, Copy, PartialEq, Eq)]pubenumLaneFault {SourceWithoutLane { source: &'static str },LaneWithoutSource { source: &'static str },}pubfn meaning_lane_totality() -> Result<(), LaneFault> {for source in &EMBED_SOURCES {if !SEMANTIC_LANES .iter() .any(|lane| lane.source == source.source) {returnErr(LaneFault::SourceWithoutLane { source: source.source }); } }for lane in SEMANTIC_LANES.iter() {if !EMBED_SOURCES .iter() .any(|source| source.source == lane.source) {returnErr(LaneFault::LaneWithoutSource { source: lane.source }); } }Ok(())}// ── the defined lane: a table its definition describes ─────────────────────/// The storage a data-only table's records live in — the table/// `cotton_store::schema::package_tables::from_definition` derives from its/// definition's columns.pubfn defined_storage(table_id: &str) -> String { format!("cotton_{table_id}")}/// One record of a table found through its DEFINITION rather than a lane/// written for it: an imported or made data-only table is searchable the day/// it arrives (lane T7, 22 Oct 2026: search stops hand-listing tables).#[derive(Debug, Clone, PartialEq, Serialize)]#[serde(rename_all = "camelCase")]pubstructDefinedHit {/// The table id, which is also the kind a caller addresses the record by.pub table: String,pub id: String,/// The title column's value (an account number shows only its ending).pub title: String,/// The matched stretch of the first column that matched.pub snippet: String,/// The definition's archive column holds a value: found, after every live/// one, so it can be brought back.pub archived: bool,/// The definition's `when` column's value.pub when: Option<String>,}/// What one defined table answers: its page of hits, and how many it holds.#[derive(Debug, Clone, Default, PartialEq, Serialize)]pubstructDefinedRead {pub hits: Vec<DefinedHit>,pub total: i64,}/// The statement one defined table is searched with, built from its/// definition alone: the title column, every stored text column (text,/// longtext, url, place), the archive column and the `when` column. Only keys/// the definition declares are named in SQL, and every key was validated as an/// identifier (`[a-z][a-z0-9_]*`) when the definition was read. Matching is a/// LIKE over each column; ranking puts a live record before an archived one,/// then an exact title, then a title containing the words, then the rest,/// newest first. `offset` skips that many hits, so a section reads its next/// page.pubfn defined_table_query( definition: &crate::definitions::TableDefinition, workspace_id: &str, query: &str, per_kind: i64, offset: i64, left_out: &[String],) -> SearchQuery {usecrate::definitions::ColumnType;let stored = |key: &str| definition.column(key).filter(|column| column.computed.is_none());// A definition may title records by a number or a boolean: search that// scalar's display text.let title = match stored(&definition.title) {Some(column) if column.column_type == ColumnType::Bool => { format!("CASE \"{}\" WHEN 1 THEN 'true' WHEN 0 THEN 'false' ELSE '' END", column.key) }Some(column) => format!("COALESCE(CAST(\"{}\" AS TEXT), '')", column.key),None => "''".to_string(), };// An account number is shown by its ending and never matched whole.let account_title = stored(&definition.title).is_some_and(|column| column.column_type == ColumnType::AccountNumber);letmut expressions = vec![if account_title { "''".to_string() } else { title.clone() }]; expressions.extend( definition .columns .iter() .filter(|column| column.computed.is_none()) .filter(|column| matches!(column.column_type, ColumnType::Text | ColumnType::Longtext | ColumnType::Url | ColumnType::Place)) .filter(|column| column.key != definition.title) .map(|column| format!("COALESCE(\"{}\", '')", column.key)), );let matches: Vec<String> = expressions.iter().map(|expression| format!("({expression}) LIKE ?2 ESCAPE '\\'")).collect();let snippet = expressions .iter() .zip(&matches) .map(|(expression, matched)| { format!("WHEN {matched} THEN substr(({expression}), max(1, instr(lower(({expression})), lower(?3))-80), 240)") }) .collect::<Vec<_>>() .join(" ");let archived = match definition.archived.as_deref().and_then(stored) {Some(column) => format!("COALESCE(\"{}\", '') NOT IN ('', 0)", column.key),None => "0".to_string(), };let when = match definition.when_column().and_then(stored) {Some(column) => format!("\"{}\"", column.key),None => "NULL".to_string(), };// Rows the reader leaves out by id (HIDE FROM SCREEN, CORE 4: a hidden title of his films and its plays), left out// HERE, where the rows are read: the hits, their snippets and the `total` are all made without them.// One parameter, a JSON list, however many are left out.let left = if left_out.is_empty() { "" } else { " AND id NOT IN (SELECT value FROM json_each(?6))" };let sql = format!("SELECT id, ({title}) AS title, CASE {snippet} ELSE '' END AS snippet, ({archived}) AS archived, {when} AS d_when, COUNT(*) OVER() AS total FROM {table} WHERE workspace_id = ?1 AND deleted_at IS NULL AND ({any}){left} ORDER BY archived ASC, CASE WHEN ({first}) = ?3 COLLATE NOCASE THEN 3 WHEN {first_match} THEN 2 ELSE 1 END DESC, updated_at DESC, id LIMIT ?4 OFFSET ?5", table = defined_storage(&definition.id), any = matches.join(" OR "), first = expressions[0], first_match = matches[0], );letmut params = vec![SqlValue::Text(workspace_id.to_string()),SqlValue::Text(format!("%{}%", escape_like_pattern(query))),SqlValue::Text(query.to_string()),SqlValue::Integer(per_kind.max(1)),SqlValue::Integer(offset.max(0)), ];if !left_out.is_empty() { params.push(SqlValue::Text(serde_json::Value::from(left_out.to_vec()).to_string())); }SearchQuery { sql, params }}/// Search one defined table: [`defined_table_query`], each row read as a/// [`DefinedHit`].pubfn search_defined_table( driver: &dynSearchDriver, definition: &crate::definitions::TableDefinition, workspace_id: &str, query: &str, per_kind: i64, offset: i64,) -> Result<DefinedRead, SearchError> { search_defined_table_leaving(driver, definition, workspace_id, query, per_kind, offset, &[])}/// [`search_defined_table`], leaving out the rows of `left_out` by id before anything is counted or paged.pubfn search_defined_table_leaving( driver: &dynSearchDriver, definition: &crate::definitions::TableDefinition, workspace_id: &str, query: &str, per_kind: i64, offset: i64, left_out: &[String],) -> Result<DefinedRead, SearchError> {let statement = defined_table_query(definition, workspace_id, query, per_kind, offset, left_out);let rows = driver.all(&statement.sql, &statement.params)?;let account_title = definition .column(&definition.title) .is_some_and(|column| column.column_type == crate::definitions::ColumnType::AccountNumber);let total = rows.first().and_then(|row| row.number_opt("total")).unwrap_or_default();let hits = rows .iter() .map(|row| {let title = row.text("title").unwrap_or_default();DefinedHit { table: definition.id.clone(), id: row.text("id").unwrap_or_default().to_string(), title: if account_title { crate::records::account_number_ending(title) } else { title.to_string() }, snippet: row.text("snippet").unwrap_or_default().to_string(), archived: row.number_opt("archived").unwrap_or_default() != 0, when: row.text("d_when").map(str::to_string), } }) .collect();Ok(DefinedRead { hits, total })}#[cfg(test)]#[path = "search_everything_tests.rs"]mod tests;