Cotton code
281 lines · 12.8 KB · RustRaw
//! The places table's guards: total over the catalogue, no write a feed, the//! feeds and the ordinary tools named by the design, and every named//! database a real argument.use std::collections::HashSet;use serde_json::Value;use super::*;use crate::mcp::protocol::{tool_by_name, McpScope, TOOLS};/// RULE: every catalogue tool has a places class. The wrapper reads the class and nothing else, so a tool without one would have no answer to "which file does this call run in" — and the answer it fell back to would be nobody's decision.#[test]fn every_catalogue_tool_has_a_places_class() {    let missing: Vec<&str> = TOOLS        .iter()        .map(|tool| tool.name)        .filter(|name| class_of(name).is_none())        .collect();    assert!(missing.is_empty(), "no places class for: {missing:?}");    let stale: Vec<&str> = PLACES_CLASSES        .iter()        .map(|(name, _)| *name)        .filter(|name| tool_by_name(name).is_none())        .collect();    assert!(stale.is_empty(), "classed but not catalogued: {stale:?}");    let mut seen = HashSet::new();    for (name, _) in PLACES_CLASSES {        assert!(seen.insert(*name), "{name} is classed twice");    }}/// RULE: no write verb is `feed`. A feed asked `database: "all"` runs in every file in reach with the same arguments; a write asked that way would land in every database the token reaches.#[test]fn no_write_tool_is_classed_feed() {    for (name, class) in PLACES_CLASSES {        let tool = tool_by_name(name).expect("catalogued");        if matches!(class, PlacesClass::Feed { .. }) {            assert_eq!(tool.scope, McpScope::Read, "{name} writes and is classed feed");            assert!(                tool.annotations.read_only_hint,                "{name} writes and is classed feed"            );        }    }}/// RULE (ninth draft 3.8): the feeds are exactly today_agenda, search_records and search_documents — the three reads that may cross databases. Any other list is one database's, so a fourth feed is a design change, not a classing.#[test]fn the_feeds_are_the_three_the_design_names() {    let feeds: HashSet<&str> = PLACES_CLASSES        .iter()        .filter(|(_, class)| matches!(class, PlacesClass::Feed { .. }))        .map(|(name, _)| *name)        .collect();    let named: HashSet<&str> = ["today_agenda", "search_records", "search_documents"]        .into_iter()        .collect();    assert_eq!(feeds, named);}/// RULE (ninth draft 3.8, owner decision 174779b2): passwords and people are ordinary tools — a team's passwords and contacts live in the team's database — so none of them is personal-only.#[test]fn repository_tools_act_in_the_projects_database() {    for name in [        "create_secret",        "list_secrets",        "list_people",        "create_person",    ] {        assert!(            matches!(class_of(name), Some(PlacesClass::OneFile { .. })),            "{name} is an ordinary tool and must be classed one_file: {:?}",            class_of(name)        );    }}/// RULE (ninth draft 3.8; owner 11 Oct 2026 took albums, news and the journal out): mail, a chat's private marks, calls, the contacts import, Code sessions, devices, the dev_ tools, Connected AIs and storage are personal-only — they arrive in the personal database and are never copied into a project's — and each refusal names its kind.#[test]fn the_personal_only_tools_are_the_listed_kinds() {    for name in [        "ingest_emails",        "mark_thread_unread",        "delete_thread",        "hide_chat_messages",        "star_message",        "list_calls",        "sync_device_contacts",        "create_session",        "list_sessions",        "list_devices",        "storage_summary",    ] {        match class_of(name) {            Some(PlacesClass::PersonalOnly { what, .. }) => {                assert!(!what.is_empty(), "{name} names no kind");            }            other => panic!("{name} must be personal-only: {other:?}"),        }    }    for (name, class) in PLACES_CLASSES {        if name.starts_with("dev_") {            assert!(                matches!(class, PlacesClass::PersonalOnly { .. }),                "{name} starts work on the owner's Macs and is personal-only"            );        }    }}/// RULE (architect's filing brief, 11 Oct 2026): The three Messages reads run in the database the call names, because a chat filed in a shared database is read there by the people of that database.////// A read classed personal-only would answer a member of the shared database/// "no such tool here" for the very chat that was filed for them to read.#[test]fn a_filed_chat_is_read_where_it_is_filed() {    for name in ["list_message_threads", "read_message_thread", "search_messages"] {        let class = class_of(name);        assert!(matches!(class, Some(PlacesClass::OneFile { .. })), "{name} reads the database named: {class:?}");        assert_eq!(tool_by_name(name).expect("catalogued").scope, McpScope::Read, "{name} only reads");    }}/// RULE (architect's filing brief, landing 5, 12 Oct 2026): Pinning, muting, archiving and clearing a chat, and the read stamp its page makes on opening, act on the chat in the database the call names — in a shared database the FILED COPY — and are never sent to the personal database; one reader's own marks (unread, a kept message, a message deleted from his copy, the chat deleted) stay personal-only.////// While these were personal-only a device sent every one of them to the/// personal database whatever database it showed: Pin on a filed copy pinned/// the filer's own chat of the same id, Clear chat cleared it, and for any/// other member each failed with "no such conversation".#[test]fn an_act_on_a_chat_runs_in_the_database_named_and_a_readers_own_marks_stay_personal() {    let class = class_of("mark_thread_read");    assert!(matches!(class, Some(PlacesClass::OneFile { .. })), "opening a chat stamps it in the database named: {class:?}");    // A reader's own pin, mute, archive and clear are kept in their personal    // database, about the database the chat is filed in (architect, 12 Oct    // 2026): never on the copy every member reads.    for name in ["set_thread_pinned", "set_thread_muted", "set_thread_archived", "clear_thread"] {        let class = class_of(name);        assert!(matches!(class, Some(PlacesClass::PersonalInto)), "{name} is kept in the reader's personal database: {class:?}");    }    for name in ["mark_thread_unread", "star_message", "hide_chat_messages", "delete_thread"] {        let class = class_of(name);        assert!(matches!(class, Some(PlacesClass::PersonalOnly { .. })), "{name} is one reader's own mark: {class:?}");    }}/// RULE: Only an act about another database declares `database` in its own schema: the wrapper takes `database` out of every other call as the place it runs in, so a tool that declared one would never be handed it.////// And the other way: an act classed `PersonalInto` that declared none could/// not be told which database it is about.#[test]fn only_an_act_on_another_database_declares_database() {    for (name, class) in PLACES_CLASSES {        let schema = tool_by_name(name).expect("catalogued").input_schema_json();        let declares = schema["properties"].get("database").is_some();        assert_eq!(            declares,            matches!(class, PlacesClass::PersonalInto),            "{name}: `database` is the wrapper's argument unless the tool's class is an act about another database"        );    }}/// RULE (owner 11 Oct 2026): albums, news and the journal are ordinary tools — a database holds its own albums over its own photos, its own news topics and editions, and its own journal — so every album, news and journal verb runs in the database the call names.#[test]fn album_news_and_journal_tools_act_in_the_database_named() {    let tools: Vec<&str> = PLACES_CLASSES        .iter()        .map(|(name, _)| *name)        .filter(|name| name.contains("album") || name.contains("news") || name.contains("journal"))        .collect();    assert!(        !tools.is_empty(),        "the catalogue has no album, news, or journal tools to classify"    );    for name in tools {        assert!(            matches!(class_of(name), Some(PlacesClass::OneFile { .. })),            "{name} is an ordinary tool and must be classed one_file: {:?}",            class_of(name)        );    }}/// Does `path` name an argument this schema declares? `x` is a top-level/// property; `x[].y` is property `y` of each item of array `x`.fn schema_has(schema: &Value, path: &str) -> bool {    let properties = &schema["properties"];    match path.split_once("[].") {        None => properties.get(path).is_some(),        Some((array, field)) => properties[array]["items"]["properties"]            .get(field)            .is_some(),    }}/// RULE: every id argument a class says another argument names the database of is a pair of arguments the tool's schema declares, so the wrapper's reach check reads the argument the caller actually sends./// The pairs: `create_link`'s `toId` in `toDatabase`, `create_session`'s `todoId` in `todoDatabase`.#[test]fn every_named_database_is_an_argument_the_schema_declares() {    for (name, class) in PLACES_CLASSES {        let schema = tool_by_name(name).expect("catalogued").input_schema_json();        for id in named_ids(class) {            for path in [id.path, id.database] {                assert!(                    schema_has(&schema, path),                    "{name}'s places row names {path:?}, which its input schema does not declare"                );            }        }    }}/// Does this schema property hold a list of record ids — an array named `ids`/// or `…Ids`, or an array of objects that each carry an `id`?fn is_a_list_of_ids(name: &str, property: &Value) -> bool {    property["type"] == "array"        && (name == "ids" || name.ends_with("Ids") || property["items"]["properties"].get("id").is_some())}/// Lists of ids that are PART of the one record the call writes, with the/// reason each needs no routing of its own.const PART_OF_ONE_RECORD: &[(&str, &str, &str)] = &[    ("create_note", "attachments", "the files attached to the note being made, in the database it is made in"),    ("update_note", "attachments", "the files attached to the one note `id` names, which routes the call"),];/// RULE: Every write tool that runs in one database and takes a list of record ids says in MANY_IDS how each id finds its database, so a list naming a project's records is never answered "missing" from the personal file.#[test]fn every_write_tool_naming_many_ids_says_how_each_finds_its_database() {    let mut unrouted = Vec::new();    for tool in TOOLS {        if tool.scope == McpScope::Read || !matches!(class_of(tool.name), Some(PlacesClass::OneFile { .. })) {            continue;        }        let schema = tool.input_schema_json();        let Some(properties) = schema["properties"].as_object() else {            continue;        };        for (name, property) in properties {            if !is_a_list_of_ids(name, property) {                continue;            }            if PART_OF_ONE_RECORD.iter().any(|(tool_name, arg, _)| *tool_name == tool.name && arg == name) {                continue;            }            match many_ids(tool.name) {                Some(ManyIds::Each { arg, .. } | ManyIds::Together { arg }) if arg == name => {}                _ => unrouted.push(format!("{}.{name}", tool.name)),            }        }    }    assert!(        unrouted.is_empty(),        "a list of ids with no row in MANY_IDS (places_classes.rs) — its ids in another database would be answered missing: {unrouted:?}"    );    for (name, arg, reason) in PART_OF_ONE_RECORD {        let schema = tool_by_name(name).unwrap_or_else(|| panic!("{name} is not in the catalogue")).input_schema_json();        assert!(is_a_list_of_ids(arg, &schema["properties"][arg]), "{name}.{arg} is not a list of ids any more");        assert!(reason.len() > 20, "{name}.{arg} needs its reason");    }    for (name, many) in MANY_IDS {        let tool = tool_by_name(name).unwrap_or_else(|| panic!("{name} is in MANY_IDS and not in the catalogue"));        let (ManyIds::Each { arg, .. } | ManyIds::Together { arg }) = many;        assert!(            is_a_list_of_ids(arg, &tool.input_schema_json()["properties"][arg]),            "{name}'s MANY_IDS row names {arg:?}, which its schema does not declare as a list of ids"        );        assert!(tool.scope != McpScope::Read, "{name} is a read: a feed reads across databases");    }}/// RULE: A preserving move's IDs belong to one source and one atomic batch, so admission cannot split it into separate per-record writes across homes.#[test]fn a_move_batch_is_admitted_together() {    assert!(matches!(many_ids("move_records"),Some(ManyIds::Together{arg:"ids"})));}