//! 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.<name>`** — 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;pubmod 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.pubmod chat;pubmod mail_history;pubmod business;pubmod adopt;pubmod link_open;pubmod personal_object;pubmod account_delete;pubmod restore;pubmod account_passkey;pubmod getting_in;pubmod signin_approval;pubmod copy_aside;pubmod copy_standing;pubmod first_sync;pubmod card_actions;pubmod card_when;pubmod date_choices;pubmod opened;pubmod today_deck;pubmod 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.pubmod commands;/// `project.conversation` — the phone opening a project's standing/// conversation, and the row a project page carries.pubmod conversation;pubmod database_appearance;pubmod database_calls;pubmod databases;pubmod sync_state;pub(crate) mod stamps;pub(crate) mod find_words;pub(crate) mod presence;pubmod device_here;pubmod device_preferences;pubmod film_intake;pubmod film_subtitle_file;pubmod song_intake;pubmod money;pubmod film_player;pubmod cinemas_home;pubmod cinemas_shared;pubmod films;/// What this device keeps of each podcast episode (`episodes.here.*`)./// What this device keeps of each book's file (`books.here.*`, `books.remove`).pubmod books;/// What this device keeps of each picture in the library (Cotton Photos' On this phone).pubmod pictures_here;/// `reader.open` — the phone's own act that opens a book.pubmod reader;/// `passkey.*` — what Cotton Keys' credential provider hands the app.pubmod passkeys;pubmod passwords;/// `keys.*` — Cotton Keys as a whole password manager: every kind, codes, the generator, Health, AutoFill, the bin, the exports.pubmod keys;/// Cotton Calling's calls (`calls.*`).pubmod calls;pubmod chat_ahead;pubmod chat_face;pubmod chat_app;/// Comms' You, grouped (`chat.you`).pubmod chat_you;pubmod sites;pubmod chat_storage;/// The voice player's core half: the speed, and waveforms for old voice messages.pubmod chat_voice;pubmod chat_people;pubmod chat_calls;pubmod call_notes;pubmod chat_recordings;pubmod chat_files;pubmod cotton_chat;pubmod chat_group;pubmod chat_agent;pubmod chat_ratchet;pubmod chat_safety;pubmod chat_sms;pubmod chat_timer;pub(crate) mod chat_revoked;pubmod cotton_send;pubmod send_seal;pubmod shared_list;pubmod your_people;pubmod circle;pubmod 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.pubmod days;pubmod days_google;pubmod days_people;pubmod days_invite;pubmod days_push;pubmod story;/// Cotton Health: HealthKit's readings landed sealed, the export read, the summaries.pubmod health;pubmod contacts_io;pubmod contacts_labels;pubmod health_app;pubmod 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`).pubmod songs;pubmod songs_zip;/// `shell.player` — Music's player: the queue, the listen and the settings row.pubmod shell_player;/// `object.act` — an admitted act at the person's own object (a podcast subscribed or read now).pubmod book_acts;pubmod object_acts;pubmod rekey;pubmod devices;pubmod dictation;pubmod disk;pubmod domains;pubmod export;/// The Cotton package: `package.export` and `package.import`.pubmod package;pubmod feedback_note;pubmod feedback_send;pubmod media_describe;pubmod front_door;pubmod 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.pubmod io_trouble;pubmod joined_places;pubmod keep;/// `keep.rules`, `keep.set`, `keep.clear` — what this phone keeps, through/// the keep-rule tools.pubmod keep_rules;pubmod keyboard;pubmod list_head;pubmod mail_index;pub(crate) mod landed;pubmod file_check;pubmod media;/// The pictures sweep: the thumbnails a phone on the personal object fetches/// ahead of its screens, after every pass.pubmod media_sweep;pubmod trim;pubmod dev_served_copy;pubmod dev_kept_pictures;pubmod dev_whatsapp_faces;pubmod dev_senders;pubmod dev_people_walk;pubmod dev_look;pubmod dev_unsent;pubmod dev_revoke;pubmod dev_fake_mac;pubmod seal_kept;/// `meetings.create` — a recording (made here or brought in) becomes a meeting/// the server's pipeline transcribes.pubmod meetings_app;pubmod member_actions;pubmod members;pubmod owner;/// Me's name and picture, carried one way to the owner's person in every/// shared database.pubmod owner_face;pubmod page;pubmod share_door;pubmod share_fetch;pubmod look;pubmod backup;pubmod notes;pubmod notes_import;pubmod notes_side;pubmod notes_assistant;pubmod notes_files;pubmod notes_export;pubmod notes_pdf;pubmod 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.pubmod people_city;pubmod published_reader;pubmod people_prints;/// `phrase.parse` — the local phrase parser, through the same `parse_phrase`/// handler an assistant calls.pubmod phrase;pubmod 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.pubmod push;pubmod seal;pubmod person_key;pubmod 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.pubmod reads_work;pubmod record_acts;pubmod samples;/// Cross-database record moves, signed to the serving Mac.pubmod 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.pubmod record_thread;/// `definitions.tables`, `definitions.tools` and the eight `records.*`/// generic verbs — each verb its MCP tool, through the same handler.pubmod 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.pubmod rejected;/// The local reminder pass's desired set — a read with no screen, and so a/// method until the read table can hold one.pubmod reminders;pubmod routes;/// The project scope on the LIST reads (Mac redesign spec §4).pubmod scope;pubmod serve_from;pubmod become_runner;/// `definitions.catalogue` — every definition a database draws, decoded by the core.pubmod catalogue;pubmod session_queue;pubmod settings_devices;pubmod metering;pubmod settings_support_reads;pubmod settings_list;pubmod settings_message_imports;pubmod settings_writes;/// `spotify.*` — Spotify on the person's own object.pubmod spotify;pubmod stale_copy;pubmod storage;/// The Code tool's raw terminal — four methods and two events.pubmod terminal;pubmod theme_save;pubmod tools;/// A tool's own acts (`tools.act`): Connect Google Calendar, Connect Spotify.pubmod fan_tile;pub(crate) mod face_choice;pubmod tool_acts;pubmod tool_views;/// The composed reads behind people's traffic and money (4g).pubmod traffic;pubmod 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.pubmod assistants;/// Account › Assistants › one assistant: what each key may do (ADMIN KEYS 3).pubmod assistant_keys;pubmod owner_asks;pubmod unlock;pubmod vault;pubmod secrets_app;pubmod contacts_app;pubmod contacts_same;pubmod contacts_facts;/// Cotton Data: what is inside the database, read only (assets/design/data/CONTRACT.md).pubmod data_app;/// Cotton Contacts: groups, archive and unarchive (assets/design/shared/CONTACTS-ANSWERS.md).pubmod contacts_groups;pubmod albums_app;pubmod albums_faces;pubmod albums_shared;pubmod vault_app;pub(crate) mod vault_carry;pubmod vault_approval;pubmod recovery;pubmod recovery_circle;pubmod recovery_screens;pubmod voice;pubmod voice_methods;pub(crate) mod voice_words;pubmod whatsapp;/// `import.whatsappExport` — route 2 of the WhatsApp runbook, on the phone.pubmod whatsapp_import;pubmod you;use serde_json::{json, Map, Value};usecrate::handle::CottonHandle;usecrate::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<Map<String, Value>, 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}"), )), }}pubfn write(handle: &CottonHandle, request: &Value) -> Result<Value, MethodError> {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() {returnErr(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.<name>` — answer one screen's query.pubfn read(handle: &CottonHandle, method: &str, request: &Value) -> Result<Value, MethodError> {letSome(entry) = reads::read_for(method) else {returnErr(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)]letmut 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();ifletSome(id) = client.reading_database_id() {ifletSome(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<String, Value> {ifletSome(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.pubfn answer_read( client: &crate::shell::client::ClientController, entry: &reads::ScreenRead, args: &Map<String, Value>,) -> Result<Value, String> {// Home's card set and Today never wait on the shared read pool: every// connection they take is the short lane's (`ShortRead`).ifletSome(short) = crate::shell::client::ShortRead::named(&format!("read.{}", entry.name)) {returncrate::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<String, Value>,) -> Result<Value, String> {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)? { returnOk(()); } }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.letSome(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))?;letmut 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()), );ifletSome(kind) = record_kind {letmut ids: Vec<String> = 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<String, Value>,) -> Result<Value, String> {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) => {letmut 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.pubfn method_names() -> Vec<String> {letmut names: Vec<String> = 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;pubmod 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;