Cotton code
491 lines · 20.3 KB · RustRaw
//! Each catalogue tool's PLACES CLASS — which database one call runs in//! (design 3.8, ninth draft).//!//! Every tool takes `database`: a file id or a registry name in the token's//! reach ("no such database" otherwise). An existing-record write uses the record's home. A create with no named//! database uses the session's project binding (or a project credential's//! own file), else refuses with "name the database". One call runs in one database. The classes//! say the two ways a tool departs from that.//!//! Keyed by tool name, as data, in a file of its own rather than on the//! entries of `catalogue.rs`: the wrapper that runs every call//! (`cotton_server::mcp::places`) reads the class and nothing else, and a//! class a reviewer can read down one column is a class nobody chose by//! accident. `places_classes_tests` makes the table total over the catalogue//! and holds the rules a class must keep.//!//! | class | behaviour |//! |---|---|//! | [`PlacesClass::OneFile`] | ordinary writes use `database`, named project, or binding, else refuse; reads discover the home; ids resolve in that one file; a bulk call is one file, one transaction |//! | [`PlacesClass::Feed`] | `today_agenda`, `search_records`, `search_documents`: `database: "all"` asks every file in reach, rows carry `database` and `databaseId`, each file keeps its cursor, counts are never summed — here only |//! | [`PlacesClass::PersonalOnly`] | mail, a chat's private state, calls, the contacts import, Code sessions and their tools, devices, `dev_` tools, provider keys, Connected AIs, and storage: run in the personal database (albums and the journal are ordinary: each database keeps its own; so are the Messages READS, since a chat filed in a shared database is read there); a project database named is refused with a sentence; a seat or project token gets "no such tool here" |//! | [`PlacesClass::PersonalInto`] | a reader's own pin, mute, archive and clear of a chat (filed or not): run in the personal database, and `database` is the tool's OWN argument — the other database the act is about, which must be in reach; a seat or project token gets "no such tool here" |/// Which way one order key runs.#[derive(Debug, Clone, Copy, PartialEq, Eq)]pub enum Dir {    Asc,    Desc,}/// One array of rows in a merged answer, and the order it is merged by.////// `order` names fields the ROWS carry, as emitted. A null or absent key/// sorts after every value, in either direction; a tie keeps file order, the/// personal database first. An EMPTY order is declared where the tool's own/// order is a key its rows do not carry (a search rank): each file's rows/// then follow the file before's, in that file's own order.#[derive(Debug, Clone, Copy, PartialEq, Eq)]pub struct MergeList {    pub key: &'static str,    pub order: &'static [(&'static str, Dir)],}/// One id argument whose DATABASE another argument may name.////// `path` is a top-level argument (`"toId"`) or one field of each item of an/// array argument (`"records[].id"`); `database` is the argument that says/// which file that id lives in (`create_link`'s `toDatabase`,/// `create_session`'s `todoDatabase`). The wrapper checks every database so/// named is in the token's reach — "no such database" otherwise — before the/// call runs; the handler then resolves the id in that file. Nothing else/// about an id is the wrapper's: every other id resolves in the one file the/// call runs in.#[derive(Debug, Clone, Copy, PartialEq, Eq)]pub struct IdPath {    pub path: &'static str,    pub database: &'static str,}/// How a tool chooses the database it runs in.#[derive(Debug, Clone, Copy, PartialEq, Eq)]pub enum PlacesClass {    /// Runs in `database`, else the token's own. `ids` are the id arguments    /// whose database another argument may name; empty for most tools.    OneFile { ids: &'static [IdPath] },    /// A read across databases. Without `database`, or with one named, it is    /// `one_file`; with `database: "all"` every file in reach answers and the    /// `lists` merge by their own order, each row stamped `database` and    /// `databaseId`, every other top-level field (counts) answered per    /// database under `byDatabase`. Never a write: `no_write_tool_is_classed_feed`.    Feed { lists: &'static [MergeList] },    /// Runs in the personal database. `what` is the kind the refusal names    /// when `database` is a project database: "<What> lives in your personal    /// database, not in <name>." `ids` as on `one_file`.    PersonalOnly {        what: &'static str,        ids: &'static [IdPath],    },    /// An act of the personal database ABOUT another one: filing a chat of    /// the personal Messages in a shared database, and unfiling it; and a    /// reader's own pin, mute, archive or clear of a chat filed there, kept    /// in their personal database (left out, the chat is the personal one's    /// own). It runs    /// in the personal database, where the chat and the filing's row are, and    /// `database` does not say where it runs: it is the tool's own argument,    /// declared in its schema, naming the database the chat is filed in. The    /// wrapper holds that database to the token's reach ("no such database"    /// otherwise) and hands the tool its id, whichever of id or name the    /// caller gave. These are the ONLY tools whose schema declares `database`    /// (`only_an_act_on_another_database_declares_database`).    PersonalInto,}const fn at_in(path: &'static str, database: &'static str) -> IdPath {    IdPath { path, database }}const fn list(key: &'static str, order: &'static [(&'static str, Dir)]) -> MergeList {    MergeList { key, order }}/// The tool's order is a key its rows do not carry. See [`MergeList`].const OWN_ORDER: &[(&str, Dir)] = &[];use Dir::Asc;/// The ordinary class: this database, or the token's own.const ONE: PlacesClass = PlacesClass::OneFile { ids: &[] };const fn personal(what: &'static str) -> PlacesClass {    PlacesClass::PersonalOnly { what, ids: &[] }}const MAIL: PlacesClass = personal("Mail");/// One reader's own marks on a chat — unread, a kept message, a message/// deleted from his copy, the chat deleted. The chat itself may be filed in a/// shared database; these never are, so the kind is not "Messages".////// NOT where a chat stands in the list (pinned, muted, archived, cleared) nor/// the read stamp its page makes on opening: those are ordinary, and act on/// the chat in the database named — in a shared database the FILED COPY,/// never the filer's personal chat of the same id.const CHAT_STATE: PlacesClass = personal("A reader's own mark on a chat (unread, kept, deleted)");const CALLS: PlacesClass = personal("Calls");const MONEY: PlacesClass = ONE;const CONTACTS_IMPORT: PlacesClass = personal("The contacts import");const SESSIONS: PlacesClass = personal("Code sessions");const DEVICES: PlacesClass = personal("Devices");const DEV: PlacesClass = personal("Developer tools");const CONNECTED: PlacesClass = personal("Connected AIs");const STORAGE: PlacesClass = personal("Storage");const TOOLKITS: PlacesClass = personal("Toolkits");const CONNECTIONS: PlacesClass = personal("Connections");/// Every catalogue tool's class. Grouped as the catalogue is; the guard reads/// it as a set.pub static PLACES_CLASSES: &[(&str, PlacesClass)] = &[    // ── language and search ──    ("parse_phrase", ONE),    // Ranked within each kind, and the rank is not emitted.    (        "search_records",        PlacesClass::Feed {            lists: &[list("records", OWN_ORDER)],        },    ),    ("get_record", ONE),    ("update_summary", ONE),    (        "today_agenda",        PlacesClass::Feed {            lists: &[                list("todos", &[("dueAt", Asc)]),                list("events", &[("startsAt", Asc)]),            ],        },    ),    // ── todos ──    ("create_todo", ONE),    ("complete_todo", ONE),    ("list_todos", ONE),    ("update_todo", ONE),    ("update_todos", ONE),    // ── notes and events ──    ("create_note", ONE),    ("create_event", ONE),    ("list_events", ONE),    ("update_event", ONE),    ("update_events", ONE),    ("delete_event", ONE),    ("delete_events", ONE),    ("append_journal", ONE),    ("update_note", ONE),    ("archive_note", ONE),    ("unarchive_note", ONE),    ("upsert_managed_note", ONE),    ("list_managed_notes", ONE),    // ── people and locations (ordinary: a team's contacts live in the team's database) ──    ("list_people", ONE),    ("create_person", ONE),    ("update_person", ONE),    ("merge_people", ONE),    ("archive_person", ONE),    ("unarchive_person", ONE),    // ── messages and mail ──    // Ordinary: a chat arrives in the personal database only, and one filed    // in a shared database is read THERE by the people of that database — a    // shared database's Messages holds its filed chats and nothing else.    ("list_message_threads", ONE),    ("read_message_thread", ONE),    ("search_messages", ONE),    // The two acts on a chat of the personal Messages that are about another    // database: `database` is theirs, the database the chat is filed in.    ("ingest_emails", MAIL),    ("list_email_threads", MAIL),    ("update_email", MAIL),    ("update_emails", MAIL),    ("list_email_senders", MAIL),    ("block_sender", MAIL),    ("unblock_sender", MAIL),    ("list_blocked_senders", MAIL),    ("add_sender_to_people", MAIL),    ("empty_junk", MAIL),    // ── the bin ──    ("list_bin", ONE),    ("restore_from_bin", ONE),    ("empty_bin", ONE),    ("read_email_thread", MAIL),    // ── money ──    ("list_money_accounts", MONEY),    ("list_money_transactions", MONEY),    ("record_transaction", MONEY),    ("update_transaction", MONEY),    ("delete_transaction", MONEY),    // A statement, its evidence and its money rows share the filed document's home.    ("read_statement", MONEY),    ("list_statements", MONEY),    ("get_statement", MONEY),    ("update_statement_line", MONEY),    ("book_statement", MONEY),    ("submit_statement_reading", MONEY),    ("attach_evidence", MONEY),    ("remove_evidence", MONEY),    ("settle_expected", MONEY),    ("set_period", MONEY),    ("set_tag", MONEY),    ("set_person", MONEY),    ("mark_transfer", MONEY),    ("match_external", MONEY),    ("create_money_account", MONEY),    ("update_money_account", MONEY),    // ── tools and the records store ──    ("export_tool", ONE),    ("import_tool", ONE),    ("list_tools", ONE),    ("list_toolkits", TOOLKITS),    ("save_toolkit", TOOLKITS),    ("update_toolkit", TOOLKITS),    ("delete_toolkit", TOOLKITS),    ("remove_tool", ONE),    ("add_tool", ONE),    ("update_definition", ONE),    ("arrange_tools", ONE),    ("list_records", ONE),    ("summarize_records", ONE),    ("get_record_by_table", ONE),    // Reservations change one database's claim table; never fan a write out.    // Copies every served database itself; never fanned out per file.    ("backup_now", ONE),    ("reserve_record", ONE),    ("cancel_reservation", ONE),    ("create_record", ONE),    ("run_record_act", ONE),    ("update_record", ONE),    ("save_theme", ONE),    ("get_board", ONE),    ("update_board", ONE),    ("delete_record", ONE),    ("reorder_records", ONE),    ("link_records", ONE),    ("undo", ONE),    ("list_groups", ONE),    ("create_group", ONE),    ("update_group", ONE),    ("delete_group", ONE),    // Connections (Spec 9.7): the rows live in the personal database only.    ("list_connections", ONE),    ("get_connection", ONE),    ("propose_connection_mapping", CONNECTIONS),    ("set_connection_mapping", CONNECTIONS),    ("connect", CONNECTIONS),    // ── thoughts and meetings (ordinary: a meeting lives with its event) ──    // ── documents ──    ("list_documents", ONE),    (        "search_documents",        PlacesClass::Feed {            lists: &[list("documents", OWN_ORDER)],        },    ),    ("get_document", ONE),    ("get_document_bytes", ONE),    ("request_document_upload", ONE),    ("file_document", ONE),    ("update_document", ONE),    ("delete_document", ONE),    ("export_package", ONE),    ("import_package", ONE),    ("notify_owner", ONE),    // ── memory, sessions and the bus ──    // An entry in a project database is that database's: no tag, no note.    ("brief", ONE),    ("recall", ONE),    ("remember", ONE),    ("log_session", ONE),    ("list_sessions", SESSIONS),    // The session lives in the personal database; the todo it starts from    // may be a project's, named by `todoDatabase` (the personal database when    // left out), which must be in reach.    (        "create_session",        PlacesClass::PersonalOnly {            what: "Code sessions",            ids: &[at_in("todoId", "todoDatabase")],        },    ),    ("get_session", SESSIONS),    ("open_project_conversation", SESSIONS),    ("archive_database", DEVICES),    ("list_databases", DEVICES),    ("list_devices", DEVICES),    // A phone's keep rules are rows of the database they are about: a group    // or a record is kept from the file it is in.    ("list_keep_rules", ONE),    ("set_keep_rule", ONE),    ("clear_keep_rule", ONE),    // A record's audience is a row of the database the record is in.    ("set_audience", ONE),    // ── projects ──    ("list_projects", ONE),    ("get_project", ONE),    ("create_project", ONE),    ("update_project", ONE),    ("link_to_project", ONE),    ("unlink_from_project", ONE),    ("memory_update", ONE),    ("memory_reorder", ONE),    ("memory_archive", ONE),    // ── feedback ──    // ── calls ──    ("list_calls", CALLS),    ("get_call", CALLS),    // ── photos and videos ──    ("list_photos", ONE),    ("get_photo", ONE),    ("get_photo_bytes", ONE),    ("update_photo", ONE),    ("add_photo", ONE),    ("remove_photo", ONE),    ("update_face", ONE),    ("list_duplicates", ONE),    ("decide_duplicate", ONE),    ("list_videos", ONE),    ("get_video", ONE),    ("update_video", ONE),    ("remove_video", ONE),    // ── albums, storage, secrets ──    ("list_albums", ONE),    ("get_album", ONE),    ("decide_album", ONE),    ("update_album", ONE),    ("create_album", ONE),    ("storage_summary", STORAGE),    ("media_repair", STORAGE),    // Passwords are ordinary: a team's passwords live in the team's database,    // under its own vault key.    ("create_secret", ONE),    ("list_secrets", ONE),    ("delete_secret", ONE),    ("update_secret", ONE),    // ── owner tools (classed for totality; no token reaches them) ──    ("restore_version", ONE),    ("make_todo_recurring", ONE),    ("update_todo_recurrence", ONE),    ("stop_todo_recurrence", ONE),    ("materialize_todo_recurrences", ONE),    ("respond_to_invite", ONE),    ("update_attendees", ONE),    ("sync_device_contacts", CONTACTS_IMPORT),    ("rename_session", SESSIONS),    ("move_session", SESSIONS),    ("move_record", ONE),    ("move_records", ONE),    // The edge is written where `fromId` lives. `toId` is in that file too,    // unless `toDatabase` names the database it is in (a link from the    // personal database into a project's), which must be in reach.    (        "create_link",        PlacesClass::OneFile {            ids: &[at_in("toId", "toDatabase")],        },    ),    ("hide_chat_messages", CHAT_STATE),    ("star_message", CHAT_STATE),    ("mark_thread_unread", CHAT_STATE),    ("delete_thread", CHAT_STATE),    // Opening a chat stamps its read cursor in the database named: on a filed    // copy in a shared database it stamps nothing (a cursor is one reader's,    // and the copy is everybody's).    ("mark_thread_read", ONE),    // Where a reader keeps a chat — pinned, muted, archived, cleared — is    // theirs alone (architect, 12 Oct 2026). On a chat of the personal    // Messages it is that chat's own row; on a chat FILED in a shared    // database it is a row of the reader's PERSONAL database naming that    // database and the copy (`cotton_msg_thread_marks`), never the copy,    // which every member reads. So each runs in the personal database, and    // `database`, when it names a shared one, is the database the copy is in.    ("set_thread_muted", PlacesClass::PersonalInto),    ("set_thread_pinned", PlacesClass::PersonalInto),    ("set_thread_archived", PlacesClass::PersonalInto),    ("clear_thread", PlacesClass::PersonalInto),    // ── developer tools (they start work on the owner's Macs) ──    ("dev_reveal_secret", DEV),];/// This tool's class, or `None` for a name the table does not hold.pub fn class_of(name: &str) -> Option<&'static PlacesClass> {    PLACES_CLASSES        .iter()        .find(|(tool, _)| *tool == name)        .map(|(_, class)| class)}/// The id arguments of this class whose database another argument names.pub fn named_ids(class: &PlacesClass) -> &'static [IdPath] {    match class {        PlacesClass::OneFile { ids } | PlacesClass::PersonalOnly { ids, .. } => ids,        PlacesClass::Feed { .. } | PlacesClass::PersonalInto => &[],    }}/// How a write that names MANY records by id finds the database of each.////// Every project is its own database, and a call that names no `database`/// starts in the token's own file. A tool given one `id` is asked of the other/// files in reach when that file refuses it; a tool given a LIST answered/// "missing" for every id that lives in another database, because a list is/// not a refusal (4 Oct 2026: `update_todos` over a project's todos).#[derive(Debug, Clone, Copy, PartialEq, Eq)]pub enum ManyIds {    /// Each id is its own record: the call runs once in each database that    /// holds some of the ids, with that database's ids, and the answers are    /// joined. `table` is where an id of `arg` lives.    Each {        arg: &'static str,        table: &'static str,    },    /// The records belong together — one list reordered, one project linked    /// to — so the whole call runs in one database: the token's own, else the    /// first other in reach that does not refuse it.    Together { arg: &'static str },}/// Every write tool of a one-file class whose arguments name many records by/// id. `places_classes_tests` holds it total over the catalogue.pub const MANY_IDS: &[(&str, ManyIds)] = &[    ("update_todos", ManyIds::Each { arg: "ids", table: "cotton_todos" }),    ("update_events", ManyIds::Each { arg: "ids", table: "cotton_events" }),    ("delete_events", ManyIds::Each { arg: "ids", table: "cotton_events" }),    // A preserving move is one atomic batch from one source; never split it by id.    ("move_records", ManyIds::Together { arg: "ids" }),    ("reorder_records", ManyIds::Together { arg: "ids" }),    ("link_to_project", ManyIds::Together { arg: "records" }),    ("unlink_from_project", ManyIds::Together { arg: "records" }),    // An album is over its own database's photos (owner, 11 Oct 2026).    ("create_album", ManyIds::Together { arg: "photoIds" }),];/// How this tool's list of ids is routed, when it takes one.pub fn many_ids(name: &str) -> Option<&'static ManyIds> {    MANY_IDS        .iter()        .find(|(tool, _)| *tool == name)        .map(|(_, many)| many)}#[cfg(test)]#[path = "places_classes_tests.rs"]mod tests;/// A Personal-only tool cannot redirect an arrival into a business database.pub fn personal_refusal(genesis: cotton_core::genesis::Genesis, name: &str) -> Option<&'static str> {    (genesis == cotton_core::genesis::Genesis::None        && matches!(class_of(name), Some(PlacesClass::PersonalOnly { .. } | PlacesClass::PersonalInto { .. })))        .then_some(cotton_core::genesis::NO_PERSONAL_MESSAGE)}#[cfg(test)]mod genesis_tests {    use super::*;    // RULE: Personal-only tools refuse under genesis none; ordinary business records stay usable.    #[test]    fn genesis_none_refuses_personal_tools() {        for name in ["list_email_threads", "list_calls", "sync_device_contacts", "storage_summary"] {            assert!(class_of(name).is_some());            assert_eq!(personal_refusal(cotton_core::genesis::Genesis::None, name), Some(cotton_core::genesis::NO_PERSONAL_MESSAGE), "{name}");            assert_eq!(personal_refusal(cotton_core::genesis::Genesis::Personal, name), None);        }        assert_eq!(personal_refusal(cotton_core::genesis::Genesis::None, "create_record"), None);    }}