Cotton code
1994 lines · 98.3 KB · RustRaw
//! Cotton Notes on the phone: every `notes.*` method the new Notes draws//! from. The rules are `cotton_rules::writing`'s (styling, buttons, title,//! preview, hashtags, import); the rows are this device's own copy (signed//! out too; a write queues for the object like any other). The phone decides//! nothing: order, titles, previews, dates, tags, spans, words and colours//! all come from here. The method shapes are written down in the lane's//! `shapes.md` and held by `notes_tests.rs`.//!//! A note is one row of `note` (`cotton_notes`, kind `note`): its `body` is//! the whole Markdown text and its `title` column is kept in step with the//! title the text derives, for every surface that reads the column (search,//! an assistant over MCP). An old note — a stored title over a body that does//! not head with it, pictures attached in `note_attachment` — opens as one//! text with no migration ([`writing::derive::opened_text`],//! [`writing::derive::with_pictures`]); its first edit writes that text.//!//! **Tags are groups.** A hashtag files its note into the note group named//! with its hash (`#work`, `#home/garden`); the hash in the name is what//! tells a group hashtags made from a list a person made by hand, which this//! never touches. The `#` groups mirror the notes' hashtags exactly: an edit//! here files at once, and `notes.list` and `notes.fan` put right whatever an//! edit elsewhere (an assistant over MCP, another phone) left behind. A `#`//! group left with no member goes.//!//! **Pictures** are `photo` records, written in the text where they sit as//! `![words](<record id>)` — a photo's id is `photo:<sha256 of its bytes>`,//! so the same picture is one record wherever it is put, and an assistant//! reads it by that id with `get_media`. `notes.open` answers each picture's media key for the phone//! to draw (`media.ensure`).use std::collections::{BTreeMap, BTreeSet, HashMap};use serde_json::{json, Map, Value};use cotton_core::cotton_rules::writing::{self, derive, find, folds, format, links, search, style, Selection};use cotton_core::rules::notes_writing;use cotton_tools::mcp::dispatch::Ctx;use cotton_tools::mcp::handlers::common::{author_stamp, insert_row, rows as query_rows, update_row};use cotton_tools::mcp::handlers::records_1::notes as note_writes;use cotton_tools::mcp::read_db::Query;use crate::handle::CottonHandle;use crate::methods::MethodError;pub const METHODS: [&str; 35] = [    "notes.archive",    "notes.bin",    "notes.edit",    "notes.empty_bin",    "notes.export",    "notes.fan",    "notes.file",    "notes.find",    "notes.format",    "notes.import",    "notes.info",    "notes.leave",    "notes.link",    "notes.links",    "notes.list",    "notes.memory",    "notes.merge_tags",    "notes.new",    "notes.open",    "notes.picture",    "notes.pin",    "notes.pin_tag",    "notes.remove",    "notes.restore",    "notes.settings",    "notes.side",    "notes.style",    "notes.tag",    "notes.tag_icon",    "notes.tag_icons",    "notes.tags",    "notes.themes",    "notes.unarchive",    "notes.unpin",    "notes.untag",];/// The store table notes live in.pub const NOTES: &str = "cotton_notes";/// The table a group of notes gathers.pub const NOTE: &str = "note";/// The face settings row Notes keeps its look and type in.pub const SETTINGS_ROW: &str = "notes";/// What a picture's address starts with in a note's text: a photo's own id.pub const PHOTO_SRC: &str = "photo:";use cotton_tools::mcp::handlers::records_1::note_tags::GROUP_NAME_MAX;pub(crate) fn bad(why: impl Into<String>) -> MethodError {    MethodError::new("bad_request", why.into())}/// A line of the notes set, filled.pub(crate) fn line(name: &str, fills: &[(&str, &str)]) -> Result<String, MethodError> {    cotton_core::rules::shell_lines::LineSet::shipped("notes")        .and_then(|lines| lines.say(name, fills))        .ok_or_else(|| MethodError::new("unreadable", format!("the notes set says no line {name}")))}/// A count's line: `{name}.zero` for none when the set has one, else the/// plural the count picks.pub(crate) fn counted_line(name: &str, n: usize) -> Result<String, MethodError> {    let said = cotton_core::rules::shell_lines::number(n as i64);    if n == 0 {        if let Ok(zero) = line(&format!("{name}.zero"), &[("n", &said)]) {            return Ok(zero);        }    }    let form = cotton_core::rules::shell_lines::plural_form(&said);    line(&format!("{name}.{form}"), &[("n", &said)])}fn no_note() -> MethodError {    MethodError::new("not_found", line("refusal.no_note", &[]).unwrap_or_default())}/// Answer one of [`METHODS`]. WHILE THE COPY HAS NOT COME WHOLE (its first/// pull under way, or failing: `phone::copy_standing`) an empty list says/// so in place of "No notes yet", and a note not found is `not_here_yet`,/// never "not here any more" (incident, 21 Nov 2026).pub fn call(handle: &CottonHandle, method: &str, request: &Value) -> Result<Value, MethodError> {    use crate::phone::copy_standing;    match answer(handle, method, request) {        Ok(mut answer) if method == "notes.list" => {            let has_rows = answer["rows"].as_array().is_some_and(|rows| !rows.is_empty());            copy_standing::said_on_list(copy_standing::of(&handle.client()), &mut answer, &["empty"], has_rows);            Ok(answer)        }        Err(refused) if refused.code == "not_found" => Err(copy_standing::not_here(copy_standing::of(&handle.client()), refused)),        answered => answered,    }}fn answer(handle: &CottonHandle, method: &str, request: &Value) -> Result<Value, MethodError> {    match method {        "notes.style" => styled_answer(request),        "notes.format" => format_answer(request),        "notes.themes" => themes(handle),        "notes.list" => {            refile(handle)?;            with_read(handle, method, |ctx| list(ctx, request))        }        "notes.fan" => {            refile(handle)?;            with_read(handle, method, fan)        }        "notes.tags" => {            refile(handle)?;            with_read(handle, method, |ctx| Ok(json!({ "tags": tag_tree(ctx)? })))        }        "notes.open" => with_read(handle, method, |ctx| open(ctx, request)),        "notes.info" => with_read(handle, method, |ctx| info(ctx, request)),        "notes.new" => with_write(handle, method, |ctx| new(ctx, request)),        "notes.edit" => with_write(handle, method, |ctx| edit(ctx, request)),        "notes.tag" => with_write(handle, method, |ctx| tag(ctx, request)),        "notes.untag" => with_write(handle, method, |ctx| untag(ctx, request)),        "notes.leave" => with_write(handle, method, |ctx| leave(ctx, request)),        "notes.archive" => with_write(handle, method, |ctx| put_away(ctx, request, Away::Archive)),        "notes.unarchive" => with_write(handle, method, |ctx| put_away(ctx, request, Away::Unarchive)),        "notes.bin" => with_write(handle, method, |ctx| put_away(ctx, request, Away::Bin)),        "notes.restore" => with_write(handle, method, |ctx| put_away(ctx, request, Away::Restore)),        "notes.remove" => with_write(handle, method, |ctx| remove(ctx, request)),        "notes.empty_bin" => with_write(handle, method, |ctx| empty_bin(ctx, request)),        "notes.settings" => settings(handle, request),        "notes.picture" => picture(handle, request),        "notes.import" => super::notes_import::import(handle, request),        "notes.side" => super::notes_side::side(handle, request),        "notes.memory" => super::notes_assistant::memory(handle, request),        "notes.file" => super::notes_files::file(handle, request),        "notes.merge_tags" => merge_tags(handle, request),        "notes.pin" => with_write(handle, method, |ctx| super::notes_side::pin(ctx, request, true)),        "notes.unpin" => with_write(handle, method, |ctx| super::notes_side::pin(ctx, request, false)),        "notes.pin_tag" => super::notes_side::pin_tag(handle, request),        "notes.tag_icon" => super::notes_side::tag_icon(handle, request),        "notes.tag_icons" => super::notes_side::tag_icons(),        "notes.links" => with_read(handle, method, |ctx| link_suggestions(ctx, request)),        "notes.link" => {            let make = request.get("make").and_then(Value::as_bool).unwrap_or(false);            if make { with_write(handle, method, |ctx| open_link(ctx, request)) } else { with_read(handle, method, |ctx| open_link(ctx, request)) }        }        "notes.find" => find_answer(request),        "notes.export" => super::notes_export::export(handle, request),        other => Err(MethodError::new("unknown_method", format!("`{other}` is not a notes method"))),    }}/// Cotton Notes' fan cards (the shared fan's tile for the notebook), and the/// card it stands on.pub(crate) fn fan_cards(client: &crate::shell::client::ClientController) -> Result<(Vec<Value>, Option<String>), MethodError> {    let mut refusal: Option<MethodError> = None;    let answer = client.read_rows("notes.fan", &mut |ctx| {        fan(ctx).map_err(|refused| {            let said = refused.message.clone();            refusal = Some(refused);            said        })    });    let answer = answer.map_err(|why| refusal.take().unwrap_or_else(|| MethodError::new("unreadable", why)))?;    Ok((answer["cards"].as_array().cloned().unwrap_or_default(), answer["current"].as_str().map(str::to_string)))}pub(crate) fn with_read(handle: &CottonHandle, label: &str, mut body: impl FnMut(&mut Ctx<'_>) -> Result<Value, MethodError>) -> Result<Value, MethodError> {    let mut refusal: Option<MethodError> = None;    let answer = handle.client().read_rows(label, &mut |ctx| {        body(ctx).map_err(|refused| {            let said = refused.message.clone();            refusal = Some(refused);            said        })    });    match (answer, refusal) {        (Ok(answer), _) => Ok(answer),        (Err(_), Some(refused)) => Err(refused),        (Err(why), None) => Err(MethodError::new("unreadable", why)),    }}pub(crate) fn with_write(handle: &CottonHandle, label: &str, mut body: impl FnMut(&mut Ctx<'_>) -> Result<Value, MethodError>) -> Result<Value, MethodError> {    let mut refusal: Option<MethodError> = None;    let answer = handle.client().write_rows(label, &mut |ctx| {        body(ctx).map_err(|refused| {            let said = refused.message.clone();            refusal = Some(refused);            said        })    });    match (answer, refusal) {        (Ok(answer), _) => Ok(crate::authoring::own_answer(answer)),        (Err(_), Some(refused)) => Err(refused),        (Err(why), None) => Err(MethodError::new("write_refused", why)),    }}pub(crate) fn tool(failure: cotton_tools::mcp::protocol::ToolFailure) -> MethodError {    MethodError::new("write_refused", failure.to_string())}fn object(value: Value) -> Map<String, Value> {    value.as_object().cloned().unwrap_or_default()}fn text<'a>(request: &'a Value, key: &str) -> Option<&'a str> {    request.get(key).and_then(Value::as_str)}pub(crate) fn id_of<'a>(request: &'a Value) -> Result<&'a str, MethodError> {    text(request, "id").map(str::trim).filter(|id| !id.is_empty()).ok_or_else(|| bad("this names the note's `id`"))}fn selection_of(request: &Value, text_len: u32) -> Selection {    let pick = |key: &str| request.get("selection").and_then(|s| s.get(key)).and_then(Value::as_u64).map(|n| n as u32);    let cursor = request.get("cursor").and_then(Value::as_u64).map(|n| n as u32);    let start = pick("start").or(cursor).unwrap_or(text_len).min(text_len);    let end = pick("end").unwrap_or(start).min(text_len);    Selection { start, end }}// ── a note's row ────────────────────────────────────────────────────────────/// One note as this copy holds it.#[derive(Debug, Clone)]pub(crate) struct Held {    pub id: String,    pub title: Option<String>,    pub body: String,    pub archived: bool,    pub binned: bool,    pub edited: String,    pub made: String,    pub external_id: Option<String>,    /// Pinned in Notes: on top of every list.    pub pinned: bool,    /// The tag keys it is pinned inside.    pub pinned_in: Vec<String>,    /// Written by an assistant (`author_kind` agent).    pub by_assistant: bool,    /// Its attached pictures in order, when read with every note at once ([`every_note`]); `None`: asked per note.    pub attached: Option<Vec<String>>,}const NOTE_COLUMNS: [&str; 11] = ["id", "kind", "title", "body", "archived_at", "trashed_at", "updated_at", "created_at", "external_id", "pinned", "author_kind"];/// Every note's `pinned_in` (a kit column this copy keeps once its kit has/// it: read straight from the table, none where it is not kept yet).fn pins_inside(ctx: &Ctx<'_>, id: Option<&str>) -> BTreeMap<String, Vec<String>> {    let db = ctx.read.driver();    let kept = db.all("SELECT name FROM pragma_table_info('cotton_notes')", &[]).map(|rows| rows.iter().any(|row| row.text("name") == Some("pinned_in"))).unwrap_or(false);    if !kept {        return BTreeMap::new();    }    let ws = rusqlite::types::Value::Text(ctx.workspace_id.to_string());    let found = match id {        Some(id) => db.all("SELECT id, pinned_in FROM cotton_notes WHERE workspace_id = ? AND id = ? AND pinned_in IS NOT NULL", &[ws, rusqlite::types::Value::Text(id.to_string())]),        None => db.all("SELECT id, pinned_in FROM cotton_notes WHERE workspace_id = ? AND pinned_in IS NOT NULL", &[ws]),    };    found        .unwrap_or_default()        .iter()        .filter_map(|row| Some((row.text("id")?.to_string(), serde_json::from_str::<Vec<String>>(row.text("pinned_in")?).ok()?)))        .collect()}fn held_of(row: &Map<String, Value>) -> Held {    let said = |key: &str| row.get(key).and_then(Value::as_str).map(str::to_string).filter(|value| !value.is_empty());    Held {        id: said("id").unwrap_or_default(),        title: said("title"),        body: said("body").unwrap_or_default(),        archived: said("archived_at").is_some(),        binned: said("trashed_at").is_some(),        made: said("created_at").unwrap_or_default(),        edited: said("updated_at").or_else(|| said("created_at")).unwrap_or_default(),        external_id: said("external_id"),        pinned: row.get("pinned").is_some_and(|v| v.as_bool().unwrap_or_else(|| v.as_i64().is_some_and(|n| n != 0))),        pinned_in: Vec::new(),        by_assistant: said("author_kind").as_deref() == Some("agent"),        attached: None,    }}/// Every note of this copy (live, archived and binned; never a journal day).pub(crate) fn every_note(ctx: &Ctx<'_>) -> Result<Vec<Held>, MethodError> {    let found = query_rows(ctx, &Query::on(NOTES).columns(&NOTE_COLUMNS).eq("kind", "note".to_string())).map_err(tool)?;    let mut pins = pins_inside(ctx, None);    // Every note's pictures in one read: asked note by note, a list of a thousand notes asked a thousand times    // (Words' launch, 23 Nov 2026: the largest part of a list's and a side page's time).    let mut pictures = every_attached(ctx);    Ok(found.iter().map(held_of).map(|mut held| {        held.pinned_in = pins.remove(&held.id).unwrap_or_default();        held.attached = Some(pictures.remove(&held.id).unwrap_or_default());        held    }).collect())}pub(crate) fn note(ctx: &Ctx<'_>, id: &str) -> Result<Held, MethodError> {    let found = query_rows(ctx, &Query::on(NOTES).columns(&NOTE_COLUMNS).eq("id", id.to_string()).eq("kind", "note".to_string())).map_err(tool)?;    let mut held = found.first().map(held_of).ok_or_else(no_note)?;    held.pinned_in = pins_inside(ctx, Some(id)).remove(id).unwrap_or_default();    Ok(held)}/// An old note's attached pictures (`note_attachment`), in their old order,/// as the addresses the text writes them by.fn attached(ctx: &Ctx<'_>, id: &str) -> Result<Vec<String>, MethodError> {    let found = query_rows(ctx, &Query::on(note_writes::ATTACHMENTS).columns(&["note_id", "record_kind", "record_id", "position"]).eq("note_id", id.to_string())).unwrap_or_default();    Ok(attached_by_note(found).remove(id).unwrap_or_default())}/// Every note's attached pictures, by note, each note's in order: [`attached`] for every note in one read.fn every_attached(ctx: &Ctx<'_>) -> BTreeMap<String, Vec<String>> {    attached_by_note(query_rows(ctx, &Query::on(note_writes::ATTACHMENTS).columns(&["note_id", "record_kind", "record_id", "position"])).unwrap_or_default())}/// Attachment rows as each note's pictures, by position: a photo's (or an untyped one's) address.fn attached_by_note(mut found: Vec<Map<String, Value>>) -> BTreeMap<String, Vec<String>> {    found.sort_by(|a, b| {        let place = |row: &Map<String, Value>| row.get("position").and_then(Value::as_f64).unwrap_or(0.0);        place(a).total_cmp(&place(b))    });    let mut by_note: BTreeMap<String, Vec<String>> = BTreeMap::new();    for row in found.iter().filter(|row| matches!(row.get("record_kind").and_then(Value::as_str), Some("photo") | None)) {        let (Some(note), Some(id)) = (row.get("note_id").and_then(Value::as_str), row.get("record_id").and_then(Value::as_str)) else { continue };        by_note.entry(note.to_string()).or_default().push(if id.starts_with(PHOTO_SRC) { id.to_string() } else { format!("{PHOTO_SRC}{id}") });    }    by_note}/// [`derive::derive`] of `text`, kept: the list's rows and the side page's counts read every note's at every ask,/// and a note's reading changes only with its text (Words' launch, 23 Nov 2026). Keyed by the whole text, so no two/// texts ever share one; let go whole past [`DERIVED_MOST`] bytes of text.pub(crate) fn derived(text: &str) -> derive::Derived {    static KEPT: std::sync::Mutex<Option<(usize, HashMap<String, derive::Derived>)>> = std::sync::Mutex::new(None);    let mut kept = KEPT.lock().unwrap_or_else(std::sync::PoisonError::into_inner);    let (bytes, map) = kept.get_or_insert_with(|| (0, HashMap::new()));    if let Some(held) = map.get(text) {        return held.clone();    }    let read = derive::derive(text);    if *bytes + text.len() > DERIVED_MOST {        map.clear();        *bytes = 0;    }    *bytes += text.len();    map.insert(text.to_string(), read.clone());    read}/// How much note text [`derived`] keeps readings for.const DERIVED_MOST: usize = 32 * 1024 * 1024;/// The one text a note is: its body, an old note's title and pictures folded in.pub(crate) fn text_of(ctx: &Ctx<'_>, held: &Held) -> Result<String, MethodError> {    let opened = derive::opened_text(held.title.as_deref(), &held.body);    let attached = match &held.attached {        Some(read) => read.clone(),        None => attached(ctx, &held.id)?,    };    // Nothing attached, nothing to fold in: the text is not read for its pictures (most notes, at every list).    if attached.is_empty() {        return Ok(opened);    }    // An attached picture the text already shows (by either address) is not added again.    let shown: BTreeSet<String> = derive::pictures(&opened).iter().map(|src| photo_id(src).to_string()).collect();    let pictures: Vec<String> = attached.into_iter().filter(|src| !shown.contains(src)).collect();    Ok(if pictures.is_empty() { opened } else { derive::with_pictures(&opened, &pictures) })}/// Write a note's text: the body as given, the title column kept in step./// The same columns MCP's `update_note` writes, so either side reads the other.fn write_text(ctx: &mut Ctx<'_>, id: &str, text: &str) -> Result<(), MethodError> {    let mut patch = Map::new();    for (key, value) in author_stamp(ctx) {        patch.insert(key, value);    }    patch.insert("body".into(), json!(text));    patch.insert("title".into(), json!(derive::stored_title(text)));    update_row(ctx, NOTES, id, patch).map_err(tool)?;    ctx.commit().map_err(tool)?;    Ok(())}/// Make a note of `text`, its tags filed: the row MCP's `create_note` writes/// (kind, title, body, the author stamp), an empty one too — a compose/// starts with no words, which `create_note` itself refuses.pub(crate) fn create(ctx: &mut Ctx<'_>, text: &str) -> Result<String, MethodError> {    let id = ctx.new_uuid();    let mut row = Map::new();    row.insert("kind".into(), json!("note"));    row.insert("title".into(), derive::title(text).map_or(Value::Null, Value::from));    row.insert("body".into(), json!(text));    for (key, value) in author_stamp(ctx) {        row.insert(key, value);    }    insert_row(ctx, NOTES, &id, row).map_err(tool)?;    ctx.commit().map_err(tool)?;    file(ctx, &id, &derive::tags(text))?;    Ok(id)}// ── tags as groups ──────────────────────────────────────────────────────────pub(crate) use cotton_tools::mcp::handlers::records_1::note_tags::{group_name, TagGroup};/// Every `#` group of notes, oldest first (two phones that each made `#work`/// apart answer as one tag: the oldest group files, both are read).pub(crate) fn tag_groups(ctx: &Ctx<'_>) -> Result<Vec<TagGroup>, MethodError> {    cotton_tools::mcp::handlers::records_1::note_tags::tag_groups(ctx).map_err(tool)}/// File one note under exactly `tags` (`note_tags::file`, the one rule an/// assistant's write files by too). Answers the tags it filed into and the/// ones it took the note out of.pub(crate) fn file(ctx: &mut Ctx<'_>, id: &str, tags: &[String]) -> Result<(Vec<String>, Vec<String>), MethodError> {    cotton_tools::mcp::handlers::records_1::note_tags::file(ctx, id, tags).map_err(tool)}/// Whether notes are filed now: only over a copy that holds what the object holds (`copy_standing`).pub(crate) fn files_now(handle: &CottonHandle) -> bool {    crate::phone::copy_standing::of(&handle.client()) == crate::phone::copy_standing::Standing::Held}/// Put right every note whose `#` groups do not match its hashtags (an edit/// made elsewhere: an assistant over MCP, another phone, an old note). A/// binned note is filed nowhere; an archived one keeps its tags./// The tables [`refile`] reads: the notes and their `#` groups. A move of any other table leaves its filing standing.const FILED_BY: [&str; 3] = [NOTES, "cotton_groups", "cotton_group_members"];/// Where [`refile`] last ran to the end, by the file's bus: the bus's count when it began. Held while it runs, so a/// list and a side page asked together (every launch) file once, the second after the first.static REFILED: std::sync::Mutex<Option<(u64, u64)>> = std::sync::Mutex::new(None);pub(crate) fn refile(handle: &CottonHandle) -> Result<(), MethodError> {    // FILED ONCE UNTIL SOMETHING IT READS MOVES (Words' launch, 23 Nov 2026): every list and side page read every    // note's text again to file its tags, 85-135 ms each over a thousand notes (a debug core), twice at each launch    // and again at every place or search asked. A move of the notes or the groups (a write here, a pass that landed,    // a move naming no table) files again.    let client = handle.client();    let mut refiled = REFILED.lock().unwrap_or_else(std::sync::PoisonError::into_inner);    let bus = client.bus();    if let Some(at) = *refiled {        if at.0 == bus.moved().0 && !bus.moved_since(at.1, &|table| !FILED_BY.contains(&table)) {            return Ok(());        }    }    let began = client.moved();    let filed = refile_now(handle);    *refiled = match filed {        Ok(true) => Some(began),        _ => None,    };    filed.map(|_| ())}/// [`refile`] itself: `Ok(false)` when the copy does not file yet (its first pull under way), so nothing is kept.fn refile_now(handle: &CottonHandle) -> Result<bool, MethodError> {    // Only over a copy that holds what the object holds (live, 21 Nov 2026: a    // copy on its first pull holds notes whose groups and members have not    // come yet; refiling them made each member again, which the object    // refused as held already (409 duplicate_id, then an update), and made    // a second group of a name it holds). The pass that ends the pull lets    // the next list file what is truly unfiled.    if !files_now(handle) {        return Ok(false);    }    let wrong = with_read(handle, "notes.refile", |ctx| {        let notes = every_note(ctx)?;        let groups = tag_groups(ctx)?;        let mut held: BTreeMap<&str, BTreeSet<String>> = BTreeMap::new();        for group in &groups {            for member in &group.members {                held.entry(member.as_str()).or_default().insert(derive::tag_key(&group.tag));            }        }        let mut wrong: Vec<(String, Vec<String>)> = Vec::new();        for note in &notes {            let tags = if note.binned { Vec::new() } else { derive::tags(&text_of(ctx, note)?) };            let wanted: BTreeSet<String> = tags.iter().filter(|tag| group_name(tag).chars().count() <= GROUP_NAME_MAX).map(|tag| derive::tag_key(tag)).collect();            if held.get(note.id.as_str()).cloned().unwrap_or_default() != wanted {                wrong.push((note.id.clone(), tags));            }        }        Ok(json!(wrong))    })?;    // Same-name groups first, so every note is filed by the one group of its tag. Counted first and written only    // when there is something to merge: a write that changes nothing still says rows changed, and every list and    // side page asks again on that, so writing on each list looped for good (the launch walk, 22 Nov 2026: Words    // asked `notes.list` and `shell.home` sixty times a second, at 100-270% of the emulator's processor, from launch).    let to_merge = with_read(handle, "notes.merge_tags", |ctx| {        let counted = cotton_tools::mcp::handlers::records_1::note_tags::merge_duplicates(ctx, false, MERGE_A_LIST).map_err(tool)?;        Ok(json!(counted.groups))    })    .ok()    .and_then(|groups| groups.as_u64())    .unwrap_or(0);    if to_merge == 0 {    } else if let Err(refused) = with_write(handle, "notes.merge_tags", |ctx| {        let counted = cotton_tools::mcp::handlers::records_1::note_tags::merge_duplicates(ctx, true, MERGE_A_LIST).map_err(tool)?;        if counted.groups > 0 {            eprintln!("[notes] merged same-name tag groups: {} tags held by more than one group, {} later groups ({} at most this list), {} members moved", counted.tags, counted.groups, MERGE_A_LIST, counted.moved);        }        Ok(json!(counted))    }) {        eprintln!("[notes] same-name tags were not merged: {} ({})", refused.message, refused.code);    }    let wrong: Vec<(String, Vec<String>)> = serde_json::from_value(wrong).unwrap_or_default();    // In bounded batches, each one change per group (`note_tags::file_all`):    // a copy's first list files thousands of notes at once.    for batch in wrong.chunks(REFILE_BATCH) {        if file_batch(handle, batch).is_ok() {            continue;        }        // FILING NEVER STOPS A LIST (notes-empty, 21 Nov 2026: one archived        // note the groups refused failed every list and side page on both        // phones): a batch refused whole is filed note by note, and a note        // that cannot be is left as it stands, said in the log, and the list        // reads on.        for one in batch {            if let Err(refused) = file_batch(handle, std::slice::from_ref(one)) {                eprintln!("[notes] a note's tags were not filed: {} ({})", refused.message, refused.code);            }        }    }    drop_unheld(handle);    Ok(true)}/// The `#` groups no note holds go into the Bin, so the drawer and every reader of the groups (an assistant's too)/// stop naming them: counted first and written only when there is one (a write that changes nothing makes every list/// ask again, `refile`'s merge says why), [`MERGE_A_LIST`] at a time. A failure is said in the log and the list reads on.fn drop_unheld(handle: &CottonHandle) {    let holders = |ctx: &Ctx<'_>| -> Result<BTreeSet<String>, MethodError> { Ok(every_note(ctx)?.into_iter().filter(|note| !note.binned).map(|note| note.id).collect()) };    let count = with_read(handle, "notes.drop_unheld", |ctx| {        let held = holders(ctx)?;        Ok(json!(cotton_tools::mcp::handlers::records_1::note_tags::drop_unheld(&mut *ctx, &held, false, MERGE_A_LIST).map_err(tool)?))    })    .ok()    .and_then(|n| n.as_u64())    .unwrap_or(0);    if count == 0 {        return;    }    if let Err(refused) = with_write(handle, "notes.drop_unheld", |ctx| {        let held = holders(ctx)?;        let gone = cotton_tools::mcp::handlers::records_1::note_tags::drop_unheld(ctx, &held, true, MERGE_A_LIST).map_err(tool)?;        eprintln!("[notes] tags no note holds went into the Bin: {gone}");        Ok(json!(gone))    }) {        eprintln!("[notes] tags no note holds were not let go: {} ({})", refused.message, refused.code);    }}/// `notes.merge_tags { apply? }`: the same-name `#` groups the old 409 loop made (21 Nov 2026), merged/// into the oldest of each name, the one that files (`note_tags::merge_duplicates`): its missing/// members added, each later group deleted into the Bin. Without `apply: true` nothing is written and/// the counts say what would be. Answers `{tags, groups, moved, applied}`. A list merges by itself too/// (`refile`), [`MERGE_A_LIST`] groups at a time.fn merge_tags(handle: &CottonHandle, request: &Value) -> Result<Value, MethodError> {    let apply = request.get("apply").and_then(Value::as_bool).unwrap_or(false);    if apply && !files_now(handle) {        return Err(MethodError::new("not_yet", "the tags are merged once this phone holds what the object holds"));    }    let run = |ctx: &mut Ctx<'_>| {        let counted = cotton_tools::mcp::handlers::records_1::note_tags::merge_duplicates(ctx, apply, if apply { MERGE_A_CALL } else { usize::MAX }).map_err(tool)?;        let mut answer = json!(counted);        answer["applied"] = json!(apply);        Ok(answer)    };    if apply { with_write(handle, "notes.merge_tags", run) } else { with_read(handle, "notes.merge_tags", run) }}/// Later same-name groups one `notes.merge_tags` deletes at most, and one list.const MERGE_A_CALL: usize = 2_000;const MERGE_A_LIST: usize = 200;/// How many notes one filing write takes at most.const REFILE_BATCH: usize = 500;fn file_batch(handle: &CottonHandle, batch: &[(String, Vec<String>)]) -> Result<Value, MethodError> {    with_write(handle, "notes.refile", |ctx| {        cotton_tools::mcp::handlers::records_1::note_tags::file_all(ctx, batch).map_err(tool)?;        Ok(Value::Null)    })}/// Tags as a tree: each `{tag, name, count, depth, parent, children}`, most/// used first among its siblings. `a/b` folds under `a`, which stands even/// when only its child is used; a parent counts every note under it.pub(crate) fn tag_tree(ctx: &Ctx<'_>) -> Result<Vec<Value>, MethodError> {    let notes: BTreeSet<String> = every_note(ctx)?.into_iter().filter(|note| !note.binned && !note.archived).map(|note| note.id).collect();    // Every tag path and the live notes under it.    let mut under: BTreeMap<String, (String, BTreeSet<String>)> = BTreeMap::new();    for group in tag_groups(ctx)? {        let mut path = String::new();        for part in group.tag.split('/') {            if !path.is_empty() {                path.push('/');            }            path.push_str(part);            let entry = under.entry(derive::tag_key(&path)).or_insert_with(|| (path.clone(), BTreeSet::new()));            entry.1.extend(group.members.iter().filter(|m| notes.contains(*m)).cloned());        }    }    // A tag no live note holds is never listed (the owner's drawer, 22 Nov 2026: tags of 0 notes stood there,    // their notes long gone or no longer tagged so).    under.retain(|_, (_, members)| !members.is_empty());    fn children(of: Option<&str>, under: &BTreeMap<String, (String, BTreeSet<String>)>, depth: usize) -> Vec<Value> {        let mut out: Vec<(&String, &(String, BTreeSet<String>))> = under            .iter()            .filter(|(key, _)| derive::tag_parent(key) == of && key.split('/').count() == depth + 1)            .collect();        out.sort_by(|a, b| b.1 .1.len().cmp(&a.1 .1.len()).then_with(|| a.1 .0.to_lowercase().cmp(&b.1 .0.to_lowercase())));        out.into_iter()            .map(|(key, (tag, members))| {                json!({                    "tag": tag,                    "name": tag.rsplit('/').next().unwrap_or(tag),                    "count": members.len(),                    "depth": depth,                    "parent": derive::tag_parent(tag),                    "children": children(Some(key), under, depth + 1),                })            })            .collect()    }    Ok(children(None, &under, 0))}fn flatten(tree: &[Value], out: &mut Vec<Value>) {    for node in tree {        let mut flat = node.clone();        flat.as_object_mut().map(|o| o.remove("children"));        out.push(flat);        flatten(node["children"].as_array().map(Vec::as_slice).unwrap_or_default(), out);    }}// ── the fan ─────────────────────────────────────────────────────────────────/// The fan: Notes, Untagged, Archive, Bin, then a card per tag, most used/// first, a nested tag folding under its parent (`depth`, `parent`). Each/// card's `notes` is the `notes.list` request that draws it.fn fan(ctx: &mut Ctx<'_>) -> Result<Value, MethodError> {    let notes = every_note(ctx)?;    let tagged: BTreeSet<String> = tag_groups(ctx)?.into_iter().flat_map(|group| group.members).collect();    let live = notes.iter().filter(|n| !n.binned && !n.archived);    let counts = [        ("all", live.clone().count()),        ("untagged", live.filter(|n| !tagged.contains(&n.id)).count()),        ("archive", notes.iter().filter(|n| n.archived && !n.binned).count()),        ("bin", notes.iter().filter(|n| n.binned).count()),    ];    let mut cards = Vec::new();    for (view, count) in counts {        cards.push(json!({            "id": format!("notes:{view}"),            "label": line(&format!("fan.{view}"), &[])?,            "default": view == "all",            "count": count,            "face": "notes.list",            "read": { "table": NOTE },            "notes": { "view": view },        }));    }    let mut flat = Vec::new();    flatten(&tag_tree(ctx)?, &mut flat);    for node in flat {        let tag = node["tag"].as_str().unwrap_or_default().to_string();        cards.push(json!({            "id": format!("notes:tag:{tag}"),            "label": node["name"],            "default": false,            "count": node["count"],            "face": "notes.list",            "read": { "table": NOTE },            "notes": { "view": "tag", "tag": tag },            "tag": tag,            "depth": node["depth"],            "parent": node["parent"],        }));    }    Ok(json!({ "cards": cards, "current": "notes:all" }))}// ── the list ────────────────────────────────────────────────────────────────/// What the row's date says: the time today, Yesterday, the day and month/// this year, the whole date before.pub(crate) fn date_words(ctx: &Ctx<'_>, iso: &str, zone: Option<&str>) -> String {    use cotton_core::cotton_rules::zoned_clock::{day_number, zoned_parts};    let Ok(when) = chrono::DateTime::parse_from_rfc3339(iso) else { return String::new() };    let zone = zone.map(str::to_string).or_else(|| cotton_tools::mcp::handlers::common::workspace_timezone(ctx).ok()).unwrap_or_else(|| "UTC".to_string());    let now_ms = cotton_tools::mcp::handlers::common::now_ms(ctx);    let (Ok(then), Ok(now)) = (zoned_parts(when.timestamp_millis(), &zone).or_else(|_| zoned_parts(when.timestamp_millis(), "UTC")), zoned_parts(now_ms, &zone).or_else(|_| zoned_parts(now_ms, "UTC"))) else {        return String::new();    };    let words = cotton_core::records::page::DateWords::shipped();    let then_day = day_number(then.year, then.month, then.day);    match then_day - day_number(now.year, now.month, now.day) {        0 => words.clock(then.hour, then.minute),        -1 => words.heading(-1).unwrap_or_default(),        _ => words.day_month(then_day, now.year),    }}/// One list row.fn row(ctx: &Ctx<'_>, held: &Held, zone: Option<&str>, on_top: bool) -> Result<Value, MethodError> {    let text = text_of(ctx, held)?;    let derived = derived(&text);    // A NOTE WITH NO TITLE IS TITLED BY ITS FIRST LINE (owner, 21 Nov 2026):    // drawn grey and light as preview, it read as a lesser note. Its first line    // stands as the row's title, in a titled note's weight, and the lines after    // it are the preview; the note itself still has no title.    let (title, preview, preview_lines) = match (&derived.title, derived.preview.split_once('\n')) {        (Some(title), _) => (Some(title.clone()), derived.preview.clone(), derived.preview_lines),        (None, Some((first, rest))) => (Some(first.to_string()), rest.to_string(), 2),        (None, None) if !derived.preview.is_empty() => (Some(derived.preview.clone()), String::new(), 2),        (None, None) => (None, line("list.empty_note", &[])?, derived.preview_lines),    };    Ok(json!({        "id": held.id,        "kind": "note",        "title": title,        "preview": preview,        "preview_lines": preview_lines,        "empty": derived.title.is_none() && derived.preview.is_empty(),        "date": date_words(ctx, &held.edited, zone),        "edited_at": held.edited,        "tags": derived.tags,        "picture": derived.picture,        "archived": held.archived,        "binned": held.binned,        "pinned": on_top,        "pinned_in_notes": held.pinned,        "checklist": (derived.checks > 0).then(|| json!({ "done": derived.checks_done, "total": derived.checks })),        "thumbnail": thumbnail(ctx, derived.picture.as_deref()),        "by_assistant": held.by_assistant,    }))}/// A row's thumbnail: the first picture's media key, when this copy has it.fn thumbnail(ctx: &Ctx<'_>, src: Option<&str>) -> Value {    let Some(src) = src.map(photo_id) else { return Value::Null };    if !src.starts_with(PHOTO_SRC) {        return Value::Null;    }    let found = query_rows(ctx, &Query::on("cotton_photos").columns(&["id", "key", "width", "height"]).eq("id", src.to_string())).unwrap_or_default();    match found.first() {        Some(photo) if photo.get("key").is_some_and(|key| !key.is_null()) => json!({ "photo": src, "key": photo.get("key"), "width": photo.get("width"), "height": photo.get("height") }),        _ => Value::Null,    }}/// A picture's address as Notes draws it: `cotton:photo/photo:<sha>`, the/// address assistants were once told to write, is that same photo.pub(crate) fn photo_id(src: &str) -> &str {    src.strip_prefix("cotton:photo/").unwrap_or(src)}/// `notes.list { view?, tag?, search?, zone? }`: the notes of one view, newest/// edit first, each row said; the count and the empty words. `view` is `all`/// (the default), `untagged`, `archive`, `bin` or `tag` (with `tag`, its/// nested tags' notes too). `search` narrows to the notes whose words hold it.pub(crate) fn list(ctx: &mut Ctx<'_>, request: &Value) -> Result<Value, MethodError> {    let view = text(request, "view").unwrap_or("all");    let zone = text(request, "zone");    let notes = every_note(ctx)?;    let groups = tag_groups(ctx)?;    let tagged: BTreeSet<&String> = groups.iter().flat_map(|group| group.members.iter()).collect();    let live = |n: &&Held| !n.binned && !n.archived;    let search = text(request, "search").map(str::trim).filter(|words| !words.is_empty());    let terms = search.map(search::parse).unwrap_or_default();    // THE PERSON'S OWN LIST IS THEIR OWN (owner, 21 Nov 2026): Notes, Todo,    // Today and Untagged hold the notes the person wrote; an assistant's are    // under "From your assistant" (view `assistant`), or here when a search    // asks for them (`@assistant`). Pinned, tags, lists, the archive and the    // bin hold whatever the person put there, whoever wrote it.    let asks_assistant = terms.iter().any(|term| term.kind == search::TermKind::Special && term.value == "assistant" && !term.not);    let own = |n: &&Held| !n.by_assistant || asks_assistant;    let mut list_name: Option<String> = None;    let mut tag_key_of_view: Option<String> = None;    let mut chosen: Vec<&Held> = match view {        "all" => notes.iter().filter(live).filter(own).collect(),        "assistant" => notes.iter().filter(live).filter(|n| n.by_assistant).collect(),        "pinned" => notes.iter().filter(live).filter(|n| n.pinned).collect(),        "todo" => {            let mut out = Vec::new();            for held in notes.iter().filter(live).filter(own) {                let derived = derived(&text_of(ctx, held)?);                if derived.checks > derived.checks_done {                    out.push(held);                }            }            out        }        "today" => notes.iter().filter(live).filter(own).filter(|n| is_today(ctx, n, zone)).collect(),        "list" => {            let id = text(request, "list").map(str::trim).filter(|id| !id.is_empty()).ok_or_else(|| bad("a list's notes name its `list`"))?;            let (name, members) = super::notes_side::list_members(ctx, id)?;            list_name = Some(name);            notes.iter().filter(live).filter(|n| members.contains(&n.id)).collect()        }        "untagged" => notes.iter().filter(|n| !n.binned && !n.archived && !tagged.contains(&n.id)).filter(own).collect(),        "archive" => notes.iter().filter(|n| n.archived && !n.binned).collect(),        "bin" => notes.iter().filter(|n| n.binned).collect(),        "tag" => {            let tag = text(request, "tag").map(str::trim).filter(|tag| !tag.is_empty()).ok_or_else(|| bad("a tag's list names its `tag`"))?;            let key = derive::tag_key(tag.trim_start_matches('#'));            tag_key_of_view = Some(key.clone());            let members: BTreeSet<&String> = groups                .iter()                .filter(|group| {                    let own = derive::tag_key(&group.tag);                    own == key || own.starts_with(&format!("{key}/"))                })                .flat_map(|group| group.members.iter())                .collect();            notes.iter().filter(|n| !n.binned && !n.archived && members.contains(&n.id)).collect()        }        other => return Err(bad(format!("`{other}` is no view of Notes"))),    };    if !terms.is_empty() {        let mut kept = Vec::new();        for held in chosen {            let written = text_of(ctx, held)?;            let derived = derived(&written);            let facts = search::Facts {                text: &written,                tags: &derived.tags,                open_checks: derived.checks - derived.checks_done,                checks: derived.checks,                today: is_today(ctx, held, zone),                pictures: !derive::pictures(&written).is_empty(),                pinned: held.pinned,                by_assistant: held.by_assistant,            };            if search::matches(&terms, &facts) {                kept.push(held);            }        }        chosen = kept;    }    // Pinned first: in a tag's list, pinned in that tag or in Notes; in the    // archive and the bin, nothing is.    let on_top = |held: &Held| match view {        "archive" | "bin" => false,        "tag" => held.pinned || tag_key_of_view.as_ref().is_some_and(|key| held.pinned_in.contains(key)),        _ => held.pinned,    };    chosen.sort_by(|a, b| on_top(b).cmp(&on_top(a)).then_with(|| b.edited.cmp(&a.edited)).then_with(|| b.made.cmp(&a.made)).then_with(|| a.id.cmp(&b.id)));    let pinned_count = chosen.iter().filter(|held| on_top(held)).count();    let mut rows = chosen.iter().map(|held| row(ctx, held, zone, on_top(held))).collect::<Result<Vec<_>, _>>()?;    if view == "assistant" {        // The assistant's web pages beside its notes, newest first with them (a pinned note still on top).        let words: Vec<String> = terms.iter().filter(|term| matches!(term.kind, search::TermKind::Word | search::TermKind::Phrase) && !term.not).map(|term| term.value.clone()).collect();        let only_words = terms.iter().all(|term| matches!(term.kind, search::TermKind::Word | search::TermKind::Phrase) && !term.not);        if only_words {            for page in super::notes_assistant::pages(ctx)?.iter().filter(|page| super::notes_assistant::page_matches(page, &words)) {                rows.push(super::notes_assistant::page_row(page, date_words(ctx, &page.edited, zone))?);            }        }        let edited = |row: &Value| row["edited_at"].as_str().unwrap_or_default().to_string();        rows.sort_by(|a, b| b["pinned"].as_bool().cmp(&a["pinned"].as_bool()).then_with(|| edited(b).cmp(&edited(a))));    }    let empty = if !rows.is_empty() {        None    } else if let Some(words) = search {        Some(line("list.empty.search", &[("words", words)])?)    } else if view == "tag" {        Some(line("list.empty.tag", &[("tag", text(request, "tag").unwrap_or_default())])?)    } else if view == "list" {        Some(line("list.empty.list", &[])?)    } else {        Some(line(&format!("list.empty.{view}"), &[])?)    };    let heading = match view {        "tag" => text(request, "tag").unwrap_or_default().rsplit('/').next().unwrap_or_default().to_string(),        "list" => list_name.clone().unwrap_or_default(),        other => line(&format!("side.{other}"), &[])?,    };    // One tap from the person's own list to the assistant's: a quiet line over Notes, while the assistant wrote any.    let to_assistant = if view == "all" && !asks_assistant {        let count = notes.iter().filter(live).filter(|n| n.by_assistant).count() + super::notes_assistant::pages(ctx)?.len();        (count > 0).then(|| json!({ "label": line("side.assistant", &[]).unwrap_or_default(), "count": count, "list": { "view": "assistant" } }))    } else {        None    };    Ok(json!({        "view": view,        "tag": text(request, "tag"),        "heading": heading,        "assistant": to_assistant,        "rows": rows,        "count": rows.len(),        "count_words": counted_line("list.count", rows.len())?,        "empty": empty,        "search_hint": line("list.search_hint", &[])?,        "search_clear": line("list.search_clear", &[])?,        "compose": line("list.compose", &[])?,        "pinned_count": pinned_count,        "list": text(request, "list"),        "search_terms": terms.iter().map(|term| json!({ "kind": term.kind, "not": term.not, "said": term.said })).collect::<Vec<_>>(),    }))}/// Was this note made or edited today, in the person's zone?pub(crate) fn is_today(ctx: &Ctx<'_>, held: &Held, zone: Option<&str>) -> bool {    use cotton_core::cotton_rules::zoned_clock::{day_number, zoned_parts};    let zone = zone.map(str::to_string).or_else(|| cotton_tools::mcp::handlers::common::workspace_timezone(ctx).ok()).unwrap_or_else(|| "UTC".to_string());    let day = |ms: i64| zoned_parts(ms, &zone).or_else(|_| zoned_parts(ms, "UTC")).ok().map(|p| day_number(p.year, p.month, p.day));    let today = day(cotton_tools::mcp::handlers::common::now_ms(ctx));    [&held.edited, &held.made].iter().any(|iso| chrono::DateTime::parse_from_rfc3339(iso).ok().and_then(|when| day(when.timestamp_millis())).is_some_and(|d| Some(d) == today))}// ── writing ─────────────────────────────────────────────────────────────────/// The pictures a text shows, by address: the media key each draws from.fn pictures_of(ctx: &Ctx<'_>, text: &str) -> Result<Value, MethodError> {    let mut out = Map::new();    for src in derive::pictures(text) {        let id = photo_id(&src).to_string();        if !id.starts_with(PHOTO_SRC) {            continue;        }        let id = id.as_str();        let found = query_rows(ctx, &Query::on("cotton_photos").columns(&["id", "key", "width", "height"]).eq("id", id.to_string())).unwrap_or_default();        let entry = match found.first() {            Some(photo) => json!({ "photo": id, "key": photo.get("key"), "width": photo.get("width"), "height": photo.get("height") }),            None => json!({ "photo": id, "key": null, "missing": line("picture.missing", &[])? }),        };        out.insert(src, entry);    }    Ok(Value::Object(out))}/// What a writer draws for a text: its blocks, spans and tables, its folds/// and note links, and what it derives. With `hide_marks` false every mark/// that would hide is drawn dim instead (an indent stays hidden).fn drawn(text: &str, cursor: Option<u32>, hide_marks: bool) -> Value {    let mut styled = style::style(text, cursor);    if !hide_marks {        for span in styled.spans.iter_mut() {            if span.style == style::Style::Mark && span.look == style::Look::Hidden {                span.look = style::Look::Dim;            }        }    }    let derived = derive::derive(text);    json!({        "blocks": styled.blocks,        "spans": styled.spans,        "tables": styled.tables,        "folds": folds::folds(text),        "links": links::links(text).into_iter().map(|link| json!({ "start": link.start, "end": link.end, "target": link.target, "heading": null, "note": null })).collect::<Vec<_>>(),        "title": derived.title,        "tags": derived.tags,        "words": derived.words,    })}fn hide_marks_of(request: &Value) -> bool {    request.get("hide_marks").and_then(Value::as_bool).unwrap_or(true)}/// The note links of a drawn answer, each with the note it opens (or null)/// and the heading it names.fn resolve_links(ctx: &Ctx<'_>, answer: &mut Value) -> Result<(), MethodError> {    let titles = titles(ctx)?;    if let Some(found) = answer.get_mut("links").and_then(Value::as_array_mut) {        for link in found.iter_mut() {            let target = link["target"].as_str().unwrap_or_default().to_string();            let (title, heading) = links::split(&target, |t| titles.contains_key(&links::title_key(t)));            let note = titles.get(&links::title_key(title)).map(|(id, _)| id.clone());            link["note"] = json!(note);            link["heading"] = json!(heading);        }    }    Ok(())}/// Every titled note a link may open (not binned): title key → (id, made)./// Where two share a title, the oldest made.pub(crate) fn titles(ctx: &Ctx<'_>) -> Result<BTreeMap<String, (String, String)>, MethodError> {    let mut out: BTreeMap<String, (String, String)> = BTreeMap::new();    for held in every_note(ctx)?.into_iter().filter(|n| !n.binned) {        let Some(title) = derive::title(&text_of(ctx, &held)?) else { continue };        let key = links::title_key(&title);        let older = out.get(&key).is_none_or(|(_, made)| (held.made.as_str(), held.id.as_str()) < (made.as_str(), out[&key].0.as_str()));        if older {            out.insert(key, (held.id.clone(), held.made.clone()));        }    }    Ok(out)}/// `notes.style { text, cursor?, hide_marks? }`: the text styled (no write).fn styled_answer(request: &Value) -> Result<Value, MethodError> {    let text = text(request, "text").ok_or_else(|| bad("this styles a `text`"))?;    Ok(drawn(text, request.get("cursor").and_then(Value::as_u64).map(|c| c as u32), hide_marks_of(request)))}/// `notes.find { text, words }`: where the words stand in a note.fn find_answer(request: &Value) -> Result<Value, MethodError> {    let text = text(request, "text").ok_or_else(|| bad("this finds in a `text`"))?;    let words = text_of_key(request, "words");    let matches = find::find(text, words);    Ok(json!({ "matches": matches, "count": matches.len(), "count_words": counted_line("find.found", matches.len())? }))}fn text_of_key<'a>(request: &'a Value, key: &str) -> &'a str {    request.get(key).and_then(Value::as_str).unwrap_or_default()}/// `notes.links { id?, text, cursor }`: the notes a `[[` being typed may name.fn link_suggestions(ctx: &mut Ctx<'_>, request: &Value) -> Result<Value, MethodError> {    let written = text(request, "text").ok_or_else(|| bad("this reads a `text`"))?;    let cursor = request.get("cursor").and_then(Value::as_u64).map(|c| c as u32).unwrap_or_else(|| writing::len16(written));    let Some((start, end, query)) = links::typing(written, cursor) else { return Ok(json!({ "open": false })) };    let own = text(request, "id");    let mut found: Vec<(Held, String)> = Vec::new();    for held in every_note(ctx)?.into_iter().filter(|n| !n.binned && Some(n.id.as_str()) != own) {        let note_text = text_of(ctx, &held)?;        if let Some(title) = derive::title(&note_text) {            if find::holds(&title, &query) {                found.push((held, title));            }        }    }    found.sort_by(|a, b| b.0.edited.cmp(&a.0.edited));    found.truncate(8);    let notes: Vec<Value> = found        .into_iter()        .map(|(held, title)| {            let with = format!("[[{title}]]");            let preview = derive::derive(&text_of(ctx, &held).unwrap_or_default()).preview;            json!({ "id": held.id, "title": title, "preview": preview, "cursor": start + writing::len16(&with), "with": with })        })        .collect();    Ok(json!({ "open": true, "query": query, "replace": { "start": start, "end": end }, "notes": notes, "none": notes.is_empty().then(|| line("links.none", &[("words", &query)]).unwrap_or_default()) }))}/// `notes.link { target, make? }`: the note a link opens, and where its/// heading starts; or the offer to make it (made, with `make`).fn open_link(ctx: &mut Ctx<'_>, request: &Value) -> Result<Value, MethodError> {    let target = text(request, "target").map(str::trim).filter(|t| !t.is_empty()).ok_or_else(|| bad("a link names its `target`"))?;    let titles = titles(ctx)?;    let (title, heading) = links::split(target, |t| titles.contains_key(&links::title_key(t)));    if let Some((id, _)) = titles.get(&links::title_key(title)) {        let held = note(ctx, id)?;        let at = heading.and_then(|heading| folds::heading_at(&text_of(ctx, &held).unwrap_or_default(), heading));        return Ok(json!({ "id": id, "heading_at": at }));    }    if request.get("make").and_then(Value::as_bool).unwrap_or(false) {        let text = format!("# {}\n", title.replace('\n', " "));        let id = create(ctx, &text)?;        let mut opened = open(ctx, &json!({ "id": id, "cursor": writing::len16(&text) }))?;        opened["made"] = json!(true);        return Ok(opened);    }    Ok(json!({ "missing": true, "offer": line("links.make", &[("title", title)])?, "title": title }))}/// `notes.format { text, selection | cursor, action }`: what a button does/// (no write): the new text, the one replacement, the selection, and the/// text styled at it. The writer saves with `notes.edit`.fn format_answer(request: &Value) -> Result<Value, MethodError> {    let text = text(request, "text").ok_or_else(|| bad("a button works on a `text`"))?;    let mut action: format::Action = serde_json::from_value(request.get("action").cloned().unwrap_or(Value::Null))        .map_err(|_| MethodError::new("bad_request", line("refusal.unknown_action", &[]).unwrap_or_default()))?;    if let format::Action::Today { words } = &mut action {        if words.is_empty() {            *words = today_words(text_of_key(request, "zone"))?;        }    }    let selection = selection_of(request, writing::len16(text));    let edited = format::apply(text, selection, &action);    let mut answer = drawn(&edited.text, Some(edited.selection.end), hide_marks_of(request));    if matches!(action, format::Action::Fold) {        // The fold the cursor stands in: the nearest folding line at or above it whose section holds it.        let at = edited.selection.start;        let fold = folds::folds(&edited.text).into_iter().filter(|fold| fold.line <= at && at <= fold.end).max_by_key(|fold| fold.line);        answer["fold"] = json!(fold);    }    answer["text"] = json!(edited.text);    answer["replace"] = json!(edited.replace);    answer["selection"] = json!(edited.selection);    Ok(answer)}/// The formatting keyboard as the kit lays it out, each key with its words:/// a cell's `label` is `format.<key>` (`heading_2` is `format.heading.2`),/// a bar key's is `bar.<key>`, and `letters` is what the format key says/// while the grid stands (it takes the phone back to the letters).fn keyboard(kit: &Value) -> Result<Value, MethodError> {    fn cell(c: &Value) -> Result<Value, MethodError> {        let cap = c.get("key").and_then(Value::as_str).unwrap_or_default();        let name = match cap.strip_prefix("heading_") {            Some(level) => format!("format.heading.{level}"),            None => format!("format.{cap}"),        };        let mut out = c.clone();        out["label"] = json!(line(&name, &[])?);        if let Some(hold) = c.get("hold").and_then(Value::as_array) {            out["hold"] = json!(hold.iter().map(cell).collect::<Result<Vec<_>, _>>()?);        }        Ok(out)    }    let bar_side = |side: &str| -> Result<Value, MethodError> {        let keys = kit.pointer(&format!("/bar/{side}")).and_then(Value::as_array).cloned().unwrap_or_default();        Ok(json!(keys.iter().filter_map(Value::as_str).map(|cap| Ok(json!({ "key": cap, "label": line(&format!("bar.{cap}"), &[])? }))).collect::<Result<Vec<_>, MethodError>>()?))    };    let grid = kit.get("grid").and_then(Value::as_array).cloned().unwrap_or_default().iter()        .map(|row| row.as_array().cloned().unwrap_or_default().iter().map(cell).collect::<Result<Vec<_>, _>>())        .collect::<Result<Vec<_>, _>>()?;    let foot = |side: &str| -> Result<Value, MethodError> {        let cap = kit.pointer(&format!("/foot/{side}")).and_then(Value::as_str).unwrap_or_default();        Ok(json!({ "key": cap, "label": line(&format!("format.{cap}"), &[])? }))    };    Ok(json!({        "bar": { "left": bar_side("left")?, "right": bar_side("right")? },        "grid": grid,        "foot": { "left": foot("left")?, "right": foot("right")? },        "letters": line("bar.letters", &[])?,        "letters_face": line("bar.letters_face", &[])?,    }))}/// Today's date in the person's [zone] (UTC when it names none), in the/// core's words: `format.today_date` with the month's whole name (`dates`).fn today_words(zone: &str) -> Result<String, MethodError> {    use cotton_core::cotton_rules::zoned_clock::zoned_parts;    let now = chrono::Utc::now().timestamp_millis();    let zone = if zone.trim().is_empty() { "UTC" } else { zone };    let parts = zoned_parts(now, zone).or_else(|_| zoned_parts(now, "UTC")).map_err(|_| bad("no clock"))?;    const MONTHS: [&str; 12] = ["jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec"];    let month_short = MONTHS[(parts.month.clamp(1, 12) - 1) as usize];    let month = cotton_core::rules::shell_lines::resolve("dates", &format!("month_names.{month_short}"), &[], &[]).unwrap_or_default();    line("format.today_date", &[("day", &parts.day.to_string()), ("month", &month), ("year", &parts.year.to_string())])}/// `notes.open { id, cursor? }`: the note's one text, drawn, its pictures,/// where it stands, and the writer's words.fn open(ctx: &mut Ctx<'_>, request: &Value) -> Result<Value, MethodError> {    let held = note(ctx, id_of(request)?)?;    let text = text_of(ctx, &held)?;    let cursor = request.get("cursor").and_then(Value::as_u64).map(|c| c as u32);    let mut answer = drawn(&text, cursor, hide_marks_of(request));    resolve_links(ctx, &mut answer)?;    answer["id"] = json!(held.id);    answer["text"] = json!(text);    hold_for_writer(&held.id, &text);    answer["pictures"] = pictures_of(ctx, &text)?;    answer["files"] = super::notes_files::files_of(ctx, &held.id)?;    answer["pinned_in_notes"] = json!(held.pinned);    answer["pinned_in"] = json!(held.pinned_in);    answer["by_assistant"] = json!(held.by_assistant);    answer["archived"] = json!(held.archived);    answer["binned"] = json!(held.binned);    answer["edited_at"] = json!(held.edited);    answer["hint"] = json!(line("writer.hint", &[])?);    Ok(answer)}/// `notes.info { id, zone? }`: the note's info card: its words and/// characters as the core counts them, and when it was made and last edited,/// each a fact with its words.fn info(ctx: &mut Ctx<'_>, request: &Value) -> Result<Value, MethodError> {    let held = note(ctx, id_of(request)?)?;    let zone = text(request, "zone");    let written = text_of(ctx, &held)?;    let derived = derive::derive(&written);    let characters = written.chars().filter(|c| *c != '\n' && *c != '\r').count();    let fact = |name: &str, value: String| -> Result<Value, MethodError> { Ok(json!({ "key": name, "label": line(&format!("info.{name}"), &[])?, "value": value })) };    let read_minutes = if derived.words == 0 { 0 } else { derived.words.div_ceil(200) };    let mut facts = vec![        fact("words", grouped(derived.words))?,        fact("characters", grouped(characters as u64))?,        fact("paragraphs", grouped(u64::from(derived.paragraphs)))?,        fact("read_time", counted_line("info.minutes", read_minutes as usize)?)?,    ];    if !held.made.is_empty() {        facts.push(fact("created", full_date_words(ctx, &held.made, zone)?)?);    }    facts.push(fact("edited", full_date_words(ctx, &held.edited, zone)?)?);    if !derived.tags.is_empty() {        facts.push(fact("tags", derived.tags.iter().map(|tag| hashtag(tag)).collect::<Vec<_>>().join("  "))?);    }    // Contents, the links out, and the live notes that link here.    let titles = titles(ctx)?;    let is_title = |t: &str| titles.contains_key(&links::title_key(t));    let links_out: Vec<Value> = links::links(&written)        .into_iter()        .map(|link| {            let (title, _) = links::split(&link.target, is_title);            json!({ "target": link.target, "note": titles.get(&links::title_key(title)).map(|(id, _)| id.clone()) })        })        .collect();    let mut here: Vec<(Held, String)> = Vec::new();    for other in every_note(ctx)?.into_iter().filter(|n| !n.binned && !n.archived && n.id != held.id) {        let other_text = text_of(ctx, &other)?;        let names_this = links::links(&other_text).iter().any(|link| {            let (title, _) = links::split(&link.target, is_title);            titles.get(&links::title_key(title)).is_some_and(|(id, _)| *id == held.id)        });        if names_this {            here.push((other, other_text));        }    }    here.sort_by(|a, b| b.0.edited.cmp(&a.0.edited));    let links_here: Vec<Value> = here        .iter()        .map(|(other, other_text)| {            let d = derive::derive(other_text);            json!({ "id": other.id, "title": d.title, "preview": d.preview })        })        .collect();    Ok(json!({        "id": held.id,        "title": line("info.title", &[])?,        "facts": facts,        "paragraphs": derived.paragraphs,        "read_minutes": read_minutes,        "contents": folds::contents(&written),        "links_here": links_here,        "links_out": links_out,        "parts": {            "statistics": line("info.statistics", &[])?,            "contents": line("info.contents", &[])?,            "links_here": line("info.links_here", &[])?,            "none_here": line("info.none_here", &[])?,            "no_contents": line("info.no_contents", &[])?,        },        "words": derived.words,        "characters": characters,        "created_at": held.made,        "edited_at": held.edited,        "tags": derived.tags,        "close": line("nav.close", &[])?,    }))}/// A count as it is read: 12,345.fn grouped(n: u64) -> String {    let digits = n.to_string();    let mut out = String::new();    for (i, digit) in digits.chars().enumerate() {        if i > 0 && (digits.len() - i) % 3 == 0 {            out.push(',');        }        out.push(digit);    }    out}/// A moment in full: "Thu 19 Nov 2026, 14:05", in the person's zone.fn full_date_words(ctx: &Ctx<'_>, iso: &str, zone: Option<&str>) -> Result<String, MethodError> {    use cotton_core::cotton_rules::zoned_clock::{day_number, zoned_parts};    let Ok(when) = chrono::DateTime::parse_from_rfc3339(iso) else { return Ok(String::new()) };    let zone = zone.map(str::to_string).or_else(|| cotton_tools::mcp::handlers::common::workspace_timezone(ctx).ok()).unwrap_or_else(|| "UTC".to_string());    let Ok(then) = zoned_parts(when.timestamp_millis(), &zone).or_else(|_| zoned_parts(when.timestamp_millis(), "UTC")) else { return Ok(String::new()) };    let words = cotton_core::records::page::DateWords::shipped();    let date = words.weekday_date_year(day_number(then.year, then.month, then.day));    let time = words.clock(then.hour, then.minute);    line("info.at", &[("date", &date), ("time", &time)])}/// `notes.new { text?, tag? }`: a new note. Made from a tag's list, it/// starts with that tag on its own line. Answers it opened.fn new(ctx: &mut Ctx<'_>, request: &Value) -> Result<Value, MethodError> {    let mut text = text(request, "text").unwrap_or_default().to_string();    if let Some(tag) = text_tag(request) {        let wanted = derive::tag_key(&tag);        if !derive::tags(&text).iter().any(|t| derive::tag_key(t) == wanted) {            if !text.is_empty() && !text.ends_with('\n') {                text.push('\n');            }            text.push_str(&hashtag(&tag));        }    }    let id = create(ctx, &text)?;    open(ctx, &json!({ "id": id, "cursor": 0 }))}fn text_tag(request: &Value) -> Option<String> {    text(request, "tag").map(|tag| tag.trim().trim_start_matches('#').trim().to_string()).filter(|tag| !tag.is_empty())}/// A tag as it is written: `#work`, or `#two words#` when it holds a space.pub(crate) fn hashtag(tag: &str) -> String {    if tag.contains(char::is_whitespace) { format!("#{tag}#") } else { format!("#{tag}") }}/// Words' table as the object names it: the edit bases are kept under it/// (`cotton_client::seal::EDIT_BASE`).const SERVED_NOTE: &str = "note";/// The body this edit is written over, kept for the first edit since the object last took the/// note: if the object refuses the post because the note moved (an assistant's rewrite while/// this phone was offline), the edit is merged over the newer body rather than sent over it.fn keep_edit_base(ctx: &mut Ctx<'_>, id: &str, before: &str) -> Result<(), MethodError> {    let db = ctx.read.driver();    let failed = |error: cotton_store::StoreError| MethodError::new("write_refused", error.to_string());    db.exec(cotton_client::seal::EDIT_BASE_DDL).map_err(failed)?;    db.run(        "INSERT OR IGNORE INTO _edit_base (tbl, row_id, col, base) VALUES (?, ?, 'body', ?)",        &[rusqlite::types::Value::Text(SERVED_NOTE.into()), rusqlite::types::Value::Text(id.into()), rusqlite::types::Value::Text(before.into())],    )    .map_err(failed)?;    Ok(())}/// After a pass: each note whose post the object refused as moved, and whose newer body the pull/// brought, has this phone's edit merged over it (`writing::merge`, the edit's base below both),/// written as a new edit that the next pass sends at the version now held. A base whose note has/// nothing left to send goes. Answers how many notes were merged.pub(crate) fn merge_waiting(client: &crate::shell::client::ClientController) -> Result<usize, String> {    let mut merged = 0usize;    client.write_rows("notes merge", &mut |ctx| {        let db = ctx.read.driver();        let held = db.get("SELECT 1 AS here FROM sqlite_master WHERE type = 'table' AND name = '_edit_base'", &[]).map_err(|e| e.to_string())?;        if held.is_none() {            return Ok(json!(0));        }        let waiting = db            .all("SELECT row_id, base, theirs FROM _edit_base WHERE tbl = ? AND col = 'body' AND theirs IS NOT NULL", &[rusqlite::types::Value::Text(SERVED_NOTE.into())])            .map_err(|e| e.to_string())?;        for row in &waiting {            let (Some(id), Some(base), Some(theirs)) = (row.text("row_id"), row.text("base"), row.text("theirs")) else { continue };            let (id, base, theirs) = (id.to_string(), base.to_string(), theirs.to_string());            if let Ok(note) = note(ctx, &id) {                let mine = text_of(ctx, &note).map_err(|e| e.message)?;                let made = writing::merge::merge(&base, &mine, &theirs);                tracing::warn!(note = %id, both_kept = made.both_kept, "notes: an edit refused because the note moved is merged over the newer body");                if made.text != mine {                    write_text(ctx, &id, &made.text).map_err(|e| e.message)?;                }                merged += 1;            }            ctx.read                .driver()                .run("UPDATE _edit_base SET base = ?, theirs = NULL, moved = 0 WHERE tbl = ? AND row_id = ? AND col = 'body'", &[rusqlite::types::Value::Text(theirs), rusqlite::types::Value::Text(SERVED_NOTE.into()), rusqlite::types::Value::Text(id)])                .map_err(|e| e.to_string())?;        }        ctx.read            .driver()            .run(                &format!(                    "DELETE FROM _edit_base WHERE tbl = ? AND theirs IS NULL AND moved = 0 AND NOT EXISTS \                     (SELECT 1 FROM _outbox o JOIN _writes w ON w.op_id = o.op_id WHERE w.tbl = '{NOTES}' AND w.row_id = _edit_base.row_id)"                ),                &[rusqlite::types::Value::Text(SERVED_NOTE.into())],            )            .map_err(|e| e.to_string())?;        ctx.commit().map_err(|e| e.to_string())?;        Ok(json!(merged))    })?;    Ok(merged)}/// A long text a writer saves whole, laid over what the copy holds (STALE, 21 Nov 2026): when the/// copy's text moved from `base` (the text the writer last loaded) and the writer changed it too, the/// two are merged line by line (`writing::merge`), the writer's lines first where both changed one./// Answers the text to keep and, when it merged, whether both sides changed a line. With no `base`/// the writer's text stands as before. Story's scenes and Days' notes save through it.pub(crate) fn laid_over(held: &str, sent: &str, base: Option<&str>) -> (String, Option<bool>) {    match base {        Some(base) if base != held && sent == base => (held.to_string(), None),        Some(base) if base != held && sent != held => {            let made = writing::merge::merge(base, sent, held);            tracing::warn!(both_kept = made.both_kept, "a long text changed under its writer; the save was merged over it");            (made.text, Some(made.both_kept))        }        _ => (sent.to_string(), None),    }}/// The text each open writer holds, by note: what `notes.open` answered, then what each/// `notes.edit` sent. A writer draws the text it loaded and never reloads it on a pull, so this/// is the base a save was written over (owner's lost edit, 21 Nov 2026).static WRITERS_HOLD: std::sync::Mutex<Vec<(String, String)>> = std::sync::Mutex::new(Vec::new());/// How many notes' writer texts are remembered (a writer opens one note at a time).const WRITERS_REMEMBERED: usize = 16;fn hold_for_writer(id: &str, text: &str) {    let mut held = WRITERS_HOLD.lock().unwrap_or_else(std::sync::PoisonError::into_inner);    held.retain(|(note, _)| note != id);    held.push((id.to_string(), text.to_string()));    let over = held.len().saturating_sub(WRITERS_REMEMBERED);    held.drain(..over);}fn writer_holds(id: &str) -> Option<String> {    WRITERS_HOLD.lock().unwrap_or_else(std::sync::PoisonError::into_inner).iter().find(|(note, _)| note == id).map(|(_, text)| text.clone())}/// `notes.edit { id, text | replace: {start, end, with}, base?, cursor? }`: save the/// writer's text (whole, or one replacement of what this copy holds). Files/// its tags; answers it drawn, with the tags it was filed into and out of./// `base`, the text the writer last sent (or loaded, or took from an answer): when the note/// moved since, the save is merged over it (`merged`, `both_kept`, `said`),/// and a save of `base` itself changes nothing and answers the newer text,/// which is how an open writer reloads after a pull (CONTRACT.md §14).fn edit(ctx: &mut Ctx<'_>, request: &Value) -> Result<Value, MethodError> {    let held = note(ctx, id_of(request)?)?;    if held.binned {        return Err(MethodError::new("refused", line("refusal.no_note", &[])?));    }    let before = text_of(ctx, &held)?;    let mut merged = None;    let after = match (text(request, "text"), request.get("replace")) {        // The writer's whole text, over the text it holds (`writer_holds`). When the copy's body        // moved since (a pull brought the assistant's rewrite while the note stood open), the two        // are merged over it: the newer body is never replaced whole and unseen.        // A writer that takes the answer's text says what it last loaded (`base`, STALE): its own        // word wins over what this core remembers it sent.        (Some(whole), _) => match text(request, "base").map(str::to_string).or_else(|| writer_holds(&held.id)) {            // The writer changed nothing since it loaded: the newer body is            // its answer, the way a writer reloads when a pull moved its note.            Some(base) if base != before && whole == base => before.clone(),            Some(base) if base != before && whole != before => {                let made = writing::merge::merge(&base, whole, &before);                tracing::warn!(note = %held.id, both_kept = made.both_kept, "notes.edit: the note changed under the writer; the save was merged over what it opened");                let text = made.text.clone();                merged = Some(made);                text            }            _ => whole.to_string(),        },        (None, Some(replace)) => {            let start = replace["start"].as_u64().unwrap_or(0) as u32;            let end = replace["end"].as_u64().unwrap_or(start as u64) as u32;            let with = replace["with"].as_str().unwrap_or_default();            let (a, b) = (writing::byte_at(&before, start.min(end)), writing::byte_at(&before, start.max(end)));            format!("{}{with}{}", &before[..a], &before[b..])        }        (None, None) => return Err(bad("an edit gives the `text` or a `replace`")),    };    // The text as stored: an old note's first edit writes its folded-in title    // and pictures too, so the body holds them from now on.    if after != held.body || held.title.as_deref().unwrap_or_default() != derive::stored_title(&after) {        keep_edit_base(ctx, &held.id, &before)?;        write_text(ctx, &held.id, &after)?;    }    // What the writer holds now: the text it sent (it draws its own, not the answer's), or the    // replacement's result.    hold_for_writer(&held.id, text(request, "text").unwrap_or(&after));    let (filed, unfiled) = file(ctx, &held.id, &derive::tags(&after))?;    let cursor = request.get("cursor").and_then(Value::as_u64).map(|c| c as u32);    let mut answer = drawn(&after, cursor, hide_marks_of(request));    if let Some(made) = &merged {        answer["merged"] = json!(true);        answer["both_kept"] = json!(made.both_kept);        // Said, so the person knows the note holds the other writer's words too (STALE, 21 Nov 2026).        answer["said"] = json!(line(if made.both_kept { "writer.merged_both" } else { "writer.merged" }, &[])?);    }    resolve_links(ctx, &mut answer)?;    answer["id"] = json!(held.id);    answer["text"] = json!(after);    answer["preview"] = json!(derive::derive(&after).preview);    answer["filed"] = json!(filed);    answer["unfiled"] = json!(unfiled);    answer["pictures"] = pictures_of(ctx, &after)?;    Ok(answer)}/// `notes.tag { id, tag, cursor? }`: the bar's Tag: the hashtag goes at the/// end of the note on a line of tags (or the cursor's spot, given), and files it.fn tag(ctx: &mut Ctx<'_>, request: &Value) -> Result<Value, MethodError> {    let held = note(ctx, id_of(request)?)?;    let tag = text_tag(request).ok_or_else(|| bad("this names the `tag`"))?;    let before = text_of(ctx, &held)?;    let key = derive::tag_key(&tag);    if derive::tags(&before).iter().any(|t| derive::tag_key(t) == key) {        return edit(ctx, &json!({ "id": held.id, "text": before }));    }    let mut after = before.trim_end_matches('\n').to_string();    let last = after.rsplit('\n').next().unwrap_or_default();    let only_tags = !last.trim().is_empty() && derive::tags(last).len() == last.split_whitespace().count();    if only_tags {        after.push(' ');    } else if !after.is_empty() {        after.push_str("\n\n");    }    after.push_str(&hashtag(&tag));    edit(ctx, &json!({ "id": held.id, "text": after, "cursor": writing::len16(&after) }))}/// `notes.untag { id, tag }`: the tag taken off the note wherever it is/// written (`writing::derive::untag`), a line that held only it gone too;/// answers as `notes.edit`. A tag the note does not hold changes nothing.fn untag(ctx: &mut Ctx<'_>, request: &Value) -> Result<Value, MethodError> {    let held = note(ctx, id_of(request)?)?;    let tag = text_tag(request).ok_or_else(|| bad("this names the `tag`"))?;    let before = text_of(ctx, &held)?;    let after = derive::untag(&before, &tag);    let cursor = writing::len16(&after);    edit(ctx, &json!({ "id": held.id, "text": after, "cursor": cursor }))}/// `notes.leave { id, title? }`: the writer closed. A note with no words/// goes for good (a compose tapped and left leaves nothing behind); answers/// `left`. With the `title` the note opened with, a title changed since/// rewrites the links that opened this note to name the new one (`relinked`,/// how many notes were rewritten).fn leave(ctx: &mut Ctx<'_>, request: &Value) -> Result<Value, MethodError> {    let held = note(ctx, id_of(request)?)?;    let text = text_of(ctx, &held)?;    let was = text_of_key(request, "title").trim().to_string();    let now = derive::title(&text).unwrap_or_default();    if !was.is_empty() && !now.is_empty() && was != now && !held.binned {        let relinked = relink(ctx, &held, &was, &now)?;        return Ok(json!({ "id": held.id, "left": "kept", "relinked": relinked }));    }    if text.trim().is_empty() && !held.binned {        file(ctx, &held.id, &[])?;        note_writes::set_trashed(ctx, &held.id, true).map_err(tool)?;        cotton_tools::mcp::handlers::bin::erase(ctx, cotton_core::constants::BinKind::Note, &[held.id.clone()]).map_err(tool)?;        ctx.commit().map_err(tool)?;        return Ok(json!({ "id": held.id, "left": "removed" }));    }    Ok(json!({ "id": held.id, "left": "kept" }))}/// The links that named `held` by its old title, rewritten to its new one,/// in every note that holds them (this one too). Only when the old title/// opened this note: no other note titled so, made earlier, takes it.fn relink(ctx: &mut Ctx<'_>, held: &Held, was: &str, now: &str) -> Result<usize, MethodError> {    let old_key = links::title_key(was);    let all = every_note(ctx)?;    let mut texts = Vec::new();    for other in &all {        texts.push((other.clone(), text_of(ctx, other)?));    }    let another_older = texts.iter().any(|(other, t)| {        other.id != held.id && !other.binned && derive::title(t).is_some_and(|title| links::title_key(&title) == old_key) && (other.made.as_str(), other.id.as_str()) < (held.made.as_str(), held.id.as_str())    });    if another_older {        return Ok(0);    }    let titled: BTreeSet<String> = texts.iter().filter(|(o, _)| !o.binned).filter_map(|(_, t)| derive::title(t)).map(|t| links::title_key(&t)).collect();    let mut rewritten = 0;    for (other, other_text) in &texts {        if other.binned {            continue;        }        if let Some(after) = links::renamed(other_text, was, now, |t| titled.contains(&links::title_key(t))) {            write_text(ctx, &other.id, &after)?;            rewritten += 1;        }    }    Ok(rewritten)}// ── archive, bin ────────────────────────────────────────────────────────────enum Away {    Archive,    Unarchive,    Bin,    Restore,}fn put_away(ctx: &mut Ctx<'_>, request: &Value, away: Away) -> Result<Value, MethodError> {    let held = note(ctx, id_of(request)?)?;    let args = object(json!({ "id": held.id }));    let said = match away {        Away::Archive => {            note_writes::archive_note(ctx, &args).map_err(tool)?;            "acts.archived"        }        Away::Unarchive => {            note_writes::unarchive_note(ctx, &args).map_err(tool)?;            "acts.restored"        }        Away::Bin => {            if !held.binned {                note_writes::set_trashed(ctx, &held.id, true).map_err(tool)?;                ctx.commit().map_err(tool)?;            }            // A binned note is filed nowhere; its hashtags file it again on restore.            file(ctx, &held.id, &[])?;            "acts.binned"        }        Away::Restore => {            if held.binned {                note_writes::set_trashed(ctx, &held.id, false).map_err(tool)?;                ctx.commit().map_err(tool)?;            }            let back = note(ctx, &held.id)?;            let tags = derive::tags(&text_of(ctx, &back)?);            file(ctx, &held.id, &tags)?;            "acts.restored"        }    };    let now = note(ctx, &held.id)?;    Ok(json!({ "id": now.id, "archived": now.archived, "binned": now.binned, "said": line(said, &[])? }))}/// The ask a phone shows before anything is deleted for good.fn ask(message: String) -> Result<Value, MethodError> {    Ok(json!({ "ask": {        "title": line("acts.remove_title", &[])?,        "message": message,        "act": line("acts.remove_act", &[])?,        "cancel": line("acts.cancel", &[])?,        "destructive": true,    } }))}fn confirmed(request: &Value) -> bool {    request.get("confirmed").and_then(Value::as_bool).unwrap_or(false)}/// `notes.remove { id, confirmed? }`: a note deleted for good. Unconfirmed,/// nothing is deleted and the ask comes back for the phone to show.fn remove(ctx: &mut Ctx<'_>, request: &Value) -> Result<Value, MethodError> {    let held = note(ctx, id_of(request)?)?;    if !confirmed(request) {        let title = derive::title(&text_of(ctx, &held)?);        return ask(match title {            Some(title) => line("acts.remove_named", &[("title", &title)])?,            None => line("acts.remove_ask", &[])?,        });    }    if !held.binned {        note_writes::set_trashed(ctx, &held.id, true).map_err(tool)?;    }    file(ctx, &held.id, &[])?;    cotton_tools::mcp::handlers::bin::erase(ctx, cotton_core::constants::BinKind::Note, &[held.id.clone()]).map_err(tool)?;    ctx.commit().map_err(tool)?;    Ok(json!({ "id": held.id, "said": line("acts.removed", &[])? }))}/// `notes.empty_bin { confirmed? }`: every binned note deleted for good./// Unconfirmed, nothing is deleted and the ask comes back.fn empty_bin(ctx: &mut Ctx<'_>, request: &Value) -> Result<Value, MethodError> {    let binned: Vec<String> = every_note(ctx)?.into_iter().filter(|n| n.binned).map(|n| n.id).collect();    if !confirmed(request) && !binned.is_empty() {        return ask(counted_line("acts.empty_bin_ask", binned.len())?);    }    for id in &binned {        file(ctx, id, &[])?;    }    if !binned.is_empty() {        cotton_tools::mcp::handlers::bin::erase(ctx, cotton_core::constants::BinKind::Note, &binned).map_err(tool)?;        ctx.commit().map_err(tool)?;    }    Ok(json!({ "removed": binned.len(), "said": line("acts.removed", &[])? }))}// ── look and type ───────────────────────────────────────────────────────────/// `notes.themes {}`: the four themes with their names and both appearances,/// the typefaces, the bounds, the formatting panel's buttons and the bar's/// keys, each with its words./// The ink kept in Notes' settings row (`ink`), or the default when none is kept or this build knows no such ink.fn chosen_ink(handle: &CottonHandle) -> &'static notes_writing::Ink {    let held = settings_row(handle, SETTINGS_ROW).ok();    notes_writing::ink_or_default(held.as_ref().and_then(|row| row.get("ink")).and_then(Value::as_str))}fn themes(handle: &CottonHandle) -> Result<Value, MethodError> {    let data = notes_writing::writing();    // Every paper is answered in the person's ink (CONTRACT §10 "Ink"), so a sample and the standing look agree.    let ink = chosen_ink(handle);    let themes = data        .themes        .iter()        .map(|theme| {            Ok(json!({                "id": theme.id,                "name": line(&format!("theme.names.{}", theme.id), &[])?,                "light": notes_writing::inked(theme, ink, false),                "dark": notes_writing::inked(theme, ink, true),            }))        })        .collect::<Result<Vec<_>, MethodError>>()?;    let inks = data        .inks        .iter()        .map(|one| Ok(json!({ "id": one.id, "name": line(&format!("ink.names.{}", one.id), &[])?, "light": one.light, "dark": one.dark })))        .collect::<Result<Vec<_>, MethodError>>()?;    let fonts = data.fonts.iter().map(|font| Ok(json!({ "id": font, "name": line(&format!("type.fonts.{font}"), &[])? }))).collect::<Result<Vec<_>, MethodError>>()?;    let widths = data        .line_width        .choices        .iter()        .map(|width| Ok(json!({ "value": width, "name": line(&format!("type.line_widths.{width}"), &[])? })))        .collect::<Result<Vec<_>, MethodError>>()?;    let buttons = data        .formatting        .iter()        .map(|button| Ok(json!({ "action": button, "label": line(&notes_writing::action_line(button), &[])? })))        .collect::<Result<Vec<_>, MethodError>>()?;    let shortcuts = data        .shortcuts        .iter()        .map(|shortcut| {            let label = match (&shortcut.action, &shortcut.command) {                (Some(action), _) => line(&notes_writing::action_line(action), &[])?,                (None, Some(command)) => line(&format!("shortcut.{command}"), &[])?,                (None, None) => String::new(),            };            let mut answer = serde_json::to_value(shortcut).unwrap_or_default();            answer["label"] = json!(label);            Ok(answer)        })        .collect::<Result<Vec<_>, MethodError>>()?;    let bar = data.bar.iter().map(|key| Ok(json!({ "key": key, "label": line(&format!("bar.{key}"), &[])? }))).collect::<Result<Vec<_>, MethodError>>()?;    Ok(json!({        "themes": themes,        "inks": inks,        "ink": ink.id,        "fonts": fonts,        "font_size": data.font_size,        "line_height": data.line_height,        "line_widths": widths,        "paragraph_spacing": data.paragraph_spacing,        "faces": data.faces,        "defaults": data.defaults,        "formatting": buttons,        "bar": bar,        "keyboard": keyboard(&data.keyboard)?,        "shortcuts": shortcuts,        "scale": data.scale,        "words": {            "look": line("theme.title", &[])?,            "ink": line("ink.title", &[])?,            "light": line("theme.light", &[])?,            "dark": line("theme.dark", &[])?,            "type": line("type.title", &[])?,            "font": line("type.font", &[])?,            "size": line("type.size", &[])?,            "line_height": line("type.line_height", &[])?,            "line_width": line("type.line_width", &[])?,            "paragraph_spacing": line("type.paragraph_spacing", &[])?,            "hide_marks": line("type.hide_marks", &[])?,            "shortcuts": line("shortcut.title", &[])?,            "back": line("nav.back", &[])?,            "more": line("nav.more", &[])?,            "share": line("nav.share", &[])?,            "settings": line("nav.settings", &[])?,            "close": line("nav.close", &[])?,            "return": line("format.return", &[])?,            "tick": line("format.tick", &[])?,            "sample": line("theme.sample", &[])?,        },    }))}/// `notes.settings { light_theme?, dark_theme?, ink?, font?, font_size?,/// line_height?, line_width? }`: the look and type chosen, read; with any/// key given, that choice written first. They sync as `face_settings` rows,/// as Books' reader settings do: the row keyed `notes` (its face the light/// theme; font, font_size, line_height; `margins` the line width) and the/// row keyed `notes_dark` (its face the dark theme). `ink` (22 Nov 2026) is/// a column of the notes row; a copy that never chose one writes in blue.pub const DARK_ROW: &str = "notes_dark";/// One of Notes' face settings rows, as kept (empty when none is).pub(crate) fn settings_row(handle: &CottonHandle, key: &str) -> Result<Map<String, Value>, MethodError> {    let listed = super::records::call(&handle.client(), "records.list", &json!({ "table": "face_settings", "where": { "table": key } }))?;    Ok(listed["records"].as_array().and_then(|rows| rows.first()).map(|row| object(row["data"].clone())).unwrap_or_default())}/// A kept settings row as it can be written again: without its id and the times the store and the object stamp./// `chosen_at` is the object's ("when the object accepted the choice", a full timestamp in a date column); written/// back, every later change was refused ("Chosen at takes a date written YYYY-MM-DD"), on the iPhone's second ink/// (launch-ios, 22 Nov 2026) and on any setting changed after the row had synced once.pub(crate) fn rewritable(mut row: Map<String, Value>) -> Map<String, Value> {    row.retain(|column, _| !matches!(column.as_str(), "id" | "created_at" | "updated_at" | "chosen_at"));    row}/// Write `patch` into one of Notes' face settings rows, the rest kept.pub(crate) fn write_settings_row(handle: &CottonHandle, key: &str, mut patch: Map<String, Value>) -> Result<(), MethodError> {    // Look's face, fitted to a server deployed before Look (no `type_face`): kept beside the copy there.    super::look::fit_face(handle, key, &mut patch)?;    if patch.is_empty() {        return Ok(());    }    let defaults = &notes_writing::writing().defaults;    let mut row = rewritable(settings_row(handle, key)?);    row.insert("table".into(), json!(key));    row.entry("face").or_insert(json!(if key == DARK_ROW { &defaults.dark_theme } else { &defaults.light_theme }));    row.extend(patch);    super::records::call(&handle.client(), "records.create", &json!({ "table": "face_settings", "data": Value::Object(row) }))?;    Ok(())}/// A theme id as kept, read as this build's: an old id is its new theme.fn theme_id(id: &str) -> Option<String> {    let id = notes_writing::writing().renamed.get(id).map(String::as_str).unwrap_or(id);    notes_writing::theme(id).map(|_| id.to_string())}fn settings(handle: &CottonHandle, request: &Value) -> Result<Value, MethodError> {    let data = notes_writing::writing();    let defaults = &data.defaults;    let read = |handle: &CottonHandle, key: &str| settings_row(handle, key);    let in_range = |value: f64, range: &notes_writing::Range| value >= range.min - 1e-9 && value <= range.max + 1e-9;    let refuse = |key: &str| MethodError::new("bad_request", format!("{} ({key})", line("refusal.bad_setting", &[]).unwrap_or_default()));    let theme_of = |key: &str| -> Result<Option<String>, MethodError> {        match text(request, key) {            None => Ok(None),            Some(theme) => theme_id(theme).map(Some).ok_or_else(|| MethodError::new("bad_request", line("refusal.no_theme", &[]).unwrap_or_default())),        }    };    let mut patch = Map::new();    if let Some(theme) = theme_of("light_theme")? {        patch.insert("face".into(), json!(theme));    }    let dark = theme_of("dark_theme")?;    if let Some(font) = text(request, "font") {        // Look's faces (shared/DECISIONS.md "Look"); `mono` and `system`, the ids before Look, are still taken.        if !data.fonts.iter().any(|f| f == font) && !matches!(font, "mono" | "system") {            return Err(refuse("font"));        }        let face = super::look::words_face_of_font(font).unwrap_or("own");        patch.insert("font".into(), json!(super::look::words_font_of_face(face)));        patch.insert("type_face".into(), json!(face));    }    if let Some(size) = request.get("font_size").and_then(Value::as_f64) {        if !in_range(size, &data.font_size) {            return Err(refuse("font_size"));        }        patch.insert("font_size".into(), json!(size));    }    if let Some(height) = request.get("line_height").and_then(Value::as_f64) {        if !in_range(height, &data.line_height) {            return Err(refuse("line_height"));        }        patch.insert("line_height".into(), json!(height));    }    if let Some(width) = request.get("line_width").and_then(Value::as_f64) {        if !data.line_width.choices.iter().any(|w| (*w - width).abs() < 1e-9) {            return Err(refuse("line_width"));        }        patch.insert("margins".into(), json!(width));    }    if let Some(spacing) = request.get("paragraph_spacing").and_then(Value::as_f64) {        if !in_range(spacing, &data.paragraph_spacing) {            return Err(refuse("paragraph_spacing"));        }        patch.insert("paragraph_spacing".into(), json!(spacing));    }    if let Some(hide) = request.get("hide_marks").and_then(Value::as_bool) {        patch.insert("hide_marks".into(), json!(hide));    }    if let Some(ink) = text(request, "ink") {        if notes_writing::ink(ink).is_none() {            return Err(refuse("ink"));        }        patch.insert("ink".into(), json!(ink));    }    let write = |key: &str, patch: Map<String, Value>| write_settings_row(handle, key, patch);    if !patch.is_empty() {        write(SETTINGS_ROW, patch)?;    }    if let Some(theme) = dark {        write(DARK_ROW, Map::from_iter([("face".to_string(), json!(theme))]))?;    }    let held = read(handle, SETTINGS_ROW)?;    let held_dark = read(handle, DARK_ROW)?;    let said = |row: &Map<String, Value>, column: &str| row.get(column).and_then(Value::as_str).map(str::to_string);    let number = |column: &str| held.get(column).and_then(Value::as_f64);    let light = said(&held, "face").and_then(|id| theme_id(&id)).unwrap_or(defaults.light_theme.clone());    let dark = said(&held_dark, "face").and_then(|id| theme_id(&id)).unwrap_or(defaults.dark_theme.clone());    // The face is Look's (`look`): `font` answers it in the ids before Look, `face` in Look's own.    let look = cotton_core::look::app("notes").expect("Words has a look");    let face = super::look::chosen(handle, "notes", look)?.face;    let font = if face == "own" { "sans".to_string() } else { face.clone() };    let ink = notes_writing::ink_or_default(said(&held, "ink").as_deref());    Ok(json!({        "light_theme": light,        "dark_theme": dark,        "ink": ink.id,        "light": notes_writing::theme(&light).map(|t| notes_writing::inked(t, ink, false)),        "dark": notes_writing::theme(&dark).map(|t| notes_writing::inked(t, ink, true)),        "font": font,        "face": face,        "font_size": number("font_size").filter(|v| in_range(*v, &data.font_size)).unwrap_or(defaults.font_size),        "line_height": number("line_height").filter(|v| in_range(*v, &data.line_height)).unwrap_or(defaults.line_height),        "line_width": number("margins").filter(|v| data.line_width.choices.iter().any(|w| (w - v).abs() < 1e-9)).unwrap_or(defaults.line_width),        "paragraph_spacing": number("paragraph_spacing").filter(|v| in_range(*v, &data.paragraph_spacing)).unwrap_or(defaults.paragraph_spacing),        "hide_marks": held.get("hide_marks").and_then(Value::as_bool).unwrap_or(defaults.hide_marks),    }))}// ── pictures ────────────────────────────────────────────────────────────────/// Keep one picture file (a path on this phone) as a photo record: answers/// its address in a note's text. The same bytes kept twice are one photo.pub(crate) fn keep_picture(handle: &CottonHandle, path: &str, mime: &str, filename: Option<&str>) -> Result<String, MethodError> {    let sha = sha256_file(path)?;    let known = with_read(handle, "notes.picture", |ctx| {        let found = query_rows(ctx, &Query::on("cotton_photos").columns(&["id", "trashed_at"]).eq("id", format!("{PHOTO_SRC}{sha}"))).unwrap_or_default();        Ok(found.iter().find(|row| row.get("trashed_at").is_none_or(Value::is_null)).and_then(|row| row.get("id").cloned()).unwrap_or(Value::Null))    })?;    if let Some(id) = known.as_str() {        return Ok(id.to_string());    }    let args = super::media::validate_capture(&json!({ "path": path, "mime": mime, "kind": "photo", "filename": filename }))?;    let client = handle.client();    let layout = client.layout().clone();    let device_key = client.self_device_id();    let answer = client.write_rows("notes.picture", &mut |ctx| super::media::write_media(ctx, &layout, &args, device_key.as_deref())).map_err(|reason| MethodError::new("capture_refused", reason))?;    let answer = crate::authoring::own_answer(answer);    let id = answer["recordId"].as_str().ok_or_else(|| MethodError::new("capture_refused", "no photo for the picture"))?;    Ok(id.to_string())}pub(crate) fn sha256_file(path: &str) -> Result<String, MethodError> {    use sha2::{Digest, Sha256};    let bytes = std::fs::read(path).map_err(|why| MethodError::new("unreadable", format!("{path}: {why}")))?;    Ok(hex::encode(Sha256::digest(&bytes)))}/// `notes.picture { id, path, mime, filename?, alt?, text?, selection? }`: a/// picture from the library, the camera, a paste or a drop goes into the/// note on its own line after the cursor's; answers what `notes.edit` does,/// with the new `selection`.fn picture(handle: &CottonHandle, request: &Value) -> Result<Value, MethodError> {    let id = id_of(request)?.to_string();    let path = text(request, "path").map(str::trim).filter(|p| !p.is_empty()).ok_or_else(|| bad("a picture comes as the `path` of its file"))?;    let mime = text(request, "mime").unwrap_or("image/jpeg");    let src = keep_picture(handle, path, mime, text(request, "filename"))?;    let alt = text(request, "alt").unwrap_or_default().to_string();    with_write(handle, "notes.picture", |ctx| {        let held = note(ctx, &id)?;        let base = match text(request, "text") {            Some(given) => given.to_string(),            None => text_of(ctx, &held)?,        };        let selection = selection_of(request, writing::len16(&base));        let edited = format::apply(&base, selection, &format::Action::Picture { src: src.clone(), alt: alt.clone() });        let mut answer = edit(ctx, &json!({ "id": id, "text": edited.text, "cursor": edited.selection.end }))?;        answer["selection"] = json!(edited.selection);        answer["src"] = json!(src);        Ok(answer)    })}#[cfg(test)]#[path = "notes_tests.rs"]mod tests;#[cfg(test)]#[path = "notes_bear_tests.rs"]mod bear_tests;