3431 lines · 163.5 KB · RustRaw
//! `read.<name>` — ONE method per screen query, with the screen named beside it.//!//! Design P4. The phone does not use `browse.*`: that is a GENERIC table//! browser built for the Mac's bulk work — a column list, a keyset predicate, a//! 500 ceiling — and a phone screen is a designed answer. The day surface joins//! todos and expanded occurrences and sorts them by time; the person page wants//! an avatar, a local clock, a summary and a chat card; the money screen wants a//! balance the engine computed. So each of those is a NAMED read, declared here//! with the route it serves, and the totality test below is what stops the two//! tables drifting apart.//!//! ## Where a read's answer comes from — and one correction to the design//!//! P4 says the reads are "implemented over `cotton-core`'s services against the//! replica — the same 68 services `packages/core/src/services/` exposes today".//! **That is not what the Rust tree holds, and the code wins**//! ([feedback-should-be-a-primitive-weigh-it-by-who-said-it-and-how-m]).//! `cotton-core` is PURE — no SQLite, no I/O, its own module note says so — and//! the TypeScript services were never ported into it. What they were ported//! into is `cotton-tools`: the 183 handlers, 72 of them reads, each already a//! synchronous function over a driver.//!//! So the mechanism P4 asks for exists, one layer over: **where a screen's//! query IS a tool's list, the read CALLS THE HANDLER rather than restating//! it** — which is the sentence P4 already contains, and here it is the common//! case rather than the exception. Where a screen's query is a JOIN no single//! tool answers (the day surface, the boot gate, the sync banner), the read is//! a [`ReadSource::Query`] written here, over the replica's own driver.//!//! Either way there is ONE implementation of the answer, and a project page on//! the Mac still counts what the phone's counts.//!//! ## What is here in 4a part 2, and what is not//!//! The TABLE and the mechanism are complete. The ENTRIES are the ones 4b needs//! to boot, pair and sync, plus a representative set of tool-backed screens so//! the totality test has teeth. The rest arrive with the screens that need them//! — 4d for Home, the two decision queues, the strip and the mic (landed);//! 4e–4g for the day, the person, work, reference, traffic and money. Every one of//! those routes is on [`DEFERRED`] with the sub-step that owes it, so a route//! can never sit in the table quietly unread. A route that is answered by//! NOTHING, on purpose — a deep link, an import job, a legal page — is the third state and is on [`READ_LESS`], so the//! deferral list stays a list of debts that shrinks to nothing.//!//! The EXTENSION read — `keyboardSnapshot`, the Android input method's — is//! the reason [`Audience`] exists: an input method draws an answer and has no//! route at all.use super::scope::{list, IdAt, List, Narrowing};use std::collections::{BTreeMap, HashMap};use rusqlite::types::Value as SqlValue;use serde_json::{json, Map, Value};use crate::shell::file::ReadFile;use cotton_core::constants::{MemoryOriginKind, MemoryStatus, MemoryVisibility, ProjectLinkKind};use cotton_core::rules::home_arrangement::{ arrange_projects, ArrangedProject, HomeArrangement,};use cotton_core::rules::home_today::{ select_today_band, BandOccurrence, BandTodo, TodayBandInput,};use cotton_core::transforms::project_activity::{ project_last_activity, project_order, OrderedProject, ProjectActivityInput,};use cotton_core::rules::done_for_you::{ city_fill_acts, done_action, done_label, done_path, done_text, done_rows, junk_day_act, removed_from_act, CityFill, DoneAct, DoneKind, DONE_FOR_YOU_LIMIT,};use cotton_core::rules::asked_of_you::{ asked_rows, asked_total, AskedInput, AskedRow, DecidableEvent,};use cotton_core::transforms::zoned_clock::{day_key, day_number, local_day_key, zoned_parts};use cotton_store::driver::{Driver, Row};use cotton_store::protocol::js::{parse_date_ms, to_iso_string};use cotton_tools::mcp::dispatch::Ctx;use cotton_tools::mcp::handlers::projects::engine_shim::project_kind_table;use crate::shell::client::ClientController;/// 4e's own reads — the day surface's queries, in their own file so the lanes/// landing beside this one touch different bytes. No `#[path]`: with `reads.rs`/// as the parent, Rust already looks in `reads/`.pub mod day;pub mod person;/// Where one screen's answer comes from.pub enum ReadSource { /// The screen's query IS a tool's list. The handler is called directly — /// one implementation, and the tool's own argument validation defends the /// app's read for free. Tool(&'static str), /// The same, at **whole-set scale**: the seam sends `limit: "all"` and the /// tool answers every row rather than its own page. /// /// A page size is an ASSISTANT'S concern — a model's context is finite. A /// screen is the other case: the file is one person's, it is already on the /// device, and the list being drawn IS the set, so "the first fifty" is a /// wrong answer wearing the shape of a right one. `/bin` drew fifty rows /// per kind out of a bin of any depth for exactly as long as this variant /// did not exist (ledger `bin-no-limit-truncation`). /// /// `bounded_limit` is what reads the string, and `call_tool` refuses it /// from an MCP connection — see `handlers/common.rs`'s `WHOLE_SET`. Use /// this ONLY where the whole set is what the screen draws; a screen that /// pages for itself stays on [`ReadSource::Tool`] and says so in the guard /// table. ToolWholeSet(&'static str), /// A join or a count no single tool answers. Written here, over the /// replica's driver, and never a second copy of something a tool already /// says. Query(fn(&ReadFile<'_>, &Map<String, Value>) -> Result<Value, String>), /// A read that needs the CONTROLLER and not merely the replica. /// /// **Three different reasons now, and all three are real.** The variant is /// honestly "the controller's, for one of these", and a `Controller` entry /// says in its own comment which: /// /// 1. it must answer BEFORE there is a replica to read — the boot gate and /// the sync banner. A phone with no server, no file and no device key /// still has to draw something, and "not connected" is a FACT rather /// than an error, so a [`ReadSource::Query`] here would refuse the one /// call the first launch makes. This is the reason the variant was /// ADDED for, and it is now the smallest of the three; /// 2. it needs a seam a [`ReadSource::Query`] cannot reach. `Query`'s /// signature is `fn(&ReadFile<'_>, &Map) -> …` and nothing else is in scope, /// while the 4d reads want the CLOCK (`now_iso`, the seam a test /// replaces), the DEVICE'S ZONE (`time_zone`, handed down at open) and /// the tool caller (`read_tool`). `home`, `decide`, `mood` and /// `take` are all in this class: they DO open the replica, and a phone /// that has never paired gets the same refusal any read gets; /// 3. it is a COMPOSITE — two or more tool answers, or a tool answer with /// replica columns joined on, returned as one. This is 4f's whole /// shape and is the majority of the variant's uses today: a screen has /// exactly one read, so a page drawing a meeting AND its transcript AND /// its comment threads is one `Controller` calling three handlers, /// never three reads racing to paint the same screen. `read_tool` is /// the controller's, which is the mechanical reason these cannot be a /// `Query`. /// /// Widening `Query` to take a small read context would collapse (1) and (2) /// into one classification and leave (3) standing on its own. Until it /// does, this list is the taxonomy — /// Cotton note "The phone's boundary to the database core" describes the first two only and /// needs the third. Controller(fn(&ClientController, &Map<String, Value>) -> Result<Value, String>), /// SEVERAL tools plus a join, over the same context one tool runs on. /// /// The variant 4g needed and the earlier lanes did not. A money screen is /// the accounts AND how many of their movements nobody has explained; a /// mailbox is the threads AND the same folder grouped by sender; a chat is /// its messages AND its receipts AND its calls. Each of those is one /// screen asking one question, and answering it as three /// [`ReadSource::Tool`] reads would be three round trips and three chances /// to paint a half-resolved page. /// /// It is NOT a licence to restate a tool. The body gets a `Ctx`, so every /// part of the answer that a handler already knows how to produce is /// produced by calling that handler; what the body adds is the join no tool /// asks for. `ClientController::read_rows` runs it inside the same /// transaction a tool-backed read uses and REFUSES, loudly and with a /// rollback, if anything wrote. Composed(fn(&mut Ctx<'_>, &Map<String, Value>) -> Result<Value, String>),}/// Who a read's answer is drawn by.////// Every read had a screen until 4i, and the two totality tests below are built/// on that: a read names at least one route, and a route is claimed by exactly/// one read. Then the extensions arrived. A keyboard snapshot is read by a/// TARGET — a separate process with its own memory budget, which has no route/// at all (design P9).////// A bare `screens: &[]` allowance was refused: it would let any future read/// declare no consumer whatever, which is exactly the drift the reads table/// exists to prevent. So the consumer is still DECLARED, and for an extension/// it is declared as the App Group key the answer is written under — the one/// name the app and the extension both know each other by.pub enum Audience { /// Routes in [`super::routes::ROUTES`]. At least one, always. /// /// A screen may also name one PANEL of a route — `/settings#storage` — a /// part of that screen that opens in place (a sheet or a disclosure) and /// loads its own answer. The settings page is one sheet whose rows open /// their own panels, so each panel's read names the panel rather than the /// page: one read per panel, and still never two reads for one string. /// [`route_of`] is what the route half is held to. Screens(&'static [&'static str]), /// An app EXTENSION process, named by the App Group `UserDefaults` key its /// answer is written under. One of [`EXTENSION_CHANNELS`]. Extension(&'static str),}impl Audience { /// The routes this read serves — empty for an extension, which has none. pub fn screens(&self) -> &'static [&'static str] { match self { Audience::Screens(routes) => routes, Audience::Extension(_) => &[], } }}/// The route a screen string belongs to: `/settings#storage` → `/settings`.pub fn route_of(screen: &str) -> &str { screen.split_once('#').map_or(screen, |(route, _)| route)}/// The App Group keys an [`Audience::Extension`] may name.////// **Wire protocol, and declared in two languages.** The keyboard's literal is/// the Android input method's (`apps/cotton-android/…/keyboard/`), which reads/// its snapshot through this read. This list is NOT held byte-equal to that by/// a guard, deliberately: a Rust test reading a file outside `crates/` is what/// the crate-local reads test sweeps for, and the/// honest ledger entry is better than an exempted read. The list still has/// teeth on this side — a read cannot invent a second channel.pub static EXTENSION_CHANNELS: &[&str] = &["cotton.keyboard.snapshot.v1"];/// One `read.<name>` method.pub struct ScreenRead { /// The method name WITHOUT its `read.` prefix. pub name: &'static str, /// Who draws this answer: routes, or one extension process. pub audience: Audience, pub source: ReadSource, /// Whether this read takes the Mac's project scope (`projects: [slug]`), /// and how its answer is narrowed to it — see [`super::scope`]. `None` /// refuses a scope by name. /// /// Declared HERE, on the read, and nowhere else: the scope list is derived /// from this table (`scope_tests.rs` holds it), so deleting a read /// deletes its scope. pub scope: Option<Narrowing>,}impl ScreenRead { /// The tool this read runs, whatever its scale — `None` for a read that is /// not a tool's answer. /// /// ONE accessor rather than a `match` per test: the day a third tool-backed /// variant appears, a sweep that matched `ReadSource::Tool` alone would go /// quiet rather than red, and the sweeps below are the only thing holding /// the table to the catalogue. pub fn tool(&self) -> Option<&'static str> { match self.source { ReadSource::Tool(name) | ReadSource::ToolWholeSet(name) => Some(name), _ => None, } }}/// The declared reads — grouped by the lane that added them, and alphabetical/// by name WITHIN a group.////// It is not one alphabetical list and has not been since 4d: the `── 4x ──`/// headers are the real structure, and a lane appends its own block rather/// than interleaving its entries with everyone else's. 4k's sits at the top/// only because `activity` sorts first inside it. What the table is actually/// held to is `no_two_reads_share_a_name_or_a_screen` and/// `every_screen_is_answered_or_deferred_by_name`; the order is for readers.pub static READS: &[ScreenRead] = &[ // ── 4k: the assistant, and the file's own facts under it ────────────── ScreenRead { // The transparency screen, whole: which file this phone is holding and // how much of it has not gone up yet, what the assistant has been asked // to do, and what an assistant has done in this database. // // It was `read.replicaFacts` and answered the header alone. `/activity` // may hold ONE read (`no_two_reads_share_a_name_or_a_screen`) and 4k // adds no route, so the runs fold in here and it takes the screen's // name — which is how every other read in this table is named. name: "activity", audience: Audience::Screens(&["/activity"]), source: ReadSource::Query(crate::phone::activity::activity), scope: None, }, // ── The boot gate, pairing and sync: what 4b needs and nothing more ──── ScreenRead { // Who this phone belongs to, off `connection.json` and `refusal.json`: // is there a server, who is here, what is it called, and is this // device refused. Whether the FILE is open is deliberately not here — // see the function: that answer costs an attach, and a gate that waits // on one behind a ceiling decides "nobody is here" the moment the // ceiling wins. name: "boot", audience: Audience::Screens(&["/"]), source: ReadSource::Controller(boot), scope: None, }, ScreenRead { // THE DATABASES THIS DEVICE HOLDS (`databases.rs`): the switcher's // rows, off the connection record alone, so listing a dozen idle // databases opens none of them. name: "databases", audience: Audience::Screens(&["/#databases"]), source: ReadSource::Controller(super::databases::list), scope: None, }, ScreenRead { name: "members", audience: Audience::Screens(&["/members"]), source: ReadSource::Controller(super::members::read), scope: None, }, ScreenRead { // The sync banner and the settings row read the same thing, because // there is one answer to "is this phone up to date". name: "syncStatus", audience: Audience::Screens(&["/device#sync"]), source: ReadSource::Controller(sync_status), scope: None, }, ScreenRead { name: "sync_state", audience: Audience::Screens(&["/#databaseSync"]), source: ReadSource::Controller(super::sync_state::read), scope: None, }, ScreenRead { // Every device admitted to this database, off the person's OWN file. // `cotton_devices` is synced (Cotton note "Devices — how a machine is admitted to your database", *The // rows*), so the list is on this phone whether or not a Mac answers, // and a Devices screen that waited on `devices.list` over HTTP was a // skeleton over rows the phone already held. What is NOT here is what // the file does not carry — the pairings still waiting (`registry.db` // on the serving Mac, `devices.pending`) and the registry's // `lastSeenAt`; the screen draws the rows first and asks for the // queue after, never the other way round. name: "devices", audience: Audience::Screens(&["/devices"]), source: ReadSource::Controller(super::reads_work::devices), scope: None, }, // ── Tool-backed screens: the representative set ─────────────────────── ScreenRead { // A SIBLING of `list_todos`, not a caller of it — see the function. // The tool pages, answers `repeating: true` where the repeat editor // needs the series' id, and answers no `updatedAt`, which is the only // column the dropped list can group by. // // 4a2 bound this to the tool as the representative example. Three // screens read it, so it answers the POOL and the DROPPED list in one // call — two queries, because the app makes two. name: "todos", // `/projects/[slug]/todos` is NOT here, and that is a choice rather // than a limit: this read DOES take a `project` (4e's, for `/todos`'s // own `?project=` scoping). But the project page's list is not the // workspace's list narrowed — it is what `get_project` already answers, // scoped by membership and counted open and closed in the same call the // rest of that page reads. One screen, one read (P4), so that route // reads `read.project` and this list stays the workspace's. audience: Audience::Screens(&["/todos", "/todos/done", "/todos/dropped"]), source: ReadSource::Query(day::todos), scope: Some(Narrowing::After(&[list("todos", "todo"), list("dropped", "todo")])), }, ScreenRead { // The todo detail screen, which `read.record` cannot answer — the same // correction the goal read is: `get_record`'s todo shape is the // assistant's, and this screen edits the series, the raw priority and // the capture trail. name: "todo", audience: Audience::Screens(&["/todos/todo/[id]"]), source: ReadSource::Query(day::todo), scope: None, }, ScreenRead { // Generic on purpose: the store has ONE "fetch this row by kind and id" // and every detail screen is that question. A per-kind read here would // be sixty methods saying the same sentence. name: "record", audience: Audience::Screens(&[ "/notes/note/[id]", // `/thoughts/thought/[id]` is not here: the capture page finds its // row in `read.thoughts`' ledger, because `get_record`'s thought // shape carries neither `route_confidence` nor `route_proposal`. // `/goals/goal/[id]` is NOT here, and its absence is the // correction: `get_record`'s kinds are todo, event, note, journal, // person, location, meeting, document, memory, transaction and // thought — there is no `goal`, so this read answered a tapped goal // with "kind must be one of …". It has its own read below. // // `/locations/location/[id]` is not here EITHER, for a different // reason and by the same remedy: the place page draws the // *Projects…* sheet, which needs the project roster and this // record's memberships, and `get_record` is an ASSISTANT's tool // whose shape must not grow a phone screen's needs. `read.location` // answers the identical row plus those two keys. // // And `/memory/[id]` is gone for the third version of the same // story: the entry page draws its comments and its projects, which // `get_record` does not answer. `read.memoryEntry` does. ]), // COMPOSED since 4k, and the tool's own answer is untouched inside it: // `get_record` answers the row and the body adds `threads`, the // conversation on it. A note screen with no comment surface made an // assistant's answer note a dead end — commenting on it IS the re-ask // gesture — and a second read for the thread is what the one-read-per- // screen rule forbids. `record_thread` says the rest. source: ReadSource::Composed(super::record_thread::record), scope: None, }, ScreenRead { // Split out of `read.record` — see the comment there. name: "location", audience: Audience::Screens(&["/locations/location/[id]"]), source: ReadSource::Query(day::location), scope: None, }, ScreenRead { // A COMPOSITE for two keys `list_projects` does not answer and the // list cannot be drawn without: the project's `id`, and WHEN it last // moved. The list is most-recently-worked-first, which is a question // about every record linked to a project rather than about the project // row — so it is the engine's (`project_last_activity`), computed by // the same function Home's band uses. name: "projects", audience: Audience::Screens(&["/projects"]), source: ReadSource::Controller(super::reads_work::projects), scope: None, }, ScreenRead { // `get_project` is the ONE session-start call, and the project page is // the screen it was written for. name: "project", audience: Audience::Screens(&[ "/projects/[slug]", "/projects/[slug]/[section]", // The brand kit rides `get_project`: the palette is the project's // own column and the logo files are its document links. "/projects/[slug]/brand", // And so do the project's todos: `linked.todos` is already the // membership-scoped set, with `openCount` and `closedCount` beside // it. See the note on `read.todos` for why the list tool cannot // answer this one. "/projects/[slug]/todos", ]), // Whole set: `get_project` is one record, but its `linked.*` groups // are lists the tool caps at fifty for an assistant (`GROUP_CAP`), // and the page draws them. `limit: "all"` lifts that cap for the // groups alone; the count beside each was always the true total. source: ReadSource::Controller(super::reads_work::project), scope: None, }, ScreenRead { // NOT `list_people`, and the difference is the whole address book. // // The tool pages at fifty, so `/people` drew fifty of about 1,900 and // searched only those fifty. A phone screen's list read answers the // WHOLE set at personal scale — the rule is in // Cotton note "The phone and Mac app — how a screen is built", the guard is // `a_tool_backed_list_read_is_paged_or_whole` in `reads_tests.rs`, and // the query says why it is not the tool. name: "people", audience: Audience::Screens(&["/people"]), source: ReadSource::Query(person::people), scope: Some(Narrowing::After(&[List { path: "people", kind: "person", id: IdAt::Id, total: Some("total") }])), }, ScreenRead { // A SIBLING of `list_thoughts`, not a caller of it — see the function. // The tool is an assistant's reading of the ledger (open captures by // default, capped, a voice note folded into one `text`, three outcomes // collapsed into one word); this is the person's own ledger, // unpaginated, dismissed rows included, and the capture page draws its // routing story off the distinctions that word erases. // // The list screen it was written for folded into `/decide` on // 2026-09-15 and came back on 2026-09-28, when To decide stopped // holding thoughts: `/thoughts` is every capture, newest first, and it // was the only place an unsure one could still be seen. // // 4a2 bound this to the tool. Five columns the tool does not read are // why that could not draw the screen, and they are named at the query. name: "thoughts", audience: Audience::Screens(&["/thoughts", "/thoughts/thought/[id]"]), source: ReadSource::Query(day::thoughts), scope: None, }, ScreenRead { // THE PERSON'S OWN NOTES, which is not what `list_managed_notes` // answers: that tool is an ASSISTANT'S sync index — "the notes you // previously published under one managedBy key" — and it requires a // `managedBy` argument the notes screen has none of. Pointed at it, // `/notes` showed an agent's mirror or nothing at all. // // A [`ReadSource::Tool`] cannot fix it, because no read tool answers // this question: `list_notes` does not exist, and its absence is // deliberate — an assistant reads a person's notes through `search` // and `get_record`, not by listing them. So the screen's query is one // no single tool answers, which is exactly what // [`ReadSource::Query`] is for. name: "notes", audience: Audience::Screens(&["/notes"]), source: ReadSource::Query(own_notes), scope: Some(Narrowing::After(&[list("notes", "note")])), }, ScreenRead { // The goal detail screen, which `read.record` cannot answer — see the // note on its screen list. name: "goal", audience: Audience::Screens(&["/goals/goal/[id]"]), source: ReadSource::Query(goal), scope: None, }, ScreenRead { // Where a file's bytes are on THIS device, and never a fetch. The // viewer's whole question is "what do I render", and the answer is a // path or an honest `present: false` — `media.ensure` is the method // that goes and gets it, and it is a method rather than a read for // precisely that reason. // // **THE LIST IS NOT THE SET OF CALLERS**, and `/notes/note/[id]` is // the reason it has to be said: a note's attachment strip draws // through this read too, and it is not named here because a screen may // be claimed by exactly ONE read // (`reads_tests::no_two_reads_share_a_name_or_a_screen`) and that // screen is `read.record`'s. The audience declares which screen this // read ANSWERS, not who may call it; nothing at run time consults it. // The controller supplies the local serving ObjectStore root; the // file read and tier ordering remain shared with the replica. name: "mediaPath", audience: Audience::Screens(&["/documents/document/[id]/viewer"]), source: ReadSource::Controller(crate::phone::media::media_path), scope: None, }, ScreenRead { // A COMPOSITE, not the bare tool. `brief` answers the compiled text, // the estimate and the over-budget flag — and the screen draws three // more things: the chip rail of active projects (a briefing is a // PROJECT's, v34, so there is always one to name), and the count of // entries that brief only on their own machine, which this preview // compiles WITHOUT one and so must state rather than silently drop. name: "briefing", audience: Audience::Screens(&["/briefing"]), source: ReadSource::Controller(super::reads_work::briefing), scope: None, }, // ── The extensions: a read with no screen (design P9) ───────────────── ScreenRead { // The Android input method's own tray of takes // (`apps/cotton-android/…/keyboard/KeyboardSnapshotBridge.kt`). name: "keyboardSnapshot", audience: Audience::Extension("cotton.keyboard.snapshot.v1"), source: ReadSource::Query(crate::phone::keyboard::keyboard_snapshot), scope: None, }, ScreenRead { // THIS PHONE'S DISK, which is not what `storage_summary` answers. // That tool adds up the workspace's own record rows — every photo, // video, document and meeting in the FILE, sightings counted once per // copy — which is a true and useful number about the database and says // nothing at all about the device the screen is running on. A person // opening Storage on a phone is asking how much of THEIR // PHONE Cotton is using and whether there is room for more. // // A [`ReadSource::Controller`] because the answer is not in the // database: it is the data directory's own size, read through the // injected [`crate::phone::disk::Disk`] seam so a test can be three // gigabytes full without writing a byte. // `/devices/[id]/storage` is another device's rows, asked by its key. name: "storage", audience: Audience::Screens(&["/storage", "/devices/[id]/storage"]), source: ReadSource::Controller(storage), scope: None, }, // ── 4g — people's traffic and money ─────────────────────────────────── ScreenRead { // The PHONE's call log — what a person means when they say "my calls", // and now the only one. Cotton's own live calling and its `/calls` // screen went at schema 5 with the rest of the sharing era. // Composed rather than `Tool`, for one reason: the ceiling. See // `traffic::call_log`. name: "callLog", audience: Audience::Screens(&["/calls/history"]), source: ReadSource::Composed(crate::phone::traffic::call_log), scope: None, }, ScreenRead { name: "call", audience: Audience::Screens(&["/calls/call/[id]"]), source: ReadSource::Tool("get_call"), scope: None, }, ScreenRead { // One folder, both ways round: the threads and the same folder grouped // by sender. The screen flips between them locally, so reading them // apart would read the mailbox twice for one segment control. name: "email", audience: Audience::Screens(&["/email"]), source: ReadSource::Composed(crate::phone::traffic::email), // `list_email_threads` caps the conversations it reads BEFORE it orders // them, so the member thread ids go into the query, ahead of the cap. scope: Some(Narrowing::InRead { record_kind: Some("email_thread") }), }, ScreenRead { // Composed rather than `Tool`, solely so the whole thread comes back // rather than its newest fifty — see `traffic::email_thread`. name: "emailThread", audience: Audience::Screens(&["/email/[id]"]), source: ReadSource::Composed(crate::phone::traffic::email_thread), scope: None, }, ScreenRead { // The grid IS the library: no ceiling, the videos beside the pictures, // and a picture the person has agreed is a copy is filtered out rather // than deleted. None of that is reachable through `list_photos`' // arguments — see `traffic::photos`. `/videos` is the video table's // own list (`records.list`), so there is no `videos` read. name: "photos", audience: Audience::Screens(&["/photos"]), source: ReadSource::Composed(crate::phone::traffic::photos), scope: Some(Narrowing::After(&[list("photos", "photo"), list("videos", "video"), list("albums", "album")])), }, ScreenRead { name: "albums", audience: Audience::Screens(&["/photos/albums"]), source: ReadSource::Composed(crate::phone::traffic::albums), scope: None, }, ScreenRead { // The pairs AND both pictures of each: the screen draws two real tiles // with their sizes, and a read per pair is a read per tile. name: "duplicates", audience: Audience::Screens(&["/photos/duplicates"]), source: ReadSource::Composed(crate::phone::traffic::duplicates), scope: None, }, ScreenRead { // Whom the Mac thinks it recognises. The names and the pictures resolve // ONCE for the whole list — a hook per row is how forty suggestions // become eighty reads. name: "faceSuggestions", audience: Audience::Screens(&["/photos/people"]), source: ReadSource::Composed(crate::phone::traffic::face_suggestions), scope: None, }, ScreenRead { // Composed rather than `Tool`, for the same reason the grid's rows are: // `get_album`'s members say WHICH pictures are in the album and nothing // a tile can paint with. See `traffic::album`. name: "album", audience: Audience::Screens(&["/photos/album/[id]"]), source: ReadSource::Composed(crate::phone::traffic::album), scope: None, }, ScreenRead { name: "addablePhotos", audience: Audience::Screens(&["/photos/album/[id]/add"]), source: ReadSource::Composed(crate::phone::traffic::addable_photos), scope: None, }, ScreenRead { // One picture, its faces and everywhere it has been seen. name: "photo", audience: Audience::Screens(&["/photos/photo/[id]"]), source: ReadSource::Composed(crate::phone::traffic::photo), scope: None, }, ScreenRead { name: "video", audience: Audience::Screens(&["/videos/video/[id]"]), source: ReadSource::Composed(crate::phone::traffic::video), scope: None, }, ScreenRead { // One row per THREAD, and the person-merge left to the screen. // Archived is a filter the tool does not have; see // `traffic::threads`. The search pill is the same screen, so a // `query` makes this read answer its hits — one read per screen. name: "threads", audience: Audience::Screens(&["/messages"]), source: ReadSource::Composed(crate::phone::traffic::threads), // A merged conversation is several threads under one row. scope: Some(Narrowing::After(&[List { path: "threads", kind: "thread", id: IdAt::IdOrEach("threadIds"), total: None, }])), }, ScreenRead { // A window that GROWS, assembled from the tool's own `before` cursor // when it is asked for more than one call can answer. name: "thread", audience: Audience::Screens(&["/messages/[thread]"]), source: ReadSource::Composed(crate::phone::traffic::thread), scope: None, }, ScreenRead { name: "threadInfo", audience: Audience::Screens(&["/messages/[thread]/info"]), source: ReadSource::Composed(crate::phone::traffic::thread_info), scope: None, }, ScreenRead { name: "threadMedia", audience: Audience::Screens(&["/messages/[thread]/media"]), source: ReadSource::Composed(crate::phone::traffic::thread_media), scope: None, }, ScreenRead { // Starring is the OWNER's own column, so no tool asks this. name: "starred", audience: Audience::Screens(&["/messages/starred"]), source: ReadSource::Composed(crate::phone::traffic::starred), scope: None, }, // ── 4e: the day and the person ──────────────────────────────────────── ScreenRead { // The person page: fifteen lists in ONE answer, in its own file // because it is the biggest read on the phone. `get_record`'s person // is the assistant's shape — a name and a summary — and this screen // is the local clock, the notes, the money, the shared photos, the // chat card, the suggestions and everything linked either way. name: "person", audience: Audience::Screens(&["/people/person/[id]", "/people/person/[id]/[section]"]), source: ReadSource::Query(person::person), scope: None, }, ScreenRead { // The alarm list, which no tool answers: `list_alarms` does not exist // and its absence is deliberate — an alarm is the owner's own act and // no assistant reads or sets one. See `handlers/alarms.rs`. name: "alarms", audience: Audience::Screens(&["/alarms"]), source: ReadSource::Query(day::alarms), scope: None, }, ScreenRead { // THE PERSON'S OWN JOURNAL, which `list_notes` does not answer for the // same reason `read.notes` above exists — and with one clause more: // a project's journal entry is the same kind in the same file, and // showing it here would put an assistant's page in somebody's diary. // THREE screens, one query, deliberately: the journal home, one day of // it, and "today's page". All three ask `listJournal` the same // question and then FIND in it — the day screens resolve a page by its // day key rather than fetching one — so a second read would be a // second answer to which page a day has. name: "journal", audience: Audience::Screens(&["/journal", "/journal/[date]", "/notes/journal-today"]), source: ReadSource::Query(day::journal), // Its query keeps project pages OUT, so there is nothing in its answer // to narrow to: scoped, it reads the chosen projects' pages instead. scope: Some(Narrowing::InRead { record_kind: None }), }, ScreenRead { // The day surface: the calendar's occurrences, the todos due that day // and the invitations still waiting. One read, because the screen is // ONE answer — an agenda assembled from three tables, and three round // trips is three chances to draw a half-built day. name: "day", audience: Audience::Screens(&["/calendar"]), source: ReadSource::Query(day::day), scope: Some(Narrowing::After(&[ List { path: "occurrences", kind: "event", id: IdAt::AnyOf(&["eventId", "seriesId"]), total: None }, list("invites", "event"), list("todos", "todo"), ])), }, ScreenRead { name: "month", audience: Audience::Screens(&["/calendar/month"]), source: ReadSource::Query(day::month), scope: Some(Narrowing::After(&[ List { path: "occurrences", kind: "event", id: IdAt::AnyOf(&["eventId", "seriesId"]), total: None }, list("todos", "todo"), ])), }, ScreenRead { // The detail screen and the editor read the same event, its guests and // the address book a guest is matched against — one read for both, // because they are one record seen twice. name: "event", audience: Audience::Screens(&["/calendar/event/[id]", "/calendar/event/edit"]), source: ReadSource::Query(day::event), scope: None, }, ScreenRead { name: "locations", audience: Audience::Screens(&["/locations"]), source: ReadSource::Query(day::locations), scope: Some(Narrowing::After(&[list("locations", "location")])), }, ScreenRead { name: "goals", audience: Audience::Screens(&["/goals"]), source: ReadSource::Query(day::goals), scope: Some(Narrowing::After(&[list("goals", "goal")])), }, ScreenRead { // Which of this device's contacts are already people here. NOT // `list_people`: that tool pages, and answers no `deviceContactId` — // which is the only field this screen reads. name: "peopleImport", audience: Audience::Screens(&["/people/import"]), source: ReadSource::Query(day::people_import), scope: None, }, ScreenRead { // Tools needs the arrangement, not Home's counts, event expansion or // project activity. Read on this device even while its Mac is busy. name: "toolOrder", audience: Audience::Screens(&["/tools"]), source: ReadSource::Controller(tool_order), scope: None, }, // ── 4d ── Home, the two decision queues, the strip and the mic ───────── ScreenRead { // Home is a GLANCE, and a glance is ONE answer: the queue, the memory // row, the projects band, the fifteen tool figures, who this is and // where the sync loop got to. Fifteen round trips would be fifteen // chances to paint a half-resolved screen, which is the same reason // `boot` is one call rather than four. name: "home", audience: Audience::Screens(&["/home"]), source: ReadSource::Controller(home), scope: None, }, ScreenRead { // One `figure` part of Home's board (a business's "Cash taken today"): // the tool card's figure worked out and said in the part's own words // (`tool_figures::part_line`), so the app draws the core's line and // composes nothing. `{part, today?, timezone?}` → `{line, today}`; no // line is silence. `today` is the day the figure was worked for, // `YYYY-MM-DD`: the ask's own when it names one, else this device's // clock on `timezone`'s local calendar (else the reading zone) — never // a UTC stamp, so the app computes no day key of its own. name: "homeFigure", audience: Audience::Screens(&["/home"]), source: ReadSource::Controller(home_figure), scope: None, }, ScreenRead { name: "mood", audience: Audience::Screens(&["/mood"]), source: ReadSource::Controller(mood), scope: None, }, ScreenRead { // The mic screen and the keyboard's hop into it read the same two // facts, because they are the same screen reached two ways. name: "take", audience: Audience::Screens(&["/take", "/keyboard-take"]), source: ReadSource::Controller(take), scope: None, }, // ── 4h — settings, sharing, Find and the Bin ────────────────────────── // // An APPENDED BLOCK rather than entries threaded through the table above: // the `reads.rs` split into `phone/reads/{mod,day,work,traffic}.rs` is // another lane's, and this block is what moves into `phone/reads/ // settings.rs` whole when it lands. Every one of these deleted its own // `DEFERRED` line; the routes that legitimately read nothing moved to // `READ_LESS`, which is where a permanent line belongs. // ── the vault — the Passwords screens (spec §6.3) ──────────────────── ScreenRead { // The list, the kind counts and the STATUS LINE above it, in one // answer. The status rides this read rather than being a second one // because a screen with two reads is two answers to one question // (`no_two_reads_share_a_name_or_a_screen`), and the line above the // list is part of the same picture as the list. // // API keys are one of the list's kinds ("API keys" is a chip), not a // second screen: the settings page's AI screen folded into it. name: "secrets", audience: Audience::Screens(&["/passwords"]), source: ReadSource::Controller(crate::phone::vault::secrets_read), scope: None, }, ScreenRead { // One secret's page: the plain columns, the machines it is written // onto, and the projects it belongs to. **Never the payload** — that is // `vault.reveal`, behind the presence prompt and the five-minute // unlock, and a read that could answer it would be a reveal with no // prompt in front of it. name: "secret", audience: Audience::Screens(&["/passwords/[id]"]), source: ReadSource::Controller(crate::phone::vault::secret_read), scope: None, }, ScreenRead { // The workspace ROW, which two settings screens ask two questions of: // what is this person called, and where do they live. ONE read rather // than two, because it is one row and two reads over it would be two // chances to disagree about it. // // The ADDRESS is not here and must not be: `read.boot` already answers // `serverName`, resolved through `relay_name_of` off the connection // file. Asking `GET /v1/me/server` for it would be a network round // trip for something this core already holds. name: "account", audience: Audience::Screens(&["/database", "/device", "/device#city"]), source: ReadSource::Query(account), scope: None, }, ScreenRead { // Spec 10.3 "You": the owner's own person and how this database is // signed into now, in words. A `Controller` read because it reads // the PERSONAL database whichever one is shown, and this device's // own key and zone (`phone::you`). It writes nothing. name: "you", // `/me` is the Me card's page: the same person, opened by this id. audience: Audience::Screens(&["/me", "/people/person/[id]#you"]), source: ReadSource::Controller(super::you::read), scope: None, }, ScreenRead { // The keyboard screen's only read, and its whole figure: two aggregates // and no row to decode. name: "dictationStats", audience: Audience::Screens(&["/device#keyboard"]), source: ReadSource::Query(dictation_stats), scope: None, }, ScreenRead { // The device's own dictation language model's source (every name and // the person's own lines); the app compiles it, nothing renders it. name: "voiceCorpus", audience: Audience::Screens(&["/voice-words#model"]), source: ReadSource::Controller(super::voice_words::corpus), scope: None, }, ScreenRead { name: "voiceContext", audience: Audience::Screens(&["/voice-words#heard"]), source: ReadSource::Controller(super::voice_words::context_for), scope: None, }, ScreenRead { name: "database", audience: Audience::Screens(&["/database#page"]), source: ReadSource::Controller(super::database_appearance::page), scope: None, }, ScreenRead { // Spec 10.5: what every device of this database keeps, per tool. name: "databaseStorage", audience: Audience::Screens(&["/database#storage"]), source: ReadSource::Controller(super::storage::database_storage), scope: None, }, ScreenRead { name: "storageFacts", audience: Audience::Screens(&["/photos#storage"]), source: ReadSource::Controller(super::storage::facts), scope: None, }, ScreenRead { name: "keepFetch", audience: Audience::Screens(&["/devices/[id]#storage"]), source: ReadSource::Controller(super::storage::keep_fetch), scope: None, }, ScreenRead { name: "device", audience: Audience::Screens(&["/devices/[id]#host"]), source: ReadSource::Controller(crate::methods::host_settings::device_page), scope: None, }, ScreenRead { // The serving Mac's off-Mac backup, for the board's notices on Home // and the database page: a Mac whose copy FAILED or fell BEHIND (its // own judgement, past its `lag_minutes`) is one notice there. Answered // by the Mac — its own relay, or over `/v1` from a phone — and never // from silence (`methods/host_settings.rs`). name: "servingBackup", audience: Audience::Screens(&["/home#backup", "/database#backup"]), source: ReadSource::Controller(crate::methods::host_settings::serving_backup_page), scope: None, }, ScreenRead { // Home's Recent shelf: the person's own opens, kept in the personal // database whichever database Home shows (`phone/usage.rs`). name: "recentVisits", audience: Audience::Screens(&["/home#recent"]), source: ReadSource::Controller(|client, args| { let _personal = client.name_database(None)?; client.with_file(|file| crate::phone::usage::recent(file.driver, file.workspace_id, args)) }), scope: None, }, ScreenRead { name: "voiceVocabulary", audience: Audience::Screens(&["/voice-words"]), source: ReadSource::Controller(|client, args| { let _personal = client.name_database(None)?; client.with_file(|file| voice_vocabulary(file, args)) }), scope: None, }, ScreenRead { // Find, over the ENGINE rather than over the `search_records` tool — // see the function's own note for why those are different answers. name: "find", audience: Audience::Screens(&["/search"]), source: ReadSource::Query(find), scope: None, }, // ── 4f — work and reference ─────────────────────────────────────────── // // The BODY of every `Query`/`Controller` below lives in // [`super::reads_work`], so three lanes filling this table at once conflict // on an append rather than on four hundred lines of query. A `Controller` // here is a COMPOSITE — two handlers joined into the one answer a screen // draws — rather than a "before there is a replica" read; each one says so. ScreenRead { // WHOLE SET: `list_feedback` pages at fifty and the screen sends no // page of its own, so a project past fifty pieces of feedback drew // fifty of them with nothing saying so. name: "projectFeedback", // One piece of feedback's page reads the same whole set and draws the // row its id names (`ProjectFeedbackTableSource`). audience: Audience::Screens(&["/projects/[slug]/feedback", "/projects/[slug]/feedback/[id]"]), source: ReadSource::ToolWholeSet("list_feedback"), scope: None, }, ScreenRead { name: "memory", audience: Audience::Screens(&["/projects/[slug]/memory", "/memory/dropped"]), source: ReadSource::Query(super::reads_work::memory), scope: None, }, ScreenRead { name: "memoryEntry", audience: Audience::Screens(&["/memory/[id]"]), source: ReadSource::Controller(super::reads_work::memory_record), scope: None, }, // There is no `read.codeContext` any more. It answered "which // repositories does this project name" for the two code screens, and the // Code tool (phase 4, Cotton note "The Code tool — why a Mac holds the sessions") made those screens // the QUEUE: the sessions, the launches, the Macs and the logins, which is // `read.sessions`' answer. A screen names exactly one read, and a screen // may be named by exactly one read // (`no_two_reads_share_a_name_or_a_screen`) — so the repositories moved // onto that answer's `projects` rows, parsed by the same `remotes_of` this // read used, and the read itself went with the directory it drew. ScreenRead { // THE QUEUE, and the three screens that draw it. `/code` is the ONE // list (Cotton note "The Code tool — why a Mac holds the sessions", *Screens*): the Macs strip, // the four sections, the cards. `/projects/[slug]/code` is that list // filtered to one project, and `/code/new` is the ONE form, which // needs the same Macs, agents and projects the list already carries. // // There is no `/sessions` list any more and no separate launch form: // two lists over the same rows were two opinions about which session // is waiting on the person, and five forms were five ways to ask the // same four questions. name: "sessions", audience: Audience::Screens(&["/code", "/code/new"]), source: ReadSource::Controller(super::reads_work::sessions), scope: None, }, ScreenRead { // WHAT A PROJECT'S SESSIONS HEADING OPENS: that project's sessions of // ALL TIME, newest first, a page at a time, with the same `total` the // heading shows. Not the queue: `/code` is what is happening this // week, and a project page's count is every session it ever held, so // a list cut to the week under a heading counting all of them said two // different numbers about one set. name: "projectSessions", audience: Audience::Screens(&["/projects/[slug]/code"]), source: ReadSource::Controller(super::reads_work::project_sessions), scope: None, }, ScreenRead { name: "session", audience: Audience::Screens(&["/sessions/[id]"]), source: ReadSource::Query(super::reads_work::session), scope: None, }, ScreenRead { name: "documents", audience: Audience::Screens(&["/documents", "/documents/import"]), source: ReadSource::Controller(super::reads_work::documents), scope: Some(Narrowing::After(&[list("documents", "document"), list("hits.documents", "document")])), }, ScreenRead { // A COMPOSITE, not the bare tool: `get_document` answers a document as // an ASSISTANT reads it, and the screen needs the vault's own columns // beside it — the date the paper is about, the period it covers, and // above all the OBJECT PATH the viewer reads from, which is the // unlocked rendition when one exists and the original otherwise. name: "document", audience: Audience::Screens(&["/documents/document/[id]"]), source: ReadSource::Controller(super::reads_work::document), scope: None, }, ScreenRead { name: "pages", audience: Audience::Screens(&["/reader"]), source: ReadSource::Query(super::reads_work::pages), scope: None, }, ScreenRead { name: "page", audience: Audience::Screens(&["/reader/page/[id]"]), source: ReadSource::Query(super::reads_work::page), scope: None, }, ScreenRead { name: "meetings", audience: Audience::Screens(&["/meetings"]), source: ReadSource::Controller(super::reads_work::meetings), scope: None, }, ScreenRead { name: "meeting", audience: Audience::Screens(&["/meetings/meeting/[id]"]), source: ReadSource::Controller(super::reads_work::meeting), scope: None, }, ScreenRead { // `/news` opens on the latest edition, which is this read with no id // — and, since 2026-09-21, carries the LIST of editions with it, so // the past ones sit under today's on the same page instead of behind // a `/news/editions` index nobody went looking for. name: "newsEdition", audience: Audience::Screens(&["/news", "/news/edition/[id]"]), source: ReadSource::Query(super::reads_work::news_edition), scope: None, }, ScreenRead { name: "newsTopics", audience: Audience::Screens(&["/news/topic/[id]", "/news/topic/new"]), source: ReadSource::Query(super::reads_work::news_topics), scope: None, }, ScreenRead { name: "newsSettings", audience: Audience::Screens(&["/news/settings"]), source: ReadSource::Query(super::reads_work::news_settings), scope: None, }, // gen-kind: reads];/// Every route that has no read YET, each with the sub-step that OWES it.////// **This list is the guard, not a to-do.** A route with neither a read, a line/// here, nor a line in [`READ_LESS`] fails/// [`every_screen_is_answered_or_deferred_by_name`], so a screen cannot be/// added and quietly left unreadable; and a sub-step landing its screens/// DELETES its lines from here, so the list shrinks to NOTHING rather than/// becoming furniture. It is written as pairs so a red run names the sub-step/// as well as the path.////// **A DEBT, never a decision.** Every line here is a read somebody still has/// to write. A route that is answered by nothing ON PURPOSE is a third state/// and belongs in [`READ_LESS`]: it is never going to be deleted from a list,/// so keeping it here would make "the deferral list shrinks to nothing" a/// sentence that could never come true, and would leave the two kinds of line/// indistinguishable at a glance./// **It is EMPTY, and that is the shape it was always meant to reach.** Its one/// remaining line was `/call/[id]`, the paused live-call screen — and a line/// that was never going to be closed was furniture wearing a debt's clothes,/// which is exactly what [`READ_LESS`] exists to hold instead. Live calling is/// not paused any more, it is deleted (schema 5), so the route went with it and/// the debt closed by subtraction. A new deferral goes here with the sub-step/// that owes it.pub static DEFERRED: &[(&str, &str)] = &[];/// Every route this app answers with NOTHING, on purpose — and what answers/// instead.////// **The third state.** A route is either read ([`READS`]), owed a read/// ([`DEFERRED`]) or answered by nothing at all, and the three are different/// facts about the same app. This list is the last of them, and it exists/// because the second list is supposed to shrink to nothing: a permanent line/// parked in `DEFERRED` is furniture wearing a debt's clothes, and it makes/// "the deferral list is empty" a thing that can never be said.////// A line here is a PROMISE that no read will ever be written for the route,/// so each one names what answers instead — a method family the app calls, the/// operating system, the lens, or nothing but the words on the screen. The/// totality test consumes this list beside `DEFERRED`, so the route is still/// named on every run and nobody comes looking for a read that should not/// exist.////// A route here that later GROWS a read is a `ScreenRead` and the deletion of/// its line, exactly as a deferral would be — the promise is revocable, it is/// just not a debt.pub static READ_LESS: &[(&str, &str)] = &[ ("/about", "installed bundle version/build and links; no database read"), ("/about/help", "reserved Help page; no text or database read yet"), ("/about/whats-new", "bundled release words; no database read"), // Settings › Bring in: the Files picker, then the share drain's own // branches (`CottonKit/ShareIntake`), which call `capture.media`, // `meetings.create` and `page.save` — the screen reads nothing. ("/bring-in", "the Files picker and the share drain's capture calls; no database read"), // Settings › Backup and Cotton server: shell screens over the personal // object's session (`Join/PersonalObject.swift`) — the sign-in sheet's // calls and `personal.*`; the device card they show once connected is // `device.facts`, read by the part itself. ("/backup", "the personal object's session and its personal.* calls; no screen read"), ("/server", "the manifest's server address and the session's stand; no database read"), // Settings › Export: the tables it lists are the window's own catalogue, // and `package.export` writes the file the share sheet is handed. ("/export", "the window's table catalogue and package.export; no screen read"), // The Code tool's other lists (Spec 9.3 (d), was Settings › Code): each a // table over the `code.*` methods its source calls (`SettingsTables.code`), // a page by its list's own row. // A definition create route enters an existing form. A visit never mints // an invite; the person's submission invokes the existing method. ("/members/admit", "read.members supplies canAdmit/admitReason; the existing invite flow calls databases.invite for the selected database and shares its returned link"), ("/code/defaults", "the code_default table's one page: the household's permission default, off the file, and this device's model"), // The Bin is a tool (Spec 9.3): its table's list, read through // `records.list`; Settings' count of it went with its row. ("/bin", "the bin table's list"), // A data tool of more than one table: its own board, a tile per table, // each read through `records.list` as Home's tiles are. ("/tools/board/[id]", "the data tool's tables' tiles — records.list per table, as Home's tiles"), // One of this device's host-drawn pages (a Mac's API keys, its sources): // the host's own model draws it, over methods only a host answers. ("/device/[page]", "the host's own page model (`HostSettingsSlot`), never a screen read"), // Money as data: shared TableListRoute/TablePageRoute call the generic verbs. ("/money", "the money_account table's list"), ("/money/accounts/[id]", "the money_account record's page"), ("/money/transactions/[id]", "the transaction record's page"), ("/money/statements/[id]", "the statement record's page"), // One table's list narrowed by a link on a list or a page: the shared // list over the generic verbs, its `where` carried in the path. ( "/lists/[table]", "one table's list narrowed by a where — records.list/records.total through the generic verbs", ), // One record of a table no named route addresses (a data tool's row, an // alarm, the database's own record): the shared page over the generic verbs. ( "/lists/[table]/[id]", "one record's page — records.get through the generic verbs, or the Settings source that holds its table", ), // The Camera tool's capture surface: a live camera, which writes through // `camera.shot` and reads nothing. ( "/camera", "the Camera tool's live capture surface — every shot is a camera.shot write; it reads nothing", ), // The capture deep link resolves straight through and draws nothing of its // own (4d). ( "/capture", "an instruction the navigator turns into capture mode on Home; it draws nothing of its own", ), // The Videos tool: the video table's own list, read as every table's list // is (`records.list` on `video`), its albums through `groups.list`. ( "/videos", "the video table's list — records.list answers it as it answers every table's list, \ and groups.list its albums counted in films", ), // The chat import (lane N). What the screen shows is the answer of the job // it ran over a file the person picked — `import.whatsappExport` — and // the thread it opens afterwards has its own read. // A Cotton chat started (Messages' Plus): a number typed or a person // found by name, answered by `chat.start`, which opens the thread. ( "/messages/new", "chat.start — the screen takes a number or finds a person by records.list on person, \ and opens the thread chat.start answers; nothing on it is a row until then", ), ( "/messages/import", "import.whatsappExport — the screen runs the import over a file the person \ picked or shared, and shows what the verb answered; nothing on it is a row \ in this file until the thread it opens", ), // The recorder: the meetings list with the recorder sheet over it. The // sheet holds the microphone, not a query: everything on it — the title // being typed, the elapsed stamp, the live meter — is device state that // exists only while it is up, and the one thing it produces is a // `meetings.create` call at Stop. The list under it is the meeting table's // own list; a read here would have nothing more in the file to answer from. ( "/meetings/record", "nothing in the file — the recorder sheet over the meetings list is the \ device's microphone and its own elapsed clock, and `meetings.create` at \ Stop is what writes the row whose page it then opens", ), // One device asking to join, drawn from the PENDING LIST rather than from // this person's database: the registry is `registry.db` on the server and // is deliberately never in the workspace, so there is nothing in the file // for a read to answer from. The push carries the pairing id, the screen // asks `devices.pending` for the row, and `devices.approvePending` / // `devices.declinePending` are the two verbs on it. ( "/settings/join-request/[id]", "devices.pending — the waiting request lives in the server's registry, never in \ this person's database, and the screen picks its row out of that list by \ pairing id", ), // The writes this device parked rather than folded. `sync.rejected` is a // METHOD, not a read, and stays one: the rows are in `_parked`, a // DEVICE-LOCAL table that never syncs, so what the screen draws is this // device's own diagnosis rather than anything in the person's database. ( "/rejected", "sync.rejected — the parked writes live in this device's own `_parked` \ table, which never syncs, and `sync.retryRejected` is the one verb on the \ screen", ), // A voice word's PAGE (Spec 9.3, the Voice words tool): its row is the list's own. ( "/voice-words/[id]", "read.voiceVocabulary for the row — the list's own read, asked by name; the page owns none", ), // A member's PAGE (Spec 9.3): its row is the Members list's own. ( "/members/[id]", "read.members for the row — the list's own read, asked by name; the page owns none", ), // One line of the Storage tool's page (Spec 9.3, was Settings › Storage // and Free up space): the list's own read, asked by name. ( "/storage/[id]", "read.storage for the row — the list's own read, asked by name; the page owns none", ), // A session's terminal, pushed from its page: the pane streams over // `terminal.*` (attach, write, resize, detach) and the bytes arrive as // events, so there is nothing to read. ( "/sessions/[id]/terminal", "the terminal streams over terminal.* — attach, write, resize, detach; no read", ), // The legal pages (4h): read nothing but their own words. ("/legal/privacy", "static text, and nothing else"), ("/legal/terms", "static text, same as /legal/privacy"),];/// The read this method name asks for, or nothing.pub fn read_for(method: &str) -> Option<&'static ScreenRead> { let name = method.strip_prefix("read.")?; READS.iter().find(|entry| entry.name == name)}/// Every `read.*` method THIS build answers, for the method table.pub fn method_names() -> Vec<String> { READS .iter() .map(|entry| format!("read.{}", entry.name)) .collect()}#[cfg(test)]#[path = "reads_tests.rs"]mod tests;// The 4d reads' own suite, against a seeded synthetic replica. A sibling file// rather than a block here for the reason `reads_tests.rs` is one: the table// and the queries are what a reader comes to this file for, and a fixture is// not.// `pub(crate)` for its `workspace` helper alone: 4k's `activity_tests.rs` needs// a seeded synthetic replica behind a controller whose clock does not move, and// that assembly lives here. One place a fixture phone is built, rather than a// second copy of fifty lines that could come to disagree with this one about// what a replica looks like.#[cfg(test)]#[path = "reads_home_tests.rs"]pub(crate) mod home_tests;// ── The queries no single tool answers ────────────────────────────────────/// Who this phone belongs to, read off the FILES and nothing else.////// Every field is a FACT about this device, never a screen's decision: the app/// decides what to paint. A read that answered "show the pairing screen" would/// be this core deciding a route, and P6 keeps routing in Swift.////// **It does not open the replica, and that is the whole of this read's/// design.** It used to: it asked [`ClientController::sync_status`], which/// `attach`es — a SQLite open, and after a force-quit an open that pays the/// whole write-ahead log's recovery, on a boundary that answers one call at a/// time. Above it, `BootModel` read it under a five-second ceiling and, past/// the ceiling, decided with what it had: "nobody is here" — the Join screen,/// on a phone whose `connection.json` was sitting right there naming an/// approved server. That is the bug this whole pass is about, and no amount of/// ceiling-raising fixes it: a clock cannot answer "has this phone joined".////// So the split is by SOURCE rather than by convenience. `paired`, the/// identity, the address and the standing refusal are `connection.json` and/// `refusal.json` — two small reads that cannot block — and whether the file/// is OPEN is `read.syncStatus`, which the app asks separately and waits for/// as long as it takes, with the splash and a sentence up.////// **An unreadable `connection.json` is an ERROR here**, not a `paired:false`./// `read_connection`'s own rule, and this is the caller it was written for.fn boot(client: &ClientController, _args: &Map<String, Value>) -> Result<Value, String> { // CACHE ONLY, never the network and never the replica. A phone with no // server has to reach Join in one frame, and a phone WITH one has to leave // Join in one frame — both are the same question asked of the same file. let joined = client.joined_workspace()?; let refusal = client.standing_refusal(); // The gate's own order, ported from `replicaGateStage.ts`. A device // REFUSAL paints first — ahead of signed-out — because the sentence saying // why has to outlive everything under it. let stage = if refusal.is_some() { "refused" } else if !joined { // No server. Join renders straight through, wrapped in the resting // sync context — never a bare tree. "pairing" } else { // A server, and this read says nothing about whether the file is open: // `ready` and `bootstrap` are the OPEN's two words and they are // `read.syncStatus`'s `connected` to answer. A stage that named one // here would be this read attaching again. "joined" }; // Who is here, where their file is, and which server holds it — all off // the cache the join wrote, so a refusal screen can name the server and // pre-fill the Join form without a round trip. let cached = client.cached_identity()?; Ok(json!({ // Has this phone joined a server at all? Everything else is downstream // of it, which is why it is first here as it is first in the gate. "paired": joined, "flavor": cotton_core::flavor::current().map(|flavor| flavor.as_str()), "single_database": cotton_core::flavor::single_database(), "manifest": if cotton_core::flavor::single_database() { cotton_core::flavor::business_manifest().ok().map(|manifest|manifest.for_clients()) } else { None }, // `null` is "nobody is here", which is the gate's `signed-out`. "ownerId": cached.get("ownerId").cloned().unwrap_or(Value::Null), "workspaceId": cached.get("workspaceId").cloned().unwrap_or(Value::Null), "serverUrl": cached.get("serverUrl").cloned().unwrap_or(Value::Null), "serverName": cached.get("serverName").cloned().unwrap_or(Value::Null), // `null` when nothing stands. A screen keys on `refusal.code` and // pre-fills the Join form with `refusal.serverUrl`. "refusal": refusal, // What the app should hold still for, said as a name rather than as a // route: 4b's Swift maps these to screens, and this core names no // screen. "stage": stage, }))}/// Where the sync loop is, as the banner, the settings row and the BOOT GATE/// read it.////// Answered through the controller rather than the replica so it works on a/// phone that has never paired: "not connected, and here is why" is the first/// thing the settings row has to be able to draw.////// **`connected` is also the gate's "is there a file?"** — the other half of/// the boot read, asked separately because this one attaches and `read.boot`/// must not. It is the same fact for both readers rather than a second opinion/// about it, which is why the gate asks this read rather than growing a/// private one.fn sync_status(client: &ClientController, _args: &Map<String, Value>) -> Result<Value, String> { Ok(client.sync_status())}// ── 4d: Home, the two decision queues, the strip and the mic ──────────────//// WHY SO MUCH SQL HERE, and so few `read_tool` calls. P4's rule is "where a// screen's query IS a tool's list, CALL THE HANDLER" — and Home's figures are// not lists. Every `list_*` tool in the catalogue is written for an assistant:// it PAGES (`bounded_limit`, 50 by default and 100 or 500 at the ceiling) and// it shapes each row for reading. Counting the rows of a capped page would// answer "50" for a workspace with four hundred todos and never say so, which// is precisely the silent wrong answer this repo bans. So a FIGURE is a query// written here, and a LIST the screen actually draws is the tool's. Each// function below names the tool it was weighed against.//// The DECISIONS, though, are never restated: `asked_rows`,// `select_today_band`, `unread_count`,// `project_last_activity` and `project_order` are cotton-core's, called with// rows read here. cotton-core is pure; all SQL lives in this crate./// The instant a 4d read bands by, floored to the minute.////// `now` may be NAMED in the args — the phone stands where its owner does and/// hands its own wall clock down when it wants the band to agree with the/// clock on the screen — and otherwise it is the CONTROLLER's own clock seam/// ([`ClientController::now_iso`]). Never `Utc::now()` inside a read: the seam/// is the thing a test replaces.////// Flooring is `minuteFloor`'s (`tools/me/lib/memoryScope.ts`): due-ness moves/// once a minute at most, so a second-resolution instant buys no accuracy and/// costs every memo downstream a fresh value per frame.fn banding_instant( client: &ClientController, args: &Map<String, Value>,) -> Result<(i64, String), String> { let named = args.get("now").and_then(Value::as_str); let iso = match named { Some(iso) => iso.to_string(), None => client.now_iso(), }; let at = parse_date_ms(&iso).ok_or_else(|| format!("`now` is not an ISO instant: {iso}"))?; let floored = at - at.rem_euclid(60_000); let floored_iso = to_iso_string(floored) .ok_or_else(|| format!("{floored} is not an instant a calendar can read"))?; Ok((floored, floored_iso))}/// How long an IDLE session still counts as one the person has open.////// AN HOUR. An agent sitting at its prompt with nothing to do is a session/// somebody is in the middle of; one that has said nothing since this morning/// is a tab they forgot. `CodeFacts.bands` cuts the sections on `/code` at the/// same hour, and the figure on Home and those sections must agree.pub const IDLE_STILL_OPEN_MS: i64 = 60 * 60 * 1000;fn param(value: &str) -> SqlValue { SqlValue::Text(value.to_string())}fn rows_of(db: &Driver, sql: &str, params: &[SqlValue]) -> Result<Vec<Row>, String> { db.all(sql, params).map_err(|error| format!("{error}; query: {sql}"))}/// One `SELECT count(*) AS n …`. Never a `len()` over a tool's page.fn count_of(db: &Driver, sql: &str, params: &[SqlValue]) -> Result<i64, String> { Ok(rows_of(db, sql, params)? .first() .and_then(|row| row.int("n")) .unwrap_or(0))}fn owned(row: &Row, column: &str) -> Option<String> { row.text(column).map(str::to_string)}fn required(row: &Row, column: &str) -> Result<String, String> { owned(row, column).ok_or_else(|| format!("a row answered no {column}"))}fn or_null(value: Option<String>) -> Value { value.map_or(Value::Null, Value::from)}// The WORKSPACE's zone (`cotton_news_settings.timezone`, which cotton-tools// reads as `workspace_timezone_or_null`) is deliberately not read here at all.// It is the SERVER's answer to "which day is it" for a workspace nobody is// holding; a phone is always being held by somebody standing somewhere, and// that somewhere is the answer — see [`reading_zone`]./// The zone a READER bands in: THE DEVICE'S, handed down at open.////// The same zone the WRITER stamps with, from the same place. Every day/// boundary the app draws is the device's calendar day — `deviceTimezone()` in/// the TypeScript, used by BOTH halves (`tools/mood/lib/zone.ts` and/// `tools/accounts/lib/day.ts`) — so a check-in tapped at 00:30 IST is written/// to today and read back as today. When the reader took the WORKSPACE's zone/// (or UTC when it had none) and the writer took the phone's, that row was/// stamped tomorrow and filtered out of "Today": the row you just tapped/// vanished.////// **No UTC fallback.** A reader that has no zone refuses, exactly as/// `record_mood`'s `writer_zone` refuses, because a fortnight silently drawn in/// the wrong zone is a screen full of wrong days that says nothing about it./// The workspace's own zone is deliberately NOT consulted: the app never/// consults it either, and a second source for one answer is the drift this/// whole table exists to refuse.fn reading_zone(client: &ClientController) -> Result<String, String> { client.time_zone().map(str::to_string).ok_or_else(|| { "This phone did not say which timezone it is standing in, and a day cannot be guessed — \ a check-in, a journal page and every \"today\" on Home are its own calendar day." .to_string() })}// ── the memory row on Home ─────────────────────────────────────────────/// How many memory rows this build could not read. Memory has no review/// state (the owner, 25 Oct 2026): a sentence a session writes is simply/// live, so Home counts no band of it — only the rows a file ahead of this/// binary holds that it cannot name.////// **An unreadable row is SKIPPED and COUNTED, never fatal.** The file syncs/// from a server that may already run a newer schema, so the day a new status,/// visibility or origin ships, an older install would otherwise lose the WHOLE/// of Home to one row it cannot name — for a file that is/// otherwise perfectly fine. `memories.service.ts` names that exact failure and/// refuses it in the same words ("Never silent, never fatal"), and the count/// travels in the answer as `unreadable` so the surface can say so.fn unreadable_memories(db: &Driver, workspace_id: &str) -> Result<usize, String> { let found = rows_of( db, "SELECT status, visibility, origin_kind, COUNT(*) AS n \ FROM cotton_memories WHERE workspace_id = ? GROUP BY status, visibility, origin_kind", &[param(workspace_id)], )?; let mut unreadable = 0usize; for row in &found { let status_text = required(row, "status")?; let origin_text = required(row, "origin_kind")?; let visibility_text = required(row, "visibility")?; // Skipped rather than defaulted, and never guessed. All three columns // carry a CHECK, so a value none of the enums knows is a row from a // later schema. if MemoryStatus::parse(&status_text).is_none() || MemoryOriginKind::parse(&origin_text).is_none() || MemoryVisibility::parse(&visibility_text).is_none() { unreadable += row.int("n").unwrap_or(0).max(0) as usize; } } Ok(unreadable)}/// The Tools directory: the database's tools, alphabetical by name (the fan's/// order in every database, always — owner, 17 Oct 2026), each with/// whether it holds a record, whether Remove is offered (always: every tool is/// a package record, and removing one leaves its tables and data — 72nd/// amendment) and whether its tile is on Home, and the kit tools Add tool may/// bring here.fn home_figure(client: &ClientController, args: &Map<String, Value>) -> Result<Value, String> { let part = args.get("part").filter(|part| part.is_object()).ok_or("homeFigure takes the figure part as {part}")?; let key = match args.get("today").and_then(Value::as_str) { Some(day) => day.to_string(), None => { let zone = match args.get("timezone").and_then(Value::as_str) { Some(zone) => zone.to_string(), None => reading_zone(client).map_err(|error| format!("read.homeFigure.reading_zone: {error}"))?, }; cotton_core::transforms::zoned_clock::local_day_key(client.clock().now().timestamp_millis(), &zone) .map_err(|_| "timezone is a named time zone".to_string())? } }; let today = chrono::NaiveDate::parse_from_str(&key, "%Y-%m-%d").map_err(|_| "today is a day, YYYY-MM-DD".to_string())?; let line = client .with_file(|replica| cotton_tools::tool_figures::part_line(replica.driver, replica.workspace_id, part, today).map_err(|failure| failure.to_string())) .map_err(|error| format!("read.homeFigure: {error}"))?; Ok(json!({ "line": line, "today": key }))}fn tool_order(client: &ClientController, _args: &Map<String, Value>) -> Result<Value, String> { let personal = personal_database(client)?; client.with_file(|replica| { let personal = personal.as_deref() == Some(replica.workspace_id); let saved = home_arrangement(replica.driver, replica.workspace_id)?; let home = database_home(replica.driver, replica.workspace_id, saved.as_ref(), personal)?; let mut tools = Vec::with_capacity(home.tools.len()); for key in &home.tools { let holds = cotton_tools::home_arrangement::holds_records(replica.driver, replica.workspace_id, key)?; let on_home = home.shows(&cotton_core::rules::home_arrangement::tool_view(key)); tools.push(json!({ "key": key, "holds": holds, "removable": true, "onHome": on_home })); } // What add_tool would take: a kit tool not here. let addable: Vec<&str> = cotton_core::kit::ids().into_iter().filter(|id| !home.tools.iter().any(|tool| tool == id)).collect(); Ok(json!({ "projectSlugs": saved.map(|row| row.project_slugs).unwrap_or_default(), "tools": tools, "addable": addable, "viewIds": home.views, })) })}// ── Home ──────────────────────────────────────────────────────────────────/// Everything Home draws, as ONE answer.////// Home is a GLANCE (spec §D1): the queue of things only the owner can settle,/// the memory row, the projects band, the fifteen tool figures, who this is,/// and where the sync loop got to. Everything the FILE answers is read in a/// single pass under ONE lock ([`home_answer`]), because fifteen round trips is/// fifteen chances to paint a screen that is half yesterday's — the same/// reason [`boot`] is one call rather than four. The sync banner is the one/// fact that is not the file's: it is asked first, of the controller, and it/// takes the replica lock of its own before the pass does.////// **The person's own order of Home is applied HERE and nowhere in Swift.** The/// `cotton_home_arrangement` row is read once ([`home_arrangement`]) and both/// grids come out arranged: `projects` is already in the order the person left/// it, and the `arrangement` block carries the tool grid, whose default the app/// cannot compute from this answer alone. The rules live in one place/// (`cotton_core::rules::home_arrangement`), so the phone and the Mac cannot/// come to hold two opinions about one drag.////// **`aiAccess` is deliberately absent from `askedOfYou.rows`.** It is a CLIENT/// flag — a Jotai atom, session-only, never persisted, meaning "the gate/// refused routing THIS session" — so it has no row in anybody's file and this/// read must not invent one. The engine is therefore called with/// `ai_access_needed: false`, and the Swift model APPENDS that row itself when/// the flag is set; that is correct rather than a shortcut, because `aiAccess`/// is LAST in `ASKED_KEYS` and a row appended to a band-ordered list is/// still in band order. **`joinRequests` is absent for the same kind of/// reason**: a person asking to join waits in a serving Mac's registry, not in/// this file, and Home never waits on a Mac — the Swift model asks each Mac/// the person admits people at and PREPENDS that row (it is FIRST).fn home(client: &ClientController, args: &Map<String, Value>) -> Result<Value, String> { let (now_ms, now) = banding_instant(client, args).map_err(|error| format!("read.home.banding_instant: {error}"))?; let zone = reading_zone(client).map_err(|error| format!("read.home.reading_zone: {error}"))?; // The banner is the controller's own answer and never the file's — it is // what a phone with no replica has to be able to draw. This read is not // that phone's, though: `home_answer` opens the replica below and an // unpaired phone gets the refusal every read gets. The BOOT gate is the // screen that stands in front of this one. let sync = client.sync_status(); let personal = personal_database(client).map_err(|error| format!("read.home.personal_database: {error}"))?; // THIS DEVICE'S OWN RECEIPTS, off its connection record: each database it // was removed from, said once on the Personal database's Home. let removed: Vec<DoneAct> = client .removed_copies() .iter() .map(|copy| removed_from_act(©.database_id, ©.name, copy.removed_by.as_deref(), ©.removed_at)) .collect(); let mut answer = client.with_file(|replica| { let personal = personal.as_deref() == Some(replica.workspace_id); let local: &[DoneAct] = if personal { &removed } else { &[] }; home_answer(replica, &now, now_ms, &zone, personal, local) }).map_err(|error| format!("read.home.open/read: {error}"))?; if let Value::Object(fields) = &mut answer { fields.insert("sync".to_string(), sync); } Ok(answer)}/// The person's own database's id, as the device holds it: the one Home/// draws the person's tools on by default (`PERSON_TOOL_KEYS`). `None` before/// the device holds any.pub(crate) fn personal_database(client: &ClientController) -> Result<Option<String>, String> { Ok(client.databases()?.into_iter().find(|held| held.personal).map(|held| held.id))}/// What waits on the owner in one database, as Home's "Asked of you" counts/// it.struct Asked { rows: Vec<AskedRow>,}const HOME_NOTES: &str = "SELECT count(*) AS n FROM cotton_notes INDEXED BY idx_cotton_notes_home WHERE workspace_id = ? AND kind = 'note' AND managed_by IS NULL AND archived_at IS NULL AND trashed_at IS NULL";const HOME_TODOS: &str = "SELECT count(*) AS n FROM cotton_todos INDEXED BY idx_cotton_todos_open WHERE workspace_id = ? AND status = 'open' AND trashed_at IS NULL";const HOME_JOURNAL: &str = "SELECT body FROM cotton_notes WHERE workspace_id = ? AND journal_date = ? AND kind = 'journal' AND project_id IS NULL AND archived_at IS NULL AND trashed_at IS NULL";fn asked( now: &str, occurrences: &[(BandOccurrence, Option<String>, bool)], counts: &Value,) -> Result<Asked, String> { let events: Vec<DecidableEvent> = occurrences .iter() .map(|(occurrence, my_response, organizer_is_self)| DecidableEvent { starts_at: occurrence.starts_at.clone(), my_response: my_response.clone(), organizer_is_self: *organizer_is_self, }) .collect(); let locked_documents = counts .get("lockedDocuments") .and_then(Value::as_u64) .map_or(0, |n| usize::try_from(n).unwrap_or(usize::MAX)); let rows = asked_rows(&AskedInput { events: &events, locked_documents, ai_access_needed: false, // The waiting requests are each serving Mac's, not this file's: the // app asks the Macs and counts them itself (`asked_of_you`). join_requests: 0, now, }); Ok(Asked { rows })}fn home_answer( replica: &ReadFile<'_>, now: &str, now_ms: i64, zone: &str, personal: bool, local_done: &[DoneAct],) -> Result<Value, String> { let db = replica.driver; let workspace_id = replica.workspace_id; let unreadable_memories = unreadable_memories(db, workspace_id).map_err(|error| format!("read.home.unreadable_memories: {error}"))?; let occurrences = event_occurrences(db, now_ms).map_err(|error| format!("read.home.event_occurrences: {error}"))?; let counts = tool_counts(db, workspace_id, now, now_ms, zone, &occurrences).map_err(|error| format!("read.home.tool_counts: {error}"))?; let Asked { rows } = asked(now, &occurrences, &counts).map_err(|error| format!("read.home.asked: {error}"))?; let total = asked_total(&rows); let mut asked_rows_out: Vec<Value> = rows .iter() .map(|row| json!({ "key": row.key.as_str(), "count": row.count })) .collect(); // Read ONCE, and hand to both readers of it: the band below and the tool // grid in the answer. A file with no row is a person who has never // arranged, which reads as the default order everywhere. let arrangement = home_arrangement(db, workspace_id).map_err(|error| format!("read.home.home_arrangement: {error}"))?; let (projects, facts_missing) = projects_band(db, workspace_id, arrangement.as_ref()).map_err(|error| format!("read.home.projects_band: {error}"))?; let home = database_home(db, workspace_id, arrangement.as_ref(), personal).map_err(|error| format!("read.home.database_home: {error}"))?; let done_for_you = done_for_you(db, workspace_id, now, local_done).map_err(|error| format!("read.home.done_for_you: {error}"))?; let workspace = rows_of( db, // The city is the Me person's (one city, on the Me card): the owner // the workspace names, while that person is present. "SELECT w.id, w.name, p.city AS city_name FROM cotton_workspaces w LEFT JOIN cotton_people p ON p.id = w.owner_person_id AND p.archived_at IS NULL WHERE w.id = ?", &[param(workspace_id)], )? .into_iter() .next() .map_or_else( || json!({ "id": workspace_id, "name": Value::Null, "cityName": Value::Null }), |row| { json!({ "id": owned(&row, "id").unwrap_or_else(|| workspace_id.to_string()), "name": or_null(owned(&row, "name")), "cityName": or_null(owned(&row, "city_name")), }) }, ); Ok(json!({ "askedOfYou": { "rows": asked_rows_out, "total": total, }, // What Cotton did by itself, newest first — never a count, never a // badge: nothing on it waits on the owner. Each row carries its one // action; the tool that performs it is the app's to call. "doneForYou": done_for_you, // How many memory rows this build could not read at all. Zero is the // ordinary answer; anything else is a file ahead of the binary, and the // figure is here rather than swallowed because a queue that quietly // shortened itself would be the worse failure. "unreadableMemories": unreadable_memories, "projects": projects, "projectFactsMissing": facts_missing, // Home's tiles and the database's tools (`arrangement_answer`). "arrangement": arrangement_answer(arrangement.is_some(), &home), // Every figure a tool's tile names (`tool.figures` in its definition) // reads from here. "counts": with_worked_figures(counts, db, workspace_id, now_ms, zone), "workspace": workspace, // 4k's cross-lane addition to 4d's read. The design's sentence is // "Working on 2 · Researching X · 12 min" → /activity, and the figure // and the task under it are `crate::phone::activity`'s — the SAME // function `/activity` draws its own header from, so Home and the // screen it opens cannot come to hold two opinions about how many runs // are in flight. Never absent: `count: 0` with both `oldest*` null is // the empty answer, because every other figure here is // present-or-null and the Swift decoder is written for that. // // The AGE in words is not here. "12 min" is a formatter and // `CottonUI/Format/DateFormats.swift` already owns it; Rust answers the // instant. "workingOn": crate::phone::activity::working_on(db, workspace_id).map_err(|error| format!("read.home.working_on: {error}"))?, }))}/// Done for you, read: the three kinds of act `done_for_you` orders.////// Each query is capped and newest-first on its own, so the merge below never/// reads a whole table; the engine keeps the window and the final limit.////// - A FILING is a thought the router stamped `routed` with a record kind. A/// thought that stayed a thought (`routed`, no kind) and a question the/// router asked (`assistant_run`) are not filings. `updated_at` is the/// filing's instant: the stamp is the last write a filed thought gets, and/// the table has no column of its own for it./// - A REMEMBERED entry is an active one an assistant wrote. The owner's own/// entries are his act, not Cotton's./// - A document that COULD NOT BE READ is `failed`, at the instant it failed./// A locked one is a question, and is Asked of you instead./// - A CITY FILL is one pass of `people.fillCities`, at its stamp, listing the/// people whose city is still the one their zone named.////// `local` are this device's own receipts, read off no file (a removal of/// this device from a shared database), ranked with the file's.fn done_for_you(db: &Driver, workspace_id: &str, now: &str, local: &[DoneAct]) -> Result<Vec<Value>, String> { let cap = DONE_FOR_YOU_LIMIT.to_string(); let mut acts = local.to_vec(); for row in rows_of( db, &format!( "SELECT id, raw_text, transcript, routed_kind, updated_at FROM cotton_inbox_items \ WHERE workspace_id = ? AND route_status = 'routed' \ AND routed_kind IS NOT NULL AND routed_kind <> 'assistant_run' \ ORDER BY updated_at DESC, id ASC LIMIT {cap}" ), &[param(workspace_id)], )? { acts.push(DoneAct { kind: DoneKind::Filed, id: owned(&row, "id").unwrap_or_default(), text: owned(&row, "raw_text") .or_else(|| owned(&row, "transcript")) .unwrap_or_default(), filed_as: owned(&row, "routed_kind"), at: owned(&row, "updated_at").unwrap_or_default(), count: 1, opens: None, by: None, listed: Vec::new(), }); } for row in rows_of( db, &format!( "SELECT id, title, created_at FROM cotton_memories \ WHERE workspace_id = ? AND origin_kind = 'agent' AND status = 'active' \ ORDER BY created_at DESC, id ASC LIMIT {cap}" ), &[param(workspace_id)], )? { acts.push(DoneAct { kind: DoneKind::Remembered, id: owned(&row, "id").unwrap_or_default(), text: owned(&row, "title").unwrap_or_default(), filed_as: None, at: owned(&row, "created_at").unwrap_or_default(), count: 1, opens: None, by: None, listed: Vec::new(), }); } for row in rows_of( db, &format!( "SELECT id, title, original_name, status_changed_at FROM cotton_documents \ WHERE workspace_id = ? AND status = 'failed' AND trashed_at IS NULL \ ORDER BY status_changed_at DESC, id ASC LIMIT {cap}" ), &[param(workspace_id)], )? { acts.push(DoneAct { kind: DoneKind::CouldNotRead, id: owned(&row, "id").unwrap_or_default(), text: owned(&row, "title") .filter(|title| !title.trim().is_empty()) .or_else(|| owned(&row, "original_name")) .unwrap_or_default(), filed_as: None, at: owned(&row, "status_changed_at").unwrap_or_default(), count: 1, opens: None, by: None, listed: Vec::new(), }); } // The newest passes by their own stamp (one format, written by one writer), // then each pass's people whose city still stands — the undo's own question. let mut fills = Vec::new(); for row in rows_of( db, &format!( "SELECT DISTINCT city_filled_at FROM cotton_people \ WHERE workspace_id = ? AND city_filled_at IS NOT NULL \ ORDER BY city_filled_at DESC LIMIT {cap}" ), &[param(workspace_id)], )? { let Some(at) = owned(&row, "city_filled_at") else { continue }; for (person_id, name, city) in crate::phone::people_city::still_filled(db, workspace_id, &at)? { fills.push(CityFill { person_id, name, city, at: at.clone() }); } } acts.extend(city_fill_acts(&fills)); // The junk classifier, a day a row: the senders it filed into Junk that // day and still stands behind (a Keep since makes the owner the decider). // The whole set: every sender folds into its day's one row, and // `done_rows` bounds what the screen shows — a page would drop senders // from a day's count. let mut days: Vec<(String, String, Vec<String>)> = Vec::new(); for row in rows_of( db, "SELECT address, decided_at FROM cotton_email_senders \ WHERE workspace_id = ? AND decided_by = 'assistant' AND verdict = 'junk' \ AND decided_at IS NOT NULL \ ORDER BY decided_at DESC, address ASC", &[param(workspace_id)], )? { let (Some(address), Some(at)) = (owned(&row, "address"), owned(&row, "decided_at")) else { continue }; let day: String = at.chars().take(10).collect(); match days.iter_mut().find(|(seen, _, _)| *seen == day) { Some((_, _, addresses)) => addresses.push(address), None => days.push((day, at, vec![address])), } } acts.extend(days.iter().map(|(day, at, addresses)| junk_day_act(day, at, addresses))); let lines = cotton_tools::presentation::line_rows(db, workspace_id); Ok(done_rows(&acts, now, DONE_FOR_YOU_LIMIT) .iter() .map(|act| { json!({ "kind": act.kind.as_str(), "id": act.id, "label": done_label(act, &lines), "text": done_text(act, &lines), "at": act.at, "action": done_action(act.kind).as_str(), "path": done_path(act), }) }) .collect())}/// Today's occurrences, the response the owner has (or has not) given, and/// whether the owner organizes it (an invite is someone else's).////// **A stored event row, not an expanded occurrence.** `useTodayOccurrences`/// expands recurrence in the app; the RRULE expansion is 4e's, and calling a/// half-ported one here would be a second answer to "when does this repeat"./// Said out loud rather than hidden: a recurring event whose FIRST instance is/// behind `now` does not count as an invitation to answer until 4e lands, and/// nothing here pretends otherwise. Weighed against `list_events`, which pages/// and shapes rows for an assistant rather than answering "what is left of/// today".// Every event of this database — an event is the database's, never reached// through a calendar (the object keeps none) — by its date window, then the// unanswered invitations outside it. The explicit paths keep each half on// its own index on a fresh copy with no statistics.fn home_events_sql() -> &'static str { "SELECT e.id AS id, e.starts_at AS starts_at, e.ends_at AS ends_at, e.all_day AS all_day, e.my_response AS my_response, e.organizer_is_self AS organizer_is_self FROM cotton_events e INDEXED BY idx_cotton_events_range WHERE e.trashed_at IS NULL AND e.starts_at >= ?1 AND e.starts_at < ?2 UNION ALL SELECT e.id, e.starts_at, e.ends_at, e.all_day, e.my_response, e.organizer_is_self FROM cotton_events e INDEXED BY idx_cotton_events_invites WHERE e.trashed_at IS NULL AND e.my_response = 'needs_action' AND e.organizer_is_self = 0 AND NOT (e.starts_at >= ?1 AND e.starts_at < ?2)"}fn event_occurrences( db: &Driver, now_ms: i64,) -> Result<Vec<(BandOccurrence, Option<String>, bool)>, String> { // A coarse UTC window includes today's start in every IANA zone and // every stored offset. The existing engine still makes the exact cut. // Unanswered invitations remain available regardless of their date. let lower = to_iso_string(now_ms.saturating_sub(3 * 86_400_000)).ok_or("the event window starts outside the calendar")?; let upper = to_iso_string(now_ms.saturating_add(4 * 86_400_000)).ok_or("the event window ends outside the calendar")?; let sql = home_events_sql(); let found = rows_of(db, sql, &[param(&lower[..10]), param(&upper[..10])])?; Ok(found .iter() .filter_map(|row| { let starts_at = owned(row, "starts_at")?; Some(( BandOccurrence { id: owned(row, "id").unwrap_or_default(), all_day: row.int("all_day").unwrap_or(0) != 0, starts_at, ends_at: owned(row, "ends_at"), }, owned(row, "my_response"), row.int("organizer_is_self").unwrap_or(1) != 0, )) }) .collect())}// ── the projects band ─────────────────────────────────────────────────────/// One project as the band orders it.struct BandProject { id: String, name: String, slug: String,}impl OrderedProject for BandProject { fn id(&self) -> &str { &self.id } fn name(&self) -> &str { &self.name }}impl ArrangedProject for BandProject { fn slug(&self) -> &str { &self.slug }}// Home's arrangement is read where the MCP writer reads it too// (`cotton_tools::home_arrangement`), so the phone and an assistant start from one answer.pub(super) use cotton_tools::home_arrangement::{home as database_home, stored as home_arrangement};/// Home's arrangement as `read.home` answers it.////// `manual` says whether a row exists at all. `tiles` is Home in the order it/// is drawn — alphabetical by the name each tile is drawn with, in every/// database, always (owner, 17 Oct 2026; the core sorts with ICU root/// collation, as the app's localized compare does) — each a view (`tool/<key>`, `ready/today`, `chart/mood`,/// `<table>/<groupId>`, `ready/everything`) with the tool whose picture it/// wears, its own name (null for a tool's list and Everything), the path it/// opens (null: its tool, or its group's list), the table whose list it/// opens for a table of a tool with several (`<tool>/<table>`; null for/// every other view) and `empty` when it has/// nothing to show, drawn faint in its place (owner's ruling, 12 Oct 2026)./// `viewIds` is the same tiles — membership, what Add a tile and Remove start/// from — and `tools` is the database's tools, alphabetical too. `offers`/// is what "Add a tile" offers: tools not already represented on Home,/// plus missing project sections and Everything, in catalogue order/// (`cotton_tools::home_arrangement::offers`).pub(super) fn arrangement_answer(manual: bool, home: &cotton_tools::home_arrangement::Home) -> Value { let view = |view: &str| home.view(view); let tiles: Vec<Value> = home .tiles .iter() .map(|tile| { let known = view(&tile.id); json!({ "id": tile.id, "empty": tile.empty, "tool": known.and_then(|known| known.tool.clone()), "name": known.and_then(|known| known.name.clone()), "opens": known.and_then(|known| known.opens.clone()), "table": known.and_then(|known| known.table.clone()), }) }) .collect(); let offers: Vec<Value> = cotton_tools::home_arrangement::offers(home) .into_iter() .map(|offer| json!({ "view": offer.view, "tool": offer.tool, "name": offer.name, "opens": offer.opens, "table": offer.table })) .collect(); json!({ "manual": manual, "tiles": tiles, "viewIds": home.views, "tools": home.tools, "offers": offers })}/// The ACTIVE projects, in THE order (`project_order`) and then the person's/// own ([`arrange_projects`]), and whether the activity facts could be read at/// all.////// Weighed against `list_projects`, which is the tool the `/projects` screen/// reads — and refused for THIS band, because it answers no last-activity at/// all: the band exists to order by activity, and `list_projects` would leave/// it with nothing to order by.////// **A failed FACTS read is not a failed PROJECTS read.** The app draws every/// row either way and says one line above them ("these are in name order"),/// because a project's NAME is not what failed. So a failure here answers/// `projectFactsMissing: true` with an empty overview map — which makes/// `project_order` fall to the alphabet, exactly as the app's does — rather/// than refusing the whole screen.fn projects_band( db: &Driver, workspace_id: &str, arrangement: Option<&HomeArrangement>,) -> Result<(Vec<Value>, bool), String> { let mut projects: Vec<BandProject> = Vec::new(); for row in rows_of( db, "SELECT id, name, slug FROM cotton_memory_projects \ WHERE workspace_id = ? AND status = 'active'", &[param(workspace_id)], )? { projects.push(BandProject { id: required(&row, "id")?, name: required(&row, "name")?, slug: required(&row, "slug")?, }); } let (overviews, facts_missing) = match project_overviews(db, workspace_id) { Ok(overviews) => (overviews, false), Err(_) => (HashMap::new(), true), }; projects.sort_by(|a, b| project_order(a, b, &overviews)); // THE order first, then the person's own over the top of it. A project // born since their last drag is not in the stored list and lands where // activity put it, which is why the arrangement is applied to an already // ordered band rather than instead of one. let projects = arrange_projects(projects, arrangement); let out = projects .iter() .map(|project| { json!({ "id": project.id, "name": project.name, "slug": project.slug, "lastActivity": overviews .get(&project.id) .and_then(Option::as_deref) .map_or(Value::Null, Value::from), }) }) .collect(); Ok((out, facts_missing))}/// Each project's last activity, from the two streams the engine names.////// The LINKED stream is every linked record's own `updated_at`, reached/// through `project_kind_table` — cotton-tools' exhaustive match on/// `ProjectLinkKind`, so a new kind is a compile error there rather than a/// silently invisible stream here. A kind whose table has no `updated_at`/// column contributes nothing and is not an error: `pragma_table_info` is/// asked rather than a hand-kept list, because a hand-kept one is what goes/// quiet when a column moves.////// It also carries the DERIVED half (`derivedMembersForPeople`, spec/// 2026-09-05 §D8): the DM threads and call-log rows of the project's linked/// PEOPLE. Until that half existed, a person linked to a project contributed/// nothing but their name — so the one thing a project is actually made of,/// talking to people, was the one thing that never moved it up the band./// Derived rows are computed at read time and never written, so a person in/// two projects moves both, which is the truth of it.pub(super) fn project_overviews( db: &Driver, workspace_id: &str,) -> Result<HashMap<String, Option<String>>, String> { let mut linked: HashMap<String, Vec<String>> = HashMap::new(); let mut by_kind: BTreeMap<&'static str, Vec<(String, String)>> = BTreeMap::new(); let mut people_by_project: HashMap<String, Vec<String>> = HashMap::new(); for row in rows_of( db, "SELECT project_id, record_kind, record_id FROM cotton_project_links \ WHERE workspace_id = ?", &[param(workspace_id)], )? { let project_id = required(&row, "project_id")?; let record_kind = required(&row, "record_kind")?; let record_id = required(&row, "record_id")?; // A kind this build does not know is a row from a later schema. It // says nothing about when the project moved, and dropping it is the // same trade `project_last_activity` makes for an unparseable instant. let Some(kind) = ProjectLinkKind::parse(&record_kind) else { continue; }; if kind == ProjectLinkKind::Person { people_by_project .entry(project_id.clone()) .or_default() .push(record_id.clone()); } by_kind .entry(project_kind_table(kind).table) .or_default() .push((project_id, record_id)); } for (table, pairs) in &by_kind { if !has_updated_at(db, table)? { continue; } // Which projects hold a given record — built ONCE per chunk. The // straightforward inner loop over `chunk` is quadratic (400 rows // against 400 pairs is 160 000 string comparisons per chunk), and one // busy project pays it on every draw of Home. for chunk in pairs.chunks(400) { let mut projects_of: HashMap<&str, Vec<&str>> = HashMap::new(); for (project_id, record_id) in chunk { projects_of .entry(record_id.as_str()) .or_default() .push(project_id.as_str()); } // `id IN (…)` with the ids inlined as bound parameters, in chunks, // so one enormous project cannot build a statement SQLite refuses. let placeholders = vec!["?"; chunk.len()].join(","); let sql = format!("SELECT id, updated_at FROM {table} WHERE id IN ({placeholders})"); let params: Vec<SqlValue> = chunk.iter().map(|(_, id)| param(id)).collect(); let found = rows_of(db, &sql, ¶ms)?; for row in &found { let Some(id) = row.text("id") else { continue }; let Some(at) = row.text("updated_at") else { continue; }; for project_id in projects_of.get(id).into_iter().flatten() { linked .entry((*project_id).to_string()) .or_default() .push(at.to_string()); } } } } derived_person_activity(db, workspace_id, &people_by_project, &mut linked)?; let mut sessions: HashMap<String, Vec<String>> = HashMap::new(); for row in rows_of( db, "SELECT project_id, last_active_at FROM cotton_sessions \ WHERE workspace_id = ? AND project_id IS NOT NULL", &[param(workspace_id)], )? { let Some(project_id) = owned(&row, "project_id") else { continue; }; let Some(at) = owned(&row, "last_active_at") else { continue; }; sessions.entry(project_id).or_default().push(at); } // ACTIVE only, as `projectOverviews` is: an archived project has no card // on Home, and computing an instant for one is work nobody reads. let mut out: HashMap<String, Option<String>> = HashMap::new(); for row in rows_of( db, "SELECT id FROM cotton_memory_projects WHERE workspace_id = ? AND status = 'active'", &[param(workspace_id)], )? { let id = required(&row, "id")?; let empty: Vec<String> = Vec::new(); let linked_for = linked.get(&id).unwrap_or(&empty); let sessions_for = sessions.get(&id).unwrap_or(&empty); let linked_refs: Vec<Option<&str>> = linked_for.iter().map(|at| Some(at.as_str())).collect(); let session_refs: Vec<Option<&str>> = sessions_for.iter().map(|at| Some(at.as_str())).collect(); let last = project_last_activity(&ProjectActivityInput { linked_updated_at: &linked_refs, session_last_active_at: &session_refs, }) .map(str::to_string); out.insert(id, last); } Ok(out)}/// The DERIVED members' `updated_at`, folded into the linked stream.////// `derivedMembersForPeople`: for every person a project holds, that person's/// DM thread (reached through `cotton_msg_contacts.person_id`, which is what/// ties a conversation to a human) and every call logged with them. Nothing/// here writes a link row — enrolling a human in a project stays a deliberate/// act, and these rows are members of the project only for as long as the read/// lasts.////// One query per stream over ALL the linked people at once, not one per/// project: a person in two projects is read once and counted into both./// De-duplication against an explicitly linked thread or call is deliberately/// not done — `project_last_activity` takes the NEWEST instant, so a row/// contributed twice cannot change the answer.fn derived_person_activity( db: &Driver, workspace_id: &str, people_by_project: &HashMap<String, Vec<String>>, linked: &mut HashMap<String, Vec<String>>,) -> Result<(), String> { // Which projects hold a given person — the same shape the chunk loop // above builds, and for the same reason. let mut projects_of: HashMap<&str, Vec<&str>> = HashMap::new(); for (project_id, people) in people_by_project { for person_id in people { projects_of .entry(person_id.as_str()) .or_default() .push(project_id.as_str()); } } if projects_of.is_empty() { return Ok(()); } for row in cotton_tools::mcp::handlers::calls::read_calls(db,workspace_id).map_err(|e|e.to_string())? { let Some(at)=row.get("updated_at").and_then(Value::as_str) else {continue}; for person in cotton_tools::mcp::handlers::calls::people_on(&row) { for project in projects_of.get(person).into_iter().flatten() { linked.entry((*project).to_string()).or_default().push(at.to_string()); } } } let people: Vec<&str> = projects_of.keys().copied().collect(); for chunk in people.chunks(400) { let placeholders = vec!["?"; chunk.len()].join(","); let mut params: Vec<SqlValue> = vec![param(workspace_id)]; params.extend(chunk.iter().map(|id| param(id))); let streams = [ format!( "SELECT person_id, updated_at FROM (SELECT {person} AS person_id, t.updated_at AS updated_at \ FROM cotton_msg_threads t \ JOIN cotton_msg_contacts c ON c.id = t.contact_id \ WHERE t.workspace_id = ? AND t.kind = 'dm') \ WHERE person_id IN ({placeholders})", person = cotton_store::protocol::who::contact_person_sql(cotton_store::protocol::who::shared_held(db), "c") ), ]; for sql in &streams { for row in &rows_of(db, sql, ¶ms)? { let Some(person_id) = row.text("person_id") else { continue; }; let Some(at) = row.text("updated_at") else { continue; }; for project_id in projects_of.get(person_id).into_iter().flatten() { linked .entry((*project_id).to_string()) .or_default() .push(at.to_string()); } } } } Ok(())}/// Does this table carry an `updated_at`? Asked of the FILE, never remembered.fn has_updated_at(db: &Driver, table: &str) -> Result<bool, String> { Ok(!rows_of( db, "SELECT name FROM pragma_table_info(?) WHERE name = 'updated_at'", &[param(table)], )? .is_empty())}// ── the fifteen figures ───────────────────────────────────────────────────/// `ToolCounts` — all fifteen, each computed the way `useToolCounts.ts`/// computes it.////// The rule the whole shape obeys is **figure or silence**: a count only ever/// appears when it is the number that would make you open the thing, so every/// zero renders as nothing and these stay plain figures. A tool's figure is/// not "how many exist" but "how much is waiting" — Reader counts what is/// still to read, Messages counts unread across threads, Alarms counts the/// ones switched ON. Calls has no figure on purpose (a missed-call count with/// no "seen" marker can never clear, and a number that cannot go away is a/// nag), and neither do Meetings, Documents-at-large or the archives: an/// ever-growing tally is a debt the owner can never pay.////// Two of the fifteen are STATES rather than counts (`journalUnwritten`,/// `freshEdition`) — each says so where it is computed./// Every figure a tool's definition works out itself (`tool.figures[]`/// with a `summary` or `formula`, `cotton_tools::tool_figures`), beside the/// fifteen: each the core's own line by its `read`, the person's day keeping/// this month's. One that cannot be worked out is said by no card and logged/// — Home never fails on a definition.fn with_worked_figures(mut counts: Value, db: &Driver, workspace_id: &str, now_ms: i64, zone: &str) -> Value { let worked = local_day(now_ms, zone) .ok() .and_then(|day| chrono::NaiveDate::parse_from_str(&day, "%Y-%m-%d").ok()) .ok_or_else(|| "the person's day could not be read".to_string()) .and_then(|today| { cotton_tools::tool_figures::worked_figures(db, workspace_id, today).map_err(|failure| failure.to_string()) }); match (counts.as_object_mut(), worked) { (Some(counts), Ok(lines)) => { for (read, line) in lines { counts.entry(read).or_insert(line); } } (_, Err(why)) => tracing::warn!(why, "read.home: the tools' worked figures were not read"), _ => {} } counts}/// Home's unread-messages count: inbound live rows past each LIVE thread's/// read cursor, less what the person hid or cleared.////// Asked of the THREADS, with each thread's unread rows found through/// `idx_cotton_msg_messages_thread_seq (thread_id, seq)` from its cursor on —/// so it costs the threads plus what is unread. As a join led by the messages/// it read every message row in the file to count the handful past a cursor/// (the serving Mac's hold of 09:14:41Z, 11 Oct 2026: 1.9M steps, 3.5 s, for/// a history of 121k messages nearly all read). `seq > read_seq` already/// leaves out a row the server has not numbered and a thread with no cursor.const UNREAD_MESSAGES: &str = "SELECT COALESCE(SUM((\ SELECT count(*) FROM cotton_msg_messages m \ WHERE m.thread_id = t.id AND m.seq > t.read_seq \ AND m.direction = 'in' AND m.origin = 'live' \ AND m.hidden_at IS NULL AND m.trashed_at IS NULL \ AND (t.cleared_before IS NULL OR m.sent_at > t.cleared_before))), 0) AS n \ FROM cotton_msg_threads t WHERE t.workspace_id = ? AND t.archived = 0";fn tool_counts( db: &Driver, workspace_id: &str, _now: &str, now_ms: i64, zone: &str, occurrences: &[(BandOccurrence, Option<String>, bool)],) -> Result<Value, String> { let ws = [param(workspace_id)]; // Messages waiting on an answer, summed across the LIVE threads — the // cursor rule (v9): a thread carries `read_seq` and an inbound live row // past it is unread. // // ONE workspace-wide aggregate, which is the shape `listThreads` uses and // says why: "the rows are already local, so the aggregate belongs where the // rows are". A query per thread is the N+1 the TypeScript deliberately // avoided. The predicate is `unread_count`'s, spelled in SQL exactly as the // TypeScript spells it there — `seq IS NOT NULL` because a row the server // has not numbered is one nobody else has seen, and `origin = 'live'` // because an imported archive arrives READ. // // Three filters the per-thread loop did not have, and each is a badge a // person had already cleared: `archived = 0` (the archive is a separate // place you go, and the app sums over the LIVE list alone), `hidden_at IS // NULL`, and the `cleared_before` cut. // // AND IT READS ONLY WHAT IS UNREAD ([`UNREAD_MESSAGES`]): one statement // still, but asked of each live thread's rows PAST its cursor, through // `(thread_id, seq)` — never of every message the file holds. let unread_messages = count_of(db, UNREAD_MESSAGES, &ws)? as usize; let open_todos = count_of( db, HOME_TODOS, &ws, )?; // Events still ahead in today — the SAME band Home reads, so the figure // and the day surface can never disagree about what is left. let band_occurrences: Vec<BandOccurrence> = occurrences .iter() .map(|(occurrence, _, _)| occurrence.clone()) .collect(); let band = select_today_band(&TodayBandInput { todos: &[] as &[BandTodo], occurrences: &band_occurrences, now_ms, timezone: zone, }) .map_err(|error| error.to_string())?; let events_left_today = band .entries .iter() .filter(|entry| entry.kind() == "event") .count(); let live_alarms = count_of( db, "SELECT count(*) AS n FROM cotton_alarms \ WHERE workspace_id = ? AND enabled = 1 AND trashed_at IS NULL", &ws, )?; // The count does not read note bodies. Today's journal is a point read // through the journal-day index, with the same trim rule as the engine. let note_count = count_of(db, HOME_NOTES, &ws)?; let today = local_day(now_ms, zone)?; let written_today = rows_of(db, HOME_JOURNAL, &[param(workspace_id), param(&today)])?.iter().any(|row| row.text("body").is_some_and(|body| !body.trim().is_empty())); let people = count_of( db, "SELECT count(*) AS n FROM cotton_people WHERE workspace_id = ? AND archived_at IS NULL", &ws, )?; let locations = count_of( db, "SELECT count(*) AS n FROM cotton_locations \ WHERE workspace_id = ? AND archived_at IS NULL", &ws, )?; // What is STILL TO READ, never what is saved. let unread_pages = count_of( db, "SELECT count(*) AS n FROM cotton_pages \ WHERE workspace_id = ? AND archived_at IS NULL AND state = 'unread'", &ws, )?; // Documents waiting on a PASSWORD — never "how many documents". A vault's // size is a number nobody opens an app about and it only ever grows; a // locked document is the one state here actually waiting on the person, // and it clears the moment they answer it. let locked_documents = count_of( db, "SELECT count(*) AS n FROM cotton_documents WHERE workspace_id = ? AND status = 'locked' \ AND trashed_at IS NULL", &ws, )?; // `hasFreshEdition`: the newest READY edition has never been opened. A // boolean and not a count, because two editions a day means an "unread" // number could only ever grow. let fresh_edition = rows_of( db, "SELECT opened_at FROM cotton_news_editions \ WHERE workspace_id = ? AND status = 'ready' ORDER BY created_at DESC LIMIT 1", &ws, )? .first() .is_some_and(|row| row.text("opened_at").is_none()); // The ONE count in here that is a size and still earns its place: it is // small, it is the shape of the person's current work, and — unlike an // archive's tally — it goes DOWN when a project is archived. let active_projects = count_of( db, "SELECT count(*) AS n FROM cotton_memory_projects \ WHERE workspace_id = ? AND status = 'active'", &ws, )?; // The Code queue's two bands, counted the way `CodeFacts.bands` cuts them // — the figure on Home and the sections on `/code` have to agree about // which session is running and which is asking for something. ONE OBJECT // (v23): both are counts of `cotton_sessions` and there is no second table // to join, so a session cannot be counted twice. // // RUNNING is a session an agent is actually IN: `starting` or `running`, // plus a HOST-OWNED `idle` one that was active within the hour — an agent // sitting at its prompt is still a session the person has open. Three // deliberate exclusions: a `queued` row has no agent yet, an ADOPTED idle // row is somebody's own terminal Cotton merely noticed, and a NULL state is // a session logged before the Code tool existed. A count that swept those // in would be a badge on Home that never cleared. let idle_cutoff = to_iso_string(now_ms - IDLE_STILL_OPEN_MS) .ok_or_else(|| format!("{now_ms} is not an instant this file can spell"))?; let running_sessions = count_of( db, "SELECT count(*) AS n FROM cotton_sessions \ WHERE workspace_id = ? AND ended_at IS NULL \ AND (state IN ('starting', 'running') \ OR (state = 'idle' AND host_owned = 1 AND last_active_at >= ?))", &[param(workspace_id), param(&idle_cutoff)], )?; // WAITING is blocked on the PERSON — a permission, a question, a prompt to // type. Read off `state` alone and before anything else, exactly as the // queue reads it: a session that is waiting is waiting whatever else its // columns say. let waiting_sessions = count_of( db, "SELECT count(*) AS n FROM cotton_sessions \ WHERE workspace_id = ? AND state = 'waiting'", &ws, )?; Ok(json!({ "unreadMessages": unread_messages, "openTodos": open_todos, "eventsLeftToday": events_left_today, "liveAlarms": live_alarms, "notes": note_count, "people": people, "locations": locations, "unreadPages": unread_pages, "journalUnwritten": !written_today, "lockedDocuments": locked_documents, "freshEdition": fresh_edition, "activeProjects": active_projects, "runningSessions": running_sessions, "waitingSessions": waiting_sessions, }))}/// The local calendar day of an instant, `YYYY-MM-DD`.fn local_day(at_ms: i64, zone: &str) -> Result<String, String> { local_day_key(at_ms, zone).map_err(|error| error.to_string())}// ── /mood ─────────────────────────────────────────────────────────────────/// How far back the timeline reads when the screen names no window.////// A fortnight: long enough to hold a shape a person recognises, short enough/// that the first screenful is the part they came for. It lives HERE rather/// than in the engine because it is a screen's decision about what to show,/// not a rule about what a mood is — the engine's own fortnight was the strip's/// width, and the strip went with the score.const MOOD_WINDOW_DAYS: usize = 14;/// The moments the timeline draws, and today's date.////// **The list IS `list_moods`'s** (P4): the tool already bounds the window,/// orders by the instant and reads the emotions back out of the column's JSON,/// so nothing is restated here. Newest first, which is the tool's own/// `at DESC` — a timeline the person scrolls, not a chart that reads left to/// right, because the chart is gone with the score it averaged.////// **There is no strip and no per-day average.** A mood was a number from one/// to five until schema v18 and this read recomputed a fortnight of means off/// the engine; a mood is a MOMENT now, and an average of named emotions is not/// a thing. The screen groups the moments under day headers, which is/// presentation over `localDay` and needs no engine.////// **`days` bounds the window** — the number of days back, today included,/// defaulting to [`MOOD_WINDOW_DAYS`]. It is asked of the tool as a `from` day/// key rather than filtered here, so a page that hit the ceiling is short by/// its OLDEST moments rather than silently missing ones in the middle.////// **`limit` is named, and it is the tool's ceiling.** `list_moods` is/// `bounded_limit(args, 100, 500)` and it orders `at DESC`, so an unasked page/// of 100 over a busy fortnight would drop the oldest moments in the window/// with nothing saying so.////// **`today` is `local_day_key`'s**, so the screen's "Today" header filters on/// the day the WRITER would have stamped rather than on one the app re-derives/// — the two disagree the moment the reader and the writer stand in different/// zones, which is every server read of a phone's write.////// The zone is [`reading_zone`]'s — the DEVICE's, the same one the writer/// stamps a moment with — and a phone that named none REFUSES here rather than/// falling to UTC: a timeline silently drawn in the wrong zone puts moments/// under the wrong headers, and the dispatcher's `unreadable` is the honest/// answer.fn mood(client: &ClientController, args: &Map<String, Value>) -> Result<Value, String> { let (now_ms, _now) = banding_instant(client, args)?; let days = match args.get("days") { None => None, Some(value) => { let days = value .as_i64() .filter(|days| *days > 0) .ok_or_else(|| "days must be a positive number of days".to_string())?; Some(days as usize) } }; let zone = reading_zone(client)?; let today = local_day_key(now_ms, &zone).map_err(|error| error.to_string())?; // The window the TOOL reads, in the tool's own `local_day` terms. let span = days.unwrap_or(MOOD_WINDOW_DAYS) as i64; let parts = zoned_parts(now_ms, &zone).map_err(|error| error.to_string())?; // Inclusive of today: a fourteen-day window is today and the thirteen // before it. let first = day_number(parts.year, parts.month, parts.day) - (span - 1); let mut tool_args = Map::new(); tool_args.insert("from".to_string(), Value::from(day_key(first))); // The tool's own ceiling, asked for by name — see the note above. tool_args.insert( "limit".to_string(), Value::from(cotton_tools::mcp::handlers::common::WHOLE_SET), ); let answer = client.read_tool("list_moods", &tool_args)?; let moments = answer .get("moments") .and_then(Value::as_array) .cloned() .unwrap_or_default(); Ok(json!({ "moments": moments, "today": today }))}// ── /take and /keyboard-take ──────────────────────────────────────────────/// What the mic screen needs before it starts listening.////// `corpusCount` is `list_thoughts`' own list, called through/// [`ClientController::read_tool`] (P4) with `standing: "all"` — the argument/// is named `standing`, not `status`, and "all" is what turns off the tool's/// open-only default. **The tool PAGES**: `bounded_limit(args, 50, 100)`, so/// the figure saturates at 100 and a workspace with four hundred thoughts/// reads as a hundred. That is stated here rather than worked around with a/// `SELECT count(*)`, because a second answer to a tool's own list is the/// drift the read table exists to prevent — and the screen's figure is a sense/// of how much has been said, not an inventory.////// `vocabularyTerms` highlights every unique word; `biasTerms` feeds the/// recogniser its ranked hundred, manual additions first. Both include the/// names derived by this device's kept voice-context pass.fn take(client: &ClientController, args: &Map<String, Value>) -> Result<Value, String> { let mut thought_args = Map::new(); thought_args.insert("standing".to_string(), Value::from("all")); thought_args.insert("limit".to_string(), Value::from(cotton_tools::mcp::handlers::common::WHOLE_SET)); let thoughts = client.read_tool("list_thoughts", &thought_args)?; let corpus_count = thoughts .get("thoughts") .and_then(Value::as_array) .map_or(0, Vec::len); // Manual additions belong to the person; automatic names come from every // database this device still holds, the open one's first. let context = super::voice_words::context_for(client, args)?; Ok(json!({ "corpusCount": corpus_count, "vocabularyTerms": context["vocabularyTerms"], "biasTerms": context["biasTerms"], }))}// ── The three corrections (4p §4) ─────────────────────────────────────────/// `/notes` — the person's OWN notes, newest first.////// `notesService.listNotes`, ported clause for clause, and each clause is load/// bearing:////// * `kind = 'note'` — a journal page is the same table and a different screen/// (`/journal`), and mixing them would put every day of a person's diary in/// their notes list;/// * `archived_at IS NULL` — an archived note is in the bin, which has its own/// screen and its own read;/// * `managed_by IS NULL` — an agent's mirror is hundreds of files, and the/// service's own comment says why they must not drown the personal list./// `includeManaged` is the option for the surfaces that mean to show them;/// the notes screen is not one, so this read does not take it.fn own_notes(replica: &ReadFile<'_>, _args: &Map<String, Value>) -> Result<Value, String> { let rows = replica .driver .all( "SELECT id, title, body, managed_by, created_at, updated_at FROM cotton_notes WHERE workspace_id = ? AND kind = 'note' AND archived_at IS NULL AND trashed_at IS NULL AND managed_by IS NULL ORDER BY updated_at DESC", &[rusqlite::types::Value::Text(replica.workspace_id.to_string())], ) .map_err(|error| error.to_string())?; // Each note's projects, in ONE query over the links rather than one per // row — the paper a note is drawn on is its first project's cap colour, // the todo board's rule, and the list draws every note at once. The same // `created_at, id` order the todo read uses, so "first" means one thing. let mut by_note: HashMap<String, Vec<Value>> = HashMap::new(); for row in replica .driver .all( "SELECT l.record_id, p.id, p.slug, p.name FROM cotton_project_links l JOIN cotton_memory_projects p ON p.id = l.project_id WHERE l.workspace_id = ? AND l.record_kind = 'note' ORDER BY p.created_at ASC, p.id ASC", &[rusqlite::types::Value::Text(replica.workspace_id.to_string())], ) .map_err(|error| error.to_string())? { let Some(note_id) = row.text("record_id") else { continue; }; by_note.entry(note_id.to_string()).or_default().push(json!({ "id": row.text("id"), "slug": row.text("slug"), "name": row.text("name"), })); } let notes: Vec<Value> = rows .iter() .map(|row| { let projects = row .text("id") .and_then(|id| by_note.get(id).cloned()) .unwrap_or_default(); json!({ "id": row.text("id"), "title": row.text("title"), "body": row.text("body"), "createdAt": row.text("created_at"), "updatedAt": row.text("updated_at"), "projects": projects, }) }) .collect(); Ok(json!({ "notes": notes }))}/// `/goals/goal/[id]` — one goal, in `list_goals`' own shape.////// The columns are `GOAL_COLUMNS`' and the names are the tool's camel-case/// ones, so the detail screen and the list screen read the same goal the same/// way. A goal that is not there answers `null` rather than refusing: a screen/// reached from a stale link draws "this goal is gone", and an error would make/// it draw a crash.fn goal(replica: &ReadFile<'_>, args: &Map<String, Value>) -> Result<Value, String> { let id = args .get("id") .and_then(Value::as_str) .map(str::trim) .filter(|id| !id.is_empty()) .ok_or_else(|| "`id` is the goal to read".to_string())?; let row = replica .driver .get( "SELECT id, title, why, target_date, status, achieved_at, sort_order, created_at, updated_at FROM cotton_goals WHERE workspace_id = ? AND id = ?", &[ rusqlite::types::Value::Text(replica.workspace_id.to_string()), rusqlite::types::Value::Text(id.to_string()), ], ) .map_err(|error| error.to_string())?; let Some(row) = row else { // EVERY key the found branch emits — Swift decodes a non-optional // stored property with `decode`, not `decodeIfPresent`, so a branch one // key short throws rather than falling back to its default. return Ok(json!({ "goal": Value::Null, "projects": [], "projectLinks": [], })); }; // The *Projects…* sheet's two keys, in the shapes it decodes on every // record kind — see `day::record_projects`. let (projects, project_links) = day::record_projects(replica, "goal", id)?; Ok(json!({ "goal": { "id": row.text("id"), "title": row.text("title"), "why": row.text("why"), "targetDate": row.text("target_date"), "status": row.text("status"), "achievedAt": row.text("achieved_at"), "createdAt": row.text("created_at"), "updatedAt": row.text("updated_at"), }, "projects": projects, "projectLinks": project_links, }))}/// `/storage` — what CottonDB is using on THIS PHONE.////// Four numbers a person can act on, each a directory they can point at, plus/// the ledger's own counts so the screen can say "and 12 files have not gone up/// yet" without a second call.////// Every byte comes through [`crate::phone::disk::Disk`] — no `std::fs` in this/// function — and `freeBytes` is `null` with its reason beside it rather than a/// number this core cannot honestly produce. See that module for why.////// ## The budget, and the three numbers that explain it////// `budgetBytes` is what this DEVICE allows the media store to grow to,/// `evictableBytes` is how much of it could go right now, and `thumbBytes` is/// the number that is deliberately OUTSIDE both. Together they are the whole/// sentence the pane has to say: this is what you are holding, this is what/// Cotton would take back if it needed room, and the small pictures in the grid/// are not part of that arithmetic.////// **`evictableBytes` is the honest number, not the optimistic one.** It counts/// only files a live device OTHER than this one also holds/// ([`cotton_store::media_evict::evictable_bytes`]), because a phone never/// drops the last copy of anything — so on a household with no second machine/// it is zero, and a person reading "0 bytes could be freed" beside four/// gigabytes of photographs is being told something true and important.fn storage(client: &ClientController, args: &Map<String, Value>) -> Result<Value, String> { let layout = client.layout().clone(); let disk = client.disk(); let replica_bytes = disk.size_of(&layout.client_dir()); let media_bytes = disk.size_of(&layout.client_media_dir()); let snapshot_bytes = disk.size_of(&layout.snapshots_dir()); let thumb_bytes = disk.size_of(&layout.thumbs_cache_dir()); let mut answer = json!({ "root": layout.root().to_string_lossy(), "bytes": { // The replica directory, which HOLDS the media store, so the media // figure is a part of it rather than a second total to add. "device": replica_bytes, "media": media_bytes, // Copies a source was read from and thumbnails: the two the person // can clear without losing anything. "snapshots": snapshot_bytes, "thumbnails": thumb_bytes, }, }); match disk.free_bytes(layout.root()) { Some(free) => answer["freeBytes"] = json!(free), None => { answer["freeBytes"] = Value::Null; // Never a bare null: a screen cannot tell "nobody could say" from // "there is no room" without the sentence, and drawing zero would // be the masked fallback this repo does not allow. answer["freeBytesUnavailable"] = json!(crate::phone::disk::NO_FREE_SPACE_READING); } } // The ledger's own counts — this device's, never the workspace's. let counts = client.with_file(|replica| { cotton_store::media_ledger::media_counts(replica.driver, replica.workspace_id) .map_err(|error| error.to_string()) })?; answer["uploads"] = json!({ "pending": counts.pending, "synced": counts.synced, "failed": counts.failed, "deletePending": counts.delete_pending, }); // THE BUDGET. Read off this device's own file (`Layout::media_budget_json`) // and never off the database: the budget is about this machine's disk, and // a phone and a Mac have no business agreeing on a number. let budget = cotton_client::media::read_budget(&layout); answer["budgetBytes"] = json!(budget); // Named beside the budget although `bytes.thumbnails` is the same walk, // because the budget's rule is ABOUT it: thumbnails are never evicted and // never counted. A pane drawing the budget needs the number that is // excluded from it right there, or the totals do not add up on screen. answer["thumbBytes"] = json!(thumb_bytes); answer["thumbCeilingBytes"] = json!(cotton_client::media::THUMB_CEILING_BYTES); // A WARNING and never a deletion. The sentence travels with the flag so the // pane has nothing to compose and no second place for the wording to live. answer["thumbCeilingWarning"] = if thumb_bytes > cotton_client::media::THUMB_CEILING_BYTES { json!(cotton_client::media::THUMB_CEILING_WARNING) } else { Value::Null }; // This device's KEY — the id its own holds name it by — so "held // somewhere else" leaves out exactly this device. let device_id = client.self_device_id().unwrap_or_default(); let (own, mut evictable) = client.with_file(|replica| { cotton_store::media_evict::evictable_bytes( replica.driver, replica.workspace_id, &device_id, ) .map(|bytes| (replica.workspace_id.to_string(), bytes)) .map_err(|error| error.to_string()) })?; // The budget is the device's, over every database it holds — so is what // the budget could take — joined ones included, as the budget pass takes // from them. A database with no media folder here has none. for id in client.syncing_databases() { if id == own || !layout.client_media_dir().join(&id).is_dir() { continue; } let file = client.open_database(&id)?; let held = file .replica .lock() .map_err(|_| "the database's file could not be read".to_string())?; evictable += cotton_store::media_evict::evictable_bytes( &held.driver, &held.workspace_id, &device_id, ) .map_err(|error| error.to_string())?; } answer["evictableBytes"] = json!(evictable); // And what those bytes actually ARE, one row per object (4g). The four // directory figures above are the disk as the filesystem sees it; this is // the same disk as the person sees it — a photo, a paper, a recording, a // chat — and it is what the screen's totals, its by-chat list, its largest // and its suggested-for-review sections are all folded from. // // ONE object, ONE row. A chat photo's `cotton_photos.key` IS the message's // key, so a reader that counted the record and the attachment separately // would tell a person their phone holds double what it does. answer["entries"] = json!(client.with_file(crate::phone::traffic::media_ledger_entries)?); let rules = crate::phone::storage::rows(client, args)?; answer.as_object_mut().expect("storage answer").extend(rules.as_object().expect("storage rows").clone()); Ok(answer)}// ─────────────────────────────────────────────────────────────────────────────// 4h — the settings, sharing, Find and Bin reads.//// An appended block, and it moves into `phone/reads/settings.rs` whole when// another lane splits this file. Every query below is scoped by// `workspace_id`: the replica holds ONE workspace, and a query that forgot the// clause would still be right today and wrong the first time that changed.// ─────────────────────────────────────────────────────────────────────────────/// The name a workspace row starts life with, which is not a name.////// `WORKSPACE_NAME_PLACEHOLDER` in the TypeScript, restated here because it has/// no Rust twin. `/settings` draws "No name yet" for it, and the server's own/// `POST /v1/me` reports it as `null` for the same reason: nobody chose it.pub(super) const WORKSPACE_NAME_PLACEHOLDER: &str = "Personal";/// The database's own name as the person gave it — whole, never shortened —/// or `None` for a blank name and for the placeholder. Never the owner/// person's name: the database and the person are two records (Spec 10 (d)).pub(super) fn database_own_name(name: &str) -> Option<String> { let name = name.trim(); if name.is_empty() || name == WORKSPACE_NAME_PLACEHOLDER { return None; } Some(name.to_string())}/// Who this is: the owner's name. Where they live is the Me person's city.////// `ownerName` is `null` for a blank name AND for the placeholder, which is the/// `ownerNameFrom` rule: a screen that drew "Personal" would be telling the/// person that is what they are called.fn account(replica: &ReadFile<'_>, _args: &Map<String, Value>) -> Result<Value, String> { let row = replica .driver .get( "SELECT name FROM cotton_workspaces WHERE id = ?", &[rusqlite::types::Value::Text(replica.workspace_id.to_string())], ) .map_err(|error| error.to_string())?; let Some(row) = row else { // A phone with an open replica and no workspace row is a file that did // not finish being born. Said out loud rather than answered as "no // name", which a screen would draw as an ordinary state. return Err("this database has no workspace row".to_string()); }; // The owner person's name once the database names one (Spec 10.3: a // rename of that person IS the owner's name); the workspace's own name // until then. The workspace's `name` is the database's and is never // written from here. let owner_name = match super::you::owner_person_name(replica)? { Some(name) => Value::from(name), None => row .text("name") .map(str::trim) .filter(|name| !name.is_empty() && *name != WORKSPACE_NAME_PLACEHOLDER) .map(Value::from) .unwrap_or(Value::Null), }; Ok(json!({ "ownerName": owner_name }))}/// `/settings#keyboard` — the corpus line, and the whole screen's only read.////// Two aggregates, so there is no row to decode. The screen draws the line only/// when `count > 0` — figures-or-silence — and never "0 takes".fn dictation_stats(replica: &ReadFile<'_>, _args: &Map<String, Value>) -> Result<Value, String> { let row = replica .driver .get( "SELECT COUNT(*) AS n, COALESCE(SUM(words), 0) AS words FROM cotton_dictations WHERE workspace_id = ?", &[rusqlite::types::Value::Text(replica.workspace_id.to_string())], ) .map_err(|error| error.to_string())?; let (count, words) = match row { None => (0, 0), Some(row) => (row.int("n").unwrap_or(0), row.int("words").unwrap_or(0)), }; Ok(json!({ "count": count, "words": words }))}/// `/voice-words` — the words dictation listens for (the Voice words tool).////// `COLLATE NOCASE` because the list is alphabetical to a person, and "nilgiri"/// filed under `n` while "Nilgiri" is under `N` is a list nobody can scan./// Automatic words are answered by `read.voiceContext`; this editor holds/// only the additions the person can change.fn voice_vocabulary(replica: &ReadFile<'_>, _args: &Map<String, Value>) -> Result<Value, String> { let rows = replica .driver .all( "SELECT id, term, source, use_count, last_used_at FROM cotton_voice_vocabulary WHERE workspace_id = ? AND source = 'manual' ORDER BY term COLLATE NOCASE ASC", &[rusqlite::types::Value::Text(replica.workspace_id.to_string())], ) .map_err(|error| error.to_string())?; let terms: Vec<Value> = rows .iter() .map(|row| { json!({ "id": row.text("id"), "term": row.text("term"), "source": row.text("source"), "useCount": row.int("use_count").unwrap_or(0), "lastUsedAt": row.text("last_used_at"), }) }) .collect(); Ok(json!({ "terms": terms }))}/// `/search` — everything in the file that says what was typed.////// **The ENGINE, not the `search_records` tool**, and they are different/// answers to different questions. Both ride/// `cotton_core::rules::search_everything::search_everything_file` — "one/// implementation, so the phone and the server rank one file one way" — but the/// TOOL is the assistant's register: it flattens to one `records` array, splits/// journal out of the note lane, substitutes a title for the nameless, appends/// the memory `[slug]` line and explains the meaning lane's absence. The app/// wants hits grouped per SECTION with `totals`, and its own words for a title./// So this read calls the engine and Swift does the grouping, exactly as/// `searchSections.ts` did.////// **The meaning lane is OFF**, which is the default and is what the app asked/// for by passing no options at all: it costs a provider call, and Find is a/// field somebody is typing into./// What a `scope` narrows Find to. `mail` is the box inside Mail: the/// mail lanes alone, while the global search (no scope) still finds mail/// beside everything else.fn find_scope( args: &Map<String, Value>,) -> Result<Option<&'static [cotton_core::rules::search_everything::EverythingKind]>, String> { use cotton_core::rules::search_everything::EverythingKind; const MAIL: &[EverythingKind] = &[EverythingKind::Email, EverythingKind::EmailThread]; match args.get("scope").and_then(Value::as_str) { None => Ok(None), Some("mail") => Ok(Some(MAIL)), Some(other) => Err(format!("unknown search scope \"{other}\"; the one scope is mail")), }}fn find(replica: &ReadFile<'_>, args: &Map<String, Value>) -> Result<Value, String> { use cotton_core::rules::search_everything::{search_everything_file, EverythingKind, EverythingSearchOptions}; let query = args .get("query") .and_then(Value::as_str) .unwrap_or_default(); // One kind alone (`kind`), as an expanded section pages through it. let kind = match args.get("kind").and_then(Value::as_str) { None => None, Some(name) => Some([EverythingKind::parse(name).ok_or_else(|| format!("unknown search kind \"{name}\""))?]), }; let kinds = match &kind { Some(one) => Some(&one[..]), None => find_scope(args)?, }; let business_kinds; let kinds = if cotton_core::flavor::single_database() { business_kinds = kinds.unwrap_or(&cotton_core::rules::search_everything::EVERYTHING_KINDS).iter().copied() .filter(|kind| cotton_tools::home_arrangement::require_table(replica.driver, replica.workspace_id, kind.as_str()).is_ok()) .collect::<Vec<_>>(); Some(business_kinds.as_slice()) } else { kinds }; // A page per kind (`limit`, from `offset`) with each kind's exact total — // the screen's first page and an expanded section's next one (architect, // 15 Oct 2026: nothing is hidden, and nothing is read all at once). With // no `limit`, EVERY hit per kind: mail's own list pages the thread ids // itself. Personal scale is the ceiling (`WHOLE_SET_LIMIT`), and a match // query bounds the set before it. let per_kind = args .get("limit") .and_then(Value::as_i64) .unwrap_or(cotton_tools::mcp::handlers::common::WHOLE_SET_LIMIT); let offset = args.get("offset").and_then(Value::as_i64).unwrap_or(0); // A newer search on the same channel stops this one (`FindFlight`). let flight = args .get("channel") .and_then(Value::as_str) .map(|channel| FindFlight::begin(channel, replica.driver)); let file = cotton_tools::mcp::handlers::records_2::search::FileSearchDriver(replica.driver); let driver = Superseded { file, flight: flight.as_ref() }; let stopped = |error: cotton_core::rules::search_everything::SearchError| match flight.as_ref().filter(|flight| flight.cancelled()) { Some(_) => SUPERSEDED.to_string(), None => error.to_string(), }; // HIDE FROM SCREEN (CORE 4, add 1): a hidden title of his films, every row naming it and every play of it, left out // where his films' tables are READ, so no hit, snippet, total or page is made of one. Asked of his films' tables // alone (`hidden::FAMILY`): no other table holds one. Inside Hidden Find is not drawn, so it is always asked. let hidden_ids: Vec<String> = cotton_tools::mcp::handlers::tables::hidden::hiding_in(replica.driver, replica.workspace_id)?.all().into_iter().collect(); let left_out = |definition: &cotton_core::definitions::TableDefinition| -> &[String] { if cotton_tools::mcp::handlers::tables::hidden::FAMILY.contains(&definition.id.as_str()) { &hidden_ids } else { &[] } }; // One imported table alone (`table`), as its expanded section pages // through it: that table's page from `offset`, and nothing else. if let Some(table) = args.get("table").and_then(Value::as_str) { let definition = defined_tables(replica)? .into_iter() .find(|definition| definition.id == table) .ok_or_else(|| format!("no imported table \"{table}\" to search"))?; let found = cotton_core::rules::search_everything::search_defined_table_leaving(&driver, &definition, replica.workspace_id, query, per_kind, offset, left_out(&definition)) .map_err(stopped)?; let rows = cotton_tools::presentation::line_rows(replica.driver, replica.workspace_id); let mut defined = Map::new(); defined.insert(definition.id.clone(), defined_section(&definition, found, &rows)?); return Ok(serde_json::json!({ "hits": [], "totals": {}, "defined": defined })); } let mut read = search_everything_file( &driver, query, // Every kind, the text lane alone, no embedded query. &EverythingSearchOptions { per_kind: Some(per_kind), kinds, mail_index: Some(cotton_tools::mcp::handlers::records_2::search::mail_index_of(replica.driver)), offset, as_sections: true, ..Default::default() }, ) .map_err(stopped)?; if cotton_core::flavor::single_database() { read.hits.retain(|hit| { let table = if hit.kind == EverythingKind::Note && hit.journal { "journal" } else { hit.kind.as_str() }; cotton_tools::home_arrangement::require_table(replica.driver, replica.workspace_id, table).is_ok() }); } let mut answer = serde_json::to_value(&read).map_err(|error| error.to_string())?; // The whole search (no `kind`, no `scope`) also reads every data-only // table this file holds through its definition — a tool imported today is // found today (`search_everything::search_defined_table`), one page each, // keyed by table id, beside the built-in sections. if kind.is_none() && find_scope(args)?.is_none() { let rows = cotton_tools::presentation::line_rows(replica.driver, replica.workspace_id); let mut defined = Map::new(); for definition in defined_tables(replica)? { let found = cotton_core::rules::search_everything::search_defined_table_leaving(&driver, &definition, replica.workspace_id, query, per_kind, offset, left_out(&definition)) .map_err(stopped)?; if !found.hits.is_empty() { defined.insert(definition.id.clone(), defined_section(&definition, found, &rows)?); } } if !defined.is_empty() { answer["defined"] = Value::Object(defined); } } Ok(answer)}/// One imported table's section of Find, every word in it the database's:/// the section is named by the definition's plural, an archived hit carries/// the `search` set's mark, and each hit's day is put beside it as day parts/// (`stamps`).fn defined_section( definition: &cotton_core::definitions::TableDefinition, found: cotton_core::rules::search_everything::DefinedRead, rows: &[cotton_core::rules::shell_lines::LineRow],) -> Result<Value, String> { let archived = cotton_core::rules::shell_lines::resolve("search", "marks.archived", rows, &[]); let mut section = serde_json::to_value(&found).map_err(|error| error.to_string())?; section["label"] = Value::String(definition.plural.clone()); for (hit, found) in section["hits"].as_array_mut().into_iter().flatten().zip(&found.hits) { if let (true, Some(mark)) = (found.archived, archived.as_ref()) { hit["mark"] = Value::String(mark.clone()); } } Ok(section)}/// The data-only tables this file holds that a tool here draws: no engine,/// not a shipped built-in, storage present. Every other table is a built-in/// section's.fn defined_tables(replica: &ReadFile<'_>) -> Result<Vec<cotton_core::definitions::TableDefinition>, String> { let shipped = cotton_core::definitions::builtin_table_definitions(); let definitions = cotton_tools::definitions::shared_table_definitions_from_driver(replica.driver, replica.workspace_id) .map_err(|error| error.to_string())?; let mut out = Vec::new(); for definition in &definitions.definitions { // A table with no face is drawn nowhere, so nothing finds its rows. if definition.engine.is_some() || !definition.has_face() || shipped.iter().any(|built| built.id == definition.id) { continue; } let held = replica .driver .get( "SELECT 1 AS here FROM sqlite_master WHERE type = 'table' AND name = ?", &[SqlValue::Text(cotton_core::rules::search_everything::defined_storage(&definition.id))], ) .map_err(|error| error.to_string())? .is_some(); let shown = !cotton_core::flavor::single_database() || cotton_tools::home_arrangement::require_table(replica.driver, replica.workspace_id, &definition.id).is_ok(); if held && shown { out.push(definition.clone()); } } Ok(out)}/// What a search stopped by a newer one on its channel answers.pub(crate) const SUPERSEDED: &str = "superseded by a newer search";/// The searches in flight, one per channel of one file: a keystroke's search/// stops the previous one (architect, 15 Oct 2026), so fast typing never/// queues stale SQL behind the read the screen is waiting for. Keyed by the/// file too: a search on another database (or another core in the process)/// never interrupts a connection that is not its own file's.static FINDS_IN_FLIGHT: std::sync::Mutex<BTreeMap<(String, String), (u64, std::sync::Arc<std::sync::atomic::AtomicBool>, rusqlite::InterruptHandle)>> = std::sync::Mutex::new(BTreeMap::new());static FIND_IDS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);/// One search on a channel, from its start until it answers. Beginning one/// stops the channel's previous search: its flag stops it between statements/// and its connection is interrupted inside the one it is running.pub(crate) struct FindFlight { channel: (String, String), id: u64, stopped: std::sync::Arc<std::sync::atomic::AtomicBool>,}impl FindFlight { pub(crate) fn begin(channel: &str, driver: &Driver) -> Self { use std::sync::atomic::Ordering; let id = FIND_IDS.fetch_add(1, Ordering::Relaxed); let stopped = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)); let channel = (driver.connection().path().unwrap_or_default().to_string(), channel.to_string()); let mut flights = FINDS_IN_FLIGHT.lock().unwrap_or_else(std::sync::PoisonError::into_inner); if let Some((_, previous, connection)) = flights.insert( channel.clone(), (id, stopped.clone(), driver.connection().get_interrupt_handle()), ) { previous.store(true, Ordering::SeqCst); connection.interrupt(); } Self { channel, id, stopped } } pub(crate) fn cancelled(&self) -> bool { self.stopped.load(std::sync::atomic::Ordering::SeqCst) }}impl Drop for FindFlight { fn drop(&mut self) { let mut flights = FINDS_IN_FLIGHT.lock().unwrap_or_else(std::sync::PoisonError::into_inner); if flights.get(&self.channel).is_some_and(|(id, _, _)| *id == self.id) { flights.remove(&self.channel); } }}/// The file's search driver, refusing every statement once a newer search on/// its channel has begun.struct Superseded<'a> { file: cotton_tools::mcp::handlers::records_2::search::FileSearchDriver<'a>, flight: Option<&'a FindFlight>,}impl Superseded<'_> { fn check(&self) -> Result<(), cotton_core::rules::search_everything::SearchError> { match self.flight.filter(|flight| flight.cancelled()) { Some(_) => Err(cotton_core::rules::search_everything::SearchError::Driver(SUPERSEDED.to_string())), None => Ok(()), } }}impl cotton_core::rules::search_everything::SearchDriver for Superseded<'_> { fn all( &self, sql: &str, params: &[cotton_core::rules::search_everything::SqlParam], ) -> Result<Vec<cotton_core::rules::search_everything::SearchRow>, cotton_core::rules::search_everything::SearchError> { self.check()?; self.file.all(sql, params) } fn get( &self, sql: &str, params: &[cotton_core::rules::search_everything::SqlParam], ) -> Result<Option<cotton_core::rules::search_everything::SearchRow>, cotton_core::rules::search_everything::SearchError> { self.check()?; self.file.get(sql, params) }}