//! 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::ValueasSqlValue;use serde_json::{Map, Value};usecrate::mcp::dispatch::Ctx;usecrate::mcp::protocol::ToolFailure;usecrate::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.pubfn iso_of_ms(ms: i64) -> String { js::to_iso_string(ms).unwrap_or_default()}/// `new Date(value).getTime()`, or `None` for `Invalid Date`.pubfn parse_ms(value: &str) -> Option<i64> { js::parse_date_ms(value)}/// The injected clock as milliseconds — never `Utc::now()`.pubfn now_ms(ctx: &Ctx<'_>) -> i64 { ctx.now.timestamp_millis()}/// The injected clock as the ISO string a row stores.pubfn 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.pubconst 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.pubconst 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.pubfn insert_row( ctx: &mutCtx<'_>, 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").pubfn update_row( ctx: &mutCtx<'_>, 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.pubconst AUTHOR_STAMP_COLUMNS: &[&str] = &["author_kind", "author_label"];pubfn 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)`.pubfn 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).pubfn 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()`.pubfn 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.pubfn 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()))}pubfn text(row: &Map<String, Value>, column: &str) -> Option<String> { row.get(column).and_then(Value::as_str).map(str::to_string)}pubfn int(row: &Map<String, Value>, column: &str) -> i64 { row.get(column).and_then(Value::as_i64).unwrap_or(0)}pubfn 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.pubfn put(out: &mutMap<String, Value>, key: &str, value: Option<Value>) {ifletSome(value) = value { out.insert(key.to_string(), value); }}/// `value ?? null` — a column that is genuinely part of the shape.pubfn 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)]pubstructCollection {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.pubfn 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.pubfn 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.pubfn read_timezone_or_null(read: &ReadDb<'_>) -> Result<Option<String>, ToolFailure> {let query = Query::on("cotton_news_settings").columns(&["timezone"]);letSome(row) = read_rows(read, &query)?.into_iter().next() else {returnOk(None); };letSome(zone) = text(&row, "timezone") else {returnOk(None); };if zone.trim().is_empty() || !is_known_zone(&zone) {returnOk(None); }Ok(Some(zone))}/// The same value with a UTC floor, for READERS. A writer must not use it.pubfn 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.pubfn 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.pubfn 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.pubfn 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.pubfn 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`.pubfn 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.pubfn 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.pubfn 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)]pubstructDayWindow {pub date: String,pub start: String,pub end: String,}pubconst DAY_MS: i64 = 24 * 60 * 60 * 1000;pubfn 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.pubfn summary_out( ctx: &Ctx<'_>, kind: SummaryKind, id: &str, row: &Map<String, Value>,) -> Result<Option<Value>, ToolFailure> {let source = summary_source(kind);letSome(prose) = text(row, source.column).filter(|text| !text.is_empty()) else {returnOk(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, };letmut 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));ifletSome(since) = since {letmut 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.pubtypeValid<T> = Result<T, ToolFailure>;pubfn fail<T>(message: implInto<String>) -> Valid<T> {Err(ToolFailure::new(message))}/// `requireString` — a non-blank string, trimmed, or `None`.pubfn 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.pubfn 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)]pubenumClearable<T> { #[default]Unchanged,Cleared,Set(T),}impl<T> Clearable<T> {pubfn is_unchanged(&self) -> bool { matches!(self, Clearable::Unchanged) }/// The JSON a patch writes for it, or `None` to leave the column alone.pubfn patch_value(&self) -> Option<Value>where T: Clone + Into<Value>, {matchself {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.pubfn 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`.pubfn iso_timestamp(value: &str) -> Option<String> { parse_ms(value).map(iso_of_ms)}/// `clearableTimestamp` — as `clearableString`, and a bad instant is refused.pubfn 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`.pubfn is_calendar_date(value: &str) -> bool {let bytes = value.as_bytes();if bytes.len() != 10 {returnfalse; }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`.pubfn 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.pubconst 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.pubconst 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.pubconst 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.pubfn 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.pubfn 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.pubfn 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.pubfn optional_enum( args: &Map<String, Value>, key: &str, allowed: &[&str],) -> Valid<Option<String>> {letSome(raw) = optional_string(args, key) else {returnOk(None); };if allowed.contains(&raw.as_str()) {Ok(Some(raw)) } else { fail(format!("{key} must be one of: {}", allowed.join(", "))) }}pubconst UUID_LENGTH: usize = 36;/// The `UUID_RE` of `protocol.ts`, as a check rather than a regex.pubfn is_uuid(value: &str) -> bool {let bytes = value.as_bytes();if bytes.len() != UUID_LENGTH {returnfalse; } bytes.iter().enumerate().all(|(index, byte)| match index {8 | 13 | 18 | 23 => *byte == b'-', _ => byte.is_ascii_hexdigit(), })}/// `requireUuid`.pubfn 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.pubfn optional_zone(args: &Map<String, Value>) -> Valid<Option<String>> {letSome(timezone) = optional_string(args, "timezone") else {returnOk(None); };if is_known_zone(&timezone) {Ok(Some(timezone)) } else {Err(zone_failure(&timezone)) }}/// `optionalStringList` — at most 20 non-blank strings.pubfn optional_string_list(args: &Map<String, Value>, key: &str) -> Valid<Option<Vec<String>>> {letSome(raw) = args.get(key) else {returnOk(None); };letSome(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")); }letmut 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.pubfn 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.pubfn js_number(value: f64) -> Value {if value.is_finite() && value.fract() == 0.0 && value.abs() < 9.007_199_254_740_992e15 {returnValue::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.pubfn patch(entries: Vec<(&str, Value)>) -> Map<String, Value> {letmut 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)]pubstructProjectRef {pub id: String,pub slug: String,pub status: String,}/// Every project, oldest first — `memoryProjects`.pubfn 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.pubfn project_by_slug(projects: &[ProjectRef], slug: &str) -> Result<ProjectRef, ToolFailure> {ifletSome(found) = projects .iter() .find(|project| project.slug == slug && project.status == "active") {returnOk(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.pubconst ID_CHUNK: usize = 50;/// Run one `IN (…)` read as several short ones, concatenated — `inChunks`.pubfn in_chunks<T>( ids: &[String],mut read: implFnMut(&[String]) -> Result<Vec<T>, ToolFailure>,) -> Result<Vec<T>, ToolFailure> {letmut 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.pubconst 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.pubfn resolve_project( projects: &[ProjectRef], slug: Option<&str>,) -> Result<Option<String>, ToolFailure> {letSome(slug) = slug.filter(|slug| !slug.is_empty()) else {returnOk(None); };ifletSome(found) = projects .iter() .find(|project| project.slug == slug && project.status == "active") {returnOk(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)]pubenumProjectFilter {/// 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.pubfn 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`.pubfn 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.pubfn 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.pubconst SESSION_TOOLS: &[&str] = &["claude-code","codex","kimi","gemini","opencode","other",];/// `SESSION_TITLE_MAX` — a title is a line, not a paragraph.pubconst 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.pubfn 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.pubfn clipped(value: Option<String>, max: usize) -> Option<String> { value.map(|value| utf16_clip(&cotton_core::transforms::redact::redact_secrets(&value), max))}