Cotton code
921 lines · 34.0 KB · RustRaw
//! What every handler group needs and none of them owns.//!//! Three things live here, and each is a port of something that was spread//! across the TypeScript rather than an invention://!//!   THE ARGUMENT READERS. `protocol.ts` builds all 183 `validateX` functions//!   out of a dozen small readers (`requireString`, `clearableString`,//!   `boundedLimit`, `optionalEnum`, …) whose exact behaviour — a blank string//!   reads as absent, `null` is an instruction, an over-large limit is clamped//!   rather than refused — IS the contract. Ported once.//!//!   THE TWO COLUMN STAMPS POSTGRES USED TO WRITE. `created_at` and//!   `updated_at` are `NOT NULL` with no DEFAULT in the file's DDL, because the//!   cell filled them: an INSERT through `pgrest/client.ts` stamped both//!   (`withDefaults`) and an UPDATE bumped `updated_at` on the 34 tables that//!   carried the `moddatetime` trigger (`pgrest/triggers.ts`). Neither is in//!   the store's own SQL, so the WRITER has to do it — see [`insert_row`] and//!   [`update_row`]. The version-history trigger is NOT reproduced here: unlike//!   `moddatetime` it IS in the file (`cotton_*_version_au`), so the fold's own//!   UPDATE fires it.//!//!   THE ZONE AND THE CALENDARS. `records.ts` reads the workspace's zone out of//!   `cotton_news_settings` and its calendars out of `cotton_collections` on//!   every call that needs one. A calendar only names an event: an event is//!   the database's, never filed into or reached through one (27 Oct 2026 —//!   the object keeps no calendars).use std::collections::HashMap;use cotton_core::constants::SummaryKind;use cotton_core::rules::summaries::{staleness_from, summary_source, SummaryStaleness};use cotton_core::transforms::zoned_clock::{    instant_from_zoned, zone_offset_ms, zoned_parts, ZonedParts,};use cotton_store::protocol::js;use cotton_store::schema::specs::codec_of;use rusqlite::types::Value as SqlValue;use serde_json::{Map, Value};use crate::mcp::dispatch::Ctx;use crate::mcp::protocol::ToolFailure;use crate::mcp::read_db::{Filter, Order, Query, ReadDb};// ── the clock, spelled the way JavaScript spells it ─────────────────────────/// `new Date(ms).toISOString()`.////// Through `js::to_iso_string` rather than chrono's own formatter because the/// two disagree at the edges JavaScript has opinions about (a negative year,/// an instant past year 9999) and the answers this server gives are compared/// character for character against the TypeScript's.pub fn iso_of_ms(ms: i64) -> String {    js::to_iso_string(ms).unwrap_or_default()}/// `new Date(value).getTime()`, or `None` for `Invalid Date`.pub fn parse_ms(value: &str) -> Option<i64> {    js::parse_date_ms(value)}/// The injected clock as milliseconds — never `Utc::now()`.pub fn now_ms(ctx: &Ctx<'_>) -> i64 {    ctx.now.timestamp_millis()}/// The injected clock as the ISO string a row stores.pub fn now_iso(ctx: &Ctx<'_>) -> String {    iso_of_ms(now_ms(ctx))}// ── the two stamps the cell used to write ───────────────────────────────────/// Tables whose UPDATEs bumped `updated_at` automatically.////// Held as a sorted slice and searched, rather than a lazy `HashSet`, because/// it is read once per write.pub const MODDATETIME_TABLES: &[&str] = &[    "cotton_agent_accounts",    "cotton_ai_access",    "cotton_alarms",    "cotton_comments",    "cotton_connections",    "cotton_device_keep",    "cotton_documents",    "cotton_event_attendees",    "cotton_events",    "cotton_goals",    "cotton_google_accounts",    "cotton_home_arrangement",    "cotton_inbox_items",    "cotton_meetings",    "cotton_memories",    "cotton_memory_projects",    "cotton_money_accounts",    "cotton_money_statements",    "cotton_money_transactions",    "cotton_msg_contacts",    "cotton_msg_owner_settings",    "cotton_msg_thread_filings",    "cotton_msg_thread_marks",    "cotton_msg_threads",    "cotton_news_editions",    "cotton_news_settings",    "cotton_outages",    "cotton_news_topics",    "cotton_notes",    "cotton_pages",    "cotton_people",    "cotton_person_handles",    "cotton_person_languages",    "cotton_project_links",    "cotton_prompts",    "cotton_session_messages",    "cotton_sessions",    "cotton_todo_recurrences",    "cotton_todos",];fn has_column(table: &str, column: &str) -> bool {    codec_of(table, column).is_some()}/// Audit columns the insertion writer stamps automatically.pub const WRITE_STAMP_COLUMNS: &[&str] = &["created_at", "updated_at"];/// A row this call is CREATING — `pgrest`'s `withDefaults` plus the upsert.////// Both stamps are filled where the table has them and the patch did not name/// them, which is what the cell's INSERT did. Without this every insert trips/// `NOT NULL` on `created_at`, since the file's DDL has no default for it.pub fn insert_row(    ctx: &mut Ctx<'_>,    table: &str,    id: &str,    mut patch: Map<String, Value>,) -> Result<(), ToolFailure> {    let stamp = now_iso(ctx);    for &column in WRITE_STAMP_COLUMNS {        if has_column(table, column) && !patch.contains_key(column) {            patch.insert(column.to_string(), Value::from(stamp.clone()));        }    }    ctx.writer()?.upsert(table, id, patch);    Ok(())}/// A row this call is CHANGING — the `moddatetime` bump, then the upsert.////// `updated_at` moves unless the caller set it, exactly as the trigger did —/// except for a write that only moves the row into or out of the bin or its/// archive (`trashed_at` and/or `archived_at`, nothing else): that is not an/// edit, so the row keeps its edited time, and a restore or a Bring back puts/// it back where it stood in its list rather than at the top (walks: "a/// restored note jumps to the top", "Bring back rewrites the edited date").pub fn update_row(    ctx: &mut Ctx<'_>,    table: &str,    id: &str,    mut patch: Map<String, Value>,) -> Result<(), ToolFailure> {    let putting_away_only = !patch.is_empty()        && patch.keys().all(|key| matches!(key.as_str(), "trashed_at" | "archived_at"));    if MODDATETIME_TABLES.contains(&table) && !patch.contains_key("updated_at") && !putting_away_only {        let stamp = now_iso(ctx);        patch.insert("updated_at".to_string(), Value::from(stamp));    }    ctx.writer()?.upsert(table, id, patch);    Ok(())}/// Credit the person on their own device, or the assistant connection writing/// for them. The device key is a wire identity, never an assistant's name.pub const AUTHOR_STAMP_COLUMNS: &[&str] = &["author_kind", "author_label"];pub fn author_stamp(ctx: &Ctx<'_>) -> Vec<(String, Value)> {    let (kind, label) = if ctx.is_owner_app() {        ("user", Value::Null)    } else {        ("agent", Value::from(ctx.agent))    };    AUTHOR_STAMP_COLUMNS.iter().zip([Value::from(kind), label]).map(|(key, value)| ((*key).into(), value)).collect()}// ── reading ─────────────────────────────────────────────────────────────────/// A read that turns a store error into the tool failure the TypeScript raises/// from `if (error) throw new ToolFailure(error.message)`.pub fn rows(ctx: &Ctx<'_>, query: &Query) -> Result<Vec<Map<String, Value>>, ToolFailure> {    read_rows(&ctx.read, query)}/// [`rows`] over a workspace's reads alone, for a reader with no connection/// in hand (Home's catalogue asks a project's sections of the file).pub fn read_rows(read: &ReadDb<'_>, query: &Query) -> Result<Vec<Map<String, Value>>, ToolFailure> {    read.select(query)        .map_err(|error| ToolFailure::new(error.to_string()))}/// The first row a query answers — `maybeSingle()`.pub fn maybe_row(ctx: &Ctx<'_>, query: &Query) -> Result<Option<Map<String, Value>>, ToolFailure> {    Ok(rows(ctx, query)?.into_iter().next())}/// One row by id, scoped to this workspace where the table carries the column.pub fn row_by_id(    ctx: &Ctx<'_>,    table: &str,    id: &str,) -> Result<Option<Map<String, Value>>, ToolFailure> {    ctx.read        .by_id(table, id)        .map_err(|error| ToolFailure::new(error.to_string()))}pub fn text(row: &Map<String, Value>, column: &str) -> Option<String> {    row.get(column).and_then(Value::as_str).map(str::to_string)}pub fn int(row: &Map<String, Value>, column: &str) -> i64 {    row.get(column).and_then(Value::as_i64).unwrap_or(0)}pub fn flag(row: &Map<String, Value>, column: &str) -> bool {    match row.get(column) {        Some(Value::Bool(value)) => *value,        Some(Value::Number(number)) => number.as_i64().unwrap_or(0) != 0,        _ => false,    }}/// Put a key in only when there is something to put — the file's own/// convention, and the reason an answer never carries a null.pub fn put(out: &mut Map<String, Value>, key: &str, value: Option<Value>) {    if let Some(value) = value {        out.insert(key.to_string(), value);    }}/// `value ?? null` — a column that is genuinely part of the shape.pub fn or_null(value: Option<String>) -> Value {    value.map_or(Value::Null, Value::from)}// ── the workspace's calendars ───────────────────────────────────────────────/// One `cotton_collections` row, as `loadCtx` reads it.#[derive(Debug, Clone)]pub struct Collection {    pub id: String,    pub name: String,    pub is_default: bool,}/// The workspace's calendars, in `sort_key` order — `loadCtx`'s one read.////// Read per call rather than once per connection: this server has no `Ctx`/// construction step, and a calendar list is one small row set.pub fn calendars(ctx: &Ctx<'_>) -> Result<Vec<Collection>, ToolFailure> {    let query = Query::on("cotton_collections")        .columns(&["id", "kind", "name", "is_default", "sort_key"])        .eq("kind", "calendar".to_string())        .filter(Filter::IsNull("archived_at".to_string()))        .order_by("sort_key", Order::Asc);    Ok(rows(ctx, &query)?        .into_iter()        .map(|row| Collection {            id: text(&row, "id").unwrap_or_default(),            name: text(&row, "name").unwrap_or_default(),            is_default: flag(&row, "is_default"),        })        .collect())}// ── the workspace's zone ────────────────────────────────────────────────────/// Where the workspace lives, or `None`.////// `cotton_news_settings.timezone` is the one workspace-scoped zone in the/// file. A zone this runtime cannot read answers `None` rather than throwing,/// exactly as the TypeScript's `try { new Intl.DateTimeFormat(…) }` does.pub fn workspace_timezone_or_null(ctx: &Ctx<'_>) -> Result<Option<String>, ToolFailure> {    read_timezone_or_null(&ctx.read)}/// [`workspace_timezone_or_null`] over a workspace's reads alone.pub fn read_timezone_or_null(read: &ReadDb<'_>) -> Result<Option<String>, ToolFailure> {    let query = Query::on("cotton_news_settings").columns(&["timezone"]);    let Some(row) = read_rows(read, &query)?.into_iter().next() else {        return Ok(None);    };    let Some(zone) = text(&row, "timezone") else {        return Ok(None);    };    if zone.trim().is_empty() || !is_known_zone(&zone) {        return Ok(None);    }    Ok(Some(zone))}/// The same value with a UTC floor, for READERS. A writer must not use it.pub fn workspace_timezone(ctx: &Ctx<'_>) -> Result<String, ToolFailure> {    Ok(workspace_timezone_or_null(ctx)?.unwrap_or_else(|| "UTC".to_string()))}/// The zone a `where` that names a day reads today in: the workspace's.pub fn where_zone(ctx: &Ctx<'_>) -> Result<cotton_core::records::Zone, ToolFailure> {    Ok(cotton_core::records::Zone::at(read_where_zone(&ctx.read)?.tz, ctx.now))}/// The day a read stands on: the zone it names (else the workspace's) at the/// call's clock, and the today it names where it names one.pub fn reading_zone(ctx: &Ctx<'_>, timezone: Option<&str>, today: Option<&str>) -> Result<cotton_core::records::Zone, ToolFailure> {    let tz = match timezone.filter(|zone| is_known_zone(zone)) {        Some(zone) => cotton_core::records::where_zone(Some(zone)).tz,        None => read_where_zone(&ctx.read)?.tz,    };    Ok(cotton_core::records::Zone::at(tz, ctx.now).on(today))}/// [`where_zone`] over a workspace's reads alone.pub fn read_where_zone(read: &ReadDb<'_>) -> Result<cotton_core::records::Zone, ToolFailure> {    Ok(cotton_core::records::where_zone(read_timezone_or_null(read)?.as_deref()))}/// Can this runtime read a clock in the zone? The only question `Intl` was/// ever asked.pub fn is_known_zone(timezone: &str) -> bool {    zone_offset_ms(0, timezone).is_ok()}fn zone_failure(timezone: &str) -> ToolFailure {    ToolFailure::new(format!(        "unknown timezone {}",        js::json_stringify(&Value::from(timezone))    ))}/// Today's calendar date in a zone — `todayIn`.pub fn today_in(timezone: &str, ms: i64) -> Result<String, ToolFailure> {    let parts = zoned_parts(ms, timezone).map_err(|_| zone_failure(timezone))?;    Ok(format!(        "{:04}-{:02}-{:02}",        parts.year, parts.month, parts.day    ))}/// Midnight local on a calendar date, as an instant — `startOfDayIn`.////// Two passes, for the reason the TypeScript spells out: which offset applies/// is itself a function of the instant, and on a DST-transition night the/// offset at noon is not the offset at midnight.pub fn start_of_day_in(date: &str, timezone: &str) -> Result<i64, ToolFailure> {    let naive = parse_ms(&format!("{date}T00:00:00Z"))        .ok_or_else(|| ToolFailure::new(format!("date must be YYYY-MM-DD, got {date}")))?;    let first = naive - zone_offset_ms(naive, timezone).map_err(|_| zone_failure(timezone))?;    Ok(naive - zone_offset_ms(first, timezone).map_err(|_| zone_failure(timezone))?)}/// The instant a wall clock in a zone names.pub fn instant_of(parts: ZonedParts, ms: i64, timezone: &str) -> Result<i64, ToolFailure> {    instant_from_zoned(parts, ms, timezone).map_err(|_| zone_failure(timezone))}/// One local day, half-open — `dayWindow`.#[derive(Debug, Clone)]pub struct DayWindow {    pub date: String,    pub start: String,    pub end: String,}pub const DAY_MS: i64 = 24 * 60 * 60 * 1000;pub fn day_window(timezone: &str, now: i64) -> Result<DayWindow, ToolFailure> {    let date = today_in(timezone, now)?;    let start = start_of_day_in(&date, timezone)?;    Ok(DayWindow {        date,        start: iso_of_ms(start),        end: iso_of_ms(start + DAY_MS),    })}// ── the summary shape ───────────────────────────────────────────────────────/// The `{ text, by, updatedAt, since? }` object a record's summary answers as/// — a port of `mcp/summaries.ts`'s `summaryOut`.////// The arrival count is a `COUNT(*)` for the same reason the TypeScript's is:/// an imported chat holds tens of thousands of rows and building them to/// discard them is the shape of a read that is fine on a fixture and ruinous/// on the owner's archive.pub fn summary_out(    ctx: &Ctx<'_>,    kind: SummaryKind,    id: &str,    row: &Map<String, Value>,) -> Result<Option<Value>, ToolFailure> {    let source = summary_source(kind);    let Some(prose) = text(row, source.column).filter(|text| !text.is_empty()) else {        return Ok(None);    };    let updated_at = text(row, source.provenance.updated_at);    let since: Option<SummaryStaleness> = match &updated_at {        Some(stamp) => staleness_from(kind, arrivals_since(ctx, kind, id, stamp)?),        None => None,    };    let mut out = Map::new();    out.insert("text".to_string(), Value::from(prose));    out.insert("by".to_string(), or_null(text(row, source.provenance.by)));    out.insert("updatedAt".to_string(), or_null(updated_at));    if let Some(since) = since {        let mut cue = Map::new();        cue.insert("count".to_string(), Value::from(since.count));        cue.insert("noun".to_string(), Value::from(since.noun.as_str()));        out.insert("since".to_string(), Value::Object(cue));    }    Ok(Some(Value::Object(out)))}fn arrivals_since(    ctx: &Ctx<'_>,    kind: SummaryKind,    id: &str,    after: &str,) -> Result<i64, ToolFailure> {    let source = summary_source(kind);    let sql = format!(        "SELECT count(*) AS n FROM {} WHERE {} = ? AND {} > ?",        source.since.table, source.since.parent_column, source.since.instant_column    );    let row = ctx        .db()        .get(            &sql,            &[                SqlValue::Text(id.to_string()),                SqlValue::Text(after.to_string()),            ],        )        .map_err(|error| ToolFailure::new(error.to_string()))?;    Ok(row.and_then(|row| row.int("n")).unwrap_or(0))}// ── argument readers — `protocol.ts`'s validation primitives ────────────────/// What a validator answers. The TypeScript's `ValidationResult<T>` is a/// discriminated union; a `Result` with the message on the error side is the/// same thing, and the message becomes the `ToolFailure`'s sentence unchanged.pub type Valid<T> = Result<T, ToolFailure>;pub fn fail<T>(message: impl Into<String>) -> Valid<T> {    Err(ToolFailure::new(message))}/// `requireString` — a non-blank string, trimmed, or `None`.pub fn require_string(args: &Map<String, Value>, key: &str) -> Option<String> {    let value = args.get(key)?.as_str()?.trim();    (!value.is_empty()).then(|| value.to_string())}/// `optionalString` — the same reading, where absence is legal.pub fn optional_string(args: &Map<String, Value>, key: &str) -> Option<String> {    require_string(args, key)}/// A field where `null` is an INSTRUCTION (clear it), not an absence.////// `Unchanged` / `Cleared` / `Set` rather than `Option<Option<String>>`, which/// reads as nothing at a call site.#[derive(Debug, Clone, Default, PartialEq, Eq)]pub enum Clearable<T> {    #[default]    Unchanged,    Cleared,    Set(T),}impl<T> Clearable<T> {    pub fn is_unchanged(&self) -> bool {        matches!(self, Clearable::Unchanged)    }    /// The JSON a patch writes for it, or `None` to leave the column alone.    pub fn patch_value(&self) -> Option<Value>    where        T: Clone + Into<Value>,    {        match self {            Clearable::Unchanged => None,            Clearable::Cleared => Some(Value::Null),            Clearable::Set(value) => Some(value.clone().into()),        }    }}/// `clearableString`. A blank string is the same instruction as `null`,/// because storing `""` where the app expects NULL renders as an empty line/// rather than as nothing.pub fn clearable_string(args: &Map<String, Value>, key: &str) -> Clearable<String> {    match args.get(key) {        None => Clearable::Unchanged,        Some(Value::Null) => Clearable::Cleared,        Some(Value::String(value)) => {            let trimmed = value.trim();            if trimmed.is_empty() {                Clearable::Cleared            } else {                Clearable::Set(trimmed.to_string())            }        }        Some(_) => Clearable::Unchanged,    }}/// An ISO timestamp we are willing to store — `isoTimestamp`.pub fn iso_timestamp(value: &str) -> Option<String> {    parse_ms(value).map(iso_of_ms)}/// `clearableTimestamp` — as `clearableString`, and a bad instant is refused.pub fn clearable_timestamp(args: &Map<String, Value>, key: &str) -> Valid<Clearable<String>> {    match args.get(key) {        None => Ok(Clearable::Unchanged),        Some(Value::Null) => Ok(Clearable::Cleared),        Some(Value::String(value)) => match iso_timestamp(value) {            Some(parsed) => Ok(Clearable::Set(parsed)),            None => fail(format!(                "{key} must be an ISO 8601 timestamp, or null to clear it"            )),        },        Some(_) => Ok(Clearable::Unchanged),    }}/// `YYYY-MM-DD` that is also a real day — `isCalendarDate`.pub fn is_calendar_date(value: &str) -> bool {    let bytes = value.as_bytes();    if bytes.len() != 10 {        return false;    }    let shaped = bytes.iter().enumerate().all(|(index, byte)| match index {        4 | 7 => *byte == b'-',        _ => byte.is_ascii_digit(),    });    shaped && parse_ms(&format!("{value}T00:00:00Z")).is_some()}/// `clearableCalendarDate`.pub fn clearable_calendar_date(args: &Map<String, Value>, key: &str) -> Valid<Clearable<String>> {    match args.get(key) {        None => Ok(Clearable::Unchanged),        Some(Value::Null) => Ok(Clearable::Cleared),        Some(Value::String(value)) => {            if is_calendar_date(value) {                Ok(Clearable::Set(value.clone()))            } else {                fail(format!("{key} must be YYYY-MM-DD, or null to clear it"))            }        }        Some(_) => Ok(Clearable::Unchanged),    }}/// The one non-number `limit` accepts, and **only the owner's own app ever/// sends it**: `"all"` means "this caller is drawing a screen over its own/// file, answer the whole set".////// A tool's page size is an ASSISTANT'S concern — a model's context is finite/// and a list that answers two thousand rows into it spends the owner's money/// on rows nobody asked for. A screen is the other case entirely: the file is/// one person's, it is on the device already, and the list being drawn IS the/// set. So the cap stays on the tool and the phone's read seam says so out/// loud, in a spelling an assistant cannot reach — `call_tool` refuses a/// non-numeric `limit` before any handler runs/// (`dispatch.rs`, `a_string_limit_is_refused_at_the_mcp_door`), and the/// phone's `read.*` path does not go through it.pub const WHOLE_SET: &str = "all";/// What `"all"` resolves to. A NUMBER rather than `i64::MAX`, because handlers/// do arithmetic on the limit (`.limit(args.limit + 1)` is how three of them/// answer `more`) and `i64::MAX + 1` is a debug-build panic. A million rows of/// anything is already past personal scale, so this is a ceiling that can never/// bite and can never overflow.pub const WHOLE_SET_LIMIT: i64 = 1_000_000;/// The most rows one list or read call answers: every tool's `limit` is/// clamped to it, and the catalogue's schemas say it.pub const MAX_LIST: i64 = 5000;/// `boundedLimit` — clamp rather than reject: an over-large limit is a/// preference, not an error.////// [`WHOLE_SET`] is the one string it reads; see that constant for who sends it.pub fn bounded_limit(args: &Map<String, Value>, fallback: i64, max: i64) -> i64 {    if args.get("limit").and_then(Value::as_str) == Some(WHOLE_SET) {        return WHOLE_SET_LIMIT;    }    match args.get("limit").and_then(Value::as_f64) {        Some(value) if value.is_finite() => (value.trunc() as i64).clamp(1, max),        _ => fallback,    }}/// `optionalBoolean` — absent is fine, wrong-typed is refused.pub fn optional_boolean(args: &Map<String, Value>, key: &str) -> Valid<Option<bool>> {    match args.get(key) {        None => Ok(None),        Some(Value::Bool(value)) => Ok(Some(*value)),        Some(_) => fail(format!("{key} must be true or false")),    }}/// `args[key] === true` — the shape a plain flag is read with.pub fn is_true(args: &Map<String, Value>, key: &str) -> bool {    args.get(key) == Some(&Value::Bool(true))}/// `optionalEnum` — REFUSED rather than downgraded when it is not in the list.pub fn optional_enum(    args: &Map<String, Value>,    key: &str,    allowed: &[&str],) -> Valid<Option<String>> {    let Some(raw) = optional_string(args, key) else {        return Ok(None);    };    if allowed.contains(&raw.as_str()) {        Ok(Some(raw))    } else {        fail(format!("{key} must be one of: {}", allowed.join(", ")))    }}pub const UUID_LENGTH: usize = 36;/// The `UUID_RE` of `protocol.ts`, as a check rather than a regex.pub fn is_uuid(value: &str) -> bool {    let bytes = value.as_bytes();    if bytes.len() != UUID_LENGTH {        return false;    }    bytes.iter().enumerate().all(|(index, byte)| match index {        8 | 13 | 18 | 23 => *byte == b'-',        _ => byte.is_ascii_hexdigit(),    })}/// `requireUuid`.pub fn require_uuid(args: &Map<String, Value>, key: &str) -> Valid<String> {    match require_string(args, key) {        Some(value) if is_uuid(&value) => Ok(value),        _ => fail(format!("{key} must be a uuid")),    }}/// `optionalZone` — the zone a call named, asked of the runtime, never a list.pub fn optional_zone(args: &Map<String, Value>) -> Valid<Option<String>> {    let Some(timezone) = optional_string(args, "timezone") else {        return Ok(None);    };    if is_known_zone(&timezone) {        Ok(Some(timezone))    } else {        Err(zone_failure(&timezone))    }}/// `optionalStringList` — at most 20 non-blank strings.pub fn optional_string_list(args: &Map<String, Value>, key: &str) -> Valid<Option<Vec<String>>> {    let Some(raw) = args.get(key) else {        return Ok(None);    };    let Some(items) = raw.as_array() else {        return fail(format!("{key} must be an array of at most 20 strings"));    };    if items.len() > 20 {        return fail(format!("{key} must be an array of at most 20 strings"));    }    let mut value = Vec::with_capacity(items.len());    for item in items {        match item.as_str() {            Some(entry) if !entry.trim().is_empty() && entry.chars().count() <= 200 => {                value.push(entry.trim().to_string());            }            _ => return fail(format!("{key} entries must be non-empty strings")),        }    }    Ok(Some(value))}/// `JSON.stringify(value)` for a string — how a refusal quotes what it was/// given.pub fn quoted(value: &str) -> String {    js::json_stringify(&Value::from(value))}/// A number the way JavaScript would put it on the wire.////// `serde_json` renders `3.0` as `3.0`; `JSON.stringify(3)` renders `3`, and/// these answers are compared field for field against the TypeScript's. So an/// integral value becomes an INTEGER `Value` — a mood day's average of exactly/// 3, a sort order, a count — and everything else keeps its fraction.pub fn js_number(value: f64) -> Value {    if value.is_finite() && value.fract() == 0.0 && value.abs() < 9.007_199_254_740_992e15 {        return Value::from(value as i64);    }    serde_json::Number::from_f64(value).map_or(Value::Null, Value::Number)}/// The natural order `Map` iteration gives, as an owned patch.pub fn patch(entries: Vec<(&str, Value)>) -> Map<String, Value> {    let mut out = Map::new();    for (key, value) in entries {        out.insert(key.to_string(), value);    }    out}// ── projects, for the tools that take one by slug ───────────────────────────/// One `cotton_memory_projects` row, as a slug lookup needs it.#[derive(Debug, Clone)]pub struct ProjectRef {    pub id: String,    pub slug: String,    pub status: String,}/// Every project, oldest first — `memoryProjects`.pub fn projects(ctx: &Ctx<'_>) -> Result<Vec<ProjectRef>, ToolFailure> {    let query = Query::on("cotton_memory_projects")        .columns(&["id", "slug", "status", "created_at"])        .order_by("created_at", Order::Asc);    Ok(rows(ctx, &query)?        .into_iter()        .map(|row| ProjectRef {            id: text(&row, "id").unwrap_or_default(),            slug: text(&row, "slug").unwrap_or_default(),            status: text(&row, "status").unwrap_or_default(),        })        .collect())}/// Address one project by slug, for a WRITE — `memoryProjectBySlug`.////// An unknown slug names `list_projects` and the projects that DO exist,/// because an assistant should never learn the vocabulary by guessing.pub fn project_by_slug(projects: &[ProjectRef], slug: &str) -> Result<ProjectRef, ToolFailure> {    if let Some(found) = projects        .iter()        .find(|project| project.slug == slug && project.status == "active")    {        return Ok(found.clone());    }    let known: Vec<&str> = projects        .iter()        .filter(|project| project.status == "active")        .map(|project| project.slug.as_str())        .collect();    Err(ToolFailure::new(if known.is_empty() {        "this workspace has no projects yet — list_projects to confirm, or create_project to start \         one"        .to_string()    } else {        format!(            "unknown project {} — list_projects names them; the active projects are: {}",            quoted(slug),            known.join(", ")        )    }))}/// How many ids one `IN (…)` read carries — `ID_CHUNK` in `records.ts`.////// A mirror with 316 managed notes is the observation that put it there: a/// single `IN` over every id of a real workspace is a statement SQLite refuses/// on its own variable limit, and the failure lands on the person whose/// database happens to be the big one.pub const ID_CHUNK: usize = 50;/// Run one `IN (…)` read as several short ones, concatenated — `inChunks`.pub fn in_chunks<T>(    ids: &[String],    mut read: impl FnMut(&[String]) -> Result<Vec<T>, ToolFailure>,) -> Result<Vec<T>, ToolFailure> {    let mut out = Vec::new();    for batch in ids.chunks(ID_CHUNK) {        out.extend(read(batch)?);    }    Ok(out)}/// The word a LIST filter accepts for "rows filed under no project".////// `list_sessions` and `list_thoughts`, whose rows carry a nullable project of/// their own. Not a project, and not a scope memory has: memory is never "under/// no project" for longer than the write that drops it.pub const NO_PROJECT_FILTER: &str = "none";/// Address one project by slug, for a READ — `resolveProject`.////// `None` when no slug was given. Its refusal is NOT/// [`project_by_slug`]'s: the two sentences differ in the TypeScript/// (`projects are:` here, `list_projects names them; the active projects are:`/// there) and they are ported as they are, because a refusal an assistant has/// learned to read is part of the surface.pub fn resolve_project(    projects: &[ProjectRef],    slug: Option<&str>,) -> Result<Option<String>, ToolFailure> {    let Some(slug) = slug.filter(|slug| !slug.is_empty()) else {        return Ok(None);    };    if let Some(found) = projects        .iter()        .find(|project| project.slug == slug && project.status == "active")    {        return Ok(Some(found.id.clone()));    }    let known: Vec<&str> = projects        .iter()        .filter(|project| project.status == "active")        .map(|project| project.slug.as_str())        .collect();    Err(ToolFailure::new(if known.is_empty() {        "this workspace has no projects yet — list_projects to confirm, create_project to start one"            .to_string()    } else {        format!(            "unknown project {} — projects are: {}",            quoted(slug),            known.join(", ")        )    }))}/// What a LIST filter over rows with a project of their own resolves to.#[derive(Debug, Clone, PartialEq, Eq)]pub enum ProjectFilter {    /// The key was absent — every row.    Every,    /// `"none"` — the rows under no project at all. NOT "no filter": answering    /// everything for it would be a silent lie to the one caller asking the    /// narrowest question.    NoProject,    /// That project's id.    Project(String),}/// `projectFilter` — refused by name when the slug is unknown.pub fn project_filter(    projects: &[ProjectRef],    slug: Option<&str>,) -> Result<ProjectFilter, ToolFailure> {    match slug {        None => Ok(ProjectFilter::Every),        Some(NO_PROJECT_FILTER) => Ok(ProjectFilter::NoProject),        Some(slug) => match resolve_project(projects, Some(slug))? {            Some(id) => Ok(ProjectFilter::Project(id)),            None => Ok(ProjectFilter::Every),        },    }}/// `projectSlugOf` — the slug of a project this workspace holds, or `None`.pub fn project_slug_of(projects: &[ProjectRef], project_id: &str) -> Option<String> {    projects        .iter()        .find(|project| project.id == project_id)        .map(|project| project.slug.clone())}/// Rows keyed by their id column, for a caller that read a set and now walks/// the ids it asked for.pub fn by_id(rows: Vec<Map<String, Value>>) -> HashMap<String, Map<String, Value>> {    rows.into_iter()        .filter_map(|row| text(&row, "id").map(|id| (id, row)))        .collect()}// ── the session vocabulary, shared by two groups ────────────────────────────//// `records_2::sessions` (`log_session`, `list_sessions`) and the phone's own// reads and send (`cotton-ffi`) both need these. The bus's four MCP verbs went// on 15 Nov 2026; the message constants stay for the rows already written and// the phone that still draws them. The permanent home is// `cotton_core::constants` — this is where they live until one of the engines// needs them too./// `SESSION_TOOLS` — which agent tool a session ran in. `other` is the seam a/// tool nobody has named yet arrives through.pub const SESSION_TOOLS: &[&str] = &[    "claude-code",    "codex",    "kimi",    "gemini",    "opencode",    "other",];/// `SESSION_TITLE_MAX` — a title is a line, not a paragraph.pub const SESSION_TITLE_MAX: usize = 140;/// `value.slice(0, max)` counted in the UTF-16 units `String.prototype.length`/// counts — a ceiling written for JavaScript, and a person's emoji must not be/// one character at the composer and two here.pub fn utf16_clip(value: &str, max: usize) -> String {    let units: Vec<u16> = value.encode_utf16().collect();    if units.len() <= max {        return value.to_string();    }    String::from_utf16_lossy(&units[..max])}/// `clipped` — redact first, then clip. The order matters: a secret cut in/// half is still most of a secret.pub fn clipped(value: Option<String>, max: usize) -> Option<String> {    value.map(|value| utf16_clip(&cotton_core::transforms::redact::redact_secrets(&value), max))}