//! The PHONE's own method families: the route table, the per-screen reads, and //! the one `write`. //! //! Design P3 and P4. What is here is the answer to two questions the Mac never //! had to ask, because a table browser reads columns and authors seventeen //! verbs, and a phone draws designed screens and authors everything: //! //! * **`write`** — one method taking a tool name and arguments, running the //! handler an assistant would run, over the REPLICA, into the outbox. //! [`crate::authoring`] is the body and it is shared with the Mac's //! window, which is what makes "one implementation of who wins" a compiled //! function. //! * **`read.`** — one method per screen query, declared in [`reads`] //! with the screen beside it and held to [`routes`] by a totality test. //! * **`export.build`** — "Export everything", the one method that answers //! with a FILE. It is neither a screen query nor a write, which is why it //! is its own name rather than a read: it walks the whole database in one //! pass and leaves a JSON document on disk for the share sheet. [`export`] //! is the body. //! //! **This module compiles and DISPATCHES on every build** (H1). It is named //! `phone` because the phone was the caller that needed every one of these //! first; a Mac answers the same names over its replica exactly as the phone //! does. Nothing in here is gated on a feature — //! `host` is the crate's only feature and it ADDS the server's methods; it //! takes none of these away. See `super::methods`. // ── 4h: the six owner-HTTP families, the geocoder, and the five settings // writes the tool surface owes no verb ───────────────────────────── // // Each module's // header says why it is a method rather than a read or a tool; [`owner`] is // the seam the HTTP families share and the one place a server refusal becomes // a `MethodError`. // // ON EVERY BUILD since H1. The five HTTP families need `net()`, which every // build now assembles at open — a serving Mac holds one with no remembered // address, so on it they refuse by name (`no_server`) rather than answering // `unknown_method`: the capability exists, the address does not. `settings_writes` writes through the one // authoring path, over whichever rail this build has. /// `/activity` — the replica's own facts, the assistant's runs and the audit /// trail, and the ONE implementation of "how many runs are in flight" that Home /// reads too. /// /// A sibling module rather than another block in [`reads`] because the query is /// ~150 lines and that file is already 2,800. pub(crate) mod mail_imap; pub mod activity; /// The OWNER'S own half of a conversation read (4m): the star, the reply /// anchor, the two windows, this person's own reaction and the private /// columns of the conversation itself — plus the visibility rule that drops /// what this device has hidden or cleared. /// /// A sibling module rather than more lines in [`traffic`] because it is the /// second half of a read the TOOL owns, and the split is the point: what an /// assistant may see, and what only the owner's own devices write. pub mod chat; pub mod mail_history; pub mod business; pub mod adopt; pub mod link_open; pub mod personal_object; pub mod account_delete; pub mod restore; pub mod account_passkey; pub mod getting_in; pub mod signin_approval; pub mod copy_aside; pub mod copy_standing; pub mod first_sync; pub mod card_actions; pub mod card_when; pub mod date_choices; pub mod opened; pub mod today_deck; pub mod code; pub(crate) mod code_preferences; pub(crate) mod settings_code_defaults; pub(crate) mod settings_database; pub(crate) mod settings_flows; pub(crate) mod settings_everything; /// Applies this Mac's synced Storage Files choice after a replica fold. pub(crate) mod device_keep_bytes; /// The three long-running commands: `join.*`, `bootstrap.*` and `migrate.*`. /// /// On every build: they hold threads, a socket and the state of a join. A Mac /// ALSO has `connect.*` for the same question, because on a Mac "which server /// do I read from" and "am I serving" are one act and `role.json` is written /// beside the connection. pub mod commands; /// `project.conversation` — the phone opening a project's standing /// conversation, and the row a project page carries. pub mod conversation; pub mod database_appearance; pub mod database_calls; pub mod databases; pub mod sync_state; pub(crate) mod stamps; pub(crate) mod find_words; pub(crate) mod presence; pub mod device_here; pub mod device_preferences; pub mod film_intake; pub mod film_subtitle_file; pub mod song_intake; pub mod money; pub mod film_player; pub mod cinemas_home; pub mod cinemas_shared; pub mod films; /// What this device keeps of each podcast episode (`episodes.here.*`). /// What this device keeps of each book's file (`books.here.*`, `books.remove`). pub mod books; /// What this device keeps of each picture in the library (Cotton Photos' On this phone). pub mod pictures_here; /// `reader.open` — the phone's own act that opens a book. pub mod reader; /// `passkey.*` — what Cotton Keys' credential provider hands the app. pub mod passkeys; pub mod passwords; /// `keys.*` — Cotton Keys as a whole password manager: every kind, codes, the generator, Health, AutoFill, the bin, the exports. pub mod keys; /// Cotton Calling's calls (`calls.*`). pub mod calls; pub mod chat_ahead; pub mod chat_face; pub mod chat_app; /// Comms' You, grouped (`chat.you`). pub mod chat_you; pub mod sites; pub mod chat_storage; /// The voice player's core half: the speed, and waveforms for old voice messages. pub mod chat_voice; pub mod chat_people; pub mod chat_calls; pub mod call_notes; pub mod chat_recordings; pub mod chat_files; pub mod cotton_chat; pub mod chat_group; pub mod chat_agent; pub mod chat_ratchet; pub mod chat_safety; pub mod chat_sms; pub mod chat_timer; pub(crate) mod chat_revoked; pub mod cotton_send; pub mod send_seal; pub mod shared_list; pub mod your_people; pub mod circle; pub mod share_sheet; /// Cotton Pages: a kept page's readable copy and the pile's export. /// Cotton Trips: a trip card's slots, a trip whole and the Places shelves. pub mod days; pub mod days_google; pub mod days_people; pub mod days_invite; pub mod days_push; pub mod story; /// Cotton Health: HealthKit's readings landed sealed, the export read, the summaries. pub mod health; pub mod contacts_io; pub mod contacts_labels; pub mod health_app; pub mod health_card; /// Cotton Music on the phone: `music.capture`, what this device keeps of each /// song's file (`songs.here.*`, `songs.remove`, `songs.keepEverything`) and /// an album's lookups (`music.findDetails`). pub mod songs; pub mod songs_zip; /// `shell.player` — Music's player: the queue, the listen and the settings row. pub mod shell_player; /// `object.act` — an admitted act at the person's own object (a podcast subscribed or read now). pub mod book_acts; pub mod object_acts; pub mod rekey; pub mod devices; pub mod dictation; pub mod disk; pub mod domains; pub mod export; /// The Cotton package: `package.export` and `package.import`. pub mod package; pub mod feedback_note; pub mod feedback_send; pub mod media_describe; pub mod front_door; pub mod google; /// The ONE place a `std::io::Error` becomes something a person reads — the raw /// text goes to the log and never to a toast. pub mod io_trouble; pub mod joined_places; pub mod keep; /// `keep.rules`, `keep.set`, `keep.clear` — what this phone keeps, through /// the keep-rule tools. pub mod keep_rules; pub mod keyboard; pub mod list_head; pub mod mail_index; pub(crate) mod landed; pub mod file_check; pub mod media; /// The pictures sweep: the thumbnails a phone on the personal object fetches /// ahead of its screens, after every pass. pub mod media_sweep; pub mod trim; pub mod dev_served_copy; pub mod dev_kept_pictures; pub mod dev_whatsapp_faces; pub mod dev_senders; pub mod dev_people_walk; pub mod dev_look; pub mod dev_unsent; pub mod dev_revoke; pub mod dev_fake_mac; pub mod seal_kept; /// `meetings.create` — a recording (made here or brought in) becomes a meeting /// the server's pipeline transcribes. pub mod meetings_app; pub mod member_actions; pub mod members; pub mod owner; /// Me's name and picture, carried one way to the owner's person in every /// shared database. pub mod owner_face; pub mod page; pub mod share_door; pub mod share_fetch; pub mod look; pub mod backup; pub mod notes; pub mod notes_import; pub mod notes_side; pub mod notes_assistant; pub mod notes_files; pub mod notes_export; pub mod notes_pdf; pub mod notes_share; /// `people.fillCities` — the city of every person who has a zone and never had a /// city, filled in from the zone by Cotton itself. pub mod people_city; pub mod published_reader; pub mod people_prints; /// `phrase.parse` — the local phrase parser, through the same `parse_phrase` /// handler an assistant calls. pub mod phrase; pub mod pictures; /// This device's APNs token, told to the server, and the memory of when it last /// was. /// /// `PUT /v1/devices` is signed by this device's key. The phone is the only /// caller: a serving Mac registers no push token — it IS the thing that sends /// them — and refuses here by name, having no remembered address. pub mod push; pub mod seal; pub mod person_key; pub mod reads; /// The work-and-reference lane's query bodies (sub-step 4f), declared in /// [`reads`] and implemented there so three lanes filling one table conflict /// on an append rather than on four hundred lines of query. pub mod reads_work; pub mod record_acts; pub mod samples; /// Cross-database record moves, signed to the serving Mac. pub mod record_moves; /// `read.record`'s second half — the conversation on a record. /// /// A sibling module rather than another block in [`reads`] for the reason /// [`activity`] is one: the join is its own subject, and that file is already /// 2,800 lines. pub mod record_thread; /// `definitions.tables`, `definitions.tools` and the eight `records.*` /// generic verbs — each verb its MCP tool, through the same handler. pub mod records; pub(crate) mod records_live; /// `sync.rejected` / `sync.retryRejected` — the writes this file could not /// fold, and one more go at them. No screen yet; the names exist so a person /// diagnosing a row that reached one device and not another has something to /// ask. pub mod rejected; /// The local reminder pass's desired set — a read with no screen, and so a /// method until the read table can hold one. pub mod reminders; pub mod routes; /// The project scope on the LIST reads (Mac redesign spec §4). pub mod scope; pub mod serve_from; pub mod become_runner; /// `definitions.catalogue` — every definition a database draws, decoded by the core. pub mod catalogue; pub mod session_queue; pub mod settings_devices; pub mod metering; pub mod settings_support_reads; pub mod settings_list; pub mod settings_message_imports; pub mod settings_writes; /// `spotify.*` — Spotify on the person's own object. pub mod spotify; pub mod stale_copy; pub mod storage; /// The Code tool's raw terminal — four methods and two events. pub mod terminal; pub mod theme_save; pub mod tools; /// A tool's own acts (`tools.act`): Connect Google Calendar, Connect Spotify. pub mod fan_tile; pub(crate) mod face_choice; pub mod tool_acts; pub mod tool_views; /// The composed reads behind people's traffic and money (4g). pub mod traffic; pub mod usage; /// `vault.*` — the passwords, sealed and opened by THIS device. /// /// It replaced `secrets.set`, whose whole reason was that the phone had no /// cipher and had to post a credential to the one process that did. Since /// schema v6 this device holds its own X25519 key in the Keychain and seals /// locally; the family writes through the ordinary outbox like every other /// write here, and the reveal never leaves the device. pub mod assistants; /// Account › Assistants › one assistant: what each key may do (ADMIN KEYS 3). pub mod assistant_keys; pub mod owner_asks; pub mod unlock; pub mod vault; pub mod secrets_app; pub mod contacts_app; pub mod contacts_same; pub mod contacts_facts; /// Cotton Data: what is inside the database, read only (assets/design/data/CONTRACT.md). pub mod data_app; /// Cotton Contacts: groups, archive and unarchive (assets/design/shared/CONTACTS-ANSWERS.md). pub mod contacts_groups; pub mod albums_app; pub mod albums_faces; pub mod albums_shared; pub mod vault_app; pub(crate) mod vault_carry; pub mod vault_approval; pub mod recovery; pub mod recovery_circle; pub mod recovery_screens; pub mod voice; pub mod voice_methods; pub(crate) mod voice_words; pub mod whatsapp; /// `import.whatsappExport` — route 2 of the WhatsApp runbook, on the phone. pub mod whatsapp_import; pub mod you; use serde_json::{json, Map, Value}; use crate::handle::CottonHandle; use crate::methods::MethodError; /// `write` — author as this device, by calling the tool an assistant calls. /// /// The tool name is checked against the catalogue BEFORE anything opens a /// transaction, so a typo reads as a vocabulary refusal rather than as a write /// that failed. A tool that exists but is not implemented on this build says /// exactly that, which is a different fact and the two must not be confused. /// A method that IS an MCP tool takes the tool's arguments as its request: /// the request object itself, an absent body read as `{}` — shared by /// `records.*` ([`records`]) and `phrase.parse` ([`phrase`]). pub(crate) fn tool_arguments(request: &Value) -> Result, MethodError> { match request { Value::Object(args) => Ok(args.clone()), Value::Null => Ok(Map::new()), other => Err(MethodError::new( "bad_request", format!("the request is the tool's arguments as one object, not {other}"), )), } } pub fn write(handle: &CottonHandle, request: &Value) -> Result { let tool = request .get("tool") .and_then(Value::as_str) .ok_or_else(|| MethodError::new("bad_request", "`tool` is the name of the tool to run"))?; if cotton_tools::mcp::protocol::tool_by_name(tool).is_none() { return Err(MethodError::new( "unknown_tool", format!("`{tool}` is not a tool this database has"), )); } let args = request .get("args") .and_then(Value::as_object) .cloned() .unwrap_or_default(); handle .client() .write(tool, &args) .map_err(|reason| MethodError::new("write_refused", reason)) } /// `read.` — answer one screen's query. pub fn read(handle: &CottonHandle, method: &str, request: &Value) -> Result { let Some(entry) = reads::read_for(method) else { return Err( MethodError::new("unknown_method", format!("this core answers no `{method}`")) .with_details(json!({ "known": reads::method_names() })), ); }; let began = std::time::Instant::now(); let steps = cotton_store::driver::Driver::thread_steps(); #[allow(unused_mut)] let mut answer = answer_read(&handle.client(), entry, &read_args(request)).map_err(|reason| { // A read the POOL refused (busy, or too long for the short lane) // is not a copy that cannot be read: it never offers removal. let pool_refused = cotton_client::replica::peek_read_refusal().is_some(); if method == "read.home" && reason.starts_with("read.home.open/read:") && !pool_refused && !reason.contains("sqlite: interrupted") { let client = handle.client(); if let Some(id) = client.reading_database_id() { if let Some(held) = client .databases() .ok() .and_then(|held| held.into_iter().find(|held| held.id == id)) { crate::shell::refused_copies::observe(&client, &id, &held.name, &reason); } } } MethodError::new("unreadable", reason) })?; crate::shell::diagnostics::read_took( method, began.elapsed(), cotton_store::driver::Driver::thread_steps().saturating_sub(steps), &answer, ); // Home's backup notice: this Mac's own daily copies when it serves, then // the Mac's name off the device rows. if method == "read.servingBackup" { crate::methods::host_settings::name_the_mac(&handle.client(), &mut answer); crate::methods::host_settings::say_backup_line(&mut answer, chrono::Utc::now()); } Ok(answer) } /// A read's arguments, whether the caller nested them or not. /// /// **`{"args": {…}}` and `{…}` are the same request, deliberately.** The /// boundary took the nested spelling only, from 4a onwards, and the app sends /// the FLAT one nearly everywhere: 26 of the 31 argument-taking read call sites /// in `apps/cotton` pass a request whose properties ARE the arguments /// (`RecordReadRequest`, `TodoIdRequest`, `PersonReadRequest`, `EventReadRequest`, /// …), and five nest. Every one of the 26 was therefore answering with an EMPTY /// argument map, which each read turned into its own refusal — `get_record` /// says *"kind is required"* — and each screen drew as its dead end. Measured /// on the simulator in 4k: a note opened *"This page isn't here anymore"* and a /// todo *"This todo isn't here any more"*, on a phone whose replica held both /// rows. /// /// **Nothing above or below could see it.** Below, every read takes a flat /// `&Map` and every crate test passes one, so the reads themselves were right. /// Above, `ScriptedCore` answers by METHOD NAME and never looks at the request, /// so no screen test could tell the two spellings apart — 3,300 green tests and /// sixteen screens that could not open a record. /// /// So the widening is HERE, in the one place both spellings arrive, rather than /// in 26 Swift types plus the 27th somebody writes next month. It hides /// nothing: a request that names `args` is read as nesting them, one that does /// not IS them, and a read with no arguments sends `{}` either way. pub(crate) fn read_args(request: &Value) -> Map { if let Some(nested) = request.get("args").and_then(Value::as_object) { return nested.clone(); } request.as_object().cloned().unwrap_or_default() } /// Run one declared read against this controller. /// /// Lifted out of [`read`] so the tests drive a read the SAME way `cotton_call` /// does. A second copy of this `match` in a test harness is a place the two can /// disagree, and a test that disagrees with the dispatch is a test that proves /// nothing about the app. pub fn answer_read( client: &crate::shell::client::ClientController, entry: &reads::ScreenRead, args: &Map, ) -> Result { // Home's card set and Today never wait on the shared read pool: every // connection they take is the short lane's (`ShortRead`). if let Some(short) = crate::shell::client::ShortRead::named(&format!("read.{}", entry.name)) { return crate::shell::client::on_short_lane(short, || answer_read_on(client, entry, args)); } answer_read_on(client, entry, args) } fn answer_read_on( client: &crate::shell::client::ClientController, entry: &reads::ScreenRead, args: &Map, ) -> Result { if cotton_core::flavor::single_database() { let shipped = cotton_core::definitions::builtin_table_definitions(); let keys: Vec<&str> = shipped.iter().filter_map(|definition| { let tool = definition.tool.as_ref()?; let root = tool.route.as_deref()?; entry.audience.screens().iter().any(|route| *route == root || route.strip_prefix(root).is_some_and(|rest| rest.starts_with('/'))) .then_some(tool.key.as_deref()).flatten() }).collect(); if !keys.is_empty() { client.with_file(|file| { for key in &keys { if cotton_tools::home_arrangement::tool_held(file.driver, file.workspace_id, key)? { return Ok(()); } } Err(format!("no such tool here: {}", keys.join(", "))) })?; } } // THE PROJECT SCOPE, once, for every read (`scope.rs`). Unscoped — the // phone, always — the read sees exactly what it always saw, minus any // seam-internal key a caller tried to send. let Some(slugs) = scope::requested(args)? else { return dispatch_read(client, entry, &scope::without_scope(args)); }; // The narrowing is declared on the read's own entry (`reads.rs`). let narrowing = entry .scope .ok_or_else(|| format!("read.{} cannot be narrowed by project", entry.name))?; let project_ids = client.with_file(|replica| scope::resolve(replica, &slugs))?; let mut inner = scope::without_scope(args); match narrowing { scope::Narrowing::After(lists) => { let answer = dispatch_read(client, entry, &inner)?; client.with_file(|replica| scope::narrow(replica, &project_ids, lists, answer)) } scope::Narrowing::InRead { record_kind } => { inner.insert( scope::PROJECT_IDS.to_string(), Value::from(project_ids.clone()), ); if let Some(kind) = record_kind { let mut ids: Vec = client .with_file(|replica| scope::members(replica, &project_ids, kind))? .into_iter() .collect(); ids.sort(); inner.insert(scope::RECORD_IDS.to_string(), Value::from(ids)); } dispatch_read(client, entry, &inner) } } } /// The dispatch itself, over arguments the scope has already been taken out of. fn dispatch_read( client: &crate::shell::client::ClientController, entry: &reads::ScreenRead, args: &Map, ) -> Result { match entry.source { // The screen's query IS the tool's list, so the handler is called // rather than restated (P4). It runs through the same `Ctx::phone` a // write does — a read tool writes nothing, and the catalogue's own // scope is what says so. reads::ReadSource::Tool(tool) => client.read_tool(tool, args), // The same handler, told to answer the whole set. The argument is // ADDED to the screen's own rather than replacing them, and a screen // that names its own `limit` keeps it — the seam states a default, it // does not overrule a caller. reads::ReadSource::ToolWholeSet(tool) => { let mut whole = args.clone(); whole .entry("limit".to_string()) .or_insert_with(|| Value::from(cotton_tools::mcp::handlers::common::WHOLE_SET)); client.read_tool(tool, &whole) } // Named in its hold, so a slow one says which read it was rather than // "nothing that named itself" at this line. reads::ReadSource::Query(query) => client.with_file(|replica| { cotton_store::held::doing(&format!("read.{}", entry.name)); query(replica, args) }), reads::ReadSource::Controller(answer) => answer(client, args), // Several tools plus a join, over one `Ctx` and inside one transaction // — and refused with a rollback if any part of it wrote. reads::ReadSource::Composed(compose) => { client.read_rows(entry.name, &mut |ctx| compose(ctx, args)) } } } /// Every method name the CLIENT half answers, on every build. /// /// Assembled rather than written out because the `read.*` half IS /// [`reads::READS`], and a second hand-kept list of the same names is the /// drift the whole table exists to prevent. pub fn method_names() -> Vec { let mut names: Vec = crate::methods::CLIENT_METHODS .iter() // `read` is the FAMILY's stand-in in the partition list, and the family // is expanded from `reads::READS` below. Leaving the bare word in would // offer an app a method that answers nothing. .filter(|name| **name != "read") .map(|name| (*name).to_string()) .collect(); names.extend(reads::method_names()); names.extend( commands::COMMAND_METHODS .iter() .map(|name| name.to_string()), ); names.extend( commands::MIGRATE_METHODS .iter() .map(|name| name.to_string()), ); names.sort(); // The command lists and `CLIENT_METHODS` both name `join.*`: one is the // partition's word on which build owns the name, the other the module's // own table of what it answers. One list for the app, said once. names.dedup(); names } #[cfg(test)] #[path = "code_tests.rs"] mod code_tests; #[cfg(test)] #[path = "commands_tests.rs"] mod commands_tests; #[cfg(test)] #[path = "traffic_tests.rs"] mod traffic_tests; #[cfg(test)] #[path = "mail_search_tests.rs"] mod mail_search_tests; #[cfg(test)] #[path = "thread_first_page_tests.rs"] mod thread_first_page_tests; #[cfg(test)] #[path = "pictures_tests.rs"] mod pictures_tests; #[cfg(test)] #[path = "media_tests.rs"] mod media_tests; #[cfg(test)] #[path = "writes_tests.rs"] mod writes_tests; #[cfg(test)] #[path = "owner_tests.rs"] mod owner_tests; #[cfg(test)] #[path = "transfer_tests.rs"] mod transfer_tests; #[cfg(test)] #[path = "settings_tests.rs"] mod settings_tests; #[cfg(test)] #[path = "you_tests.rs"] mod you_tests; #[cfg(test)] #[path = "records_tests.rs"] mod records_tests; #[cfg(test)] #[path = "launch_outbox_tests.rs"] mod launch_outbox_tests; #[cfg(test)] #[path = "launch_speed_tests.rs"] mod launch_speed_tests; #[cfg(test)] #[path = "reader_open_tests.rs"] mod reader_open_tests; #[cfg(test)] #[path = "phone_only_tests.rs"] mod phone_only_tests; mod founding; pub mod camera; #[cfg(test)] #[path = "camera_tests.rs"] mod camera_tests; pub(crate) mod database_bin; #[cfg(test)] #[path = "photos_tests.rs"] mod photos_tests; #[cfg(test)] #[path = "kit_tables_tests.rs"] mod kit_tables_tests;