//! The WORK-and-REFERENCE lane's screen reads (sub-step 4f). //! //! Projects and their code, memory, sessions, the briefing, documents, the //! reader, the scanner, meetings and news — 25 //! routes, declared in [`super::reads::READS`] and implemented here. //! //! **Why this is a file of its own rather than more of `reads.rs`.** Three //! lanes (4e, 4f, 4g) fill that table at once, and the shared pre-step that //! would have split it into `{day,work,traffic}.rs` never landed. Putting the //! ENTRIES in `reads.rs` (they must be, so the totality test sees one table) //! and the BODIES here keeps the shared edit to an append at the tail of one //! array and a deletion from `DEFERRED` — which is a conflict a person can //! read, rather than four hundred lines of query moved twice. //! //! ## The two rules every read here keeps //! //! **Where a screen's query IS a tool's answer, the read calls the handler** //! (design P4) — that is the [`ReadSource::Tool`] arm in the table, and it is //! why the project page's counts and the Mac's `decide` window's counts are //! ONE function over `cotton_project_links` rather than two that agree today. //! //! **Where it is a join no single tool answers, it is written here** — over //! the replica's own driver, or as a [`ReadSource::Controller`] composite that //! calls two handlers and joins their answers. A composite takes the //! controller rather than the replica because `read_tool` is the controller's; //! it is not a "before there is a replica" read, and each one says so. //! //! Nothing here re-counts what a tool counts, and nothing here re-derives what //! `cotton-core` decides: a screen that wanted a second opinion would be the //! drift this table exists to prevent. //! //! ## Why no query here says `WHERE workspace_id = ?` //! //! **The replica is ONE workspace's file, by construction.** It lives at //! `/client//replica.db` (`cotton_client::replica`), and //! `Replica::workspace_id` is not a value this layer chose — it is read out of //! the file's own `_meta` row when the file is opened. There is no second //! workspace in it to cross into. //! //! The scoped queries in [`super::reads`] are belt and braces on that same //! fact, and the ones that DO name the column here name it because the column //! is the KEY they are addressing by (`cotton_news_settings`' primary key is //! `workspace_id`) or because a value derived from it has to be answered //! (`media::keys` are workspace-scoped). A future replica that held two //! workspaces would break this file and `reads.rs` alike, which is why the //! statement is made once, here, rather than assumed thirty times in silence. use cotton_core::rules::session_delivery; use std::collections::BTreeMap; use chrono::{DateTime, Utc}; use cotton_store::protocol::js::{parse_date_ms, to_iso_string}; use serde_json::{json, Map, Value}; /// How many values one `IN (…)` carries before the list is asked for in /// chunks. /// /// SQLite binds a limited number of parameters per statement, and a `WHERE key /// IN (…)` built out of a field a person typed is a list nobody capped. Five /// hundred is far past any real project and far short of the limit, and the /// alternative — one statement with one `?` per entry — fails the WHOLE read /// rather than the one row that was silly. const IN_CHUNK: usize = 500; use crate::shell::file::ReadFile; use cotton_core::rules::machines::{ can_host, listed_machines, report_state, window_pct, ReportState, }; use cotton_core::rules::repo_ref::{project_repo_refs, OwnCotton}; use cotton_core::rules::samples::{retention_cutoff, thin, Reading}; use cotton_core::rules::session_model::{model_label, OFFERED_MODELS}; use rusqlite::types::Value as Sql; use crate::shell::client::ClientController; // ── Small helpers, so every query below reads like the screen it serves ──── // /// One required string argument, refused by name when it is missing. pub(crate) fn text_arg(args: &Map, name: &str) -> Result { args.get(name) .and_then(Value::as_str) .map(str::to_string) .filter(|value| !value.is_empty()) .ok_or_else(|| format!("`{name}` is required")) } /// One optional string argument. pub(crate) fn maybe_text(args: &Map, name: &str) -> Option { args.get(name) .and_then(Value::as_str) .filter(|value| !value.is_empty()) .map(str::to_string) } fn flag(args: &Map, name: &str) -> bool { args.get(name).and_then(Value::as_bool).unwrap_or(false) } /// Whether Cotton holds the session `id` and on which Mac — what /// `rules::session_delivery` reads a message's delivery against. fn addressed_session(replica: &ReadFile<'_>, id: &str) -> Result)>, String> { let row = replica .driver .get("SELECT host_owned, machine FROM cotton_sessions WHERE id = ?", &[Sql::Text(id.to_string())]) .map_err(unreadable)?; Ok(row.map(|row| (row.int("host_owned") == Some(1), row.text("machine").map(str::to_string)))) } /// A row's column as JSON: TEXT as a string, INTEGER/REAL as numbers, NULL as /// null. The screens read camelCase, so the caller names the key. pub(crate) fn cell(row: &cotton_store::driver::Row, column: &str) -> Value { match row.get(column) { Some(Sql::Text(text)) => Value::from(text.clone()), Some(Sql::Integer(number)) => Value::from(*number), Some(Sql::Real(number)) => Value::from(*number), Some(Sql::Blob(_)) | Some(Sql::Null) | None => Value::Null, } } /// A column holding JSON text, parsed — and `null` rather than a panic when /// the text is not JSON. A row written by a build ahead of this one must /// degrade to "nothing to draw", never to a screen that will not open. pub(crate) fn json_cell(row: &cotton_store::driver::Row, column: &str) -> Value { match row.text(column) { Some(text) => serde_json::from_str(text).unwrap_or(Value::Null), None => Value::Null, } } fn boolean(row: &cotton_store::driver::Row, column: &str) -> Value { Value::Bool(row.int(column).unwrap_or(0) != 0) } /// Turn a row into an object, `(json key, column)` by `(json key, column)`. pub(crate) fn object(row: &cotton_store::driver::Row, fields: &[(&str, &str)]) -> Value { let mut out = Map::new(); for (key, column) in fields { out.insert((*key).to_string(), cell(row, column)); } Value::Object(out) } pub(crate) fn unreadable(reason: impl std::fmt::Display) -> String { reason.to_string() } // ── Projects, memory and code ───────────────────────────────────────────── /// `read.memory {project?, archived?}` — the entries a project briefs with, or /// the ones that were dropped. /// /// A Query rather than a tool because `memory.list` is `Not` in the verb grid /// ("brief and recall are the readers"), which is a statement about what an /// ASSISTANT may browse. The owner's own screen is the review surface, and it /// needs the LINK row as well as the entry: `pinned` and `position` live on /// `cotton_project_links` (v34), so an entry's order is a property of its /// membership rather than of itself. pub fn memory(replica: &ReadFile<'_>, args: &Map) -> Result { let archived = flag(args, "archived"); let project = maybe_text(args, "project"); let mut sql = String::from( "SELECT m.id, m.slug, m.title, m.status, m.machine, m.source, \ m.origin_kind, m.origin_label, \ m.superseded_by, m.visibility, m.archived_at, \ m.created_at, m.updated_at \ FROM cotton_memories m", ); let mut params: Vec = Vec::new(); if let Some(slug) = &project { sql.push_str( " JOIN cotton_project_links l \ ON l.record_kind = 'memory' AND l.record_id = m.id \ JOIN cotton_memory_projects p ON p.id = l.project_id AND p.slug = ?", ); params.push(Sql::Text(slug.clone())); } sql.push_str(if archived { " WHERE m.archived_at IS NOT NULL ORDER BY COALESCE(m.archived_at, m.updated_at) DESC, m.slug ASC" } else { " WHERE m.archived_at IS NULL ORDER BY m.created_at DESC, m.slug ASC" }); let rows = replica.driver.all(&sql, ¶ms).map_err(unreadable)?; // ONE query for every entry's links rather than one per entry. The list is // unlimited — this is the whole of somebody's memory — so the per-row shape // was a statement per sentence, on the thread that paints the screen. let ids: Vec = rows .iter() .filter_map(|row| row.text("id").map(str::to_string)) .collect(); let mut links = memory_links(replica, &ids)?; let mut entries = Vec::new(); for row in &rows { let id = row.text("id").unwrap_or_default().to_string(); let mut entry = object( row, &[ ("id", "id"), ("slug", "slug"), ("title", "title"), ("status", "status"), ("machine", "machine"), ("source", "source"), ("originKind", "origin_kind"), ("originLabel", "origin_label"), ("supersededBy", "superseded_by"), ("visibility", "visibility"), ("archivedAt", "archived_at"), ("createdAt", "created_at"), ("updatedAt", "updated_at"), ], ); if let Value::Object(map) = &mut entry { map.insert( "projects".to_string(), links .remove(&id) .unwrap_or_else(|| Value::Array(Vec::new())), ); } entries.push(entry); } // How many entries have been DROPPED, whichever list is being drawn. The // live list's own footer offers "Dropped entries" and has to say whether // there are any; asking a second time from the archived screen would be a // second read for one screen, which the reads table forbids. let dropped = replica .driver .get( "SELECT COUNT(*) AS n FROM cotton_memories WHERE archived_at IS NOT NULL", &[], ) .map_err(unreadable)? .and_then(|row| row.int("n")) .unwrap_or_default(); Ok(json!({ "entries": entries, "droppedCount": dropped })) } /// Which projects each of these entries is in, with the link's own `pinned` /// and `position` — the two columns the ORDER is read from. /// /// Keyed by entry id, and an entry in no project has no key rather than an /// empty one: the caller decides what a missing entry means, and here it means /// the empty list. fn memory_links( replica: &ReadFile<'_>, memory_ids: &[String], ) -> Result, String> { let mut out: std::collections::HashMap = std::collections::HashMap::new(); if memory_ids.is_empty() { return Ok(out); } let placeholders = vec!["?"; memory_ids.len()].join(","); let rows = replica .driver .all( &format!( "SELECT l.record_id, l.project_id, l.pinned, l.\"position\", \ p.slug, p.name, p.status \ FROM cotton_project_links l \ JOIN cotton_memory_projects p ON p.id = l.project_id \ WHERE l.record_kind = 'memory' AND l.record_id IN ({placeholders}) \ ORDER BY l.pinned DESC, l.\"position\" ASC, p.slug ASC" ), &memory_ids .iter() .map(|id| Sql::Text(id.clone())) .collect::>(), ) .map_err(unreadable)?; for row in &rows { let Some(record_id) = row.text("record_id").map(str::to_string) else { continue; }; out.entry(record_id) .or_insert_with(|| Value::Array(Vec::new())) .as_array_mut() .expect("the entry was just inserted as an array") .push(json!({ "projectId": cell(row, "project_id"), "slug": cell(row, "slug"), "name": cell(row, "name"), "status": cell(row, "status"), "pinned": boolean(row, "pinned"), "position": cell(row, "position"), })); } Ok(out) } /// `read.memoryEntry {id}` — one entry, its comment threads and the entries it /// supersedes or was superseded by. /// /// A composite rather than `get_record {kind:"memory"}` because the screen /// draws four things the record alone does not carry: the project links with /// their pins, the comment threads (`list_comments`, whose open ones ride /// every briefing until they are resolved), the neighbours on either side of a /// supersession, and every ACTIVE project — which is the "Restore into" and /// "Add to" picker, part of this screen and therefore part of this read. pub fn memory_record(client: &ClientController, args: &Map) -> Result { let id = text_arg(args, "id")?; // A record that is not there is an ANSWER, not a failure: the screen draws // "This entry isn't here" for a missing row and "Couldn't read this entry" // for a read that broke, and it never conflates them. `get_record` refuses // for a missing memory, so the absence is decided here — before the tool is // asked — and every id-taking read on this screen answers a null the same // way (`page`, `session`, `newsEdition`). let present = client.with_file(|replica| { Ok(replica .driver .get( "SELECT id FROM cotton_memories WHERE id = ?", &[Sql::Text(id.clone())], ) .map_err(unreadable)? .is_some()) })?; if !present { return Ok(json!({ "entry": Value::Null, "comments": Value::Array(vec![]), "projects": Value::Array(vec![]), "allProjects": Value::Array(vec![]), "successor": Value::Null, "predecessors": Value::Array(vec![]), })); } let mut record_args = Map::new(); record_args.insert("kind".to_string(), Value::from("memory")); record_args.insert("id".to_string(), Value::from(id.clone())); let record = client.read_tool("get_record", &record_args)?; let mut comment_args = Map::new(); comment_args.insert("recordKind".to_string(), Value::from("memory")); comment_args.insert("recordId".to_string(), Value::from(id.clone())); // EVERY thread, not the open ones — `list_comments` defaults to `open`, // which is top-level rows with nothing resolved, and this screen draws the // replies AND the settled threads. The same argument `read.meeting` passes, // for the same reason: the default filter hides exactly the half that says // whether a question has been answered. comment_args.insert("status".to_string(), Value::from("all")); let comments = client.read_tool("list_comments", &comment_args)?; let neighbours = client.with_file(|replica| { let links = memory_links(replica, std::slice::from_ref(&id))? .remove(&id) .unwrap_or_else(|| Value::Array(Vec::new())); let successor = replica .driver .get( "SELECT id, slug, title FROM cotton_memories WHERE id = \ (SELECT superseded_by FROM cotton_memories WHERE id = ?)", &[Sql::Text(id.clone())], ) .map_err(unreadable)? .map(|row| object(&row, &[("id", "id"), ("slug", "slug"), ("title", "title")])) .unwrap_or(Value::Null); let predecessors = replica .driver .all( "SELECT id, slug, title FROM cotton_memories WHERE superseded_by = ? \ ORDER BY slug ASC", &[Sql::Text(id.clone())], ) .map_err(unreadable)? .iter() .map(|row| object(row, &[("id", "id"), ("slug", "slug"), ("title", "title")])) .collect::>(); // Every ACTIVE project, which is what "Restore into" and "Add to" // offer. Distinct from `projects` above, which is the entry's OWN // memberships with their pins: an entry dropped from every project has // an empty membership and still needs somewhere to go back to. let all = replica .driver .all( "SELECT id, slug, name, status FROM cotton_memory_projects \ WHERE status = 'active' ORDER BY created_at ASC, id ASC", &[], ) .map_err(unreadable)? .iter() .map(|row| { object( row, &[ ("id", "id"), ("slug", "slug"), ("name", "name"), ("status", "status"), ], ) }) .collect::>(); Ok(json!({ "projects": links, "allProjects": all, "successor": successor, "predecessors": predecessors, })) })?; Ok(json!({ "entry": record, "comments": comments, "projects": neighbours["projects"], "allProjects": neighbours["allProjects"], "successor": neighbours["successor"], "predecessors": neighbours["predecessors"], })) } /// `read.projects` — every project, with the two keys `list_projects` cannot /// answer and the list cannot be drawn without. /// /// A COMPOSITE rather than the bare tool, for `read.documents`' reason: the /// tool answers a project as an ASSISTANT reads one — slug, name, description, /// repos, status, the linked counts — and the LIST draws two more things. /// /// * **`id`.** `project_out` answers the SLUG and no id at all, which is right /// for a tool (every project verb addresses a project by slug) and leaves a /// row with nothing to hand a sheet that files by id. /// * **`lastActivity`.** The list is most-recently-worked-first, and that is a /// question about every record LINKED to a project rather than about the /// project row — its own `updated_at` moves when somebody renames it, which /// is the one thing that is not work. The answer is the engine's /// (`project_last_activity`, over the linked stream and the session stream), /// computed by the same function Home's own band uses so the two surfaces /// cannot disagree about which project moved last. /// /// ACTIVE projects only have an instant: `project_overviews` computes for those /// alone, as `projectOverviews` does, so an archived project answers `null` and /// sorts by name. pub fn projects(client: &ClientController, _args: &Map) -> Result { let mut answer = client.read_tool("list_projects", &Map::new())?; client.with_file(|replica| { let Some(rows) = answer.get_mut("projects").and_then(Value::as_array_mut) else { return Ok(()); }; // Slug → id in ONE query: the tool answers by slug and everything below // is keyed by id. let found = replica .driver .all("SELECT id, slug FROM cotton_memory_projects", &[]) .map_err(unreadable)?; let id_of: std::collections::HashMap = found .iter() .filter_map(|row| Some((row.text("slug")?.to_string(), row.text("id")?.to_string()))) .collect(); let overviews = super::reads::project_overviews(replica.driver, replica.workspace_id)?; for row in rows.iter_mut() { let Some(slug) = row.get("slug").and_then(Value::as_str).map(str::to_string) else { continue; }; let Some(id) = id_of.get(&slug) else { continue }; let last = overviews .get(id) .and_then(Option::as_deref) .map_or(Value::Null, Value::from); if let Some(map) = row.as_object_mut() { map.insert("id".to_string(), Value::from(id.clone())); map.insert("lastActivity".to_string(), last); } } Ok(()) })?; Ok(answer) } /// The repositories a project names are answered on `read.sessions`' own /// `projects` rows (`code_projects`), not by a read of their own — the /// Code screens are the queue since phase 4, and a screen names one read. /// The readable remotes of one project's `repos` column, in its own order. fn remotes_of(raw: &Value, own: &OwnCotton) -> Value { let entries: Vec<&str> = raw .as_array() .map(|rows| rows.iter().filter_map(Value::as_str).collect()) .unwrap_or_default(); Value::Array( project_repo_refs(entries, own) .iter() .map(|found| { // A repository that lives in Cotton is reached at its Cotton // address; the key stays the row's own. let home = own.home_of(found); json!({ "key": found.key(), "label": found.label(), "host": home.as_ref().map_or_else(|| found.host.clone(), |home| home.host()), "owner": found.owner, "repo": found.repo, "kind": found.kind.as_str(), "apiBaseUrl": found.api_base_url(), "webUrl": home.as_ref().map_or_else(|| found.web_url(), |home| home.web_url()), }) }) .collect::>(), ) } // ── Sessions ────────────────────────────────────────────────────────────── /// How far back `read.sessions` looks — SEVEN DAYS, by a session's last /// activity. /// /// `/code` is "what is happening" and it is the ONE list, so nothing quieter /// than this is drawn and nothing quieter than this is sent — a phone that /// downloads one has paid for a row it will never draw. A SEARCH reaches past /// it (`q`), which is how anything older is found now. ONE copy, the one the /// generic read's sections are cut by too (`cotton_tools::session_words`). pub use cotton_tools::session_words::SESSIONS_WINDOW_MS; /// And the ceiling inside that window — `list_sessions`' own maximum. /// /// It was `WHOLE_SET`, which is a million: the window is what makes the answer /// small, and this is the cap that holds when a week really did hold hundreds /// of runs. The search pill filters the pool this loaded rather than asking /// again, so the number is also how far a search can reach. pub const SESSIONS_LIMIT: i64 = 200; /// `read.devices` — every device admitted to this database, off the file. /// /// `list_devices`' rows as the tool answers them (revoked rows included, so /// "cut off" and "never here" stay distinguishable), plus `thisDevice`: the id /// the server admits THIS device by, which the tool cannot know — it reads a /// file, and a file names no reader — and which the list marks its own row /// with. `null` on a device with no identity yet, and the screen then marks /// no row rather than guessing one. /// /// Nothing here reaches the network. The pairings waiting on an answer live in /// the serving Mac's `registry.db` and stay `devices.pending`'s; a screen asks /// for them AFTER these rows are on it. /// /// Each row also carries the words a person reads of a device, so no screen /// spells a machine's figures: `serving` and `role` ("Serves this database" /// for the device the file's newest serving fact names, "Keeps a copy" for /// every other device still admitted), `health` ("Fine" or "Busy", only where /// the device has reported a reading) and `diskLine` ("60 GB free of 926 GB"), /// and `columns`: the `device` table's words for the row, keyed by its column /// (`cotton_core::device::words::table_words`). /// The figures themselves stay in the row for a developer's view. pub fn devices(client: &ClientController, _args: &Map) -> Result { let listed = client.read_tool("list_devices", &Map::new())?; let serving = client.with_file(|file| { cotton_store::serving::serving_fact(file.driver, file.workspace_id) .map(|fact| fact.map(|fact| fact.device_credential_id)) .map_err(|error| error.to_string()) })?; let mut devices = match listed.get("devices") { Some(Value::Array(devices)) => devices.clone(), _ => Vec::new(), }; // A Mac's last-heard and free disk from the one row it writes about // itself, whichever database this is (295 rule 8). crate::phone::presence::put_on_listed(&crate::phone::presence::household(client), &mut devices); let problems = client.with_file(|file| { file.driver.all( "SELECT p.device_id, s.name, p.apply_problem FROM cotton_secret_placements p JOIN cotton_secrets s ON s.id = p.secret_id AND s.workspace_id = p.workspace_id WHERE p.workspace_id = ? AND p.applied_at IS NULL AND p.apply_problem IS NOT NULL AND s.trashed_at IS NULL ORDER BY s.name COLLATE NOCASE, p.path", &[rusqlite::types::Value::Text(file.workspace_id.to_string())], ).map_err(|error| error.to_string()) })?; // The `device` table's own column words (`summary`, `load`, `kind`, // `machine`, `serving_place`, `approved_by_device` …), said over every // row — the serving order and an approver's name are read against all of // them — from the one copy the generic read says them from, so the // Devices list and its definition name the same columns. let facts: Vec = devices .iter() .filter_map(Value::as_object) .map(cotton_core::device::words::DeviceFacts::from_listed) .collect(); let order = cotton_core::device::words::serving_order(&facts); let clock = cotton_core::device::words::Clock::in_zone(client.clock().now().timestamp_millis(), "UTC"); // "SERVE FROM THIS MAC", said of every Mac it could be asked of: whether // it is offered, why not, and the lines its sheet shows before the owner // confirms (`cotton_core::device::words::serve_from`). The owner's // databases are opened for it only when some Mac could be asked. let serving_facts = serving .as_deref() .and_then(|id| facts.iter().find(|device| device.device_id.as_deref() == Some(id))); let mut copies: Option)>> = None; for (index, device) in devices.iter_mut().filter_map(Value::as_object_mut).enumerate() { let words = device_words(device, serving.as_deref()); device.extend(words); if let Some(own) = facts.get(index) { let mut columns = cotton_core::device::words::table_words(own, &facts, &order, &clock); let id = device.get("deviceId").and_then(Value::as_str).unwrap_or(""); let lines: Vec = problems.iter().filter(|row| row.text("device_id") == Some(id)) .map(|row| cotton_core::vault::placement::problem_line( row.text("name").unwrap_or(""), row.text("apply_problem").unwrap_or(""))) .collect(); columns.insert("placement_problems".to_string(), if lines.is_empty() { Value::Null } else { Value::from(lines.join("\n")) }); // What the serving Mac's Anthropic work is holding, and today's // spend in one line (its server writes both on its own row). if let Some(hold) = device.get("aiHolds").and_then(cotton_core::device::ai_hold::AiHold::from_value) { columns.extend(hold.columns()); } columns.insert( "ai_spend_line".to_string(), device.get("aiSpend").and_then(cotton_core::device::words::ai_spend_line).map_or(Value::Null, Value::from), ); // What the device said of itself with its last exchange, as plain // lines ("last answer: ok · 4:02 pm · unsent 0"). // How the app ran over the last day, by the phone's own MetricKit // payload: numbers the definition's columns say. columns.extend(cotton_core::device::words::usage_columns(device.get("reportedState"))); columns.insert( "reported_state_lines".to_string(), device .get("reportedState") .and_then(|state| cotton_core::device::words::reported_state_lines(state, &clock)) .map_or(Value::Null, Value::from), ); // Where the owner's "make this Mac a runner" stands: the held // act's two steps (`cotton_core::device::runner_steps`). let said = |key: &str| device.get(key).and_then(Value::as_str); let steps = cotton_core::device::runner_steps::steps( said("scope"), said("runnerOrderedAt"), said("runnerConfirmedAt"), said("runnerProblem"), ); columns.insert("runner_confirm".to_string(), steps.map_or(Value::Null, |(confirm, _)| Value::from(confirm))); columns.insert("runner_drop".to_string(), steps.map_or(Value::Null, |(_, dropped)| Value::from(dropped))); device.insert("columns".to_string(), Value::Object(columns)); if let Some(mut serve_from) = cotton_core::device::words::serve_from(own, serving_facts) { let copies = copies.get_or_insert_with(|| household_copies(client, &facts)); let holds = |ids: &std::collections::BTreeSet| { own.device_id.as_ref().is_some_and(|id| ids.contains(id)) }; let named = |held: bool| -> Vec { copies.iter().filter(|(_, ids)| holds(ids) == held).map(|(name, _)| name.clone()).collect() }; let sheet = cotton_core::device::words::serve_from_sheet( own.name.as_deref().unwrap_or("This Mac"), serving_facts.and_then(|serving| serving.name.as_deref()).unwrap_or("the Mac that serves"), serve_from.get("behind").and_then(Value::as_str), &named(true), &named(false), ); serve_from.insert("sheet".to_string(), json!(sheet)); device.insert("serveFrom".to_string(), Value::Object(serve_from)); } } } // HOW THE WORLD REACHES THE HOUSEHOLD, drawn on the page of the Mac that // serves it (or would, first in the serving order): the household's own // fact, said beside the one device that acts on it. let mut front_door = client.with_file(|file| Ok(crate::phone::front_door::page_answer(file.driver, file.workspace_id)))?; if let Some(door) = front_door.as_object_mut() { let on = serving.clone().or_else(|| order.first().cloned()); door.insert("onDevice".to_string(), on.map_or(Value::Null, Value::from)); } Ok(json!({ "devices": devices, "thisDevice": client.self_device_id(), "reach": front_door, })) } /// Each of the owner's household databases this device holds a copy of, by /// the name the owner knows it by, with the devices that are live in it — /// which is how "Serve from this Mac" names the databases a Mac will serve /// and the ones it holds no copy of. A database this device cannot open is /// left out: nothing is said of what was not read. fn household_copies( client: &ClientController, devices: &[cotton_core::device::words::DeviceFacts], ) -> Vec<(String, std::collections::BTreeSet)> { client .household_databases() .into_iter() .filter_map(|database| { let name = crate::phone::databases::name_of(client, &database).ok().flatten()?; let live = client .glance_in(&database, |driver, _| { Ok(devices .iter() .filter_map(|device| device.device_id.clone()) .filter(|id| cotton_tools::devices::owners_live_device(driver, id).unwrap_or(false)) .collect::>()) }) .ok()?; Some((name, live)) }) .collect() } /// The words of one device row: see [`devices`]. One copy, in /// `cotton_core::device::words`, which the `device` table's read says too. pub(crate) fn device_words(device: &Map, serving: Option<&str>) -> Map { cotton_core::device::words::read_devices_words(&cotton_core::device::words::DeviceFacts::from_listed(device), serving) } /// `read.sessions {project?}` — the log, with the Macs that reported. /// /// A composite: `list_sessions` is the log and `list_devices` is the strip /// above it, and the screen draws one answer. Asking twice from Swift would be /// two round trips for one screen and two chances to paint half of it. /// /// It was `list_machines` until schema v14. A machine IS a device (v13) and /// that rung folded the reading onto the device row, so the strip and the /// devices page can no longer disagree about the same computer. /// /// **Two hundred, and the project narrows the answer rather than the query** — /// both are `sessions.service.ts`/`sessions/index.tsx`'s own shape: /// /// * `listSessions` defaults to `options.limit ?? 200`. The tool's default is /// twenty, and twenty is the whole page: the search pill filters the pool /// this already loaded rather than asking again, so the other hundred and /// eighty would be unreachable AND unfindable. /// * the project filters the ANSWER, never the query. Passing the slug to /// `list_sessions` would change two behaviours the screen depends on: an /// UNKNOWN slug (a stale deep link) would refuse the whole read where an /// empty list is the right answer, and an ARCHIVED project's Sessions row /// would refuse too — an archived project still has a page — because /// `resolve_project` accepts active projects only. So the filter is applied /// to the answer, over `session_out`'s own `project` slug, which it /// resolves for a project of any status. pub fn sessions(client: &ClientController, args: &Map) -> Result { let project = maybe_text(args, "project"); let sessions = queue_rows(client, maybe_text(args, "q"), project.as_deref())?; let devices = client.read_tool("list_devices", &Map::new())?; let now = client.clock().now(); let (accounts, projects, settings) = client.with_file(|replica| { Ok(( agent_accounts(replica, now)?, code_projects(replica)?, code_settings(replica)?, )) })?; Ok(json!({ "sessions": sessions, "devices": devices, // The ONE window the queue is cut by, answered rather than written // down a second time in Swift: the read stops sending a session quieter than this, and the screen's // Earlier section stops drawing one — two numbers that disagreed would // be a card the read sent and the screen refused to show. "quietWindowMs": SESSIONS_WINDOW_MS, // Start a session from the phone: the agent logins the household has, // the models the picker offers, and the projects it can file a session // under — all on THIS read, because the new-session form is the same // screen family and a screen has exactly one read. **The queue is not a // second list**: a session waiting for a Mac is a `queued` row in // `sessions` above, which is the whole of schema v23. "accounts": accounts, "models": OFFERED_MODELS .iter() .map(|(id, label)| json!({ "id": id, "label": label })) .collect::>(), "projects": projects, // The household's setting, because the new-session FORM on this screen // opens on `sessionPermissionDefault` rather than on a word // written into Swift — a default nobody can change is not a default // ([sessions-start-in-bypass-permissions-mode-by-default-it-s-a-sett]). // `workspace.setCode` writes them; the Code tool's Session defaults page draws them. "settings": settings, })) } /// THE QUEUE'S ROWS, built once — `list_sessions` asked the way `/code` asks /// it, with `modelLabel` and `canResume` stamped on every row, narrowed to one /// project where a reader named one. /// /// TWO READERS, ONE BUILDER. `read.sessions` is the queue itself and /// `read.project` draws the same cards under a project's conversation /// (`ProjectThreads`), so the mapping lives here rather than once per read: a /// second copy would be a card that says `4/6` on `/code` and nothing on the /// project page, or a Resume offered on one screen and refused on the other. /// /// Answers the TOOL's whole object (`{sessions: […], …}`) — what /// `read.sessions` puts on the wire — so a caller that wants the rows alone /// takes them off it. fn queue_rows( client: &ClientController, query: Option, project: Option<&str>, ) -> Result { let mut session_args = Map::new(); session_args.insert("limit".to_string(), Value::from(SESSIONS_LIMIT)); // The prompt search is the TOOL'S — `list_sessions {q}` is FTS over what // the owner typed, folded to the sessions that hit and carrying each one's // matching snippets. A second search in Swift would be a second index. let mut searching = false; if let Some(query) = query { if query.chars().count() >= 2 { session_args.insert("q".to_string(), Value::from(query)); searching = true; } } // THE WINDOW, and it is why this read stopped asking for everything. The // helper adopts every session it finds in an agent's own transcript // directory, so a Mac that has been coding for two months holds hundreds of // rows this screen has no use for: TestFlight 168 drew four hundred and // seventy-four of them, every one of them quiet for weeks, under a heading // that said Running. The queue is about the last few days, so the read // stops sending the rest rather than asking Swift to hide them. // // A SEARCH REACHES PAST IT. `q` is the owner deliberately looking for // something they typed, and an FTS hit outside the window is exactly the // answer they asked for — the limit still caps what comes back, and the // queue's own sections drop anything too quiet to draw. if !searching { let cutoff = client.clock().now().timestamp_millis() - SESSIONS_WINDOW_MS; if let Some(since) = to_iso_string(cutoff) { session_args.insert("since".to_string(), Value::from(since)); } } let mut sessions = client.read_tool("list_sessions", &session_args)?; if let Some(slug) = project { if let Some(rows) = sessions.get_mut("sessions").and_then(Value::as_array_mut) { rows.retain(|row| row.get("project").and_then(Value::as_str) == Some(slug)); } } // One spelling of which brain answered, and it is the engine's // (`model_label`). The rows come from the tool carrying the raw id; the // label is stamped on here rather than derived in Swift, where it would be // a second parser of the same string. if let Some(rows) = sessions.get_mut("sessions").and_then(Value::as_array_mut) { for row in rows.iter_mut() { let label = row .get("model") .and_then(Value::as_str) .and_then(|model| model_label(Some(model))); // AND WHETHER IT CAN BE PICKED UP WHERE IT STOPPED. The rule is // `session_queue::can_carry_on` and nothing else spells it: a card // that offered Resume on its own reading would eventually offer it // where the method refuses. let can_resume = crate::phone::session_queue::can_carry_on( row.get("state").and_then(Value::as_str).unwrap_or_default(), row.get("hostOwned").and_then(Value::as_bool).unwrap_or(false), row.get("externalId").and_then(Value::as_str), row.get("deviceId").and_then(Value::as_str), ); if let Some(map) = row.as_object_mut() { map.insert( "modelLabel".to_string(), label.map_or(Value::Null, Value::from), ); map.insert("canResume".to_string(), Value::Bool(can_resume)); } } } Ok(sessions) } /// How many threads a PROJECT page draws under its conversation. /// /// The project page is not the queue: it opens on the conversation and the /// threads are what is running under it, with `/projects/[slug]/code` one tap /// away for the rest. Fifty is more threads than a project has in the week the /// queue looks back over, and it is a ceiling rather than a cut anybody sees. pub const PROJECT_THREADS_LIMIT: usize = 50; /// How many sessions the Sessions section of a project's page previews: /// the newest THREE that are not already drawn as running under the /// conversation. `read.project` ASKS for them — it walks the project's /// threads page by page until it has three or has read them all — so a /// project with any number running still previews three when three exist. pub const PROJECT_SESSION_PREVIEW: usize = 3; /// How many rows each step of that walk reads. const PROJECT_SESSION_WALK_PAGE: i64 = 20; /// How many sessions `/projects/[slug]/code` draws at a time: the project's /// sessions of all time, newest first, and "Show more" reads this many more. pub const PROJECT_SESSIONS_PAGE: i64 = 30; /// How long an idle session Cotton holds still counts as RUNNING: an hour. /// It is the thing the owner stepped away from, not history. The phone's /// card reads the same figure (`CodeFacts.idleIsRunningWindow`, held to this /// one by a test that reads `cotton_tools::session_words`, where the one /// copy is). pub use cotton_tools::session_words::IDLE_IS_RUNNING_MS; /// Whether a session row is one the project page draws as RUNNING under its /// conversation — the `/code` card's *Needs you* or *Running* (`CodeFacts. /// card`), inside the queue's own window (`SESSIONS_WINDOW_MS`), because /// that is the only set the page draws there. /// /// ONE rule, stated over `list_sessions`' own row, so the Sessions preview can /// ask for the rows this says false for and never draw a session twice: /// /// * a session Cotton does not hold is never running — nobody here can type /// into its terminal, and the card files it under *From the terminal*; /// * waiting on the owner is running whatever else the row says; /// * a finished row (`ended`, `failed`, `withdrawn`, or an `endedAt`) is not; /// * `queued`, `starting` and `running` are; /// * `idle` is, for [`IDLE_IS_RUNNING_MS`] after its last activity; /// * and nothing quieter than the queue's window is drawn as running at all. pub fn drawn_as_running(row: &Value, now_ms: i64) -> bool { // The card's own section rule (`cotton_tools::session_words::card`), never // a second reading of the same columns. row.as_object() .is_some_and(|row| cotton_tools::session_words::drawn_as_running(row, now_ms)) } /// The newest `want` of a project's threads that are NOT drawn as running — /// the Sessions section's preview, asked for rather than cut out of a fixed /// handful afterwards. Walks `list_sessions` a page at a time, newest first, /// and stops at `want` or at the end of the project's threads. fn settled_threads( client: &ClientController, slug: &str, want: usize, now_ms: i64, ) -> Result, String> { let mut out: Vec = Vec::new(); let mut cursor: Option = None; loop { let mut page_args = Map::new(); page_args.insert("project".to_string(), Value::from(slug)); page_args.insert("kind".to_string(), Value::from("thread")); page_args.insert("limit".to_string(), Value::from(PROJECT_SESSION_WALK_PAGE)); if let Some(cursor) = &cursor { page_args.insert("cursor".to_string(), Value::from(cursor.clone())); } let page = client.read_tool("list_sessions", &page_args)?; for row in page.get("sessions").and_then(Value::as_array).into_iter().flatten() { if !drawn_as_running(row, now_ms) { out.push(row.clone()); if out.len() == want { return Ok(out); } } } match page.get("nextCursor").and_then(Value::as_str) { Some(next) => cursor = Some(next.to_string()), None => return Ok(out), } } } /// How many threads a project holds — the Sessions heading's figure and the /// length of the list it opens (`read.projectSessions`). The set is /// `get_project`'s: the project's sessions of kind `thread`, of all time. fn project_thread_count(replica: &ReadFile<'_>, project_id: &str) -> Result { Ok(replica .driver .get( "SELECT COUNT(*) AS n FROM cotton_sessions WHERE project_id = ? AND kind = 'thread'", &[Sql::Text(project_id.to_string())], ) .map_err(unreadable)? .and_then(|row| row.int("n")) .unwrap_or(0)) } /// `read.projectSessions {slug, limit?}` — what the Sessions heading opens: /// the project's sessions of ALL TIME, newest first, `limit` of them /// ([`PROJECT_SESSIONS_PAGE`] by default; the screen asks for a page more /// each time), and `total`, the same figure the heading shows. /// /// The rows are `list_sessions`', walked by its cursor, so a card here is the /// same card `/code` and the page draw. `total` counts the same set, so the /// heading's "3 of 40" and a list that ends at forty cannot disagree. pub fn project_sessions( client: &ClientController, args: &Map, ) -> Result { let slug = text_arg(args, "slug")?; let limit = match args.get("limit") { None | Some(Value::Null) => PROJECT_SESSIONS_PAGE, Some(value) => value .as_i64() .or_else(|| value.as_str().and_then(|text| text.trim().parse().ok())) .filter(|limit| *limit >= 1) .ok_or_else(|| "`limit` is a whole number of sessions, one or more".to_string())?, }; let found = client.with_file(|replica| { let row = replica .driver .get( "SELECT id, name FROM cotton_memory_projects WHERE slug = ?", &[Sql::Text(slug.clone())], ) .map_err(unreadable)?; Ok(row.and_then(|row| Some((row.text("id")?.to_string(), cell(&row, "name"))))) })?; let Some((project_id, name)) = found else { return Err(format!("There is no project called {slug}.")); }; let total = client.with_file(|replica| project_thread_count(replica, &project_id))?; let mut sessions: Vec = Vec::new(); let mut cursor: Option = None; while (sessions.len() as i64) < limit { let mut page_args = Map::new(); page_args.insert("project".to_string(), Value::from(slug.clone())); page_args.insert("kind".to_string(), Value::from("thread")); page_args.insert("limit".to_string(), Value::from((limit - sessions.len() as i64).min(200))); if let Some(cursor) = &cursor { page_args.insert("cursor".to_string(), Value::from(cursor.clone())); } let page = client.read_tool("list_sessions", &page_args)?; sessions.extend( page.get("sessions") .and_then(Value::as_array) .cloned() .unwrap_or_default(), ); match page.get("nextCursor").and_then(Value::as_str) { Some(next) => cursor = Some(next.to_string()), None => break, } } Ok(json!({ "slug": slug, "name": name, "sessions": sessions, "total": total, "pageSize": PROJECT_SESSIONS_PAGE, })) } /// Every agent login this household has seen, newest reading first /// (schema v14). /// /// It was a derivation over `(machine, account)` pairs joined to /// `cotton_account_usage`. That table is retired and this is the row itself: a /// login is born the first time any Mac sees it and SURVIVES a logout, so /// `signedInOn: null` is a real answer — "not signed in on any Mac" — rather /// than a login that has disappeared from the picker. /// /// **WHICH MAC IS THE MAC'S OWN ANSWER.** `signedInOnDevices` is every device /// (that can host) whose own `account_ids` names this login, in device-id /// order, and `signedInOn` the first of them for a reader that takes one. It was the login's /// `seen_on_device_id` — the LAST Mac that saw it — so a login two Macs share /// was signed in on only one of them. /// /// **Cotton never touches the credential.** `email` is what the agent's own /// status line reports about the login it already has. pub fn agent_accounts(_replica: &ReadFile<'_>, _now: DateTime) -> Result, String> { // RETIRED (OPEN TABLES, owner, 24 Nov 2026; assets/design/shared/OPEN-TABLES.md): the AI-account tables are // retired and erased, so no login is read. The answer keeps its shape for the parked app's screens. Ok(Vec::new()) } /// One device key's row, as the Code page reads it — the key's LIVE row, else /// its newest (`cotton_tools::devices::KEY_ORDER`), only a device that can /// host a session (`cotton_core::rules::machines::can_host`), and one row per /// machine with none retired (`machines::listed_machines`). struct HostingDevice { device_id: String, name: String, platform: Option, sampled_at: Option, account_ids: Map, } /// Every machine in this file that can host a session, by name. /// /// A phone that has never reported is NOT here: no session helper runs on it, /// so it has no row on the Code page and no login to show. Nor is a re-joined /// Mac's old key once its new one has reported, nor a machine silent past /// `machines::RETIRED_AFTER_DAYS` — the same rule `list_agent_accounts` /// applies, so the phone and MCP name the same Macs. fn hosting_devices(replica: &ReadFile<'_>, now: DateTime) -> Result, String> { let rows = replica .driver .all( &format!( "SELECT d.device_id, d.name, d.platform, d.revoked_at, d.sampled_at, \ d.host_version, d.account_ids \ FROM cotton_devices d \ WHERE d.id = (SELECT id FROM cotton_devices \ WHERE workspace_id = d.workspace_id AND device_id = d.device_id \ {} LIMIT 1) \ ORDER BY d.name COLLATE NOCASE ASC, d.device_id ASC", cotton_tools::devices::KEY_ORDER ), &[], ) .map_err(unreadable)?; let hosts: Vec<_> = rows .iter() .filter(|row| { can_host( row.text("platform"), row.text("sampled_at"), row.text("host_version"), row.text("revoked_at"), ) }) .collect(); let names: Vec<(&str, Option<&str>)> = hosts .iter() .map(|row| { ( row.text("name").or_else(|| row.text("device_id")).unwrap_or_default(), row.text("sampled_at"), ) }) .collect(); let listed = listed_machines(&names, now); Ok(hosts .into_iter() .zip(listed) .filter(|(_, listed)| *listed) .filter_map(|(row, _)| { let device_id = row.text("device_id")?.to_string(); Some(HostingDevice { name: row.text("name").unwrap_or(&device_id).to_string(), platform: row.text("platform").map(str::to_string), sampled_at: row.text("sampled_at").map(str::to_string), account_ids: match json_cell(row, "account_ids") { Value::Object(ids) => ids, _ => Map::new(), }, device_id, }) }) .collect()) } /// `machines` on `read.agentAccounts` — one entry per device that can host a /// session, with the Claude login THAT device reports and that login's usage. /// /// **THE DEVICE'S OWN LOGIN.** The account is `account_ids['anthropic']` on /// this device's row, so a login two Macs share is on both rows, each with the /// same windows. Only the address is handed over about it (`{ email }`): an /// account is shown by its email and nothing else. /// /// **NEVER A STALE FIGURE.** `current` is `machines::report_state` against the /// ten-minute seen window. A machine that is not current carries `null` for /// its login, every usage number, reset time and reading time — the screen draws "has /// not reported since …" from `lastReportAt` and has no percentage it could /// draw by mistake. A window whose reset time has passed (`machines::window_pct`) /// is `null` too, with its reset: the figure was for a window that is over. fn machines(replica: &ReadFile<'_>, now: DateTime) -> Result, String> { let devices = hosting_devices(replica, now)?; // No login is read since the AI-account tables were retired (OPEN TABLES, owner, 24 Nov 2026): every machine // names none, as a machine that has not reported does. let logins: Vec = Vec::new(); let by_id: BTreeMap<&str, &cotton_store::driver::Row> = logins .iter() .filter_map(|row| Some((row.text("id")?, row))) .collect(); Ok(devices .iter() .map(|device| { let current = report_state(device.sampled_at.as_deref(), now) == ReportState::Current; let login = device .account_ids .get("anthropic") .and_then(Value::as_str) .and_then(|id| by_id.get(id).copied()); let window = |pct: &str, resets: &str| -> (Value, Value) { let Some(login) = login.filter(|_| current) else { return (Value::Null, Value::Null); }; match window_pct(login.real(pct), login.text(resets), now) { Some(figure) => (Value::from(figure), cell(login, resets)), None => (Value::Null, Value::Null), } }; let (five_hour_pct, five_hour_resets_at) = window("five_hour_pct", "five_hour_resets_at"); let (weekly_pct, weekly_resets_at) = window("weekly_pct", "weekly_resets_at"); let usage_read_at = match login.filter(|_| current) { Some(login) => cell(login, "seen_at"), None => Value::Null, }; json!({ "deviceId": device.device_id, "name": device.name, "platform": device.platform, "canHost": true, "lastReportAt": device.sampled_at, "current": current, // A SILENT MACHINE NAMES NO LOGIN: who it was signed in as is // as old as its last report, and an address beside "has not // reported since …" reads as who is signed in now. "account": login .filter(|_| current) .and_then(|login| login.text("email")) .map(|email| json!({ "email": email })), "fiveHourPct": five_hour_pct, "fiveHourResetsAt": five_hour_resets_at, "weeklyPct": weekly_pct, "weeklyResetsAt": weekly_resets_at, "usageReadAt": usage_read_at, }) }) .collect()) } /// `read.agentAccounts` — the Code tool's Machines list's whole read (schema v15; was Settings › Code). /// /// **THE PAGE'S ONE READ, and that is why it carries five things.** A screen /// names exactly one read and a read names exactly one screen /// (`no_two_reads_share_a_name_or_a_screen`), so `/code/machines` cannot gain a /// second `read.deviceSamples` beside this one: a page drawing the logins AND /// the strips under its Macs AND the household's two switches is ONE read /// composing them, which is the same rule `read.session` follows when it hands /// its "Move to" sheet the projects. The read keeps the name the design of /// record fixed for it (Cotton note "The Code tool — why a Mac holds the sessions"), because renaming a /// method in that contract would be a bigger change than the one this makes. /// /// It is a `Controller` rather than a `Query` for reason (2) in /// [`crate::phone::reads::ReadSource`]: thinning a thirty-day window needs the /// CLOCK, which is the seam a test replaces, and a `Query` has none in scope. /// /// The five parts: /// /// * `accounts` — every agent login this household has seen; /// * `machines` — one row per device that can host a session, with the /// login it reports and that login's usage, never stale ([`machines`]); /// * `deviceSamples` — each Mac's thirty-day strip, thinned to at most /// `STRIP_POINTS` columns by `cotton_core::rules::samples::thin`; /// * `accountSamples` — the same for each login's five-hour window; /// * `settings` — the household's `sessionPermissionDefault`, which /// `workspace.setCode` writes. pub fn agent_accounts_read( client: &ClientController, _args: &Map, ) -> Result { let now = client.clock().now(); client.with_file(|replica| { Ok(json!({ "accounts": agent_accounts(replica, now)?, "machines": machines(replica, now)?, "deviceSamples": device_sample_strips(replica, now)?, "accountSamples": account_usage_strips(replica, now)?, "settings": code_settings(replica)?, })) }) } /// The household's one setting, off `cotton_workspaces` (schema v14, written /// since v15 by `workspace.setCode`). /// /// They live HERE rather than on `read.boot` for the reason the reads table /// gives: a screen's read answers what that screen draws, and the boot gate /// answers what a phone with no file yet can still say. This is a setting on a /// page, not a fact about whether there is a database — and the new-session /// form gets the default off `read.sessions`, which is the read ITS screen /// names. /// /// NULL is impossible: the column is `NOT NULL` with a default, so a workspace /// that has never been touched reads `bypass` — which is the household this /// design ships with /// ([sessions-start-in-bypass-permissions-mode-by-default-it-s-a-sett]). pub fn code_settings(replica: &ReadFile<'_>) -> Result { let row = replica .driver .get( "SELECT session_permission_default FROM cotton_workspaces WHERE id = ?", &[Sql::Text(replica.workspace_id.to_string())], ) .map_err(unreadable)?; let Some(row) = row else { return Ok(json!({ "sessionPermissionDefault": DEFAULT_PERMISSION_MODE, })); }; Ok(json!({ "sessionPermissionDefault": row .text("session_permission_default") .unwrap_or(DEFAULT_PERMISSION_MODE), })) } /// What a session starts in when nobody has said otherwise — the column's own /// default, named once so the read and the writer cannot disagree. pub const DEFAULT_PERMISSION_MODE: &str = "bypass"; /// Each Mac's thirty-day strip of load, thinned. /// /// `load1` is the series: it is the one number that answers "is that Mac busy", /// and a strip draws one series. The rest of a sample's columns stay on the /// device ROW, which is the CURRENT reading the card already shows. fn device_sample_strips(replica: &ReadFile<'_>, now: DateTime) -> Result { strips_of( replica, now, "SELECT device_id AS subject, sampled_at, load1 AS value \ FROM cotton_device_samples \ WHERE sampled_at >= ? ORDER BY sampled_at ASC", ) } /// Each login's thirty-day strip of its five-hour window. /// /// The FIVE-HOUR window and not the weekly one: it is the number that moves /// within a day, which is what a strip at this resolution can show. fn account_usage_strips(_replica: &ReadFile<'_>, _now: DateTime) -> Result { // Retired with the AI-account tables (OPEN TABLES, owner, 24 Nov 2026): no strip. Ok(json!({})) } /// The one spelling of an instant on this boundary — the store's own, so a /// strip's bounds compare as text with every other stamp in the file. /// /// It REFUSES rather than falling back to `""`: the cutoff is a SQL bound, and /// an empty string compares less than every stamp there is, so a silent /// fallback here would quietly hand a phone the whole table. fn iso(at: DateTime) -> Result { to_iso_string(at.timestamp_millis()) .ok_or_else(|| format!("{at} is not an instant this file can spell")) } /// One query, grouped by subject and thinned — the shape both strips take. /// /// The WINDOW is applied in SQL and the THINNING in the engine: the sweep may /// not have run yet on a device that has been offline, so a read that took /// every row it found would hand a phone readings the strip has no column for. /// `cotton_core::rules::samples::thin` drops them too, and doing it twice is /// cheaper than paging a month of telemetry into memory first. fn strips_of( replica: &ReadFile<'_>, now: DateTime, sql: &str, ) -> Result { let cutoff = iso(retention_cutoff(now))?; let rows = replica .driver .all(sql, &[Sql::Text(cutoff)]) .map_err(unreadable)?; let mut by_subject: BTreeMap> = BTreeMap::new(); for row in rows.iter() { let (Some(subject), Some(at), Some(value)) = ( row.text("subject"), row.text("sampled_at").and_then(parse_date_ms), row.real("value"), ) else { // A sample with no reading of THIS series is not a zero — the // helper reports what it could read, and a Mac whose load it could // not take still reported its disk. continue; }; let Some(at) = DateTime::from_timestamp_millis(at) else { continue; }; by_subject .entry(subject.to_string()) .or_default() .push(Reading { at, value }); } let from = iso(retention_cutoff(now))?; let to = iso(now)?; Ok(Value::Object( by_subject .into_iter() .map(|(subject, readings)| { let strip = thin(&readings, now); ( subject, json!({ // The VALUES the strip draws, oldest first, with a // `null` for a stretch nobody reported in — a gap, and // never a zero. "points": strip .iter() .map(|point| point.value.map_or(Value::Null, Value::from)) .collect::>(), "from": from.clone(), "to": to.clone(), "samples": strip.iter().map(|point| point.samples).sum::(), }), ) }) .collect(), )) } /// ACTIVE projects with their ids and repos — the rows the new-session form's /// project picker takes, the same shape `read.session` hands its "Move to" /// sheet, and for the same reason: `list_projects` answers a slug and no id. fn code_projects(replica: &ReadFile<'_>) -> Result, String> { let rows = replica .driver .all( "SELECT id, slug, name, status, repos \ FROM cotton_memory_projects \ WHERE status = 'active' ORDER BY name COLLATE NOCASE ASC", &[], ) .map_err(unreadable)?; let own = cotton_tools::connections::words::own_cotton(replica.driver)?; Ok(rows .iter() .map(|row| { json!({ "id": cell(row, "id"), "slug": cell(row, "slug"), "name": cell(row, "name"), "status": cell(row, "status"), "repos": json_cell(row, "repos"), // And the READABLE ones, by the crate's own rule — the Code // screen's Repositories section draws them. `remotes_of` is // the crate's ONE parse of a remote, not a second one: the column is free // text and a Swift reading of the scp form is the shape every // naive implementation gets wrong. "remotes": remotes_of(&json_cell(row, "repos"), &own), }) }) .collect()) } /// `read.session {id}` — one run, as the conversation it was. /// /// The session row, the prompts it logged, and every `cotton_session_messages` /// row addressed TO it, FROM it, or claimed BY it — the three ways a message /// belongs to a session, which is the rule `buildSessionChatItems` filters on. /// /// **And the projects the picker offers**, because the "Move to" sheet is part /// of THIS screen and a screen has exactly one read. They ride here rather than /// on `list_projects`, which answers a project's SLUG and no id at all — a /// picker built on it sends `""` and moves the session nowhere. ACTIVE only: /// filing a session into an archived project is not an offer the sheet makes, /// and the row already in one is drawn from the session's own `projectName`. pub fn session(replica: &ReadFile<'_>, args: &Map) -> Result { let id = text_arg(args, "id")?; let row = replica .driver .get( "SELECT s.id, s.project_id, s.tool, s.external_id, s.machine, s.repo_url, s.branch, \ s.cwd, s.started_at, s.last_active_at, s.ended_at, s.summary, s.title, \ s.shipped, s.turn_count, s.prompt_count, s.transcript_ref, s.account, \ s.model, s.device_id, s.state, s.state_at, \ s.waiting_kind, s.waiting_ref, s.last_line, s.exit_code, \ s.permission_mode, s.host_owned, s.prompt, s.todo_id, s.todo_database, \ s.requested_device_id, s.chosen_by, s.hold_reason, s.error, \ s.claimed_at, s.kind, s.parent_session_id, \ p.slug AS project_slug, p.name AS project_name \ FROM cotton_sessions s \ LEFT JOIN cotton_memory_projects p ON p.id = s.project_id \ WHERE s.id = ?", &[Sql::Text(id.clone())], ) .map_err(unreadable)?; let Some(row) = row else { return Ok(json!({ "session": Value::Null })); }; let mut session = object( &row, &[ ("id", "id"), ("projectId", "project_id"), ("tool", "tool"), ("externalId", "external_id"), ("machine", "machine"), ("repoUrl", "repo_url"), ("branch", "branch"), ("cwd", "cwd"), ("startedAt", "started_at"), ("lastActiveAt", "last_active_at"), ("endedAt", "ended_at"), ("summary", "summary"), ("title", "title"), ("turnCount", "turn_count"), ("promptCount", "prompt_count"), ("transcriptRef", "transcript_ref"), ("account", "account"), ("model", "model"), // The device this session PROVED it ran on, never the machine name // dressed up as a device. ("deviceId", "device_id"), // What it is doing right now, as the agent's own hooks report it // through the session host (v14). NULL for every session logged // before the Code tool and for every session no host owns — which // is the honest answer, not "starting". ("state", "state"), ("stateAt", "state_at"), ("waitingKind", "waiting_kind"), ("waitingRef", "waiting_ref"), ("lastLine", "last_line"), ("exitCode", "exit_code"), ("permissionMode", "permission_mode"), ("hostOwned", "host_owned"), // The queue, on the one object (v23). A `queued` row has no agent // behind it yet, so what a card can say about it is what the owner // asked for and what has stopped it: the prompt, the Mac they // named (null means any Mac), who chose the one it is on, and the // SENTENCE the dispatcher wrote when it could not place it. ("prompt", "prompt"), ("todoId", "todo_id"), // The database the todo is in, when it is not this one (v53). ("todoDatabase", "todo_database"), ("requestedDeviceId", "requested_device_id"), ("chosenBy", "chosen_by"), ("holdReason", "hold_reason"), ("claimedAt", "claimed_at"), // Why a `failed` session never began. ("error", "error"), // WHAT THIS ROW IS (v31): a project's standing `conversation`, or // a `thread` — everything the owner started and everything a // conversation opened. The page draws a different screen for each, // so it is answered rather than derived from whether a parent // happens to be set. ("kind", "kind"), // And the conversation that opened it, where one did. NULL for a // session the owner started from the app. ("parentSessionId", "parent_session_id"), ("projectSlug", "project_slug"), ("projectName", "project_name"), ], ); // WHETHER IT CAN BE PICKED UP WHERE IT STOPPED, OR ASKED FOR AGAIN — // `session_queue::can_carry_on` and nothing else, so the page's verb and // the method's refusal can never disagree. `host_owned` is an INTEGER column read straight off the driver // here, so it is a 1, not a boolean. let can_resume = crate::phone::session_queue::can_carry_on( row.text("state").unwrap_or_default(), row.int("host_owned") == Some(1), row.text("external_id"), row.text("device_id"), ); if let Value::Object(map) = &mut session { // A BOOLEAN, as `read.sessions` answers it. The column is an INTEGER // and `object` hands an integer on as a number; the screen asks for a // flag, reads a `1` as "not set", and then draws every session Cotton // hosts as one found in a terminal — no Terminal tab, no Stop. map.insert("hostOwned".to_string(), boolean(&row, "host_owned")); map.insert("shipped".to_string(), json_cell(&row, "shipped")); // As in `read.sessions`: the engine's spelling, never a second one. let label = row.text("model").and_then(|model| model_label(Some(model))); map.insert( "modelLabel".to_string(), label.map_or(Value::Null, Value::from), ); map.insert("canResume".to_string(), Value::Bool(can_resume)); } let prompts = replica .driver .all( "SELECT seq, ts, role, text FROM cotton_prompts WHERE session_id = ? \ ORDER BY seq ASC", &[Sql::Text(id.clone())], ) .map_err(unreadable)? .iter() .map(|row| { json!({ "seq": cell(row, "seq"), "ts": cell(row, "ts"), "role": cell(row, "role"), "text": cell(row, "text"), }) }) .collect::>(); // The session these messages are read for, as delivery reads it. let this_session = (row.int("host_owned") == Some(1), row.text("machine").map(str::to_string)); let messages = replica .driver .all( "SELECT id, project_id, to_kind, to_session_id, from_kind, from_session_id, kind, \ body, reply_to, thought_id, status, claimed_by_session_id, claimed_at, \ done_at, media, created_at, updated_at \ FROM cotton_session_messages \ WHERE to_session_id = ? OR from_session_id = ? OR claimed_by_session_id = ? \ ORDER BY created_at ASC", &[ Sql::Text(id.clone()), Sql::Text(id.clone()), Sql::Text(id.clone()), ], ) .map_err(unreadable)? .iter() .map(|row| -> Result { let mut message = object( row, &[ ("id", "id"), ("projectId", "project_id"), ("toKind", "to_kind"), ("toSessionId", "to_session_id"), ("fromKind", "from_kind"), ("fromSessionId", "from_session_id"), ("kind", "kind"), ("body", "body"), ("replyTo", "reply_to"), // The pending permission a `decision` answers (v15). NULL // on every other kind, and never a message id: `replyTo` // is the message this answers, `requestRef` is the // AGENT's own permission. ("requestRef", "request_ref"), ("thoughtId", "thought_id"), // WHERE A REPLY GOT TO, and the only place the page can // read it. `open` is waiting — for the holding Mac's pass // on a session it owns, or for the session's own poll on // an adopted one (`hostOwned` on the session below says // which sentence to draw, `machine` says on which Mac). // `done` is delivered: typed into the terminal, or claimed // by the session. `withdrawn` carries the refusal IN ITS // BODY, which is the helper's own sentence. ("status", "status"), ("claimedBySessionId", "claimed_by_session_id"), ("claimedAt", "claimed_at"), ("doneAt", "done_at"), ("createdAt", "created_at"), ("updatedAt", "updated_at"), ], ); if let Value::Object(map) = &mut message { map.insert("media".to_string(), json_cell(row, "media")); // Where an owner's message got to, as typed facts the // definition words — the same engine the server's table read // answers through. let to = row.text("to_session_id"); let addressed = match to { Some(to) if to == id => Some(this_session.clone()), Some(to) => addressed_session(replica, to)?, None => None, }; let facts = session_delivery::delivery( row.text("from_kind").unwrap_or_default(), row.text("status").unwrap_or("open"), addressed.as_ref().map(|(host_owned, machine)| session_delivery::Addressed { host_owned: *host_owned, machine: machine.as_deref(), }), ); map.insert( "delivery".to_string(), facts.as_ref().map_or(Value::Null, |facts| Value::from(facts.delivery.as_str())), ); map.insert( "deliveredOn".to_string(), facts.and_then(|facts| facts.delivered_on).map_or(Value::Null, Value::from), ); } Ok(message) }) .collect::, String>>()?; // `created_at ASC` — the order every project list in the app is drawn in. let projects = replica .driver .all( "SELECT id, slug, name, status FROM cotton_memory_projects \ WHERE status = 'active' ORDER BY created_at ASC, id ASC", &[], ) .map_err(unreadable)? .iter() .map(|row| { object( row, &[ ("id", "id"), ("slug", "slug"), ("name", "name"), ("status", "status"), ], ) }) .collect::>(); // THE AGENT'S OWN TASK LIST, in the agent's own order (v31). The mirror // replaces the list WHOLE on every `log_session`, so `seq` is the order the // agent gave and nothing here re-sorts by anything else. An empty list is a // session that mirrored none — which is what a card draws nothing for, // never a zero. let tasks = replica .driver .all( "SELECT seq, text, state FROM cotton_session_tasks WHERE session_id = ? \ ORDER BY seq ASC", &[Sql::Text(id.clone())], ) .map_err(unreadable)? .iter() .map(|row| { json!({ "seq": cell(row, "seq"), "text": cell(row, "text"), "state": cell(row, "state"), }) }) .collect::>(); Ok(json!({ "session": session, "prompts": prompts, "tasks": tasks, "messages": messages, "projects": projects, })) } // ── Documents and the reader ────────────────────────────────────────────── /// `read.documents {status?, docType?, query?}` — the warm list, and the /// search when the person is typing. /// /// A composite because the screen has two questions with one answer: the /// facets narrow `list_documents`, and a query of two characters or more asks /// `search_documents` as well. `?status=failed` is the inbox's "something came /// back" link, so the argument is the same word the row's `status` is. /// /// **The whole vault, because search joins back onto it.** `documentsService` /// emits no `LIMIT` at all, and the vault screen matches a `search_documents` /// hit against the rows it has already loaded — so a paper outside this answer /// is not merely missing from the list, it is unfindable and unopenable. The /// tool's default of twenty-five is right for an assistant and is untouched; /// its ceiling was raised to the whole set with this read, which is /// as near to "no limit" as a bounded tool goes. pub fn documents(client: &ClientController, args: &Map) -> Result { let mut list_args = Map::new(); list_args.insert("limit".to_string(), Value::from(cotton_tools::mcp::handlers::common::WHOLE_SET)); if let Some(status) = maybe_text(args, "status") { list_args.insert("status".to_string(), Value::from(status)); } if let Some(doc_type) = maybe_text(args, "docType") { list_args.insert("docType".to_string(), Value::from(doc_type)); } let documents = client.read_tool("list_documents", &list_args)?; let hits = match maybe_text(args, "query") { Some(query) if query.chars().count() >= 2 => { let mut search_args = Map::new(); search_args.insert("query".to_string(), Value::from(query)); // Every hit, not the tool's twenty: the list half of this read // is whole, and a search that stopped where the list did not // would answer "no such document" for one the list draws. search_args.insert("limit".to_string(), Value::from(cotton_tools::mcp::handlers::common::WHOLE_SET)); Some(client.read_tool("search_documents", &search_args)?) } _ => None, }; let documents = client.with_file(|replica| with_vault_columns(replica, documents))?; Ok(json!({ "documents": documents, "hits": hits })) } /// The columns the vault SCREEN reads and the tool's own row does not carry. /// /// `list_documents` answers a document as an ASSISTANT sees it — title, kind, /// issuer, summary, status. The vault groups by the date a paper is ABOUT, /// prints its size, and offers a period facet, and none of those three are in /// that shape. Rather than widen a tool every assistant reads for the sake of /// one screen, the read joins them on here from the replica the answer already /// came out of. /// /// `secretId` is the same kind of column with a sharper reason: `get_document` /// says only `wasProtected`, because a document's password never travels to an /// assistant — not even as the id of the secret holding it. The person's own /// screen is different: since a document's password is off the Passwords list /// (`vault::listed_on_passwords`), the document's page is the one place that /// can offer the way to it, and this id is how it points there. The row carries /// the ID and nothing of the secret — the password page does its own reading /// under the vault's reveal rules. /// /// ONE query per table rather than one per row — `meeting_row_facts`' rule, /// and it bites harder here: the vault asks for a thousand papers, and a /// statement each would be a thousand statements on the thread that paints /// the screen. fn with_vault_columns(replica: &ReadFile<'_>, mut answer: Value) -> Result { let Some(rows) = answer.get_mut("documents").and_then(Value::as_array_mut) else { return Ok(answer); }; let ids: Vec = rows .iter() .filter_map(|row| row.get("id").and_then(Value::as_str).map(str::to_string)) .collect(); if ids.is_empty() { return Ok(answer); } // Named, not swept: the answer is at most a page of papers and the file // may hold far more, so reading every document to keep these would be a // table scan for a list that already knows its own ids. let placeholders = vec!["?"; ids.len()].join(","); let found = replica .driver .all( &format!( "SELECT id, document_date, period_start, period_end, byte_size, \ status_changed_at, storage_path, decrypted_path, original_name, mime, \ secret_id \ FROM cotton_documents WHERE id IN ({placeholders})" ), &ids.iter() .map(|id| Sql::Text(id.clone())) .collect::>(), ) .map_err(unreadable)?; let by_id: std::collections::HashMap = found .iter() .filter_map(|row| row.text("id").map(|id| (id.to_string(), row))) .collect(); for row in rows.iter_mut() { let Some(id) = row.get("id").and_then(Value::as_str) else { continue; }; let Some(found) = by_id.get(id) else { continue }; if let Some(map) = row.as_object_mut() { for (key, column) in [ ("documentDate", "document_date"), ("periodStart", "period_start"), ("periodEnd", "period_end"), ("byteSize", "byte_size"), ("statusChangedAt", "status_changed_at"), ("storagePath", "storage_path"), ("decryptedPath", "decrypted_path"), ("originalName", "original_name"), ("mime", "mime"), ("secretId", "secret_id"), ] { map.insert(key.to_string(), cell(found, column)); } } } Ok(answer) } /// `read.document {documentId}` — one paper, with the columns the detail /// screen and the viewer read. /// /// A composite for the same reason `read.documents` is one: `get_document` is /// the assistant's shape and the screen needs the vault's columns beside it — /// above all the OBJECT PATH, since the viewer reads the unlocked rendition /// when there is one and the original otherwise, and neither is in the tool's /// answer. pub fn document(client: &ClientController, args: &Map) -> Result { let id = text_arg(args, "documentId")?; let mut tool_args = Map::new(); tool_args.insert("documentId".to_string(), Value::from(id.clone())); let found = client.read_tool("get_document", &tool_args)?; let wrapped = json!({ "documents": [found] }); let widened = client.with_file(|replica| with_vault_columns(replica, wrapped))?; let one = widened .get("documents") .and_then(Value::as_array) .and_then(|rows| rows.first()) .cloned() .unwrap_or(Value::Null); // The projects sheet is part of THIS screen, so its two lists ride on this // screen's own answer rather than asking a second question — the same pair // `read.meeting` carries. let membership = client.with_file(|replica| project_membership(replica, "document", &id))?; Ok(json!({ "document": one, "projects": membership["projects"], "links": membership["links"], })) } /// `read.pages` — the pile of Articles, without their text (`read.page` carries it). /// /// A Query because `page.list` is `Not` in the verb grid ("the Reader is the /// browse surface"), which refuses an ASSISTANT a browsable list of the /// owner's reading. The Reader IS that surface. pub fn pages(replica: &ReadFile<'_>, args: &Map) -> Result { let archived = flag(args, "archived"); let rows = replica .driver .all( if archived { "SELECT id, url, host, title, read_at, state, text_state, created_at, updated_at, archived_at \ FROM cotton_pages WHERE archived_at IS NOT NULL \ ORDER BY archived_at DESC, created_at DESC" } else { "SELECT id, url, host, title, read_at, state, text_state, created_at, updated_at, archived_at \ FROM cotton_pages WHERE archived_at IS NULL \ ORDER BY created_at DESC" }, &[], ) .map_err(unreadable)?; Ok(json!({ "pages": rows .iter() .map(|row| object( row, &[ ("id", "id"), ("url", "url"), ("host", "host"), ("title", "title"), ("readAt", "read_at"), ("state", "state"), ("textState", "text_state"), ("createdAt", "created_at"), ("updatedAt", "updated_at"), ("archivedAt", "archived_at"), ], )) .collect::>(), })) } /// `read.page {id}` — one saved page, with the projects it could be filed into /// and the ones it already is. pub fn page(replica: &ReadFile<'_>, args: &Map) -> Result { let id = text_arg(args, "id")?; let row = replica .driver .get( "SELECT id, url, host, title, read_at, state, text, text_state, source_inbox_id, \ created_at, updated_at, archived_at \ FROM cotton_pages WHERE id = ?", &[Sql::Text(id.clone())], ) .map_err(unreadable)?; let Some(row) = row else { return Ok(json!({ "page": Value::Null })); }; let membership = project_membership(replica, "page", &id)?; Ok(json!({ "page": object( &row, &[ ("id", "id"), ("url", "url"), ("host", "host"), ("title", "title"), ("readAt", "read_at"), ("state", "state"), ("text", "text"), ("textState", "text_state"), ("sourceInboxId", "source_inbox_id"), ("createdAt", "created_at"), ("updatedAt", "updated_at"), ("archivedAt", "archived_at"), ], ), // The sheet's TWO lists, not one: `projects` is what a page could be // filed into and `links` is what it already is, the same pair every // other screen that mounts the projects sheet rides on. A list of the // links alone would draw a sheet offering only the projects the page // is already in. "projects": membership["projects"], "links": membership["links"], })) } // ── Meetings ────────────────────────────────────────────────────────────── /// `read.meetings {}` — the list, plus the three facts a ROW says that /// `list_meetings` does not carry. /// /// The tool answers a meeting as an assistant reads one: the id, the resolved /// title, the status, the day and the length. The list screen says more than /// that, and each addition is a question the tool's answer cannot settle: /// /// * **`rawTitle`** — the column as it stands, `NULL` and all. The row drops /// the date from its meta band when the TITLE is already the date, and /// `list_meetings` has coerced the two into one string by the time the phone /// sees it. Without the raw column every untitled row prints its day twice. /// * **`summaryMd`** and **`speakerNames`** — the search pill's other two /// fields. A meeting is recalled by what it was ABOUT, or by who was in it, /// far more often than by a machine-written title; a pill that searched only /// the title would be a pill over the least memorable of the three. /// * **`waitingToUpload`** — whether this device still holds the audio. It is /// a fact about the `_media` ledger, which is device-local and never synced, /// so no tool can answer it and no server knows it. Both halves are required /// (a pre-queued status AND a pending ledger row), because either alone says /// something the other contradicts. /// /// One read, as the invariant requires: the pill filters the pool this answers /// rather than asking again per keystroke. pub fn meetings(client: &ClientController, _args: &Map) -> Result { // The whole pool, because the search pill filters what is already loaded // rather than querying — the screen's own rule. Two hundred is // `list_meetings`' own ceiling and is the most this read can ask for, well // past the twenty-five an assistant gets by default. let mut listed = Map::new(); listed.insert("limit".to_string(), Value::from(cotton_tools::mcp::handlers::common::WHOLE_SET)); let mut answer = client.read_tool("list_meetings", &listed)?; let ids: Vec = answer["meetings"] .as_array() .map(|rows| { rows.iter() .filter_map(|row| row["id"].as_str().map(str::to_string)) .collect() }) .unwrap_or_default(); let facts = client.with_file(|replica| meeting_row_facts(replica, &ids))?; if let Some(rows) = answer["meetings"].as_array_mut() { for row in rows.iter_mut() { let Some(id) = row["id"].as_str().map(str::to_string) else { continue; }; let Some(row) = row.as_object_mut() else { continue; }; let found = facts.get(&id).cloned().unwrap_or(Value::Null); row.insert("rawTitle".to_string(), found["rawTitle"].clone()); row.insert("summaryMd".to_string(), found["summaryMd"].clone()); row.insert("speakerNames".to_string(), found["speakerNames"].clone()); row.insert( "waitingToUpload".to_string(), found["waitingToUpload"].clone(), ); } } Ok(answer) } /// The per-row facts above, read once for the whole page. /// /// One query per table rather than one per row: a list of 200 meetings would /// otherwise be 400 statements, on the thread that paints the screen. pub(crate) fn meeting_row_facts( replica: &ReadFile<'_>, ids: &[String], ) -> Result, String> { let mut out: std::collections::HashMap = std::collections::HashMap::new(); if ids.is_empty() { return Ok(out); } // The keys whose bytes have not left this phone. `pending` only: a // `failed` row is a different sentence (the drain gave up) and a `synced` // one is not waiting on anything. let pending: std::collections::HashSet = replica .driver .all("SELECT key FROM _media WHERE state = 'pending'", &[]) .map_err(unreadable)? .into_iter() .filter_map(|row| row.text("key").map(str::to_string)) .collect(); // Named, not swept: the page is at most 200 rows and the file may hold // thousands, and reading every meeting to keep 200 of them is a table scan // on the thread that paints the screen. let placeholders = vec!["?"; ids.len()].join(","); let rows = replica .driver .all( &format!( "SELECT id, title, summary_md, speakers, status, segments \ FROM cotton_meetings WHERE id IN ({placeholders})" ), &ids.iter() .map(|id| Sql::Text(id.clone())) .collect::>(), ) .map_err(unreadable)?; for row in rows { let Some(id) = row.text("id").map(str::to_string) else { continue; }; let status = row.text("status").unwrap_or_default().to_string(); // Both halves, as the doc comment says. `recording` and `uploading` // are the two statuses that precede the server being told at all. let pre_queued = status == "recording" || status == "uploading"; let waiting = pre_queued && meeting_audio_keys( replica.identity.id(), &id, row.text("segments"), ).iter().any(|key|pending.contains(key)); // Only NAMES. The canonical `S1`/`S2` labels are searched by nobody and // would make the query "s1" return every meeting in the file. let names: Vec = row .text("speakers") .and_then(|raw| serde_json::from_str::(raw).ok()) .and_then(|parsed| parsed.as_array().cloned()) .unwrap_or_default() .iter() .filter_map(|speaker| speaker["displayName"].as_str()) .filter(|name| !name.is_empty()) .map(Value::from) .collect(); out.insert( id, json!({ "rawTitle": row.text("title").map(Value::from).unwrap_or(Value::Null), "summaryMd": row .text("summary_md") .map(Value::from) .unwrap_or(Value::Null), "speakerNames": Value::Array(names), "waitingToUpload": Value::Bool(waiting), }), ); } Ok(out) } /// `read.meeting {id}` — the meeting, its transcript and its comment threads. /// /// Three tool answers as one, because the screen draws them as one page and /// three round trips is three chances to paint a transcript over a meeting /// that is not there. pub fn meeting(client: &ClientController, args: &Map) -> Result { let id = text_arg(args, "id")?; // `meetingId`, and it is not a typo being preserved: `get_meeting` requires // that key and `read_tool` does no key mapping, so an `id` here refused // EVERY call — a real meeting exactly as loudly as a missing one — with // "meetingId must be a uuid". The covering test asserted only that the // refusal was not SQLite's own sentence, which is how it passed on the // wrong error for as long as it did. let mut by_id = Map::new(); by_id.insert("meetingId".to_string(), Value::from(id.clone())); let meeting = client.read_tool("get_meeting", &by_id)?; // THE WHOLE TRANSCRIPT, PAGED HERE. `get_transcript` caps a page at 500 // turns and hands back a cursor; the screen scrolls one conversation and // find-in-transcript searches all of it, so a page boundary in the middle // would be a reader silently missing the second hour. The loop is bounded // by the cursor going null and by a hard stop, because a cursor that never // advanced would otherwise spin on the thread that paints the screen. // // **A transcript that has not landed is not a refusal, so nothing here is // swallowed.** `get_transcript` answers the meeting's head with an EMPTY // `utterances` list while the turns are still being written — the state the // status pane draws — and the only ways it can fail are the meeting having // vanished between two calls, a wrong argument key, or the driver. This // used to be `.unwrap_or(Value::Null)`, which rendered all four as "no // transcript, for ever, with no error" — including the wrong-key bug this // very read was fixed for, which is why the refusal now travels. let transcript = read_whole_transcript(client, &id)?; let mut comment_args = Map::new(); comment_args.insert("recordKind".to_string(), Value::from("meeting")); comment_args.insert("recordId".to_string(), Value::from(id.clone())); // EVERY thread, not the open ones. The summarizer asks its questions as // comments and the owner answers them as replies, so the default filter — // top-level rows with nothing resolved — is precisely the half that hides // whether a question has been answered. comment_args.insert("status".to_string(), Value::from("all")); let comments = client.read_tool("list_comments", &comment_args)?; // The sheet's WHOLE picker, not just this meeting's links: a screen has // one read, and the projects sheet is part of this screen. let extra = client.with_file(|replica| { Ok(json!({ "membership": project_membership(replica, "meeting", &id)?, "record": meeting_record_columns(replica, &id)?, "threads": comment_threads(replica, &id)?, // The player builds the meeting's own media key, and a key is // scoped by workspace. No tool answers it, and the phone must not // carry a second idea of which workspace this file is. "workspaceId": replica.workspace_id.to_string(), })) })?; Ok(json!({ "workspaceId": extra["workspaceId"], "meeting": meeting, "transcript": transcript, "comments": comments, "projects": extra["membership"]["projects"], "links": extra["membership"]["links"], "record": extra["record"], "threads": extra["threads"], })) } /// Every page of one meeting's transcript, folded into one answer. /// /// The pages are joined on `utterances` and the head of the FIRST page is kept /// — `meetingId`, `title`, `status` and the speaker map are the same on every /// page by construction, and taking the last page's would be reading the same /// fact from the least reliable place. fn read_whole_transcript(client: &ClientController, id: &str) -> Result { // 500 is the tool's own ceiling; 40 pages is 20,000 turns, which is far // past any real conversation and near enough to a stop that a cursor bug // ends as a short transcript rather than a hung screen. const PAGE: i64 = 500; const PAGES: usize = 40; let mut answer: Option = None; let mut all: Vec = Vec::new(); let mut after: Option = None; for _ in 0..PAGES { let mut args = Map::new(); args.insert("meetingId".to_string(), Value::from(id.to_string())); args.insert("limit".to_string(), Value::from(PAGE)); if let Some(after) = after { args.insert("after".to_string(), Value::from(after)); } let page = client.read_tool("get_transcript", &args)?; if let Some(rows) = page["utterances"].as_array() { all.extend(rows.iter().cloned()); } let next = page["nextAfter"].as_i64(); if answer.is_none() { answer = Some(page); } match next { // A cursor that did not move is the end, however it is spelled. Some(next) if after != Some(next) => after = Some(next), _ => break, } } let mut answer = answer.unwrap_or(Value::Null); if let Some(object) = answer.as_object_mut() { object.insert("utterances".to_string(), Value::Array(all)); // The cursor is spent: it named a page of an answer that no longer has // pages, and leaving it would invite a reader to ask for one. object.insert("nextAfter".to_string(), Value::Null); } Ok(answer) } /// The columns the meeting SCREEN reads and `get_meeting` does not carry. /// /// `get_meeting` answers a meeting as an ASSISTANT sees it — the title, the /// status, the speakers, the summary. The record screen answers three more /// questions, and each is one a person can act on: /// /// * **`audioDeletedAt`** decides whether "Transcribe again" and "Delete audio" /// are in the menu at all, and whether the foot says the recording is gone. /// Without it the app cannot tell a meeting whose audio the owner deleted /// from one that still has it, which is two menu items that lie. /// * **`segments`** is how the screen can say "about 12 minutes is missing" — /// the ONE failure a reader cannot spot for themselves, since a transcript /// that silently skips twelve minutes reads as a complete one. /// * **`rawTitle`** is the title as the column holds it, `NULL` and all. /// `get_meeting` coerces a missing title to a date for an assistant's sake, /// which is right for a tool and wrong for a rename sheet: seeded with the /// coerced value, the field offers a date as if the owner had typed it. /// /// Joined here rather than widened into a tool every assistant reads, for /// `with_vault_columns`' reason. fn meeting_record_columns(replica: &ReadFile<'_>, id: &str) -> Result { let found = replica .driver .get( "SELECT id, title, audio_deleted_at, segments, status_changed_at, status \ FROM cotton_meetings WHERE id = ?", &[Sql::Text(id.to_string())], ) .map_err(unreadable)?; let Some(row) = found else { return Ok(Value::Null); }; let mut out = object( &row, &[ ("rawTitle", "title"), ("audioDeletedAt", "audio_deleted_at"), ("statusChangedAt", "status_changed_at"), ], ); if let Value::Object(map) = &mut out { map.insert("segments".to_string(), json_cell(&row, "segments")); // Android reads the canonical object selected by Rust. The source may // be WAV, Opus or another accepted container, never an assumed m4a. #[cfg(target_os = "android")] { let key = android_meeting_playback_key( replica.identity.id(), id, row.text("audio_deleted_at"), &map["segments"], ); map.insert("audioKey".to_string(), key); } map.insert( "waitingToUpload".to_string(), Value::Bool(waiting_to_upload( replica, id, row.text("status").unwrap_or_default(), row.text("segments"), )?), ); map.insert( "holdsAudio".to_string(), Value::Bool(holds_audio(replica, id, row.text("segments"))?), ); } Ok(out) } /// A deleted recording or several source objects has no single playable file. /// This adapter is Android-only; the media selector remains shared Rust. #[cfg(any(target_os = "android", test))] fn android_meeting_playback_key( file_id: &cotton_store::file_identity::FileId, id: &str, deleted_at: Option<&str>, manifest: &Value, ) -> Value { use cotton_core::media::meeting_audio::{meeting_audio_object, MeetingAudioObject}; if deleted_at.is_some() { return Value::Null; } match meeting_audio_object(file_id, id, manifest) { MeetingAudioObject::At(key) => Value::from(key), MeetingAudioObject::ManyObjects => Value::Null, } } /// WHICH object a meeting's audio is, read off the row's own manifest. /// /// One spelling, shared with the server: `meeting_audio_object` is what the /// meetings pipeline asks before it transcribes, and a second answer here would /// eventually name a different key — which a person reads as a meeting stuck on /// "Uploading the audio" for ever, over bytes that went up days ago. The /// extension follows the source (a WhatsApp voice note is `full.opus`), so the /// old hard-coded `full.m4a` would miss every import that is not an m4a. /// /// A manifest naming SEVERAL objects has no single key to wait on, and the /// well-known one is the honest thing to look for — the pipeline refuses such a /// meeting anyway, and the screen's answer is "not waiting on one file". fn meeting_audio_key( file_id: &cotton_store::file_identity::FileId, id: &str, segments: Option<&str>, ) -> String { let manifest: Value = segments .and_then(|raw| serde_json::from_str(raw).ok()) .unwrap_or(Value::Null); match cotton_core::media::meeting_audio::meeting_audio_object(file_id, id, &manifest) { cotton_core::media::meeting_audio::MeetingAudioObject::At(key) => key, cotton_core::media::meeting_audio::MeetingAudioObject::ManyObjects => { cotton_core::media::keys::meeting_full_key(file_id, id) } } } fn meeting_audio_keys(file_id: &cotton_store::file_identity::FileId, id: &str, segments: Option<&str>) -> Vec { let manifest=segments.and_then(|s|serde_json::from_str(s).ok()).unwrap_or(Value::Null); if let Ok(Some(tracks))=cotton_core::media::call_tracks::call_tracks(file_id,id,&manifest) { return tracks.into_iter().map(|t|t.key).collect(); } vec![meeting_audio_key(file_id,id,segments)] } /// Whether THIS DEVICE still holds a meeting's audio. /// /// A fact about the `_media` ledger, which is device-local and never synced, so /// no tool can answer it and no server knows it — the page draws "Uploading the /// audio" off it, and a phone with no signal saying that is the lie /// `meetingFacts.ts` was written to prevent. /// /// BOTH halves are required, as they are on the list row: a pre-queued status /// (`recording` or `uploading`, the two that precede the server being told at /// all) AND a pending ledger row for the meeting's own key. Either alone says /// something the other contradicts. fn waiting_to_upload( replica: &ReadFile<'_>, id: &str, status: &str, segments: Option<&str>, ) -> Result { if status != "recording" && status != "uploading" { return Ok(false); } for key in meeting_audio_keys(replica.identity.id(), id, segments) { // `pending` only: a `failed` row is a different sentence (the drain gave // up) and a `synced` one is not waiting on anything. if replica .driver .get( "SELECT key FROM _media WHERE key = ? AND state = 'pending'", &[Sql::Text(key)], ) .map_err(unreadable)? .is_some() { return Ok(true); } } Ok(false) } /// Whether THIS DEVICE still has a meeting's audio to send, whatever the /// meeting's status says. /// /// What a meeting that failed as `upload_never_arrived` needs its phone to /// say: "this phone still has it" (keep the app open on a network, then try /// again) or "this phone does not" (it was recorded somewhere else, or the /// file has to be imported again). A `pending` row is bytes still queued; a /// `failed` one is bytes the server refused, still on the device. A `synced` /// row has nothing left to send, and no row means the bytes never were here. fn holds_audio(replica: &ReadFile<'_>, id: &str, segments: Option<&str>) -> Result { for key in meeting_audio_keys(replica.identity.id(), id, segments) { if replica .driver .get( "SELECT key FROM _media WHERE key = ? AND state IN ('pending', 'failed')", &[Sql::Text(key)], ) .map_err(unreadable)? .is_some() {return Ok(true);} } Ok(false) } /// The conversation on a meeting, as THREADS. /// /// `list_comments` answers a flat list shaped for an assistant: a rendered /// author string, and a boolean saying whether a row is resolved. The screen /// needs three things that shape cannot express — which rows are REPLIES to /// which, whether a reply came from an agent or from the owner, and WHEN a /// thread was resolved — because those three together are what say whether the /// summarizer's question has been answered and is waiting to be folded in. /// /// Read straight off the replica rather than through the tool, because the /// answer wanted here is a different shape and not a wider one. fn comment_threads(replica: &ReadFile<'_>, record_id: &str) -> Result { let rows = replica .driver .all( "SELECT id, parent_id, body, author_kind, author_label, resolved_at, created_at \ FROM cotton_comments \ WHERE record_kind = 'meeting' AND record_id = ? \ ORDER BY created_at ASC, id ASC", &[Sql::Text(record_id.to_string())], ) .map_err(unreadable)?; let mut threads: Vec = Vec::new(); for row in &rows { if row.text("parent_id").is_some_and(|id| !id.is_empty()) { continue; } let Some(id) = row.text("id") else { continue }; let mut root = object( row, &[ ("id", "id"), ("body", "body"), ("authorKind", "author_kind"), ("authorLabel", "author_label"), ("resolvedAt", "resolved_at"), ("createdAt", "created_at"), ], ); let replies: Vec = rows .iter() .filter(|reply| reply.text("parent_id") == Some(id)) .map(|reply| { object( reply, &[ ("id", "id"), ("body", "body"), ("authorKind", "author_kind"), ("authorLabel", "author_label"), ("createdAt", "created_at"), ], ) }) .collect(); if let Value::Object(map) = &mut root { map.insert("replies".to_string(), Value::Array(replies)); } threads.push(root); } Ok(Value::Array(threads)) } // ── News ────────────────────────────────────────────────────────────────── // The News lane's reads are QUERIES rather than tools because no // ASSISTANT-scope tool reads an edition: every CRUD verb in the // `news_edition` grid is `Not` ("editions are written by the news worker on // schedule"), which is a statement about what an assistant may do to the // pipeline's output. (The same grid's `also:` list does carry owner-scope // verbs — the app's own stamps and settings — but none of them lists an // edition.) The owner's own reader is these screens. /// Every edition, newest first — the rows `/news` draws under today's as /// slips. /// /// It was `read.newsEditions`, answering `/news/editions`, until the owner's /// feedback of 2026-09-21: *"Whatever is inside the Editions screen, bring it /// to below the news in the News screen."* A screen has exactly one read /// (`no_two_reads_share_a_name_or_a_screen`), so the list had to become part /// of an answer rather than a second one — this helper — and the index screen /// and its route went. /// /// The order is `covered_from`: a list is ordered by the day it is ABOUT, /// which is a different question from which single edition is the newest /// (`news_edition`, below). fn news_edition_rows(replica: &ReadFile<'_>) -> Result, String> { Ok(replica .driver .all( &format!( "SELECT {EDITION_COLUMNS} FROM cotton_news_editions \ ORDER BY covered_from DESC, created_at DESC" ), &[], ) .map_err(unreadable)? .iter() .map(edition_json) .collect()) } fn edition_json(row: &cotton_store::driver::Row) -> Value { let mut edition = object( row, &[ ("id", "id"), ("status", "status"), ("triggerKind", "trigger_kind"), ("editionLabel", "edition_label"), ("coveredFrom", "covered_from"), ("coveredTo", "covered_to"), ("storyCount", "story_count"), ("readMinutes", "read_minutes"), ("model", "model"), ("openedAt", "opened_at"), ("statusChangedAt", "status_changed_at"), ("failedStage", "failed_stage"), ("errorCode", "error_code"), ("createdAt", "created_at"), ("updatedAt", "updated_at"), ], ); if let Value::Object(map) = &mut edition { map.insert("quiet".to_string(), json_cell(row, "quiet")); map.insert("notes".to_string(), json_cell(row, "notes")); } edition } /// The columns every edition row is read with, in one place — the same list /// three queries below want and none of them may drift from. const EDITION_COLUMNS: &str = "id, status, trigger_kind, edition_label, covered_from, covered_to, \ story_count, read_minutes, quiet, notes, model, opened_at, status_changed_at, failed_stage, \ error_code, created_at, updated_at"; /// `read.newsEdition {id?}` — one edition with its ranked stories, and what the /// NEWEST run is doing; the latest READABLE edition when no id is named, which /// is what `/news` opens on. /// /// **Two editions, and they are two questions.** `editionFacts.ts` answers them /// with two functions on purpose: `latestReadyEdition` is what the reader /// opens, `newestEdition` is what the status band reports, and its doc comment /// names the exact cost of collapsing them — *"either hiding a failure behind /// yesterday's briefing or blanking a perfectly good briefing during a fetch."* /// So `edition` is the newest `ready` one and `newest` is the newest of ANY /// status, and a screen with last night's harvest still compiling draws /// yesterday's stories under a band that says today's is on its way. /// /// The pick is by `created_at`, which is the stamp both TypeScript functions /// scan for the maximum of. `news_edition_rows` sorts the LIST by /// `covered_from` — a list is ordered by the day it is about — and that is a /// different question from which single edition is the newest. pub fn news_edition(replica: &ReadFile<'_>, args: &Map) -> Result { let id = maybe_text(args, "id"); let newest = replica .driver .get( &format!( "SELECT {EDITION_COLUMNS} FROM cotton_news_editions \ ORDER BY created_at DESC, id DESC LIMIT 1" ), &[], ) .map_err(unreadable)?; let row = match &id { Some(id) => replica .driver .get( &format!("SELECT {EDITION_COLUMNS} FROM cotton_news_editions WHERE id = ?"), &[Sql::Text(id.clone())], ) .map_err(unreadable)?, None => replica .driver .get( &format!( "SELECT {EDITION_COLUMNS} FROM cotton_news_editions \ WHERE status = 'ready' ORDER BY created_at DESC, id DESC LIMIT 1" ), &[], ) .map_err(unreadable)?, }; let newest_json = newest.as_ref().map_or(Value::Null, edition_json); let Some(row) = row else { // No READABLE edition is not the same as no edition at all: the first // harvest of a new workspace, and a first harvest that failed, are two // different sentences, and `newest` is what tells them apart. // // The TOPICS ride on this path too, and they are the whole reason it // is not simply empty: a person with no topics is sent to News // settings rather than shown a page with nothing on it, and the // screen can only know that if the answer says so. return Ok(json!({ "edition": Value::Null, "newest": newest_json, "stories": [], "topics": news_topic_rows(replica)?, "editions": news_edition_rows(replica)?, })); }; let edition_id = row.text("id").unwrap_or_default().to_string(); let stories = replica .driver .all( "SELECT s.id, s.topic_id, s.rank, s.headline, s.lede, s.bullets, s.sources, \ s.why_care, s.read_minutes, s.opened_at, s.feedback, s.created_at, \ t.name AS topic_name \ FROM cotton_news_stories s \ LEFT JOIN cotton_news_topics t ON t.id = s.topic_id \ WHERE s.edition_id = ? ORDER BY s.rank ASC", &[Sql::Text(edition_id)], ) .map_err(unreadable)? .iter() .map(|row| { let mut story = object( row, &[ ("id", "id"), ("topicId", "topic_id"), ("topicName", "topic_name"), ("rank", "rank"), ("headline", "headline"), ("lede", "lede"), ("whyCare", "why_care"), ("readMinutes", "read_minutes"), ("openedAt", "opened_at"), ("feedback", "feedback"), ("createdAt", "created_at"), ], ); if let Value::Object(map) = &mut story { map.insert("bullets".to_string(), json_cell(row, "bullets")); map.insert("sources".to_string(), json_cell(row, "sources")); } story }) .collect::>(); // The TOPICS ride along, and they are not decoration: the reader's quiet // band names the topics that had nothing new, "less like this" has to // append a line to the topic's own exclusions — which it can only do over // the prose the person can actually see — and a person with NONE is sent // to News settings instead of being shown an empty page. A second read for // them would be a second answer to the same question. // // The EDITIONS ride along for the same reason, since 2026-09-21: the past // ones are drawn as slips under today's on this very page. Ok(json!({ "edition": edition_json(&row), "newest": newest_json, "stories": stories, "topics": news_topic_rows(replica)?, "editions": news_edition_rows(replica)?, })) } /// The declared interests the harvester walks, in the order the owner put /// them in. /// /// ONE shape, read by three answers — the topic form's, News settings' (which /// is the topics list as well since 2026-09-21) and the reader's, which needs /// them for the quiet band and for "less like this". Three column lists would /// have been three chances for one screen to be missing a field. fn news_topic_rows(replica: &ReadFile<'_>) -> Result, String> { Ok(replica .driver .all( "SELECT id, name, brief, exclusions, kind, source_url, active, paused_reason, \ unopened_streak, last_new_at, sort_order, created_at, updated_at \ FROM cotton_news_topics WHERE trashed_at IS NULL ORDER BY sort_order ASC, created_at ASC", &[], ) .map_err(unreadable)? .iter() .map(|row| { let mut topic = object( row, &[ ("id", "id"), ("name", "name"), ("brief", "brief"), ("exclusions", "exclusions"), ("kind", "kind"), ("sourceUrl", "source_url"), ("pausedReason", "paused_reason"), ("unopenedStreak", "unopened_streak"), ("lastNewAt", "last_new_at"), ("sortOrder", "sort_order"), ("createdAt", "created_at"), ("updatedAt", "updated_at"), ], ); if let Value::Object(map) = &mut topic { map.insert("active".to_string(), boolean(row, "active")); } topic }) .collect()) } /// `read.newsTopics` — the topic form's own read (`/news/topic/[id]` and /// `/news/topic/new`). The LIST of topics is News settings' read now. pub fn news_topics(replica: &ReadFile<'_>, _args: &Map) -> Result { Ok(json!({ "topics": news_topic_rows(replica)? })) } /// `read.newsSettings` — the topics, the edition times and the switches; the /// settings row is nothing when it has never been written, and the topics are /// answered either way. /// /// **ONE page since 2026-09-21** (the owner's feedback: *"Whatever is in /// Topics and Settings, combine into a single settings page"*). Topics and two /// switches were two screens a person had to find separately, and both answer /// the same question — how News is set up. A screen has exactly one read, so /// the merge is here rather than a second `ScreenRead`. /// /// Addressed BY KEY, not by `LIMIT 1`. `cotton_news_settings`' primary key IS /// `workspace_id` — there is no synthetic id — which is why /// `getNewsSettings` reads it with `selectById(SETTINGS, workspaceId)` and says /// so in a comment. This is the one place in this file that names the column, /// and it names it because the column is the row's address rather than a scope /// (see the module note). pub fn news_settings(replica: &ReadFile<'_>, _args: &Map) -> Result { let row = replica .driver .get( "SELECT edition_times, timezone, stale_after_minutes, stale_refresh, notify, \ next_edition_at, created_at, updated_at \ FROM cotton_news_settings WHERE workspace_id = ?", &[Sql::Text(replica.workspace_id.to_string())], ) .map_err(unreadable)?; let topics = news_topic_rows(replica)?; let Some(row) = row else { // No settings row yet is the ordinary first-run state, and it is NOT // "no topics": the screen draws the defaults over an empty settings // row and the topics it really has. return Ok(json!({ "settings": Value::Null, "topics": topics })); }; let mut settings = object( &row, &[ ("timezone", "timezone"), ("staleAfterMinutes", "stale_after_minutes"), ("nextEditionAt", "next_edition_at"), ("createdAt", "created_at"), ("updatedAt", "updated_at"), ], ); if let Value::Object(map) = &mut settings { map.insert("editionTimes".to_string(), json_cell(&row, "edition_times")); map.insert("staleRefresh".to_string(), boolean(&row, "stale_refresh")); map.insert("notify".to_string(), boolean(&row, "notify")); } Ok(json!({ "settings": settings, "topics": topics })) } /// `read.project {slug}` — `get_project`, whole set, plus the three facts the /// paper page draws that the tool does not answer. /// /// **The counts are still the tool's.** `get_project` is asked with the /// whole-set spelling and its answer is passed through untouched — the page /// draws the Mac's own `group_counts`, never a count of its own /// (`reads_work_tests::the_project_page_draws_get_projects_own_counts`). What /// rides beside it: /// /// * `createdAt` — the project's own birth, for the typed "since Aug 2026" /// under the name. The tool's `project` row has no date on it. /// * `capSlugs` — every live project's slug, because a cap's enamel is decided /// over the SET of slugs (`CapColour.assign`) and a page that knew only its /// own slug would paint the cap a colour Home does not. /// * `avatarKey` on each linked person — the people section draws prints, /// and `cotton_people.avatar_key` is already the object key, so the join /// costs one query and no second read. /// * `repositories` — one row per repository the project names that the /// `repos` worker has made a `cotton_repos` row for, joined by /// `RepoRef::key()` and in the PROJECT's order, so the page can draw /// *"3 open pull requests · 2 issues"* (or the sync state in words) and open /// `/repos/[id]`. A key with no row yet is absent rather than a row with /// nothing in it; the worker creates it on its next pass. /// * `sessions` — THE THREAD ROWS, `read.sessions`' own /// (`queue_rows`), cut to this project and bounded to /// `PROJECT_THREADS_LIMIT`. `get_project` answers a `sessions` key of its /// own — three rows of `{tool, machine, lastActiveAt, title, summary}`, with /// no `id` on them — and the page's Threads section draws the `/code` card, /// which needs the id it opens, the state it says, the `kind` and /// `parentSessionId` the threads cut is taken over, and the task counts. So /// the tool's key is REPLACED here rather than added beside: two `sessions` /// on one answer would be two lists of the same thing, and the MCP answer /// stays exactly as it was for every other caller. pub fn project(client: &ClientController, args: &Map) -> Result { let slug = text_arg(args, "slug")?; let mut whole = Map::new(); whole.insert("slug".to_string(), Value::from(slug.clone())); whole.insert("limit".to_string(), Value::from(cotton_tools::mcp::handlers::common::WHOLE_SET)); let answer = client.read_tool("get_project", &whole)?; let mut out = match answer { Value::Object(map) => map, other => return Err(format!("get_project answered {other}, which is not a project")), }; let people_ids: Vec = out .get("linked") .and_then(|linked| linked.get("people")) .and_then(Value::as_array) .map(|rows| { rows.iter() .filter_map(|row| row.get("id").and_then(Value::as_str).map(str::to_string)) .collect() }) .unwrap_or_default(); // THE PROJECT'S REPOSITORIES, in the project's own order. The keys are // `project_repo_refs`' — the crate's ONE parse of a remote, which is what // the `repos` worker keys `cotton_repos` by — so a row the worker has made // joins and one it has not is simply absent rather than a half-drawn row. // An unreadable entry is dropped by that function and says nothing here. // // A COTTON ADDRESS RESOLVES to the repository the household holds under // it, so a project naming both it and the git host's address lists that // repository ONCE — the one real row. let own = client.with_file(|replica| cotton_tools::connections::words::own_cotton(replica.driver))?; let repo_keys: Vec = out .get("project") .and_then(|project| project.get("repos")) .and_then(Value::as_array) .map(|entries| { project_repo_refs(entries.iter().filter_map(Value::as_str), &own) .iter() .map(|found| found.key()) .collect() }) .unwrap_or_default(); let extra = client.with_file(|replica| { let born = replica .driver .get( "SELECT id, created_at FROM cotton_memory_projects WHERE slug = ?", &[Sql::Text(slug.clone())], ) .map_err(unreadable)?; let created_at = born.as_ref().map_or(Value::Null, |row| cell(row, "created_at")); // THE PROJECT'S STANDING CONVERSATION, or null where nobody has opened // one. A READ never opens it — a page being looked at must not put a // session on a Mac — so the composer's empty state is drawn from the // null and `project.conversation` is what the first message calls // (`crate::phone::conversation`). let conversation = match born.as_ref().and_then(|row| row.text("id")) { Some(project_id) => { crate::phone::conversation::conversation_of(replica.driver, project_id)? .unwrap_or(Value::Null) } None => Value::Null, }; let live = replica .driver .all( "SELECT slug FROM cotton_memory_projects WHERE status <> 'archived' ORDER BY slug", &[], ) .map_err(unreadable)?; let cap_slugs: Vec = live.iter().map(|row| cell(row, "slug")).collect(); let mut avatars = Map::new(); if !people_ids.is_empty() { let marks = vec!["?"; people_ids.len()].join(", "); let params: Vec = people_ids.iter().cloned().map(Sql::Text).collect(); let rows = replica .driver .all( &format!("SELECT id, avatar_key FROM cotton_people WHERE id IN ({marks})"), ¶ms, ) .map_err(unreadable)?; for row in &rows { if let (Some(id), Some(key)) = (row.text("id"), row.text("avatar_key")) { avatars.insert(id.to_string(), Value::from(key)); } } } // One query per CHUNK of the keys the project names, then ORDERED BY // THE PROJECT rather than by the database: the field is a list a person // wrote, and a page that re-sorted it would be answering a question // nobody asked. // // CHUNKED because the `IN` carries one `?` per remote and the field is // free text. A project with more repositories than SQLite's variable // limit is not a real project — but the failure would be // `read.project` refusing to draw AT ALL, which is not an acceptable // answer to somebody pasting a long list into one field. let mut rows: Vec = Vec::new(); for chunk in repo_keys.chunks(IN_CHUNK) { let marks = vec!["?"; chunk.len()].join(", "); let params: Vec = chunk.iter().cloned().map(Sql::Text).collect(); rows.extend( replica .driver .all( &format!( "SELECT id, key, owner, name, sync_state, open_pulls, open_issues \ FROM cotton_repos WHERE key IN ({marks})" ), ¶ms, ) .map_err(unreadable)?, ); } let mut repositories: Vec = Vec::new(); for key in &repo_keys { let Some(row) = rows.iter().find(|row| row.text("key") == Some(key.as_str())) else { continue; }; repositories.push(json!({ "id": cell(row, "id"), "key": cell(row, "key"), // `owner/name`, which is what the row prints. The KEY carries // the host and is what the join is on. "label": match (row.text("owner"), row.text("name")) { (Some(owner), Some(name)) => Value::from(format!("{owner}/{name}")), _ => cell(row, "key"), }, "syncState": cell(row, "sync_state"), "openPulls": cell(row, "open_pulls"), "openIssues": cell(row, "open_issues"), })); } Ok(json!({ "createdAt": created_at, "capSlugs": cap_slugs, "avatars": avatars, "repositories": repositories, "conversation": conversation, })) })?; // THE THREADS, as cards rather than as the tool's three-line log. The rows // are `read.sessions`' — one builder, so a card drawn here and the same // card on `/code` can never disagree — and the window is that read's too, // which is why the ceiling below is a ceiling and not the cut. let mut answered = queue_rows(client, None, Some(&slug))?; let mut threads = answered .get_mut("sessions") .and_then(Value::as_array_mut) .map(std::mem::take) .unwrap_or_default(); threads.truncate(PROJECT_THREADS_LIMIT); out.insert("sessions".to_string(), Value::Array(threads)); // The window those rows were cut by, answered for the same reason // `read.sessions` answers it: the Threads section bands them by how quiet // they are, and a number written into Swift instead would band a card the // read had already stopped sending. out.insert( "quietWindowMs".to_string(), Value::from(SESSIONS_WINDOW_MS), ); // THE SESSIONS SECTION'S PREVIEW: the project's newest threads that are // NOT drawn as running under the conversation, with NO window — a // project whose last session ran a month ago still has sessions to show. // ASKED FOR, never cut out of a fixed handful: with eight running, the // newest ten held two that were not, and the section drew two. let now_ms = client.clock().now().timestamp_millis(); let preview = settled_threads(client, &slug, PROJECT_SESSION_PREVIEW, now_ms)?; out.insert("sessionPreview".to_string(), Value::Array(preview)); out.insert("createdAt".to_string(), extra["createdAt"].clone()); out.insert("capSlugs".to_string(), extra["capSlugs"].clone()); out.insert("repositories".to_string(), extra["repositories"].clone()); out.insert("conversation".to_string(), extra["conversation"].clone()); // THE CODE SECTION'S ROWS carry what the repository's own row knows — its // `owner/name`, its open pull requests and issues, its sync state — joined // by id from `repositories` above, so the section's paper row says what the // per-repository footer row used to (`RepoFacts.projectRowMeta`) and the // footer can go. A member the worker has made no row for yet stays as the // tool answered it. if let Some(members) = out .get_mut("linked") .and_then(|linked| linked.get_mut("repositories")) .and_then(Value::as_array_mut) { for member in members.iter_mut() { let Some(found) = member.get("id").and_then(Value::as_str).and_then(|id| { extra["repositories"] .as_array() .and_then(|rows| rows.iter().find(|row| row["id"].as_str() == Some(id))) .cloned() }) else { continue; }; if let Some(map) = member.as_object_mut() { for key in ["label", "syncState", "openPulls", "openIssues"] { map.insert(key.to_string(), found[key].clone()); } } } } if let Some(people) = out .get_mut("linked") .and_then(|linked| linked.get_mut("people")) .and_then(Value::as_array_mut) { for person in people.iter_mut() { let key = person .get("id") .and_then(Value::as_str) .and_then(|id| extra["avatars"].get(id)) .cloned() .unwrap_or(Value::Null); if let Some(map) = person.as_object_mut() { map.insert("avatarKey".to_string(), key); } } } Ok(Value::Object(out)) } /// The projects a record could be filed in, and the ones it already is. /// /// The projects sheet is part of the SCREEN that opens it, and a screen has /// exactly one read — so the sheet's two lists ride on the record's own answer /// rather than asking a second question. Archived projects are included when /// the record is already IN one (the sheet's own rule: an archive is not an /// offer a new link joins, but a link that exists must still be removable). fn project_membership( replica: &ReadFile<'_>, record_kind: &str, record_id: &str, ) -> Result { // THE SLUG RIDES BESIDE THE ID because the two writes behind this sheet // address a project by SLUG (`link_to_project` / `unlink_from_project`, // `required: ["project","records"]`) while the link rows below name it by // id. A sheet holding only one of the two can draw the list or file the // record, never both. let projects = replica .driver .all( "SELECT id, slug, name, status FROM cotton_memory_projects ORDER BY name ASC", &[], ) .map_err(unreadable)? .iter() .map(|row| { object( row, &[ ("id", "id"), ("slug", "slug"), ("name", "name"), ("status", "status"), ], ) }) .collect::>(); let links = replica .driver .all( "SELECT project_id, note FROM cotton_project_links \ WHERE record_kind = ? AND record_id = ?", &[ Sql::Text(record_kind.to_string()), Sql::Text(record_id.to_string()), ], ) .map_err(unreadable)? .iter() .map(|row| object(row, &[("projectId", "project_id"), ("note", "note")])) .collect::>(); Ok(json!({ "projects": projects, "links": links })) } // ── The briefing ────────────────────────────────────────────────────────── /// `read.briefing {project?}` — the compiled briefing, the rail it is chosen /// from, and the entries this preview cannot show. /// /// `brief` is the SAME engine an assistant is served by, so what the owner /// reads here is byte-what a session receives — the preview promise, kept by /// construction rather than by a second compiler in Swift agreeing with the /// first. /// /// Two facts ride beside it, because the screen draws them and the tool does /// not answer them: /// /// * the ACTIVE projects, which are the chip rail — a briefing is a project's /// (no global layer), so the screen always has one to name and /// `?project=` merely LOCKS which. In `created_at ASC`, which is /// `memoriesService.listProjects`' own order and therefore what `projects[0]` /// means below; /// * `machineScoped`, the number of this project's live entries that brief /// only on their own machine. The preview compiles with no machine — exactly /// the filter a foreign machine's session gets — so those entries are absent /// from the text, and the screen states the absence rather than letting it /// pass as a shorter briefing. /// /// **With no `project`, the FIRST active project stands in.** `briefing.tsx` /// resolves `lockedProjectId ?? chosen ?? projects[0]?.id ?? null`, so an /// unlocked briefing screen is never blank while the person has a project — /// and `brief` with no project and no `repoUrl` briefs on nothing at all, which /// would have left the rail empty, the count zero and the text a "find a /// project" instruction the owner did not need. pub fn briefing(client: &ClientController, args: &Map) -> Result { let project = maybe_text(args, "project"); // The rail first, because the default project is read out of it. let rail = client.with_file(|replica| { replica .driver .all( "SELECT id, slug, name FROM cotton_memory_projects \ WHERE status = 'active' ORDER BY created_at ASC, id ASC", &[], ) .map_err(unreadable) .map(|rows| { rows.iter() .map(|row| object(row, &[("id", "id"), ("slug", "slug"), ("name", "name")])) .collect::>() }) })?; let mut brief_args = Map::new(); let asked = project.clone().or_else(|| { rail.first() .and_then(|first| first.get("slug")) .and_then(Value::as_str) .map(str::to_string) }); if let Some(asked) = &asked { brief_args.insert("project".to_string(), Value::from(asked.clone())); } let brief = client.read_tool("brief", &brief_args)?; // Which projects the tool actually briefed on. It answers slugs, and the // count below has to be over THOSE — a rail chip is a project, not a // filter, so counting the whole file would state a number the text was // never trimmed by. let briefed: Vec = brief .get("projects") .and_then(Value::as_array) .map(|slugs| { slugs .iter() .filter_map(|slug| slug.as_str().map(str::to_string)) .collect() }) .unwrap_or_default(); let machine_scoped = client.with_file(|replica| { let mut counted = 0_i64; for slug in &briefed { let row = replica .driver .get( // BOTH halves of the compiler's own `liveMemories` filter — // `status = 'active'` AND `visibility = 'private'`, which is // what `previewBriefing` intersects before it counts, and // what `live_memories` selects on. Counting on the status // alone would state a number the text was never trimmed by // the day a shared entry exists to be excluded. "SELECT COUNT(*) AS n FROM cotton_memories m \ JOIN cotton_project_links l \ ON l.record_kind = 'memory' AND l.record_id = m.id \ JOIN cotton_memory_projects p ON p.id = l.project_id \ WHERE p.slug = ? AND m.archived_at IS NULL \ AND m.status = 'active' AND m.visibility = 'private' \ AND m.machine IS NOT NULL", &[Sql::Text(slug.clone())], ) .map_err(unreadable)?; counted += row.and_then(|row| row.int("n")).unwrap_or_default(); } Ok(counted) })?; Ok(json!({ "briefing": brief.get("briefing").cloned().unwrap_or(Value::Null), "tokensEstimate": brief.get("tokensEstimate").cloned().unwrap_or(Value::Null), "overBudget": brief.get("overBudget").cloned().unwrap_or(Value::Bool(false)), // The ceiling the meter reads against, ANSWERED rather than typed into // Swift: it is one number in `cotton_core::constants`, and a second // copy on the phone is a line that would go on saying 2400 the day the // compiler started trimming at something else. "budgetTokens": cotton_core::constants::MEMORY_BRIEFING_BUDGET_TOKENS, "briefedProjects": Value::Array(briefed.iter().map(|slug| Value::from(slug.clone())).collect()), "generatedAt": brief.get("generatedAt").cloned().unwrap_or(Value::Null), "projects": Value::Array(rail), "machineScoped": machine_scoped, })) } // The `phone` FEATURE, not merely `test`. These tests open a real replica // through `client::phone_tests::attached`, which is itself gated on the // feature — so a plain `#[cfg(test)]` here compiles the file into the default // build, where that helper does not exist, and `cargo check --all-targets` // fails on an import rather than on anything a reader would recognise. Found by // `pnpm rust:verify`, which is the only run that builds this crate without the // feature. #[cfg(test)] #[path = "reads_work_tests.rs"] mod tests;