//! What the person's assistant wrote, readable in Words (owner, 21 Nov 2026): //! the web pages an assistant made (documents of type `text/html`, the only //! documents Words pulls: the kit's `only`), listed beside the assistant's //! notes under "From your assistant", and the assistant's memory of what the //! person said (`notes.memory`), read-only, grouped as the briefing groups it: //! the entries about the person first (linked to no project), then each //! project's, in that project's own order (pinned first, then position). //! assets/design/notes/CONTRACT.md section 13 says the shapes. use serde_json::{json, Map, Value}; use cotton_tools::mcp::handlers::common::rows as query_rows; use cotton_tools::mcp::dispatch::Ctx; use cotton_tools::mcp::read_db::Query; use super::notes::{counted_line, line, tool}; use crate::handle::CottonHandle; use crate::methods::MethodError; /// The most a page may weigh and still open in the reader: the core's ceiling /// for one answer held in memory (32 MB), as the iPhone viewer holds it. pub const PAGE_CEILING_BYTES: i64 = 32 * 1024 * 1024; /// One web page an assistant made, as this copy holds it. #[derive(Debug, Clone)] pub(crate) struct Page { pub id: String, pub title: String, pub made: String, pub edited: String, pub key: Option, pub bytes: i64, } fn said(row: &Map, key: &str) -> Option { row.get(key).and_then(Value::as_str).map(str::to_string).filter(|value| !value.is_empty()) } /// Every live web page of this copy (not in the bin), any order. pub(crate) fn pages(ctx: &Ctx<'_>) -> Result, MethodError> { let query = Query::on("cotton_documents") .columns(&["id", "title", "original_name", "mime", "byte_size", "storage_path", "trashed_at", "created_at", "updated_at"]) .eq("mime", "text/html".to_string()); let found = query_rows(ctx, &query).map_err(tool)?; Ok(found .iter() .filter(|row| said(row, "trashed_at").is_none()) .map(|row| { let made = said(row, "created_at").unwrap_or_default(); Page { id: said(row, "id").unwrap_or_default(), title: said(row, "title").or_else(|| said(row, "original_name")).unwrap_or_default(), edited: said(row, "updated_at").unwrap_or_else(|| made.clone()), made, key: said(row, "storage_path"), bytes: row.get("byte_size").and_then(Value::as_i64).unwrap_or(0), } }) .collect()) } /// Does a page answer `words` (every word of the search, in its title)? pub(crate) fn page_matches(page: &Page, words: &[String]) -> bool { let title = page.title.to_lowercase(); words.iter().all(|word| title.contains(&word.to_lowercase())) } /// A page's row in the list: a row as a note's is, `kind` page, and `page` /// what the reader opens (the file's media key for `media.ensure`), or why it /// cannot. pub(crate) fn page_row(page: &Page, date: String) -> Result { let title = if page.title.is_empty() { line("assistant.untitled_page", &[])? } else { page.title.clone() }; let refused = if page.key.is_none() { Some(line("assistant.page_missing", &[])?) } else if page.bytes > PAGE_CEILING_BYTES { Some(line("assistant.page_too_big", &[])?) } else { None }; Ok(json!({ "id": page.id, "kind": "page", "title": title, "preview": line("assistant.page_preview", &[])?, "preview_lines": 1, "empty": false, "date": date, "edited_at": page.edited, "tags": [], "picture": null, "archived": false, "binned": false, "pinned": false, "pinned_in_notes": false, "checklist": null, "thumbnail": null, "by_assistant": true, "page": { "key": page.key, "bytes": page.bytes, "refused": refused }, })) } /// `notes.memory { zone? }`: the assistant's memory, read-only. pub(crate) fn memory(handle: &CottonHandle, request: &Value) -> Result { let zone = request.get("zone").and_then(Value::as_str).map(str::to_string); super::notes::with_read(handle, "notes.memory", |ctx| memory_in(ctx, zone.as_deref())) } struct Entry { id: String, slug: String, sentence: String, changed: String, made: String, } pub(crate) fn memory_in(ctx: &mut Ctx<'_>, zone: Option<&str>) -> Result { let found = query_rows(ctx, &Query::on("cotton_memories").columns(&["id", "slug", "title", "status", "archived_at", "created_at", "updated_at"])).map_err(tool)?; let entries: std::collections::BTreeMap = found .iter() .filter(|row| said(row, "status").as_deref().unwrap_or("active") == "active" && said(row, "archived_at").is_none()) .filter_map(|row| { let id = said(row, "id")?; let made = said(row, "created_at").unwrap_or_default(); Some((id.clone(), Entry { id, slug: said(row, "slug").unwrap_or_default(), sentence: said(row, "title")?, changed: said(row, "updated_at").unwrap_or_else(|| made.clone()), made })) }) .collect(); let links = query_rows(ctx, &Query::on("cotton_project_links").columns(&["id", "project_id", "record_kind", "record_id", "pinned", "position"]).eq("record_kind", "memory".to_string())).map_err(tool)?; let projects = query_rows(ctx, &Query::on("cotton_memory_projects").columns(&["id", "slug", "name", "status", "trashed_at", "created_at"])).map_err(tool)?; let flag = |row: &Map| row.get("pinned").is_some_and(|v| v.as_bool().unwrap_or_else(|| v.as_i64().is_some_and(|n| n != 0))); let linked: std::collections::BTreeSet<&str> = links.iter().filter_map(|link| link.get("record_id").and_then(Value::as_str)).collect(); let said_entry = |entry: &Entry, pinned: bool| -> Value { json!({ "id": entry.id, "slug": entry.slug, "sentence": entry.sentence, "pinned": pinned, "changed": line("memory.changed", &[("date", &super::notes::date_words(ctx, &entry.changed, zone))]).unwrap_or_default(), "changed_at": entry.changed, }) }; let mut groups = Vec::new(); // About the person: the entries linked to no project, oldest first (the briefing's Owner section). let mut own: Vec<&Entry> = entries.values().filter(|entry| !linked.contains(entry.id.as_str())).collect(); own.sort_by(|a, b| a.made.cmp(&b.made).then_with(|| a.slug.cmp(&b.slug))); if !own.is_empty() { let items: Vec = own.iter().map(|entry| said_entry(entry, false)).collect(); groups.push(json!({ "id": "owner", "label": line("memory.owner", &[])?, "project": null, "count": items.len(), "entries": items })); } // Each live project's, oldest project first; inside one, pinned first, then its position. let mut live: Vec<&Map> = projects.iter().filter(|p| said(p, "trashed_at").is_none() && said(p, "status").as_deref().unwrap_or("active") == "active").collect(); live.sort_by(|a, b| said(a, "created_at").cmp(&said(b, "created_at")).then_with(|| said(a, "slug").cmp(&said(b, "slug")))); for project in live { let Some(project_id) = said(project, "id") else { continue }; let mut mine: Vec<(&Map, &Entry)> = links .iter() .filter(|link| said(link, "project_id").as_deref() == Some(project_id.as_str())) .filter_map(|link| Some((link, entries.get(link.get("record_id")?.as_str()?)?))) .collect(); if mine.is_empty() { continue; } let position = |link: &Map| link.get("position").and_then(Value::as_f64).unwrap_or(0.0); mine.sort_by(|(a, x), (b, y)| flag(b).cmp(&flag(a)).then_with(|| position(a).total_cmp(&position(b))).then_with(|| x.id.cmp(&y.id))); let items: Vec = mine.iter().map(|(link, entry)| said_entry(entry, flag(link))).collect(); let name = said(project, "name").or_else(|| said(project, "slug")).unwrap_or_default(); groups.push(json!({ "id": project_id, "label": name, "project": said(project, "slug"), "count": items.len(), "entries": items })); } let count = entries.len(); Ok(json!({ "title": line("memory.title", &[])?, "about": line("memory.about", &[])?, "count": count, "count_words": counted_line("memory.count", count)?, "groups": groups, "empty": if count == 0 { Some(line("memory.empty", &[])?) } else { None }, })) } /// How many live entries the memory holds (the side page's count). pub(crate) fn memory_count(ctx: &Ctx<'_>) -> Result { let found = query_rows(ctx, &Query::on("cotton_memories").columns(&["id", "title", "status", "archived_at"])).map_err(tool)?; Ok(found.iter().filter(|row| said(row, "status").as_deref().unwrap_or("active") == "active" && said(row, "archived_at").is_none() && said(row, "title").is_some()).count()) } /// `developer.inventAssistantWriting { notes, pages, about_you, projects }` — /// COTTON DEV ONLY: invented writing an assistant might have made, written /// into this phone's copy as an assistant's writes land (notes with /// `author_kind` agent, web pages as `text/html` documents, memory entries /// about the person and under projects), so a look on a simulator draws /// From your assistant, the reader and Memory from the core's own answers. /// Each row's id comes from its place in the request, so asking again writes /// the same rows, never more. A page carries a media key and no bytes: the /// reader says it is not on this phone yet. The real Cotton refuses it by /// name. Every word comes from the request (an invented fixture). pub fn invent(handle: &CottonHandle, request: &Value) -> Result { if handle.flavor() != cotton_core::flavor::Flavor::Dev { return Err(MethodError::new("not_dev", "developer.inventAssistantWriting answers only in Cotton Dev")); } let list = |key: &str| request.get(key).and_then(Value::as_array).cloned().unwrap_or_default(); let text = |row: &Value, key: &str| row.get(key).and_then(Value::as_str).unwrap_or_default().to_string(); let (notes, pages, about, projects) = (list("notes"), list("pages"), list("about_you"), list("projects")); let mut rows: Vec<(&'static str, String, Map)> = Vec::new(); let object = |value: Value| value.as_object().cloned().unwrap_or_default(); for (at, note) in notes.iter().enumerate() { let title = text(note, "title"); rows.push(("cotton_notes", format!("dev-assistant-note-{at}"), object(json!({ "kind": "note", "title": title, "body": text(note, "body"), "author_kind": "agent", "author_label": "Claude", "created_at": text(note, "at"), "updated_at": text(note, "at"), })))); } for (at, page) in pages.iter().enumerate() { rows.push(("cotton_documents", format!("dev-assistant-page-{at}"), object(json!({ "title": text(page, "title"), "original_name": "page.html", "mime": "text/html", "byte_size": page.get("bytes").and_then(Value::as_i64).unwrap_or(2048), "sha256": format!("{at:0>64}"), "storage_path": "@file", "status": "ready", "created_at": text(page, "at"), "updated_at": text(page, "at"), })))); } let entry = |row: &Value| object(json!({ "slug": text(row, "slug"), "title": text(row, "title"), "body": "", "status": "active", "visibility": "private", "origin_kind": "agent", "origin_label": "Claude", "created_at": text(row, "at"), "updated_at": text(row, "at"), })); for row in &about { rows.push(("cotton_memories", format!("dev-memory-{}", text(row, "slug")), entry(row))); } for project in &projects { let project_id = format!("dev-project-{}", text(project, "slug")); rows.push(("cotton_memory_projects", project_id.clone(), object(json!({ "slug": text(project, "slug"), "name": text(project, "name"), "repos": [], "status": "active", "created_at": text(project, "at"), })))); for (position, row) in project.get("entries").and_then(Value::as_array).cloned().unwrap_or_default().iter().enumerate() { let memory = format!("dev-memory-{}", text(row, "slug")); rows.push(("cotton_memories", memory.clone(), entry(row))); rows.push(("cotton_project_links", format!("dev-link-{}", text(row, "slug")), object(json!({ "project_id": project_id, "record_kind": "memory", "record_id": memory, "pinned": row.get("pinned").and_then(Value::as_bool).unwrap_or(false), "position": position as f64, "applied_by": "agent", })))); } } let written = rows.len(); super::notes::with_write(handle, "developer.inventAssistantWriting", |ctx| { for (table, id, row) in &rows { let mut row = row.clone(); // A document's file key, made in this database's own prefix as the phone makes it. if row.get("storage_path").and_then(Value::as_str) == Some("@file") { row.insert("storage_path".into(), json!(cotton_core::media::keys::document_original_key(ctx.file.id(), id, "html"))); } cotton_tools::mcp::handlers::common::insert_row(ctx, table, id, row).map_err(tool)?; } ctx.commit().map_err(tool)?; Ok(json!({ "written": written })) }) }