Cotton code
1715 lines · 67.0 KB · RustRaw
//! `list_message_threads`, `read_message_thread`, `search_messages` — the//! messages block of `packages/server/src/mcp/records.ts`.//!//! THE MERGE IS A READ. Storage keeps a DM thread per counterpart CONTACT, and//! a person reachable from two numbers has two contacts and two threads.//! Merging them at WRITE time would mean adding a second number to somebody//! moves rows — an op per message, in a log that is forever, to express a fact//! that is one column on one contact. So the fold is here, in the app and in//! the Mac window, through the SAME pure function in//! [`cotton_core::rules::conversations`] — which is why nothing in this file//! re-derives the grouping, the interleave or the channel badges.//!//! Three rules the shapes below exist to keep://!//!   A MERGED CONVERSATION CARRIES NO `id`. It is not one thread, and handing//!   back an id somebody could pass to `read_message_thread` would be handing//!   back half a conversation. A conversation of exactly one thread keeps its//!   `id`, so that call is always right.//!//!   A DELETED MESSAGE KEEPS ITS PLACE AND LOSES ITS CONTENTS. "Delete for//!   everyone" has to mean it for an assistant too, or the product's most//!   sensitive promise is one a model can read straight past.//!//!   REACTIONS AND RECEIPTS NAME PEOPLE, NOT NUMBERS. A reaction's `actor` and//!   a receipt's `phone` are digits in the file; an assistant should read//!   "Priya reacted", and a raw number is exactly the kind of identifier this//!   product tries not to put in a transcript. `self` is the owner.use std::collections::{HashMap, HashSet};use cotton_core::constants::{MessageChannel, SummaryKind, ThreadKind};use cotton_core::rules::conversations::{    channels_present, group_threads_by_person, merge_timelines, Conversation, ConversationContact,    ConversationMessage, ConversationPerson, ConversationThread,};use cotton_core::media::keys::is_key_in_row_file;use cotton_core::messages::group_event::OWNER_ACTOR;use cotton_store::schema::codecs::decode_value;use cotton_store::schema::specs::{codec_of, spec_for};use cotton_store::search::to_match_query;use rusqlite::types::Value as SqlValue;use serde_json::{Map, Value};use crate::mcp::dispatch::{Ctx, ToolResult};use crate::mcp::handlers::common::{    bounded_limit, fail, flag, in_chunks, int, is_uuid, iso_timestamp, optional_string, rows,    summary_out, text, Valid,};use crate::mcp::protocol::ToolFailure;use crate::mcp::read_db::{Filter, Order, Query};// ── the vocabularies ────────────────────────────────────────────────────────/// `MESSAGE_GROUP_BY` in `protocol.ts`.const MESSAGE_GROUP_BY: &[&str] = &["person", "thread"];/// `MESSAGE_CHANNELS`, in the declared order `channels_present` renders badges/// in. Taken from the enum rather than re-typed, so a fifth channel cannot be/// added to core and silently left out of a badge list here.fn message_channels() -> Vec<&'static str> {    MessageChannel::ALL        .iter()        .map(|channel| channel.as_str())        .collect()}/// The projection the LIST and SEARCH readers take of a thread.const THREAD_COLUMNS: &[&str] = &[    "id",    "kind",    "title",    "contact_id",    "last_message_at",    "last_message_preview",    "archived",];/// The projection `read_message_thread` takes — the list's, plus the owner's/// paragraph about the conversation and its provenance (v15).const THREAD_COLUMNS_WITH_SUMMARY: &[&str] = &[    "id",    "kind",    "title",    "contact_id",    "last_message_at",    "last_message_preview",    "archived",    "summary",    "summary_by",    "summary_updated_at",];const MESSAGE_COLUMNS: &[&str] = &[    "id",    "workspace_id",    "thread_id",    "direction",    "channel",    "body",    "media",    "sent_at",    "sender_participant_id",    "meta",    "seq",    "edited_at",    "deleted_at",];/// The line an assistant scans in a search result, in UTF-16 code units — the/// full body is one `read_message_thread` away.const SEARCH_BODY_CAP: usize = 240;// ── raw reads, where the query builder should not go ────────────────────────/// A raw SQL read, decoded through each column's declared codec.////// `read_db`'s `select` cannot express two things this file needs — NULLS LAST/// on a descending order, and the FTS join — and the module note there says a/// handler writes those as SQL rather than growing the builder to cover them./// What a handler should NOT rewrite is the decode: a `Bool` column must read/// back `true` rather than `1` and a `Json` column its tree rather than its/// text, which is the whole reason `select` exists.////// The workspace scope is the CALLER's here, because the SQL is the caller's./// Every statement below carries `workspace_id = ?`.fn raw_rows(    ctx: &Ctx<'_>,    table: &str,    sql: &str,    params: &[SqlValue],) -> Result<Vec<Map<String, Value>>, ToolFailure> {    let spec = spec_for(table)        .ok_or_else(|| ToolFailure::new(format!("cotton-mcp: no table spec for {table}")))?;    let found = ctx        .db()        .all(sql, params)        .map_err(|error| ToolFailure::new(error.to_string()))?;    let mut out = Vec::with_capacity(found.len());    for row in found {        let mut shaped = Map::new();        for (name, value) in row.columns() {            let decoded = match codec_of(spec.name, name) {                Some(codec) => {                    decode_value(codec, value).map_err(|e| ToolFailure::new(e.to_string()))?                }                None => Value::Null,            };            shaped.insert(name.clone(), decoded);        }        out.push(shaped);    }    Ok(out)}fn holes(count: usize) -> String {    vec!["?"; count].join(", ")}/// A batch of ids as bound parameters — for a `Filter::In` and for raw SQL/// alike, which is why there is one of these rather than two.pub(crate) fn in_values(ids: &[String]) -> Vec<SqlValue> {    ids.iter().map(|id| SqlValue::Text(id.clone())).collect()}/// The unique, non-blank ids of a list — `[...new Set(ids)].filter(…)`, with/// first-appearance order kept.pub(crate) fn unique_ids(ids: impl IntoIterator<Item = String>) -> Vec<String> {    let mut seen: HashSet<String> = HashSet::new();    let mut out = Vec::new();    for id in ids {        if id.is_empty() {            continue;        }        if seen.insert(id.clone()) {            out.push(id);        }    }    out}// ── JavaScript's own readings ───────────────────────────────────────────────/// `Boolean(value)` — what `row.meta?.system` is tested with.////// TRUTHY, not `=== true`: a Cotton group event carries the structured facts in/// `meta` since 2026-08-26, and a build that wrote `system: 1` must still read/// as an event line rather than as somebody's bubble with no sender.pub(crate) fn js_truthy(value: Option<&Value>) -> bool {    match value {        None | Some(Value::Null) => false,        Some(Value::Bool(flag)) => *flag,        Some(Value::Number(number)) => number.as_f64().is_some_and(|n| n != 0.0 && !n.is_nan()),        Some(Value::String(text)) => !text.is_empty(),        // An object or an array is truthy in JavaScript, empty or not.        Some(_) => true,    }}/// `String.prototype.trim()` on an optional column, dropping a blank.fn trimmed(value: Option<String>) -> Option<String> {    value        .map(|text| text.trim().to_string())        .filter(|text| !text.is_empty())}/// `value.slice(0, at)` in UTF-16 code units — what `.length` counts.////// The cut can land inside a surrogate pair; JavaScript keeps the lone high/// surrogate and a Rust `String` cannot hold one, so `from_utf16_lossy` writes/// U+FFFD there. Both sides stay the same number of code units long, which is/// the same trade `rules::feedback` and `search_everything::first_line` make.fn slice_utf16(value: &str, at: usize) -> String {    let units: Vec<u16> = value.encode_utf16().collect();    if units.len() <= at {        return value.to_string();    }    String::from_utf16_lossy(&units[..at])}fn utf16_len(value: &str) -> usize {    value.encode_utf16().count()}// ── media ───────────────────────────────────────────────────────────────────/// The compact media echo — enough to open the file, nothing more.////// Two shapes live in `media` and both are legal: an IMPORTED row carries a/// `{url}` from before content-addressing, and everything written since carries/// a `{key}` into the server's own store.////// `is_key_in_row_file` is the wall that replaces bucket RLS. A key from/// another workspace loses its LINK and keeps its row: the assistant is told/// there was an attachment, and is given no way to read it.////// May this server mint a link for this key?////// Both halves matter and neither is the other: `is_key_in_row_file` is the/// SECURITY answer (a key from another workspace never reaches a signer) and/// `media_available` is the CAPABILITY one (a server with no object store has/// nothing to sign with).fn signable(ctx: &Ctx<'_>, key: &str, row_file: &str) -> bool {    ctx.services.media_available && is_key_in_row_file(Some(key), row_file)}/// How long a message attachment's link lives — the bytes route's own number,/// and `get_document`'s. Five minutes: an assistant that asked for one is about/// to use it, and a link still live an hour later is only useful to whoever/// finds it in a log.const ATTACHMENT_URL_TTL_SECONDS: u64 = 300;/// A five-minute link for one key, or `None` — which is a fact, not a failure.////// [`signable`] is asked FIRST and separately: a key from another workspace/// must never reach a signer, whether or not this server happens to have one./// With no rail (a server with no object store, or one on a bucket whose signer/// is async-only) the attachment comes back as its base shape — `key`,/// `contentType`, `name` — which is precisely the TypeScript's own/// no-object-store branch: an attachment is still a fact about the/// conversation, it just has no link today.fn attachment_url(ctx: &Ctx<'_>, key: &str, row_file: &str) -> Option<String> {    if !signable(ctx, key, row_file) {        return None;    }    let presign = ctx.services.presign.as_ref()?;    presign(key, ATTACHMENT_URL_TTL_SECONDS).ok()}/// What a RENDERER needs and an assistant does not, carried through from the/// stored entry when the row has it.////// `kind` is what a bubble draws (an image, a chip, a waveform); the three/// numbers are what it reserves space for before a byte has arrived, which is/// the difference between a conversation that scrolls and one that jumps as/// each picture lands. They are FACTS about the attachment, so an assistant/// gets them too — they cost a few bytes and they answer "how big is that/// photo" without a second question.////// `playbackKey`/`playbackContentType` name the playable rendition of a/// recording whose original the phone cannot play (a WhatsApp voice note's/// AAC beside its Ogg/Opus); without them the one player has nothing to play./// `contact` is a shared card's readable part (name, numbers) — what the/// card draws and what "who did they send me" answers.const RENDERER_FIELDS: [&str; 8] = [    "kind",    "width",    "height",    "sizeBytes",    "durationMs",    "playbackKey",    "playbackContentType",    "contact",];/// The one field the owner's own app gets and an assistant does not.////// A base64 JPEG, up to four kilobytes EACH, whose only use is to be drawn/// blurred until the real bytes are local. A window of fifty messages would put/// a couple of hundred kilobytes of pixels an assistant cannot see into its/// context, to answer nothing; the phone draws with it. So it travels on the/// owner-app read and stops at every other one — the same "who is asking" the/// send branch already turns on.const PREVIEW_FIELD: &str = "preview";/// A voice note's drawn waveform — sixty-four samples in 0..1, written by the/// device that recorded it. Owner-app only for the preview's reason: it exists/// to be DRAWN (the paper chat's voice strip), and sixty-four numbers per voice/// note answer an assistant nothing.const WAVEFORM_FIELD: &str = "waveform";/// `row_file` is the message row's own `workspace_id`: the wall is asked of/// the file the row was written into, not the file the reader holds open.pub(crate) fn media_out(ctx: &Ctx<'_>, value: Option<&Value>, row_file: &str) -> Vec<Value> {    let Some(Value::Array(entries)) = value else {        return Vec::new();    };    let owner_app = ctx.is_owner_app();    let mut out = Vec::new();    for entry in entries {        let Some(content_type) = entry.get("contentType").and_then(Value::as_str) else {            continue;        };        let name = entry            .get("name")            .and_then(Value::as_str)            .filter(|name| !name.is_empty());        // Carried through rather than re-derived: the writer decided what this        // attachment IS and how big it is, and a second opinion computed off        // the content type here would disagree with the bubble the sender saw.        let mut carried = Map::new();        for field in RENDERER_FIELDS {            match entry.get(field) {                None | Some(Value::Null) => {}                Some(value) => {                    carried.insert(field.to_string(), value.clone());                }            }        }        if owner_app {            if let Some(preview) = entry                .get(PREVIEW_FIELD)                .and_then(Value::as_str)                .filter(|preview| !preview.is_empty())            {                carried.insert(PREVIEW_FIELD.to_string(), Value::from(preview));            }            if let Some(samples) = entry                .get(WAVEFORM_FIELD)                .and_then(Value::as_array)                .filter(|samples| !samples.is_empty())            {                carried.insert(WAVEFORM_FIELD.to_string(), Value::Array(samples.clone()));            }        }        if let Some(url) = entry            .get("url")            .and_then(Value::as_str)            .filter(|url| !url.is_empty())        {            let mut shaped = Map::new();            shaped.insert("url".to_string(), Value::from(url));            shaped.insert("contentType".to_string(), Value::from(content_type));            if let Some(name) = name {                shaped.insert("name".to_string(), Value::from(name));            }            shaped.extend(carried);            out.push(Value::Object(shaped));            continue;        }        let Some(key) = entry            .get("key")            .and_then(Value::as_str)            .filter(|key| !key.is_empty())        else {            continue;        };        let mut base = Map::new();        base.insert("key".to_string(), Value::from(key));        base.insert("contentType".to_string(), Value::from(content_type));        if let Some(name) = name {            base.insert("name".to_string(), Value::from(name));        }        // The wall stays at the CALL SITE, not inside the rail: a key from        // another workspace must never reach a signer.        if let Some(url) = attachment_url(ctx, key, row_file) {            base.insert("url".to_string(), Value::from(url));        }        base.extend(carried);        out.push(Value::Object(base));    }    out}// ── naming ──────────────────────────────────────────────────────────────────/// `display_name` where the owner has one, else the phone — never a blank.fn contact_names_by_id(    ctx: &Ctx<'_>,    ids: &[String],) -> Result<HashMap<String, String>, ToolFailure> {    let unique = unique_ids(ids.iter().cloned());    let mut names = HashMap::new();    if unique.is_empty() {        return Ok(names);    }    let found = in_chunks(&unique, |batch| {        rows(            ctx,            &Query::on("cotton_msg_contacts")                .columns(&["id", "display_name", "phone_e164"])                .filter(Filter::In("id".to_string(), in_values(batch))),        )    })?;    for row in found {        let Some(id) = text(&row, "id") else { continue };        if let Some(name) = trimmed(text(&row, "display_name")) {            names.insert(id, name);            continue;        }        // `phone_e164` became NULLABLE at schema v38 — an iMessage counterpart        // can be an Apple ID email and nothing else, and its reachable        // addresses live in `cotton_msg_contact_handles`. `+null` was what the        // old fallback would have printed on such a contact.        let label = match text(&row, "phone_e164") {            Some(phone) if !phone.is_empty() => format!("+{phone}"),            _ => "(unknown)".to_string(),        };        names.insert(id, label);    }    Ok(names)}/// A contact's person, for the grouping. `None` where nobody has named them.fn contact_people_by_id(    ctx: &Ctx<'_>,    ids: &[String],) -> Result<Vec<ConversationContact>, ToolFailure> {    let unique = unique_ids(ids.iter().cloned());    if unique.is_empty() {        return Ok(Vec::new());    }    // A contact's person is who(handle)'s, derived as it is read (PEOPLE BUILD 1b): the same answer every screen    // gives, never the link stored when the contact was made.    let found = in_chunks(&unique, |batch| {        let marks = vec!["?"; batch.len()].join(", ");        ctx.db()            .all(                &format!(                    "SELECT c.id AS id, {person} AS person_id, c.display_name AS display_name FROM cotton_msg_contacts c WHERE c.id IN ({marks})",                    person = cotton_store::protocol::who::contact_person_sql(cotton_store::protocol::who::shared_held(ctx.db()), "c"),                ),                &in_values(batch),            )            .map_err(|error| ToolFailure::new(error.to_string()))    })?;    Ok(found        .into_iter()        .map(|row| ConversationContact {            id: row.text("id").unwrap_or_default().to_string(),            person_id: row.text("person_id").map(str::to_string),            display_name: row.text("display_name").map(str::to_string),        })        .collect())}/// The people those contacts resolve to, named.fn people_for_contacts(    ctx: &Ctx<'_>,    contacts: &[ConversationContact],) -> Result<Vec<ConversationPerson>, ToolFailure> {    let ids = unique_ids(contacts.iter().filter_map(|contact| contact.person_id.clone()));    if ids.is_empty() {        return Ok(Vec::new());    }    let found = in_chunks(&ids, |batch| {        rows(            ctx,            &Query::on("cotton_people")                .columns(&["id", "full_name"])                .filter(Filter::In("id".to_string(), in_values(batch))),        )    })?;    Ok(found        .into_iter()        .map(|row| ConversationPerson {            id: text(&row, "id").unwrap_or_default(),            full_name: text(&row, "full_name"),        })        .collect())}/// Participant rows → the name to print for each.////// A participant is the per-thread row a message attributes to (schema v5). It/// may be IDENTIFIED — it carries a contact, and the contact's name is what a/// reader should see, so renaming the contact renames every bubble — or/// UNIDENTIFIED, in which case the label the export wrote is the best name/// anyone has. Two reads, never one per message.fn participant_names_by_id(    ctx: &Ctx<'_>,    ids: &[String],) -> Result<HashMap<String, String>, ToolFailure> {    let unique = unique_ids(ids.iter().cloned());    let mut names = HashMap::new();    if unique.is_empty() {        return Ok(names);    }    let seats = in_chunks(&unique, |batch| {        rows(            ctx,            &Query::on("cotton_msg_thread_participants")                .columns(&["id", "display_name", "contact_id"])                .filter(Filter::In("id".to_string(), in_values(batch))),        )    })?;    let contact_ids: Vec<String> = seats        .iter()        .filter_map(|seat| text(seat, "contact_id"))        .collect();    let contact_names = contact_names_by_id(ctx, &contact_ids)?;    for seat in &seats {        let Some(id) = text(seat, "id") else { continue };        let from_contact = text(seat, "contact_id").and_then(|c| contact_names.get(&c).cloned());        let label = from_contact            .or_else(|| trimmed(text(seat, "display_name")))            .unwrap_or_else(|| "(unknown)".to_string());        names.insert(id, label);    }    Ok(names)}/// Whether these messages are a SHARED database's — filed copies/// (`messages::filing_copy`), read by everybody there, where "out" is only/// "mine" to the one who filed the chat. The copier says his own lines from a/// seat bound to the person he is in that database, so an outgoing line is/// signed with that seat's name, never the owner's word: to every other/// reader "owner" would say the line was theirs.fn is_filed(ctx: &Ctx<'_>) -> Result<bool, ToolFailure> {    Ok(ctx.file_kind()? == cotton_store::link_rule::FileKind::Shared)}/// A thread's human name: the counterpart's name for a dm, the title otherwise.////// A dm prefers its CONTACT over its title, because since v5 an imported dm/// carries the export's title from the moment it is created — while its/// counterpart may still be unidentified — and once someone names that person/// the contact is the truer name. A dm with no contact yet is its title; a/// group is always its title.fn thread_name(row: &Map<String, Value>, contact_names: &HashMap<String, String>) -> String {    let contact_id = text(row, "contact_id");    let unknown = || "(unknown)".to_string();    if text(row, "kind").as_deref() == Some("dm") {        if let Some(contact_id) = contact_id.as_deref().filter(|id| !id.is_empty()) {            return contact_names                .get(contact_id)                .cloned()                .unwrap_or_else(unknown);        }    }    if let Some(title) = trimmed(text(row, "title")) {        return title;    }    if let Some(contact_id) = contact_id.as_deref().filter(|id| !id.is_empty()) {        return contact_names            .get(contact_id)            .cloned()            .unwrap_or_else(unknown);    }    "(untitled)".to_string()}/// Name a phone number the way this thread already names it.////// `self` is the owner: their own reaction, in their own file.fn phone_namer(ctx: &Ctx<'_>, phones: &[String]) -> Result<HashMap<String, String>, ToolFailure> {    let unique: Vec<String> = unique_ids(phones.iter().cloned())        .into_iter()        .filter(|phone| phone != "self")        .collect();    let mut by_phone = HashMap::new();    if unique.is_empty() {        return Ok(by_phone);    }    let found = in_chunks(&unique, |batch| {        rows(            ctx,            &Query::on("cotton_msg_contacts")                .columns(&["phone_e164", "display_name"])                .filter(Filter::In("phone_e164".to_string(), in_values(batch))),        )    })?;    for row in found {        if let (Some(phone), Some(name)) = (text(&row, "phone_e164"), text(&row, "display_name")) {            by_phone.insert(phone, name);        }    }    Ok(by_phone)}fn name_for(by_phone: &HashMap<String, String>, phone: &str) -> String {    if phone == "self" {        return OWNER_ACTOR.to_string();    }    by_phone        .get(phone)        .cloned()        .unwrap_or_else(|| phone.to_string())}// ── the badge lane ──────────────────────────────────────────────────────────/// Which channels each of these threads actually holds.////// A SKIP through `idx_cotton_msg_messages_thread_channel (thread_id,/// channel)`: each thread's first channel, then the first one after it, and so/// on — one index seek per channel a thread holds, whatever its length. A/// thread spans channels (WhatsApp and iMessage under one person), so the/// answer is the messages', not a column of the thread. The DISTINCT this/// replaced walked every message of every listed thread and sorted them: on/// the owner's serving Mac 1,681,586 steps and 7.8 s under the file's hold/// (11 Oct 2026; guard `a_page_reads_its_threads_channels_without_reading_their_messages`)./// The threads are kept to this workspace's own./// The chats among `thread_ids` holding a message the owner has not read:/// one that came in live past the chat's read cursor (`read_seq`), not/// hidden, not in the bin and not cleared away — the per-chat half of the/// Home count's `UNREAD_MESSAGES`, asked through `(thread_id, seq)`.pub(crate) fn unread_threads(    ctx: &Ctx<'_>,    thread_ids: &[String],) -> Result<std::collections::HashSet<String>, ToolFailure> {    let mut out = std::collections::HashSet::new();    for batch in thread_ids.chunks(crate::mcp::handlers::common::ID_CHUNK) {        let sql = format!(            "SELECT t.id AS id FROM cotton_msg_threads t              WHERE t.workspace_id = ? AND t.id IN ({})                AND EXISTS (SELECT 1 FROM cotton_msg_messages m                             WHERE m.thread_id = t.id AND m.seq > t.read_seq                               AND m.direction = 'in' AND m.origin = 'live'                               AND m.hidden_at IS NULL AND m.trashed_at IS NULL                               AND (t.cleared_before IS NULL OR m.sent_at > t.cleared_before))",            holes(batch.len())        );        let mut params = vec![SqlValue::Text(ctx.workspace_id.to_string())];        params.extend(in_values(batch));        // Read under the chat table's own column name: a column it does not        // hold has no codec and reads as nothing (`raw_rows`), so `thread_id`        // answered no chat unread, ever.        for row in raw_rows(ctx, "cotton_msg_threads", &sql, &params)? {            if let Some(id) = text(&row, "id") {                out.insert(id);            }        }    }    Ok(out)}pub(crate) fn channels_by_thread(    ctx: &Ctx<'_>,    thread_ids: &[String],) -> Result<HashMap<String, Vec<String>>, ToolFailure> {    let mut out: HashMap<String, Vec<String>> = HashMap::new();    if thread_ids.is_empty() {        return Ok(out);    }    let vocabulary = message_channels();    let mut seen: Vec<(String, Vec<String>)> = Vec::new();    for batch in thread_ids.chunks(crate::mcp::handlers::common::ID_CHUNK) {        let sql = format!(            "WITH RECURSIVE listed(id) AS (               SELECT id FROM cotton_msg_threads WHERE workspace_id = ? AND id IN ({})             ),             held(thread_id, channel) AS (               SELECT id, (SELECT channel FROM cotton_msg_messages m                            WHERE m.thread_id = listed.id ORDER BY channel LIMIT 1)                 FROM listed               UNION ALL               SELECT thread_id, (SELECT channel FROM cotton_msg_messages m                                   WHERE m.thread_id = held.thread_id AND m.channel > held.channel                                   ORDER BY channel LIMIT 1)                 FROM held WHERE channel IS NOT NULL             )             SELECT thread_id, channel FROM held WHERE channel IS NOT NULL",            holes(batch.len())        );        let mut params = vec![SqlValue::Text(ctx.workspace_id.to_string())];        params.extend(in_values(batch));        for row in raw_rows(ctx, "cotton_msg_messages", &sql, &params)? {            let (Some(thread_id), Some(channel)) = (text(&row, "thread_id"), text(&row, "channel"))            else {                continue;            };            match seen.iter_mut().find(|(id, _)| *id == thread_id) {                Some((_, channels)) => channels.push(channel),                None => seen.push((thread_id, vec![channel])),            }        }    }    for (thread_id, channels) in seen {        // `channels_present` orders by the VOCABULARY, not by first appearance,        // so the same two channels always draw as the same pair of badges — and        // a channel this build has no word for is reported at the end rather        // than dropped.        out.insert(            thread_id,            channels_present(channels.iter().map(String::as_str), &vocabulary),        );    }    Ok(out)}// ── reactions and receipts ──────────────────────────────────────────────────/// Every reaction on these messages, grouped by message id.fn reactions_by_message(    ctx: &Ctx<'_>,    message_ids: &[String],    by_phone: &HashMap<String, String>,) -> Result<HashMap<String, Vec<Value>>, ToolFailure> {    let unique = unique_ids(message_ids.iter().cloned());    let mut out: HashMap<String, Vec<Value>> = HashMap::new();    if unique.is_empty() {        return Ok(out);    }    let found = in_chunks(&unique, |batch| {        rows(            ctx,            &Query::on("cotton_msg_reactions")                .columns(&["message_id", "emoji", "actor", "created_at"])                .filter(Filter::In("message_id".to_string(), in_values(batch)))                .order_by("created_at", Order::Asc),        )    })?;    for row in found {        let (Some(message_id), Some(emoji), Some(actor)) = (            text(&row, "message_id"),            text(&row, "emoji"),            text(&row, "actor"),        ) else {            continue;        };        let mut shaped = Map::new();        shaped.insert("emoji".to_string(), Value::from(emoji));        shaped.insert("by".to_string(), Value::from(name_for(by_phone, &actor)));        out.entry(message_id)            .or_default()            .push(Value::Object(shaped));    }    Ok(out)}/// How far each person in this thread has got. One row per reader, forever.fn receipts_for_thread(    ctx: &Ctx<'_>,    thread_id: &str,    by_phone: &HashMap<String, String>,) -> Result<Vec<Map<String, Value>>, ToolFailure> {    let found = rows(        ctx,        &Query::on("cotton_msg_receipts")            .columns(&["phone", "delivered_seq", "read_seq"])            .eq("thread_id", thread_id.to_string()),    )?;    Ok(found        .into_iter()        .map(|row| {            let phone = text(&row, "phone").unwrap_or_default();            let mut shaped = Map::new();            shaped.insert("name".to_string(), Value::from(name_for(by_phone, &phone)));            shaped.insert(                "deliveredSeq".to_string(),                Value::from(int(&row, "delivered_seq")),            );            shaped.insert("readSeq".to_string(), Value::from(int(&row, "read_seq")));            shaped        })        .collect())}// ── one message, shaped ─────────────────────────────────────────────────────/// One message, shaped for an assistant reading a conversation.////// The sender is resolved through the PARTICIPANT, never through a contact on/// the message: in the personal database ingest writes no `sender_contact_id`/// (retired in v5). A message with no participant is a dm's inbound line, and/// the thread's own name (its contact, or its title while the counterpart is/// unidentified) is who said it.////// `filed` is [`is_filed`]: in a shared database the message is a filed copy/// and an outgoing line is signed by its seat, like any other.fn message_out(    row: &Map<String, Value>,    participant_names: &HashMap<String, String>,    filed: bool,    dm_name: Option<&str>,    media: Vec<Value>,    reactions: Vec<Value>,    // Set only on a MERGED read, where a bubble's thread is not the reader's.    thread_id: Option<&str>,) -> Map<String, Value> {    let meta = row.get("meta");    let system = js_truthy(meta.and_then(|meta| meta.get("system")));    let deleted = text(row, "deleted_at").is_some();    let mut from = Value::Null;    if !system {        let out = text(row, "direction").as_deref() == Some("out");        let seat = text(row, "sender_participant_id");        from = if out && !filed {            Value::from(OWNER_ACTOR)        } else if let Some(seat) = seat {            Value::from(                participant_names                    .get(&seat)                    .cloned()                    .unwrap_or_else(|| "(unknown)".to_string()),            )        } else if out {            Value::from("(unknown)")        } else {            Value::from(dm_name.unwrap_or("(unknown)"))        };    }    let edited_at = text(row, "edited_at");    let edited =        meta.and_then(|meta| meta.get("edited")) == Some(&Value::Bool(true)) || edited_at.is_some();    // Provenance (§D5): `meta.source` is what the ingesting device wrote down    // about where a line came from — the verbatim service label, the machine    // that read it, and that source's own id. Passed through as an OBJECT and    // never restated in English.    let source = meta        .and_then(|meta| meta.get("source"))        .filter(|source| source.is_object());    let mut out = Map::new();    out.insert("id".to_string(), Value::from(text(row, "id")));    if let Some(thread_id) = thread_id {        out.insert("threadId".to_string(), Value::from(thread_id));    }    out.insert("sentAt".to_string(), Value::from(text(row, "sent_at")));    // In a shared database "out" would tell each reader the line was their    // own: it is only that to the one who filed the chat. `from` says whose.    let direction = if filed { Some("in".to_string()) } else { text(row, "direction") };    out.insert("direction".to_string(), Value::from(direction));    // Always, on every message, in both readers: the channel is a fact about    // the MESSAGE, which is exactly what lets one DM thread carry an iMessage    // and an SMS to the same person (§D4).    out.insert("channel".to_string(), Value::from(text(row, "channel")));    out.insert("from".to_string(), from);    // A deleted message keeps its place in the conversation and loses its    // contents — the same thing every reader sees.    out.insert(        "body".to_string(),        if deleted {            Value::Null        } else {            match text(row, "body") {                Some(body) => Value::from(body),                None => Value::Null,            }        },    );    out.insert(        "media".to_string(),        Value::Array(if deleted { Vec::new() } else { media }),    );    out.insert(        "seq".to_string(),        match row.get("seq").and_then(Value::as_i64) {            Some(seq) => Value::from(seq),            None => Value::Null,        },    );    if system {        out.insert("system".to_string(), Value::Bool(true));    }    if deleted {        out.insert("deleted".to_string(), Value::Bool(true));    }    // `edited: true` stays for clients that already read it; `editedAt` is the    // one schema v9 actually stores.    if edited {        out.insert("edited".to_string(), Value::Bool(true));    }    if let Some(edited_at) = edited_at {        out.insert("editedAt".to_string(), Value::from(edited_at));    }    let source_facts = source.and_then(|source| serde_json::from_value::<cotton_core::messages::MessageSource>(source.clone()).ok());    let reactions = if deleted {        Vec::new()    } else if text(row,"channel").as_deref() == Some("instagram") {        source_facts.as_ref().and_then(|source|source.instagram_reactions()).map(|facts| facts.iter().map(|fact| {            let by = if fact.from_me { "owner".to_string() }                else { fact.handle.as_ref().map(|handle|format!("@{handle}")).unwrap_or_else(||"Instagram user".into()) };            serde_json::json!({"emoji":fact.emoji,"by":by,"siteUserId":fact.user_id})        }).collect()).unwrap_or(reactions)    } else { reactions };    if !reactions.is_empty() {        out.insert("reactions".to_string(), Value::Array(reactions));    }    // Absent, not null, on a message nobody imported: a line the owner typed in    // Cotton came from nowhere else, and an empty `source` would read as a    // provenance that got lost.    if let Some(source) = source {        out.insert("source".to_string(), source.clone());    }    out}// ── list_message_threads ────────────────────────────────────────────────────struct ListMessageThreadsArgs {    group_by: String,    limit: i64,}fn validate_list_message_threads(args: &Map<String, Value>) -> Valid<ListMessageThreadsArgs> {    let group_by = optional_string(args, "groupBy");    if let Some(group_by) = &group_by {        if !MESSAGE_GROUP_BY.contains(&group_by.as_str()) {            return fail(format!(                "groupBy must be one of: {}",                MESSAGE_GROUP_BY.join(", ")            ));        }    }    Ok(ListMessageThreadsArgs {        group_by: group_by.unwrap_or_else(|| "person".to_string()),        limit: bounded_limit(args, 50, crate::mcp::handlers::common::MAX_LIST),    })}/// The message inbox — by default ONE ROW PER PERSON (schema v38, §D4).////// `groupBy: "thread"` is the raw file, one row per thread, for a caller that/// wants what is actually stored.pub fn list_message_threads(ctx: &mut Ctx<'_>, args: &Map<String, Value>) -> ToolResult {    let args = validate_list_message_threads(args)?;    // NULLS LAST on a descending order, which the query builder cannot say:    // `nullsFirst: false` over there, and SQLite sorts NULL smallest, so a    // plain DESC would put every silent thread at the top of the page and push    // the live ones off the end of the limit.    let sql = format!(        "SELECT {} FROM cotton_msg_threads        WHERE workspace_id = ?        ORDER BY last_message_at IS NULL, last_message_at DESC        LIMIT ?",        THREAD_COLUMNS.join(", ")    );    let mut rows_of_threads = raw_rows(        ctx,        "cotton_msg_threads",        &sql,        &[            SqlValue::Text(ctx.workspace_id.to_string()),            SqlValue::Integer(args.limit),        ],    )?;    let contact_ids: Vec<String> = rows_of_threads        .iter()        .filter_map(|row| text(row, "contact_id"))        .collect();    let contact_names = contact_names_by_id(ctx, &contact_ids)?;    // Group sizes, one chunked read — never one count per thread. Every    // participant counts, identified or not: an unidentified participant is    // still a person in the thread.    let group_ids: Vec<String> = rows_of_threads        .iter()        .filter(|row| text(row, "kind").as_deref() == Some("group"))        .filter_map(|row| text(row, "id"))        .collect();    let mut counts: HashMap<String, i64> = HashMap::new();    if !group_ids.is_empty() {        let members = in_chunks(&group_ids, |batch| {            rows(                ctx,                &Query::on("cotton_msg_thread_participants")                    .columns(&["thread_id"])                    .filter(Filter::In("thread_id".to_string(), in_values(batch))),            )        })?;        for member in members {            if let Some(thread_id) = text(&member, "thread_id") {                *counts.entry(thread_id).or_insert(0) += 1;            }        }    }    let thread_ids: Vec<String> = rows_of_threads        .iter()        .filter_map(|row| text(row, "id"))        .collect();    let channels = channels_by_thread(ctx, &thread_ids)?;    let conversations: Vec<Conversation> = if args.group_by == "thread" {        // One conversation per thread, keyed the way core keys a lone one, so        // both modes take exactly the same shaping code below.        rows_of_threads            .iter()            .map(|row| {                let id = text(row, "id").unwrap_or_default();                Conversation {                    key: format!("thread:{id}"),                    person_id: None,                    title: Some(thread_name(row, &contact_names)),                    thread_ids: vec![id],                    last_message_at: text(row, "last_message_at"),                }            })            .collect()    } else {        let contacts = contact_people_by_id(ctx, &contact_ids)?;        let people = people_for_contacts(ctx, &contacts)?;        let shaped: Vec<ConversationThread> = rows_of_threads            .iter()            .map(|row| ConversationThread {                id: text(row, "id").unwrap_or_default(),                kind: if text(row, "kind").as_deref() == Some("group") {                    ThreadKind::Group                } else {                    ThreadKind::Dm                },                contact_id: text(row, "contact_id"),                // The NAME this reader would give the lone thread, so core's                // fallback title and this file's `thread_name` cannot disagree                // about what an unidentified dm is called.                title: Some(thread_name(row, &contact_names)),                last_message_at: text(row, "last_message_at"),            })            .collect();        group_threads_by_person(&shaped, &contacts, &people)    };    let vocabulary = message_channels();    let mut out_threads = Vec::with_capacity(conversations.len());    for conversation in &conversations {        // The newest thread in the conversation is the one whose preview the        // row shows: a merged conversation's one-line preview is the last thing        // that was said, wherever it was said.        let mut threads: Vec<&Map<String, Value>> = conversation            .thread_ids            .iter()            .filter_map(|id| {                rows_of_threads                    .iter()                    .find(|row| text(row, "id").as_deref() == Some(id.as_str()))            })            .collect();        threads.sort_by(|a, b| {            text(b, "last_message_at")                .unwrap_or_default()                .cmp(&text(a, "last_message_at").unwrap_or_default())        });        let newest = threads.first().copied();        let lone = (threads.len() == 1).then(|| threads[0]);        let present = channels_present(            threads                .iter()                .flat_map(|row| {                    let id = text(row, "id").unwrap_or_default();                    channels.get(&id).cloned().unwrap_or_default()                })                .collect::<Vec<String>>()                .iter()                .map(String::as_str)                .collect::<Vec<&str>>(),            &vocabulary,        );        let mut shaped = Map::new();        if let Some(lone) = lone {            shaped.insert("id".to_string(), Value::from(text(lone, "id")));        }        if let Some(person_id) = conversation            .person_id            .as_deref()            .filter(|id| !id.is_empty())        {            shaped.insert("personId".to_string(), Value::from(person_id));        }        // A merged conversation is a DM by construction — a group never merges        // into anything, so a row with two threads under it is two DMs.        shaped.insert(            "kind".to_string(),            Value::from(match lone {                Some(lone) => text(lone, "kind").unwrap_or_else(|| "dm".to_string()),                None => "dm".to_string(),            }),        );        shaped.insert(            "name".to_string(),            Value::from(                conversation                    .title                    .clone()                    .unwrap_or_else(|| "(untitled)".to_string()),            ),        );        shaped.insert(            "threadIds".to_string(),            Value::Array(                conversation                    .thread_ids                    .iter()                    .map(|id| Value::from(id.clone()))                    .collect(),            ),        );        shaped.insert(            "channels".to_string(),            Value::Array(present.into_iter().map(Value::from).collect()),        );        shaped.insert(            "lastMessageAt".to_string(),            match &conversation.last_message_at {                Some(at) => Value::from(at.clone()),                None => Value::Null,            },        );        shaped.insert(            "preview".to_string(),            match newest.and_then(|row| text(row, "last_message_preview")) {                Some(preview) => Value::from(preview),                None => Value::Null,            },        );        // A conversation is archived only when EVERY thread under it is: one        // live number means the person is not filed away.        shaped.insert(            "archived".to_string(),            Value::Bool(!threads.is_empty() && threads.iter().all(|row| flag(row, "archived"))),        );        if let Some(lone) = lone {            let id = text(lone, "id").unwrap_or_default();            if text(lone, "kind").as_deref() == Some("group") {                shaped.insert(                    "participantCount".to_string(),                    Value::from(counts.get(&id).copied().unwrap_or(0)),                );            }        }        out_threads.push(Value::Object(shaped));    }    let mut out = Map::new();    out.insert("threads".to_string(), Value::Array(out_threads));    Ok(Value::Object(out))}// ── read_message_thread ─────────────────────────────────────────────────────struct ReadMessageThreadArgs {    thread_id: Option<String>,    person_id: Option<String>,    before: Option<String>,    /// The id half of the page cursor, paired with `before`.    ///    /// OPTIONAL and additive: `before` alone keeps meaning what it always has,    /// so no caller that already pages this tool changes behaviour. With both,    /// the cursor is a KEYSET and a page boundary that lands inside a run of    /// messages sharing one instant — which an import produces by the    /// hundred — no longer drops the rest of that run for ever.    before_id: Option<String>,    limit: i64,}/// `read_message_thread` opens ONE conversation, addressed either way.////// EXACTLY ONE of `threadId` and `personId`. Both together is a caller that has/// not decided which conversation it wants — the person's merged timeline and/// one thread of it are different answers — and silently preferring one would/// hand back half a conversation to somebody who asked for the whole thing.fn validate_read_message_thread(args: &Map<String, Value>) -> Valid<ReadMessageThreadArgs> {    let thread_id = optional_string(args, "threadId");    let person_id = optional_string(args, "personId");    if thread_id.is_none() == person_id.is_none() {        return fail(            "pass exactly one of threadId or personId — a thread is one conversation, a person is \             every DM thread they hold merged into one",        );    }    if let Some(thread_id) = &thread_id {        if !is_uuid(thread_id) {            return fail("threadId must be a uuid");        }    }    if let Some(person_id) = &person_id {        if !is_uuid(person_id) {            return fail("personId must be a uuid");        }    }    let before = match optional_string(args, "before") {        None => None,        Some(raw) => match iso_timestamp(&raw) {            Some(parsed) => Some(parsed),            None => return fail("before must be an ISO 8601 timestamp"),        },    };    // The id half is an OPAQUE cursor the caller echoes back from    // `nextBeforeId`, not an id anybody types — so it is checked for being    // there and nothing else. `before` is validated because a malformed    // instant silently compares as text; an id that names no row simply    // matches nothing extra, and the SQL is parameterised either way.    let before_id = match optional_string(args, "beforeId") {        None => None,        Some(raw) if !raw.trim().is_empty() => Some(raw),        Some(_) => return fail("beforeId must be the nextBeforeId from a previous page"),    };    if before_id.is_some() && before.is_none() {        return fail("beforeId is the second half of a cursor — pass before with it");    }    Ok(ReadMessageThreadArgs {        thread_id,        person_id,        before,        before_id,        limit: bounded_limit(args, 50, 100),    })}/// The threads a merged conversation is made of, and what to call it.////// `personId` names a PERSON, not a thread, so this is where "which threads are/// theirs" is answered: their contacts, then the DM threads those contacts/// hold. Groups are deliberately excluded — a group chat is not "a conversation/// with Ravi", and folding one in because he is a member would put a room full/// of other people's words under his name.fn conversation_of(    ctx: &Ctx<'_>,    person_id: &str,) -> Result<(String, Vec<Map<String, Value>>), ToolFailure> {    let person = rows(        ctx,        &Query::on("cotton_people")            .columns(&["id", "full_name"])            .eq("id", person_id.to_string())            .limit(1),    )?    .into_iter()    .next();    let contact_ids: Vec<String> = rows(        ctx,        &Query::on("cotton_msg_contacts")            .columns(&["id"])            .eq("person_id", person_id.to_string()),    )?    .into_iter()    .filter_map(|row| text(&row, "id"))    .collect();    let mut threads: Vec<Map<String, Value>> = Vec::new();    if !contact_ids.is_empty() {        threads = in_chunks(&contact_ids, |batch| {            rows(                ctx,                &Query::on("cotton_msg_threads")                    .columns(THREAD_COLUMNS_WITH_SUMMARY)                    .eq("kind", "dm".to_string())                    .filter(Filter::In("contact_id".to_string(), in_values(batch))),            )        })?;    }    if threads.is_empty() {        // One answer for "no such person", "not this workspace" and "nobody has        // ever messaged them" — the probe-resistance rule, and an empty        // conversation would read as "you have never spoken", which is a        // different and possibly untrue statement.        return Err(ToolFailure::new(            "no conversation with that person in this workspace",        ));    }    threads.sort_by(|a, b| {        text(a, "id")            .unwrap_or_default()            .cmp(&text(b, "id").unwrap_or_default())    });    let name = person        .and_then(|row| trimmed(text(&row, "full_name")))        .unwrap_or_else(|| "(unnamed)".to_string());    Ok((name, threads))}/// One conversation's messages in time order — by thread, or by PERSON.////// `personId` reads every DM thread that person's contacts hold and interleaves/// them through core's `merge_timelines`, so a person reachable from two/// numbers reads as one conversation with a channel on every line (§D4). The/// pagination is unchanged either way: the newest page by default, `before`/// walks backwards, and `nextBefore` is the oldest instant on the page.pub fn read_message_thread(ctx: &mut Ctx<'_>, args: &Map<String, Value>) -> ToolResult {    let args = validate_read_message_thread(args)?;    let mut conversation_name: Option<String> = None;    let mut thread_rows: Vec<Map<String, Value>> = match &args.person_id {        Some(person_id) => {            let (name, threads) = conversation_of(ctx, person_id)?;            conversation_name = Some(name);            threads        }        None => {            let thread_id = args.thread_id.clone().unwrap_or_default();            let found = rows(                ctx,                &Query::on("cotton_msg_threads")                    .columns(THREAD_COLUMNS_WITH_SUMMARY)                    .eq("id", thread_id)                    .limit(1),            )?            .into_iter()            .next();            // One answer for "absent" and "not this workspace" — the same            // probe-resistance rule the import endpoint follows.            let Some(thread) = found else {                return Err(ToolFailure::new("no such thread in this workspace"));            };            vec![thread]        }    };    let thread_ids: Vec<String> = thread_rows        .iter()        .filter_map(|row| text(row, "id"))        .collect();    let Some(primary) = thread_rows.first() else {        return Err(ToolFailure::new("no such thread in this workspace"));    };    let mut query = Query::on("cotton_msg_messages")        .columns(MESSAGE_COLUMNS)        .filter(Filter::In("thread_id".to_string(), in_values(&thread_ids)))        .order_by("sent_at", Order::Desc)        // The ID is the TIEBREAK the cursor below rests on. Two hundred        // WhatsApp messages imported out of one backup can share a `sent_at`        // to the second, and an order that leaves a tie to SQLite's own row        // order answers an arbitrary page each time it is asked.        .order_by("id", Order::Desc)        .limit(args.limit);    query = match (&args.before, &args.before_id) {        (Some(before), Some(before_id)) => query.filter(Filter::KeysetBefore {            column: "sent_at".to_string(),            value: SqlValue::Text(before.clone()),            tie_column: "id".to_string(),            tie: SqlValue::Text(before_id.clone()),        }),        // An instant with no id: the older, weaker cursor, kept for a caller        // that already pages this tool. It drops a tie at the boundary, which        // is why every caller in this repo now sends both.        (Some(before), None) => query.filter(Filter::Lt(            "sent_at".to_string(),            SqlValue::Text(before.clone()),        )),        _ => query,    };    let mut page = rows(ctx, &query)?;    // Chronological, the way a conversation reads — and through core's merge    // rather than a local reverse, so a tie between two sources that both stamp    // to the second breaks the SAME way here as it does on the phone.    let mut by_thread: Vec<(String, Vec<ConversationMessage>)> = Vec::new();    for row in &page {        let (Some(id), Some(thread_id), Some(sent_at), Some(channel)) = (            text(row, "id"),            text(row, "thread_id"),            text(row, "sent_at"),            text(row, "channel"),        ) else {            continue;        };        let message = ConversationMessage {            id,            thread_id: thread_id.clone(),            sent_at,            channel,        };        match by_thread.iter_mut().find(|(key, _)| *key == thread_id) {            Some((_, list)) => list.push(message),            None => by_thread.push((thread_id, vec![message])),        }    }    let lanes: Vec<&[ConversationMessage]> =        by_thread.iter().map(|(_, list)| list.as_slice()).collect();    let ordered: Vec<&Map<String, Value>> = merge_timelines(lanes)        .into_iter()        .filter_map(|message| {            page.iter()                .find(|row| text(row, "id").as_deref() == Some(message.id.as_str()))        })        .collect();    let seat_ids: Vec<String> = ordered        .iter()        .filter_map(|row| text(row, "sender_participant_id"))        .collect();    let participant_names = participant_names_by_id(ctx, &seat_ids)?;    let filed = is_filed(ctx)?;    let dm_contact_ids: Vec<String> = thread_rows        .iter()        .filter_map(|row| text(row, "contact_id"))        .collect();    let dm_names = contact_names_by_id(ctx, &dm_contact_ids)?;    // Reactions and receipts name PEOPLE by number in the file; an assistant    // should read a name. One namer for both, resolved once.    let receipt_phones: Vec<String> = in_chunks(&thread_ids, |batch| {        rows(            ctx,            &Query::on("cotton_msg_receipts")                .columns(&["phone"])                .filter(Filter::In("thread_id".to_string(), in_values(batch))),        )    })?    .into_iter()    .filter_map(|row| text(&row, "phone"))    .collect();    let reaction_actors: Vec<String> = in_chunks(&thread_ids, |batch| {        rows(            ctx,            &Query::on("cotton_msg_reactions")                .columns(&["actor"])                .filter(Filter::In("thread_id".to_string(), in_values(batch))),        )    })?    .into_iter()    .filter_map(|row| text(&row, "actor"))    .collect();    let mut phones = receipt_phones;    phones.extend(reaction_actors);    let by_phone = phone_namer(ctx, &phones)?;    let message_ids: Vec<String> = ordered.iter().filter_map(|row| text(row, "id")).collect();    let mut reactions = reactions_by_message(ctx, &message_ids, &by_phone)?;    // ONE read per call, on the HEADER: the summary is about the conversation,    // not about any line in it, and `summary_out` runs a count query — inside    // the map over messages it would run once per bubble.    //    // A MERGED conversation of several threads carries none: each summary is    // about one thread, and picking one to speak for the whole conversation    // would put a paragraph about the iMessages over the SMSes too. A merged    // read of a single thread is still that thread, and keeps its summary.    let summary = if thread_rows.len() == 1 {        let id = text(primary, "id").unwrap_or_default();        summary_out(ctx, SummaryKind::Thread, &id, primary)?    } else {        None    };    let mut receipts = Vec::new();    for row in &thread_rows {        let id = text(row, "id").unwrap_or_default();        for mut receipt in receipts_for_thread(ctx, &id, &by_phone)? {            // The thread is named only on a merged read: a receipt is a cursor            // into ONE thread's `seq`, so a list that mixed two threads' cursors            // with no way to tell them apart would be a number nobody could act            // on.            if thread_rows.len() != 1 {                receipt.insert("threadId".to_string(), Value::from(id.clone()));            }            receipts.push(Value::Object(receipt));        }    }    // A dm's seatless inbound lines are the counterpart speaking, so they take    // the conversation's own name — the person's when this is a merged read,    // the contact's when there is one, the export's title while the person is    // still unidentified.    let dm_name_of = |row: &Map<String, Value>| -> Option<String> {        if text(row, "kind").as_deref() != Some("dm") {            return None;        }        conversation_name            .clone()            .or_else(|| Some(thread_name(row, &dm_names)))    };    let mut messages = Vec::with_capacity(ordered.len());    for row in &ordered {        let id = text(row, "id").unwrap_or_default();        let owner = thread_rows            .iter()            .find(|thread| text(thread, "id") == text(row, "thread_id"))            .unwrap_or(primary);        let row_file = text(row, "workspace_id").unwrap_or_default();        let media = media_out(ctx, row.get("media"), &row_file);        messages.push(Value::Object(message_out(            row,            &participant_names,            filed,            dm_name_of(owner).as_deref(),            media,            reactions.remove(&id).unwrap_or_default(),            // Which thread a bubble came from — meaningless on a single-thread            // read, and the one thing a merged one cannot leave out.            if thread_rows.len() == 1 {                None            } else {                text(row, "thread_id")            }            .as_deref(),        )));    }    let mut thread = Map::new();    // Only when the conversation IS one thread — see `list_message_threads`.    if thread_rows.len() == 1 {        thread.insert("id".to_string(), Value::from(text(primary, "id")));    }    if let Some(person_id) = &args.person_id {        thread.insert("personId".to_string(), Value::from(person_id.clone()));    }    thread.insert(        "kind".to_string(),        Value::from(if args.person_id.is_some() {            "dm".to_string()        } else {            text(primary, "kind").unwrap_or_default()        }),    );    thread.insert(        "name".to_string(),        Value::from(            conversation_name                .clone()                .unwrap_or_else(|| thread_name(primary, &dm_names)),        ),    );    thread.insert(        "threadIds".to_string(),        Value::Array(            thread_ids                .iter()                .map(|id| Value::from(id.clone()))                .collect(),        ),    );    if let Some(summary) = summary {        thread.insert("summary".to_string(), summary);    }    let mut out = Map::new();    out.insert("thread".to_string(), Value::Object(thread));    out.insert("messages".to_string(), Value::Array(messages));    out.insert("receipts".to_string(), Value::Array(receipts));    // Page handle: the OLDEST row on this page, both halves. Full page =    // probably more. `ordered` is chronological, so the oldest is `first()`.    let oldest = (ordered.len() as i64 == args.limit)        .then(|| ordered.first())        .flatten();    out.insert(        "nextBefore".to_string(),        oldest            .and_then(|row| text(row, "sent_at"))            .map_or(Value::Null, Value::from),    );    out.insert(        "nextBeforeId".to_string(),        oldest            .and_then(|row| text(row, "id"))            .map_or(Value::Null, Value::from),    );    Ok(Value::Object(out))}// ── search_messages ─────────────────────────────────────────────────────────struct SearchMessagesArgs {    query: String,    thread_id: Option<String>,    limit: i64,}fn validate_search_messages(args: &Map<String, Value>) -> Valid<SearchMessagesArgs> {    let Some(query) = crate::mcp::handlers::common::require_string(args, "query") else {        return fail("query is required");    };    let thread_id = optional_string(args, "threadId");    if let Some(thread_id) = &thread_id {        if !is_uuid(thread_id) {            return fail("threadId must be a uuid");        }    }    Ok(SearchMessagesArgs {        query,        thread_id,        limit: bounded_limit(args, 20, 50),    })}pub fn search_messages(ctx: &mut Ctx<'_>, args: &Map<String, Value>) -> ToolResult {    let args = validate_search_messages(args)?;    // `to_match_query` turns a person's words into legal FTS5 and answers    // `None` when there is nothing searchable left — a raw query like `"" AND`    // is a MATCH syntax error, which would be a 500 for typing punctuation.    let found: Vec<Map<String, Value>> = match to_match_query(&args.query) {        None => Vec::new(),        Some(match_query) => {            // `fts_messages` is external-content: its rowid IS the message's, so the JOIN            // back to the table is how a match becomes a row.            let mut params = vec![                SqlValue::Text(match_query),                SqlValue::Text(ctx.workspace_id.to_string()),            ];            let extra = match &args.thread_id {                Some(thread_id) => {                    params.push(SqlValue::Text(thread_id.clone()));                    " AND m.thread_id = ?"                }                None => "",            };            params.push(SqlValue::Integer(args.limit));            let sql = format!(                "SELECT m.id, m.thread_id, m.direction, m.channel, m.body, m.media, m.sent_at,              m.sender_participant_id, m.meta, m.seq, m.edited_at, m.deleted_at         FROM fts_messages         JOIN cotton_msg_messages m ON m.rowid = fts_messages.rowid        WHERE fts_messages MATCH ? AND m.workspace_id = ?          AND m.deleted_at IS NULL{extra}        ORDER BY m.sent_at DESC        LIMIT ?"            );            raw_rows(ctx, "cotton_msg_messages", &sql, &params)?        }    };    let thread_ids = unique_ids(found.iter().filter_map(|row| text(row, "thread_id")));    let thread_rows = in_chunks(&thread_ids, |batch| {        rows(            ctx,            &Query::on("cotton_msg_threads")                .columns(THREAD_COLUMNS)                .filter(Filter::In("id".to_string(), in_values(batch))),        )    })?;    // Two maps, two jobs: participants name the senders, contacts name the dm    // threads.    let seat_ids: Vec<String> = found        .iter()        .filter_map(|row| text(row, "sender_participant_id"))        .collect();    let participant_names = participant_names_by_id(ctx, &seat_ids)?;    let filed = is_filed(ctx)?;    let contact_ids: Vec<String> = thread_rows        .iter()        .filter_map(|row| text(row, "contact_id"))        .collect();    let contact_names = contact_names_by_id(ctx, &contact_ids)?;    let by_phone = phone_namer(ctx, &[])?;    let message_ids: Vec<String> = found.iter().filter_map(|row| text(row, "id")).collect();    let mut reactions = reactions_by_message(ctx, &message_ids, &by_phone)?;    let mut matches = Vec::with_capacity(found.len());    for row in &found {        let id = text(row, "id").unwrap_or_default();        let thread_id = text(row, "thread_id").unwrap_or_default();        let thread = thread_rows            .iter()            .find(|thread| text(thread, "id").as_deref() == Some(thread_id.as_str()));        let dm_name = thread            .filter(|thread| text(thread, "kind").as_deref() == Some("dm"))            .map(|thread| thread_name(thread, &contact_names));        let row_file = text(row, "workspace_id").unwrap_or_default();        let media = media_out(ctx, row.get("media"), &row_file);        let shaped = message_out(            row,            &participant_names,            filed,            dm_name.as_deref(),            media,            reactions.remove(&id).unwrap_or_default(),            None,        );        // `{ threadId, threadName, ...shaped, body }` — the spread's own key        // order, and `body` re-assigned into the slot it already holds rather        // than appended, exactly as a JavaScript object literal does it.        let mut out = Map::new();        out.insert("threadId".to_string(), Value::from(thread_id));        out.insert(            "threadName".to_string(),            Value::from(match thread {                Some(thread) => thread_name(thread, &contact_names),                None => "(unknown)".to_string(),            }),        );        for (key, value) in shaped {            out.insert(key, value);        }        // The line an assistant scans; the full body is one read away.        if let Some(body) = out.get("body").and_then(Value::as_str) {            if utf16_len(body) > SEARCH_BODY_CAP {                let cut = format!("{}…", slice_utf16(body, SEARCH_BODY_CAP - 1));                out.insert("body".to_string(), Value::from(cut));            }        }        matches.push(Value::Object(out));    }    let mut out = Map::new();    out.insert("matches".to_string(), Value::Array(matches));    Ok(Value::Object(out))}#[cfg(test)]#[path = "messages_channels_tests.rs"]mod channels_tests;