//! `definitions.tables`, `definitions.tools` and the nine `records.*` verbs, //! on a paired phone's replica (`shell::client::phone_tests::attached`) — and, //! on a host build, on a serving Mac's own file. //! //! The user tables are two synthetic ones, "student" and "lesson", written as //! table-definition rows the way an imported tool writes them; the built-in is //! `todo`. Every value is invented //! ([nothing-real-ever-goes-in-cotton-s-public-tree]). use std::collections::BTreeMap; use std::sync::Arc; use rusqlite::types::Value as SqlValue; use serde_json::{json, Map, Value}; use super::records::{call, offered_choice, method_module, read_refusal_code, run_command, run_command_with, tool_for, AppMethods, METHODS, VERBS}; use crate::shell::client::phone_tests::attached_on_a_clock; use crate::shell::client::ClientController; fn student() -> Value { json!({ "id": "student", "name": "Student", "plural": "Students", "picture": null, "builtin": false, "engine": null, "columns": [ { "key": "name", "type": "text", "required": true } ], "title": "name", "date": null, "project": null, "order": null, "slip": { "title": "name", "subtitle": null, "trailing": null, "photo": null, "toggle": null }, "tile": { "face": "slip-list" }, "page": [ { "heading": null, "columns": ["name"] } ], "instructions": "A student who takes lessons." }) } fn lesson() -> Value { json!({ "id": "lesson", "name": "Lesson", "plural": "Lessons", "picture": null, "builtin": false, "engine": null, "columns": [ { "key": "title", "type": "text", "required": true }, { "key": "notes", "type": "longtext" }, { "key": "day", "type": "date" }, { "key": "level", "type": "choice", "choices": ["beginner", "advanced"] }, { "key": "fee", "type": "amount" }, { "key": "student", "type": "link", "link_to": "student" }, { "key": "paid", "type": "bool" }, { "key": "position", "type": "number" } ], "title": "title", "date": "day", "project": null, "order": "position", "slip": { "title": "title", "subtitle": "notes", "trailing": "day", "photo": null, "toggle": "paid" }, "tile": { "face": "slip-list" }, "page": [ { "heading": null, "columns": ["title", "notes"] } ], "instructions": "A lesson is one class." }) } /// One statement against the replica. fn exec(client: &ClientController, sql: &str, params: Vec) { client .with_writer(|file| { file.driver .run(sql, ¶ms) .map_err(|error| error.to_string())?; crate::fixture::receipted(file.driver, sql); Ok(()) }) .expect("the statement"); } fn workspace(client: &ClientController) -> String { client .with_writer(|file| Ok(file.workspace_id.to_string())) .expect("the workspace id") } /// A synced `cotton_table_definitions` row, written raw. fn define_raw(client: &ClientController, id: &str, definition: &str, builtin: bool, edited: bool) { let workspace = workspace(client); exec( client, "INSERT INTO cotton_table_definitions \ (id, workspace_id, definition, builtin, instructions_edited, created_at, updated_at) \ VALUES (?, ?, ?, ?, ?, '2026-10-01T09:00:00.000Z', '2026-10-01T09:00:00.000Z')", vec![ SqlValue::Text(id.to_string()), SqlValue::Text(workspace), SqlValue::Text(definition.to_string()), SqlValue::Integer(i64::from(builtin)), SqlValue::Integer(i64::from(edited)), ], ); } fn define(client: &ClientController, definition: &Value) { define_raw( client, definition["id"].as_str().expect("an id"), &definition.to_string(), false, false, ); } fn phone() -> (tempfile::TempDir, Arc) { let (dir, client, _) = phone_on_a_clock(); (dir, client) } /// The same phone, with the clock it reads by handed back. fn phone_on_a_clock() -> ( tempfile::TempDir, Arc, Arc, ) { let (dir, client, clock) = attached_on_a_clock(); define(&client, &student()); define(&client, &lesson()); // A redefinition leaves the index to its rebuild beside the phone's // writes; the suite reads lists after that rebuild has run. client.bring_moves_done_for_tests().expect("the index rebuilt"); (dir, client, clock) } fn ffi(client: &ClientController, method: &str, request: Value) -> Value { call(client, method, &request).unwrap_or_else(|error| panic!("{method} refused: {error:?}")) } fn ffi_refused(client: &ClientController, method: &str, request: Value) -> String { match call(client, method, &request) { Ok(answer) => panic!("{method} was expected to refuse, and answered {answer}"), Err(error) => error.message, } } // RULE: A records.get of a record the table no longer holds is refused as record_not_found; every other read refusal is unreadable, so a page tells gone from a read that failed. #[test] fn a_gone_records_read_is_refused_by_name() { assert_eq!(read_refusal_code("records.get", "That lesson is no longer here"), "record_not_found"); assert_eq!(read_refusal_code("records.get", "the file is locked"), "unreadable"); assert_eq!(read_refusal_code("records.list", "That lesson is no longer here"), "unreadable"); } // ── the method table ──────────────────────────────────────────────────────── /// RULE: Every records method is declared on the client half and maps to a catalogued generic verb; unrelated Home or assistant verbs cannot change that routing contract. #[test] fn every_method_is_in_the_client_half_and_every_verb_names_a_catalogued_tool() { let names = crate::phone::method_names(); for method in METHODS { assert!( names.contains(&method.to_string()), "{method} is answered and not declared" ); assert!( crate::methods::CLIENT_METHODS.contains(&method), "{method} is answered on every build, so it is the client half's" ); } // Verbs with no `records.*` method of their own: the phone edits a // table's look, acts and stacks through `definitions.saveTable` (which // calls update_definition, the same write) and arranges its tools through // the settings writes (6307dece1 update_definition, d19ebcf2a arrange_tools). const ASSISTANT_ONLY: [&str; 2] = ["update_definition", "arrange_tools"]; // Capacity admission belongs to the serving writer. A phone replica must // never expose a local reservation verb; declared acts use records.command. const SERVER_ONLY: [&str; 2] = ["reserve_record", "cancel_reservation"]; for tool in SERVER_ONLY { assert!(!VERBS.iter().any(|(_, mapped)| *mapped == tool), "{tool} must not bypass serving-writer admission through a local records method"); } let mut tools: Vec<&str> = cotton_tools::mcp::handlers::tables::handlers() .iter() .map(|(name, _)| *name) .filter(|name| !ASSISTANT_ONLY.contains(name) && !SERVER_ONLY.contains(name)) .collect(); tools.push("search_records"); for tool in &tools { let record_or_group = *tool == "undo" || *tool == "get_record_by_table" || ["_record", "_records", "_group", "_groups"].iter().any(|suffix| tool.ends_with(suffix)); if record_or_group { assert!(VERBS.iter().any(|(_, mapped)| mapped == tool), "{tool} has no client records/group method"); } } for (method, tool) in VERBS { assert!(METHODS.contains(&method)); assert!( tools.contains(&tool), "{method} calls {tool}, which is not a generic verb" ); assert!( cotton_tools::mcp::protocol::tool_by_name(tool).is_some(), "{tool} is in the MCP catalogue" ); } } #[test] fn a_method_reaches_its_module_through_cotton_call_on_this_build() { // A phone that has not joined anything: every method is ANSWERED (with a // refusal about the missing database), never `unknown_method`. let dir = tempfile::tempdir().expect("a temp container"); let handle = crate::handle::CottonHandle::open(crate::handle::OpenConfig { mode: crate::handle::OpenMode::Phone { container_path: dir.path().to_string_lossy().to_string(), previous_container_path: None, }, app_version: None, time_zone: None, device_secret: None, vault_secret: None, flavor: cotton_core::flavor::Flavor::Real, manifest: None, }) .expect("an open core"); for method in METHODS { if let Err(error) = crate::methods::dispatch(&handle, method, &json!({ "table": "todo" })) { assert_ne!(error.code, "unknown_method", "{method} is not dispatched"); } } } // ── definitions.contributors ──────────────────────────────────────────────── /// RULE: A record page asks the core what links to its table and is answered from the definitions alone — on a phone's replica too — and a table that is not there is refused in words, never answered as an empty page. #[test] fn a_record_page_is_told_which_tables_link_to_it() { let (_dir, client) = phone(); let answer = ffi(&client, "definitions.contributors", json!({ "table": "person" })); let found: Vec<(&str, &str)> = answer["contributors"] .as_array() .expect("a list") .iter() .map(|c| (c["table"].as_str().unwrap(), c["column"].as_str().unwrap())) .collect(); // An email thread with a person is contributed to the person's page. assert!(found.iter().any(|(table, _)| *table == "email_thread"), "{found:?}"); assert!(!found.iter().any(|(table, _)| *table == "person_suggestion"), "machinery links contribute nothing: {found:?}"); assert!(answer["contributors"][0]["label"].as_str().is_some_and(|label| !label.is_empty())); let reason = ffi_refused(&client, "definitions.contributors", json!({ "table": "no_such_table" })); assert!(reason.contains(&cotton_core::definitions::no_tool_draws_this_table(&[])), "{reason}"); ffi_refused(&client, "definitions.contributors", json!({})); } // ── definitions.saveTable ─────────────────────────────────────────────────── /// RULE: The owner's phone edits a built-in from its tool's page through `definitions.saveTable` — the same `update_definition` an assistant calls, as this device — and the catalogue then draws the edit (an act hidden, the stack's face changed); its answer is a receipt and an undo that puts back what was drawn, and columns are refused. #[test] fn the_phone_edits_a_builtins_acts_and_stacks_and_undoes_it() { let (_dir, client) = phone(); let shipped = cotton_core::definitions::builtin_table_definitions() .iter() .find(|definition| definition.id == "person") .expect("People ship"); let links = serde_json::to_value(&shipped.links).unwrap(); let person = |client: &ClientController| { let tables = ffi(client, "definitions.tables", json!({})); tables["definitions"].as_array().unwrap().iter().find(|d| d["id"] == "person").cloned().expect("People") }; let answer = ffi( &client, "definitions.saveTable", json!({ "table": "person", "links": [], "groups": { "stack": "slips" } }), ); assert_eq!(answer["receipt"], "Saved"); assert_eq!(answer["undo"]["method"], "definitions.saveTable"); let drawn = person(&client); assert_eq!(drawn["links"], json!([]), "every act hidden"); assert_eq!(drawn["groups"]["stack"], "slips"); ffi(&client, "definitions.saveTable", answer["undo"]["args"].clone()); let drawn = person(&client); assert_eq!(drawn["links"], links, "the undo puts the acts back"); assert_eq!(drawn["groups"], serde_json::to_value(&shipped.groups).unwrap()); let reason = ffi_refused(&client, "definitions.saveTable", json!({ "table": "person", "columns": [] })); assert!(reason.contains("never removed"), "a shipped column stays: {reason}"); let reason = ffi_refused(&client, "definitions.saveTable", json!({ "table": "person", "engine": null })); assert!(reason.contains("cannot be changed here"), "{reason}"); let reason = ffi_refused(&client, "definitions.saveTable", json!({ "table": "person" })); assert!(reason.contains("the keys it changes"), "{reason}"); } // ── definitions.tables ────────────────────────────────────────────────────── /// The built-ins a database holds: those a kit tool or the shell brings. A /// built-in no tool names (the meeting and mood tables once their /// tools left the kit, 3 Nov 2026) is defined only by the object it syncs with. fn held_builtins() -> impl Iterator { let held: std::collections::BTreeSet = cotton_core::kit::ids() .into_iter() .flat_map(|id| cotton_core::kit::package(id).expect("a kit tool").expect("the kit decodes").package.tables) .map(|table| table.id) .chain(cotton_core::kit::shell::SHELL_KIT_TABLES.iter().map(|(id, _)| id.to_string())) .collect(); cotton_core::definitions::builtin_table_definitions().iter().filter(move |definition| held.contains(&definition.id)) } #[test] fn the_definitions_are_every_builtin_then_every_user_table() { let (_dir, client) = phone(); let answer = ffi(&client, "definitions.tables", json!({})); let ids: Vec<&str> = answer["definitions"] .as_array() .expect("a list") .iter() .filter_map(|definition| definition["id"].as_str()) .collect(); let shipped: Vec = held_builtins().map(|definition| definition.id.clone()).collect(); assert_eq!( &ids[..shipped.len()], shipped.iter().map(String::as_str).collect::>() ); // Then every user table, by id: the person's own, the tables a kit // package brings that this build compiles no definition of (Music's), // and the shell kit's plain tables (the face choices). let mut users: Vec = cotton_core::kit::ids() .into_iter() .flat_map(|id| cotton_core::kit::package(id).expect("a kit tool").expect("the kit decodes").package.tables) .map(|table| table.id) .chain(cotton_core::kit::shell::SHELL_KIT_TABLES.iter().map(|(id, _)| id.to_string())) .filter(|id| cotton_core::definitions::builtin_table_definition(id).is_none()) .chain(["lesson".to_string(), "student".to_string()]) .collect(); // A table two tools read (Messages' and Agents' `session`) is one table. users.sort(); users.dedup(); assert!(users.iter().any(|id| id == "song"), "the kit brings Music's own tables"); assert_eq!(&ids[shipped.len()..], users, "then the user tables, by id"); assert_eq!(answer["refused"], json!([])); let lesson_answered = answer["definitions"] .as_array() .unwrap() .iter() .find(|definition| definition["id"] == "lesson") .unwrap(); assert_eq!( lesson_answered, &lesson(), "a user table is its row, in the shared form" ); } /// A built-in's row as a build at another definitions revision wrote it: the /// same id and instructions, every other key in a shape this build cannot /// decode — what 0f76239c1's `tool` (no `tables`) was to the builds before it. fn reshaped_builtin(shipped: &cotton_core::definitions::TableDefinition) -> String { let mut row = serde_json::to_value(shipped).unwrap(); row["tool"] = json!({ "name": ["a card a newer build draws"] }); row["columns"] = json!({ "a": "shape this build has never seen" }); row.to_string() } /// RULE: A built-in table lists whatever revision wrote its synced row: the row lends only its id and edited instructions, so a shape this build cannot decode never refuses the table (the /todos and Past imports walk finding on 8596b4af2: a phone a revision behind the server read "That couldn't be opened"). #[test] fn a_builtin_row_another_revision_wrote_never_refuses_its_list() { let shipped: Vec<&cotton_core::definitions::TableDefinition> = held_builtins().collect(); // The app's own requests (CoreRecords.listRequest with the day plan), // before and after the reshaped rows land. let todo_plan = json!({ "table": "todo", "page": 0, "limit": 50, "today": "2026-10-10", "section": "today", "timezone": "Asia/Kolkata" }); let list = |table: &str| json!({ "table": table, "page": 0, "limit": 50, "today": "2026-10-10" }); let read = |client: &ClientController, request: &Value| { call(client, "records.list", request).map_err(|error| error.message) }; let (_dir, client) = phone(); let before: Vec<_> = shipped.iter().map(|definition| read(&client, &list(&definition.id))).collect(); let todo_before = read(&client, &todo_plan); assert!(todo_before.is_ok(), "{todo_before:?}"); let workspace = workspace(&client); for definition in &shipped { exec( &client, "INSERT OR REPLACE INTO cotton_table_definitions \ (id, workspace_id, definition, builtin, instructions_edited, created_at, updated_at) \ VALUES (?, ?, ?, 1, 0, '2026-10-01T09:00:00.000Z', '2026-10-01T09:00:00.000Z')", vec![ SqlValue::Text(definition.id.clone()), SqlValue::Text(workspace.clone()), SqlValue::Text(reshaped_builtin(definition)), ], ); } client.bring_moves_done_for_tests().expect("the index rebuilt"); assert_eq!(read(&client, &todo_plan), todo_before, "the todo list's day plan"); for (definition, before) in shipped.iter().zip(before) { let after = read(&client, &list(&definition.id)); // Copy and Storage measure this device's file, which these writes // grow; both must still list when the synced definition changes. if matches!(definition.id.as_str(), "copy" | "storage") { assert!(after.is_ok() && before.is_ok(), "{} lists on any revision: {after:?}", definition.id); continue; } assert_eq!(after, before, "{} lists as it did on its shipped definition", definition.id); } let answer = ffi(&client, "definitions.tables", json!({})); assert_eq!(answer["refused"], json!([])); } // ── definitions.tools ─────────────────────────────────────────────────────── #[test] fn the_tool_definitions_are_the_synced_rows_validated() { let _bare = crate::fixture::bare(); let (_dir, client) = phone(); assert_eq!( ffi(&client, "definitions.tools", json!({})), json!({ "definitions": [], "refused": [] }), "no tool ships, so a new file has none" ); let tool = json!({ "id": "lessons", "name": "Lessons", "picture": "tool-lessons", "tables": ["lesson", "student"], "instructions": "Teaching.", "automations": [], "author": { "device": "d1", "name": "A Teacher" }, "signature": null }); let mut bad = tool.clone(); bad["id"] = json!("broken"); bad["automations"] = json!([{ "when": "never" }]); let workspace = workspace(&client); for (id, definition) in [("lessons", &tool), ("broken", &bad)] { exec( &client, "INSERT INTO cotton_tool_definitions (id, workspace_id, definition, created_at, updated_at) \ VALUES (?, ?, ?, '2026-10-01T09:00:00.000Z', '2026-10-01T09:00:00.000Z')", vec![ SqlValue::Text(id.to_string()), SqlValue::Text(workspace.clone()), SqlValue::Text(definition.to_string()), ], ); } let reason = ffi_refused(&client, "definitions.tools", json!({})); assert!(reason.starts_with("the definition of tool \"broken\" cannot be read"), "{reason}"); } // ── the verbs, on the phone ───────────────────────────────────────────────── #[test] fn every_verb_works_on_a_user_table_and_undo_round_trips() { let (_dir, client) = phone(); let asha = ffi( &client, "records.create", json!({ "table": "student", "data": { "name": "Asha" } }), ); let asha = asha["record"]["id"].as_str().unwrap().to_string(); let created = ffi( &client, "records.create", json!({ "table": "lesson", "data": { "title": "Scales", "day": "2026-10-02", "fee": 150_000, "paid": false } }), ); assert_eq!(created["change"]["verb"], "create"); assert_eq!(created["change"]["byline"], "user", "the owner's own app"); assert_eq!(created["record"]["byline"], "user"); let one = created["record"]["id"].as_str().unwrap().to_string(); let two = ffi( &client, "records.create", json!({ "table": "lesson", "data": { "title": "Arpeggios" } }), ); let two = two["record"]["id"].as_str().unwrap().to_string(); let got = ffi( &client, "records.get", json!({ "table": "lesson", "id": one }), ); assert_eq!(got["data"]["title"], "Scales"); assert_eq!(got["table"], "lesson"); let updated = ffi( &client, "records.update", json!({ "table": "lesson", "id": one, "patch": { "paid": true } }), ); assert_eq!(updated["change"]["before"]["paid"], false); assert_eq!(updated["change"]["after"]["paid"], true); let linked = ffi( &client, "records.link", json!({ "table": "lesson", "id": one, "column": "student", "target_id": asha }), ); assert_eq!(linked["record"]["data"]["student"], json!(asha)); let reordered = ffi( &client, "records.reorder", json!({ "table": "lesson", "ids": [two, one] }), ); assert_eq!(reordered["record"], Value::Null); let listed = ffi(&client, "records.list", json!({ "table": "lesson" })); let order: Vec<&str> = listed["records"] .as_array() .unwrap() .iter() .map(|record| record["id"].as_str().unwrap()) .collect(); assert_eq!( order, [two.as_str(), one.as_str()], "the order column is the list's order" ); assert_eq!(listed["next_page"], Value::Null); // The undo round trip: a delete comes back, and an update goes back. let deleted = ffi( &client, "records.delete", json!({ "table": "lesson", "id": two }), ); assert!(deleted["record"]["deleted_at"].is_string()); let restored = ffi( &client, "records.undo", json!({ "change_id": deleted["change"]["id"] }), ); assert_eq!(restored["undone"]["id"], deleted["change"]["id"]); assert_eq!(restored["record"]["deleted_at"], Value::Null); let reverted = ffi( &client, "records.undo", json!({ "change_id": updated["change"]["id"] }), ); assert_eq!(reverted["record"]["data"]["paid"], false); assert_eq!(reverted["change"]["byline"], "user"); // Every write went to the outbox, as every other phone write does. let queued = client .with_writer(|file| { Ok(file .driver .get("SELECT COUNT(*) AS n FROM _outbox", &[]) .map_err(|error| error.to_string())? .and_then(|row| row.int("n")) .unwrap_or(0)) }) .unwrap(); assert!(queued > 0, "the writes are queued for the sync loop"); } /// RULE: The app reads the bin as a table and answers it through the bin's own verbs — a binned row lists, a restore is restore_from_bin, a delete erases the row for good — over the phone's own replica. #[test] fn the_bin_answers_the_app_as_a_table() { let (_dir, client) = phone(); let workspace = workspace(&client); let binned = "a1b2c3d4-0000-4000-8000-00000000b1a1"; let erased = "a1b2c3d4-0000-4000-8000-00000000b1a2"; for (id, title, at) in [ (binned, "Pick the paint colour", "2026-09-30T10:00:00.000Z"), (erased, "Cancel the old plan", "2026-09-29T10:00:00.000Z"), ] { exec( &client, "INSERT INTO cotton_decisions (id, workspace_id, title, trashed_at, created_at, updated_at) \ VALUES (?, ?, ?, ?, '2026-09-01T09:00:00.000Z', '2026-09-01T09:00:00.000Z')", vec![ SqlValue::Text(id.into()), SqlValue::Text(workspace.clone()), SqlValue::Text(title.into()), SqlValue::Text(at.into()), ], ); } let listed = ffi(&client, "records.list", json!({ "table": "bin" })); assert_eq!(listed["records"][0]["id"], binned, "newest first"); assert_eq!( listed["records"][0]["data"], json!({ "title": "Pick the paint colour", "kind": "decision", "table": "decision", "trashed_at": "2026-09-30T10:00:00.000Z", "state": "binned" }) ); assert_eq!(listed["records"][1]["id"], erased); let restored = ffi( &client, "records.update", json!({ "table": "bin", "id": binned, "patch": { "state": "restored" } }), ); assert_eq!(restored["record"]["data"]["state"], "restored"); assert_eq!(restored["change"]["byline"], "user"); let gone = ffi(&client, "records.delete", json!({ "table": "bin", "id": erased })); assert_eq!(gone["record"], Value::Null); assert_eq!(gone["change"]["undoable"], false); let refusal = call(&client, "records.get", &json!({ "table": "bin", "id": erased })).unwrap_err(); assert!(refusal.message.ends_with("is no longer here") && !refusal.message.contains(erased), "{}", refusal.message); assert_eq!(refusal.code, "record_not_found", "a gone record is refused by name, so a page says gone and not could-not-be-read"); let left = ffi(&client, "records.list", json!({ "table": "bin" })); let ids: Vec<&str> = left["records"] .as_array() .unwrap() .iter() .filter_map(|record| record["id"].as_str()) .collect(); assert!( !ids.contains(&binned) && !ids.contains(&erased), "one restored, one erased: {ids:?}" ); let text = ffi_refused( &client, "records.create", json!({ "table": "bin", "data": {} }), ); assert!(text.contains("Nothing is created in the bin"), "{text}"); } #[test] fn every_verb_on_todo_answers_what_the_todo_tools_answer() { let (_dir, client) = phone(); let created = ffi( &client, "records.create", json!({ "table": "todo", "data": { "title": "Tune the cello" } }), ); let id = created["record"]["id"].as_str().unwrap().to_string(); assert_eq!(created["record"]["data"]["status"], "open"); assert_eq!( created["change"]["undoable"], true, "every add carries Undo: a todo's undo puts it away as dropped" ); let done = ffi( &client, "records.update", json!({ "table": "todo", "id": id, "patch": { "status": "done" } }), ); assert!( done["change"]["after"]["completed_at"].is_string(), "the todo tool stamped it" ); let undone = ffi( &client, "records.undo", json!({ "change_id": done["change"]["id"] }), ); assert_eq!(undone["record"]["data"]["status"], "open"); assert_eq!( ffi(&client, "records.get", json!({ "table": "todo", "id": id }))["id"], json!(id) ); let listed = ffi( &client, "records.list", json!({ "table": "todo", "query": "cello" }), ); assert_eq!(listed["records"][0]["id"], json!(id)); ffi_refused( &client, "records.reorder", json!({ "table": "todo", "ids": [id] }), ); let taken_back = ffi( &client, "records.undo", json!({ "change_id": created["change"]["id"] }), ); // Not this device's own fresh add to take back: the Undo moves it to the bin. assert!(taken_back["record"]["deleted_at"].is_string(), "{taken_back}"); assert_eq!(taken_back["change"]["receipt"]["said"], "Moved Tune the cello to the bin", "{taken_back}"); } /// RULE: The phone reads the one library, an album's add picker and its pictures through `records.*`, puts a picture in an album (and undoes that, the suggestion it kept open again), captions a photo and decides an album, every write bylined to the owner. #[test] fn photos_are_listed_picked_captioned_and_put_in_albums_from_the_phone() { let (_dir, client) = phone(); let workspace = workspace(&client); let at = "2026-09-20T08:00:00.000Z"; let mut photos = Vec::new(); for serial in ['a', 'b'] { let hash = serial.to_string().repeat(64); let id = format!("photo:{hash}"); exec( &client, "INSERT INTO cotton_photos (id, workspace_id, key, sha256, content_type, size_bytes, \ taken_at, created_at, updated_at) VALUES (?, ?, ?, ?, 'image/jpeg', 2048, ?, ?, ?)", vec![ SqlValue::Text(id.clone()), SqlValue::Text(workspace.clone()), SqlValue::Text(format!("{workspace}/photos/{hash}.jpg")), SqlValue::Text(hash.clone()), SqlValue::Text(at.into()), SqlValue::Text(at.into()), SqlValue::Text(at.into()), ], ); photos.push(id); } // An empty suggestion has no cover: a cover is always one of its pictures. let album = "album:trip:2026-09-20"; exec( &client, "INSERT INTO cotton_media_albums (id, workspace_id, kind, state, title, title_by, starts_at, \ ends_at, created_at, updated_at) \ VALUES (?, ?, 'trip', 'open', 'Example trip', 'derived', '2026-09-20', '2026-09-20', ?, ?)", vec![ SqlValue::Text(album.into()), SqlValue::Text(workspace.clone()), SqlValue::Text(at.into()), SqlValue::Text(at.into()), ], ); let added = ffi( &client, "records.create", json!({ "table": "album_item", "data": { "album_id": album, "record_id": photos[0] } }), ); assert_eq!(added["change"]["byline"], "user"); assert_eq!(added["record"]["data"]["record_id"], json!(photos[0])); // Putting a picture in a suggestion keeps it; the undo opens it again. let moved = &added["change"]["after"]["@album"]; assert_eq!((&moved["was"]["state"], &moved["now"]["state"]), (&json!("open"), &json!("kept"))); let album_state = |client: &ClientController| { ffi(client, "records.get", json!({ "table": "album", "id": album }))["data"]["state"].clone() }; assert_eq!(album_state(&client), "kept"); let undone = ffi(&client, "records.undo", json!({ "change_id": added["change"]["id"] })); assert_eq!(undone["undone"]["undone_by"], undone["change"]["id"]); assert_eq!(album_state(&client), "open", "the suggestion is open again"); let empty = ffi( &client, "records.list", json!({ "table": "album_item", "where": { "album_id": album } }), ); assert_eq!(empty["total"], 0); let added = ffi( &client, "records.create", json!({ "table": "album_item", "data": { "album_id": album, "record_id": photos[0] } }), ); assert_eq!(added["record"]["data"]["record_id"], json!(photos[0])); let library = ffi(&client, "records.list", json!({ "table": "media" })); assert_eq!(library["total"], 2); let picker = ffi( &client, "records.list", json!({ "table": "photo", "where": { "addable_to": album } }), ); let offered: Vec<&str> = picker["records"] .as_array() .unwrap() .iter() .filter_map(|record| record["id"].as_str()) .collect(); assert_eq!(offered, [photos[1].as_str()]); let pictures = ffi( &client, "records.list", json!({ "table": "album_item", "where": { "album_id": album } }), ); assert_eq!(pictures["total"], 1); let captioned = ffi( &client, "records.update", json!({ "table": "photo", "id": photos[0], "patch": { "caption": "The hill" } }), ); assert_eq!(captioned["record"]["data"]["caption"], "The hill"); assert_eq!(captioned["record"]["data"]["albums"], json!([album])); let decided = ffi( &client, "records.update", json!({ "table": "album", "id": album, "patch": { "state": "dismissed" } }), ); assert_eq!(decided["change"]["byline"], "user"); let listed = ffi(&client, "records.list", json!({ "table": "album" })); assert_eq!(listed["records"], json!([]), "a dismissed album leaves the list"); // A favourite is the phone's to give too (Photos, 12 Nov 2026): the star lands as the person's own change. let starred = ffi( &client, "records.update", json!({ "table": "photo", "id": photos[1], "patch": { "favourite": true } }), ); assert_eq!(starred["record"]["data"]["favourite"], true, "{starred}"); assert_eq!(starred["change"]["byline"], "user"); } #[test] fn a_request_that_is_not_an_object_is_refused_before_any_tool_runs() { let (_dir, client) = phone(); let error = call(&client, "records.list", &json!(["lesson"])).unwrap_err(); assert_eq!(error.code, "bad_request"); assert_eq!(tool_for("records.nothing"), None); assert_eq!( call(&client, "records.nothing", &json!({})) .unwrap_err() .code, "unknown_method" ); } // ── the FFI and MCP shapes are one shape ──────────────────────────────────── /// One step's answer, as JSON: the answer itself, or `{"refused": sentence}`. type Step<'a> = dyn FnMut(&str, Value) -> Value + 'a; /// The same script, whichever door it goes through. Later steps take the ids /// earlier steps answered, so each door is driven by its own answers. fn script(step: &mut Step<'_>) -> Vec { let mut out = Vec::new(); let mut run = |step: &mut Step<'_>, tool: &str, args: Value| { let answer = step(tool, args); out.push(json!({ "tool": tool, "answer": answer.clone() })); answer }; let id = |answer: &Value| answer["record"]["id"].clone(); let asha = run( step, "create_record", json!({ "table": "student", "data": { "name": "Asha" } }), ); let one = run( step, "create_record", json!({ "table": "lesson", "data": { "title": "Scales", "day": "2026-10-02", "level": "beginner", "fee": 150_000, "paid": false } }), ); let two = run( step, "create_record", json!({ "table": "lesson", "data": { "title": "Arpeggios" } }), ); run( step, "create_record", json!({ "table": "lesson", "data": { "level": "expert" } }), ); run(step, "list_records", json!({ "table": "lesson" })); run( step, "list_records", json!({ "table": "lesson", "query": "Scales", "limit": 1 }), ); run( step, "get_record_by_table", json!({ "table": "lesson", "id": id(&one) }), ); run( step, "get_record_by_table", json!({ "table": "lesson", "id": "a0000000-0000-4000-8000-00000000dead" }), ); let paid = run( step, "update_record", json!({ "table": "lesson", "id": id(&one), "patch": { "paid": true } }), ); run( step, "link_records", json!({ "table": "lesson", "id": id(&one), "column": "student", "target_id": id(&asha) }), ); run( step, "link_records", json!({ "table": "lesson", "id": id(&one), "column": "student", "target_id": null }), ); run( step, "reorder_records", json!({ "table": "lesson", "ids": [id(&two), id(&one)] }), ); let gone = run( step, "delete_record", json!({ "table": "lesson", "id": id(&two) }), ); run(step, "undo", json!({ "change_id": gone["change"]["id"] })); run(step, "undo", json!({ "change_id": paid["change"]["id"] })); run(step, "list_records", json!({ "table": "lesson" })); run(step, "list_records", json!({ "table": "spaceship" })); let todo = run( step, "create_record", json!({ "table": "todo", "data": { "title": "Tune the cello" } }), ); let done = run( step, "update_record", json!({ "table": "todo", "id": id(&todo), "patch": { "status": "done" } }), ); run(step, "undo", json!({ "change_id": done["change"]["id"] })); run(step, "undo", json!({ "change_id": todo["change"]["id"] })); run( step, "get_record_by_table", json!({ "table": "todo", "id": id(&todo) }), ); run( step, "list_records", json!({ "table": "todo", "query": "cello" }), ); run( step, "delete_record", json!({ "table": "todo", "id": id(&todo) }), ); run( step, "reorder_records", json!({ "table": "todo", "ids": [id(&todo)] }), ); out } fn is_uuid(text: &str) -> bool { text.len() == 36 && text.char_indices().all(|(at, c)| match at { 8 | 13 | 18 | 23 => c == '-', _ => c.is_ascii_hexdigit(), }) } /// One string: an id becomes its first-appearance name, anything else stays. fn normalised_id(text: &str, ids: &mut BTreeMap) -> String { if !is_uuid(text) { return text.to_string(); } let next = format!("", ids.len()); ids.entry(text.to_string()).or_insert(next).clone() } /// Ids by first appearance — values, and the keys a reorder's change is keyed /// by — and every byline one word: the two doors mint /// different ids and write under different names, and nothing else may differ. fn normalised(value: &Value, ids: &mut BTreeMap) -> Value { match value { Value::String(text) => Value::String(normalised_id(text, ids)), Value::Array(items) => { Value::Array(items.iter().map(|item| normalised(item, ids)).collect()) } Value::Object(fields) => Value::Object( fields .iter() .map(|(key, field)| { let field = if key == "byline" && field.is_string() { json!("") } else { normalised(field, ids) }; (normalised_id(key, ids), field) }) .collect::>(), ), other => other.clone(), } } /// RULE: Every records method answers exactly what its MCP tool answers for the same arguments on the same file — the FFI is the tool, never a second implementation. #[test] fn every_ffi_verb_answers_what_its_mcp_tool_answers() { // Each step a second after the last, through both doors alike, so a list // of records written by different steps has one order on either side // rather than a tie broken by the ids each door minted. let second = chrono::Duration::seconds(1); // THE FFI DOOR: `cotton_call`'s own module, over a paired phone. let (_a, phone_client, phone_clock) = phone_on_a_clock(); let mut through_ffi = |tool: &str, args: Value| { phone_clock.advance(second); let method = VERBS.iter().find(|(_, verb)| *verb == tool).unwrap().0; match call(&phone_client, method, &args) { Ok(answer) => answer, Err(error) => json!({ "refused": error.message }), } }; let ffi_answers = script(&mut through_ffi); // THE MCP DOOR: an assistant's connection (`Ctx::new` with a token's // scopes), over an identical file at the same instant — the answer // serialised to the text a `tools/call` carries and read back. let (_b, other, other_clock) = phone_on_a_clock(); let mut through_mcp = |tool: &str, args: Value| { other_clock.advance(second); let now = other.now(); let Value::Object(args) = args else { unreachable!() }; other .with_writer(|file| { let scopes = vec!["read".to_string(), "write".to_string()]; let services = cotton_tools::mcp::dispatch::ToolServices::none(); let audit = |_: &str, _: &str| {}; let mut ctx = cotton_tools::mcp::dispatch::Ctx::new( file.driver, file.identity, file.owner_id, "Claude", "token-1", &scopes, now, Arc::new(cotton_tools::random::SystemRandom), Some(cotton_tools::mcp::writer::job("test")), &services, &audit, ); let answer = cotton_tools::mcp::dispatch::call_tool(&mut ctx, tool, &args); ctx.commit().map_err(|failure| failure.to_string())?; Ok(match answer { Ok(value) => serde_json::from_str::(&value.to_string()).unwrap(), Err(failure) => json!({ "refused": failure.message() }), }) }) .unwrap() }; let mcp_answers = script(&mut through_mcp); // The bylines are the one designed difference: the owner's app, and the // connection's own name. assert_eq!(ffi_answers[0]["answer"]["change"]["byline"], "user"); assert_eq!(mcp_answers[0]["answer"]["change"]["byline"], "Claude"); // Refusals are part of the shape, and the script reaches some. assert!( ffi_answers .iter() .filter(|step| step["answer"].get("refused").is_some()) .count() >= 4 ); assert_eq!(ffi_answers.len(), mcp_answers.len()); let (mut ffi_ids, mut mcp_ids) = (BTreeMap::new(), BTreeMap::new()); for (ffi_step, mcp_step) in ffi_answers.iter().zip(&mcp_answers) { // The other designed difference: a refusal the owner's app shows names // a column as the page does, an assistant's names the key it writes. if ffi_step["answer"].get("refused").is_some() { assert!(mcp_step["answer"].get("refused").is_some(), "{}", ffi_step["tool"]); continue; } assert_eq!( normalised(ffi_step, &mut ffi_ids), normalised(mcp_step, &mut mcp_ids), "{} answered differently through the FFI", ffi_step["tool"] ); } } // ── /activity ────────────────────────────────────────────────────────────── // ── a serving Mac ─────────────────────────────────────────────────────────── /// RULE: Records and the cap's search use the same read-only search verb as MCP, without authoring an op. #[test] fn records_search_reads_generic_records_without_authoring_an_op() { let (_dir, client) = phone(); let created = ffi( &client, "records.create", json!({"table":"student","data":{"name":"Needle student"}}), ); let before = client .with_writer(|file| { file.driver .all("SELECT op_id FROM _outbox", &[]) .map(|rows| rows.len()) .map_err(|e| e.to_string()) }) .unwrap(); let out = ffi(&client, "records.search", json!({"query":"needle"})); assert!(out["records"] .as_array() .unwrap() .iter() .any(|r| r["table"] == "student" && r["id"] == created["record"]["id"])); let after = client .with_writer(|file| { file.driver .all("SELECT op_id FROM _outbox", &[]) .map(|rows| rows.len()) .map_err(|e| e.to_string()) }) .unwrap(); assert_eq!(before, after); assert_eq!(tool_for("records.search"), Some("search_records")); } // ── every built-in family, through the C entry point ──────────────────────── // // One case per family the app's routes open: the list and the read, the one // write the family's own tool takes, and the undo where its engine has an // inverse. Every value is invented. const AT: &str = "2026-09-20T08:00:00.000Z"; fn id_of(answer: &Value) -> String { answer["record"]["id"] .as_str() .unwrap_or_else(|| panic!("an id in {answer}")) .to_string() } fn listed_ids(answer: &Value) -> Vec { answer["records"] .as_array() .expect("a list") .iter() .filter_map(|record| record["id"].as_str().map(str::to_string)) .collect() } fn text(value: &str) -> SqlValue { SqlValue::Text(value.to_string()) } fn seed_person(client: &ClientController, id: &str, name: &str, source: &str) { seed_person_reaching(client, id, name, source, "+910000000001", "a@example.com"); } /// A person whose phone and email are their own: since v90 two people cannot /// share one, so a second person in the same file needs different values. fn seed_person_reaching( client: &ClientController, id: &str, name: &str, source: &str, phone: &str, email: &str, ) { exec( client, "INSERT INTO cotton_people (id, workspace_id, full_name, contact_source, \ created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?)", vec![text(id), text(&workspace(client)), text(name), text(source), text(AT), text(AT)], ); // A phone and an email are handle rows since v90. let digits: String = phone.chars().filter(char::is_ascii_digit).collect(); for (kind, value, normalised) in [("phone", phone, digits.as_str()), ("email", email, email)] { exec( client, "INSERT INTO cotton_person_handles (id, workspace_id, person_id, kind, value, \ normalised, source, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, 'manual', ?, ?)", vec![ text(&format!("handle-{id}-{kind}")), text(&workspace(client)), text(id), text(kind), text(value), text(normalised), text(AT), text(AT), ], ); } } fn seed_photo(client: &ClientController, serial: char) -> String { let workspace = workspace(client); let hash = serial.to_string().repeat(64); let id = format!("photo:{hash}"); exec( client, "INSERT INTO cotton_photos (id, workspace_id, key, sha256, content_type, size_bytes, \ taken_at, created_at, updated_at) VALUES (?, ?, ?, ?, 'image/jpeg', 2048, ?, ?, ?)", vec![ text(&id), text(&workspace), text(&format!("{workspace}/photos/{hash}.jpg")), text(&hash), text(AT), text(AT), text(AT), ], ); id } fn seed_video(client: &ClientController, serial: char) -> String { let workspace = workspace(client); let hash = serial.to_string().repeat(64); let id = format!("video:{hash}"); exec( client, "INSERT INTO cotton_videos (id, workspace_id, key, sha256, content_type, size_bytes, \ taken_at, created_at, updated_at) VALUES (?, ?, ?, ?, 'video/mp4', 4096, ?, ?, ?)", vec![ text(&id), text(&workspace), text(&format!("{workspace}/videos/{hash}.mp4")), text(&hash), text(AT), text(AT), text(AT), ], ); id } /// RULE: A note is listed, created, edited, deleted and brought back through the generic verbs on the phone, and answers the column that says what keeps it in step. #[test] fn a_note_is_written_deleted_and_brought_back_from_the_phone() { let (_dir, client) = phone(); let created = ffi( &client, "records.create", json!({ "table": "note", "data": { "title": "Example tuning", "body": "Low string first." } }), ); let id = id_of(&created); assert_eq!(created["change"]["byline"], "user"); let listed = ffi(&client, "records.list", json!({ "table": "note" })); assert!(listed_ids(&listed).contains(&id), "{listed}"); let total = listed["total"].as_i64().unwrap(); let edited = ffi( &client, "records.update", json!({ "table": "note", "id": id, "patch": { "title": "Example tuning, again" } }), ); assert_eq!(edited["record"]["data"]["title"], "Example tuning, again"); let refused = ffi_refused( &client, "records.update", json!({ "table": "note", "id": id, "patch": { "managed_by": "x" } }), ); assert!(!refused.is_empty()); let deleted = ffi(&client, "records.delete", json!({ "table": "note", "id": id })); assert!(deleted["record"]["deleted_at"].is_string()); let listed = ffi(&client, "records.list", json!({ "table": "note" })); assert_eq!(listed["total"], total - 1, "a deleted note leaves the list"); let back = ffi(&client, "records.undo", json!({ "change_id": deleted["change"]["id"] })); assert_eq!(back["record"]["deleted_at"], Value::Null); assert_eq!( ffi(&client, "records.list", json!({ "table": "note" }))["total"], total ); } /// RULE: A note with a title and no body is made from the phone — what the one input sends when its words read as a note — and the receipt's Undo takes it back off the list. #[test] fn a_titled_note_with_no_body_is_made_and_undone_from_the_phone() { let (_dir, client) = phone(); let before = ffi(&client, "records.list", json!({ "table": "note" }))["total"] .as_i64() .unwrap(); let created = ffi( &client, "records.create", json!({ "table": "note", "data": { "title": "Example carrots" } }), ); let id = id_of(&created); assert_eq!(created["record"]["data"]["title"], "Example carrots"); let listed = ffi(&client, "records.list", json!({ "table": "note" })); assert!(listed_ids(&listed).contains(&id), "{listed}"); let refused = ffi_refused( &client, "records.create", json!({ "table": "note", "data": {} }), ); assert!( !refused.is_empty(), "a note with neither a title nor a body is refused" ); ffi( &client, "records.undo", json!({ "change_id": created["change"]["id"] }), ); let listed = ffi(&client, "records.list", json!({ "table": "note" })); assert!(!listed_ids(&listed).contains(&id), "{listed}"); assert_eq!(listed["total"], before); } /// RULE: Videos and the pairs the Mac thinks are copies are listed through the generic verbs on the phone; a video takes its caption and a pair its answer. #[test] fn videos_and_their_copies_are_listed_captioned_and_answered_from_the_phone() { let (_dir, client) = phone(); let keep = seed_video(&client, 'e'); let copy = seed_video(&client, 'f'); let pair = "11111111-1111-4111-8111-0000000d0001"; exec( &client, "INSERT INTO cotton_media_duplicates (id, workspace_id, record_kind, keep_id, copy_id, \ distance, method, state, created_at, updated_at) \ VALUES (?, ?, 'video', ?, ?, 2, 'featureprint', 'open', ?, ?)", vec![text(pair), text(&workspace(&client)), text(&keep), text(©), text(AT), text(AT)], ); let videos = ffi(&client, "records.list", json!({ "table": "video" })); assert_eq!(videos["total"], 2); let captioned = ffi( &client, "records.update", json!({ "table": "video", "id": keep, "patch": { "caption": "Example lake" } }), ); assert_eq!(captioned["record"]["data"]["caption"], "Example lake"); let pairs = ffi(&client, "records.list", json!({ "table": "duplicate" })); assert_eq!(listed_ids(&pairs), [pair.to_string()]); let answered = ffi( &client, "records.update", json!({ "table": "duplicate", "id": pair, "patch": { "state": "dismissed" } }), ); assert_eq!(answered["change"]["byline"], "user"); assert_eq!( ffi(&client, "records.list", json!({ "table": "duplicate" }))["total"], 0, "an answered pair leaves the list" ); } /// RULE: People, events and messages are read through the generic verbs on the phone — a person with the addresses and numbers the faces draw — and every write to a message is refused with the read-only words. #[test] fn the_read_only_families_read_and_refuse_every_write_from_the_phone() { let (_dir, client) = phone(); let workspace = workspace(&client); let person = "11111111-1111-4111-8111-000000010001"; seed_person(&client, person, "Example Singer", "manual"); let calendar = "11111111-1111-4111-8111-000000010002"; exec( &client, "INSERT INTO cotton_collections (id, workspace_id, kind, name, created_at) \ VALUES (?, ?, 'calendar', 'Example calendar', ?)", vec![text(calendar), text(&workspace), text(AT)], ); let event = "11111111-1111-4111-8111-000000010003"; exec( &client, "INSERT INTO cotton_events (id, collection_id, title, starts_at, sync_state, created_at, \ updated_at) VALUES (?, ?, 'Example rehearsal', '2026-09-21T10:00:00.000Z', 'synced', ?, ?)", vec![text(event), text(calendar), text(AT), text(AT)], ); let thread = "11111111-1111-4111-8111-000000010004"; exec( &client, "INSERT INTO cotton_msg_threads (id, workspace_id, kind, title, created_at, updated_at) \ VALUES (?, ?, 'group', 'Example choir', ?, ?)", vec![text(thread), text(&workspace), text(AT), text(AT)], ); let message = "11111111-1111-4111-8111-000000010005"; exec( &client, "INSERT INTO cotton_msg_messages (id, thread_id, workspace_id, direction, channel, origin, \ body, sent_at, created_at) VALUES (?, ?, ?, 'in', 'cotton', 'live', 'Example hello', ?, ?)", vec![text(message), text(thread), text(&workspace), text(AT), text(AT)], ); for (table, id, patch) in [ ("person", person, json!({ "full_name": "Renamed" })), ("event", event, json!({ "title": "Renamed" })), ("message", message, json!({ "body": "Rewritten" })), ] { let listed = ffi(&client, "records.list", json!({ "table": table })); assert!(listed_ids(&listed).contains(&id.to_string()), "{table}: {listed}"); let got = ffi(&client, "records.get", json!({ "table": table, "id": id })); assert_eq!(got["id"], id, "{table}"); // A person and an event are written by their own tools now. // A message that arrived is still refused every write: messages are // added to, never edited (the old send path and its edits left in // 9f199924aa), and only a failed text of the owner's goes in the bin. if table == "message" { let refused = ffi_refused(&client, "records.update", json!({ "table": table, "id": id, "patch": patch })); assert!(refused.contains("never edited"), "{refused}"); let refused = ffi_refused(&client, "records.delete", json!({ "table": table, "id": id })); assert!(refused.contains("Only a text of yours that failed to send goes in the bin"), "{refused}"); } } let got = ffi(&client, "records.get", json!({ "table": "person", "id": person })); assert_eq!(got["data"]["emails"], json!(["a@example.com"])); assert_eq!(got["data"]["phones"], json!(["+910000000001"])); let got = ffi(&client, "records.get", json!({ "table": "event", "id": event })); assert_eq!(got["data"]["sync_state"], "synced"); } /// RULE: A face the Mac thinks it recognises is listed as "Is this …?" with its hedge and the picture it was found in, a yes names the person through update_face and takes it off the list, and the answer cannot be undone. #[test] fn a_face_is_confirmed_from_the_phone() { let (_dir, client) = phone(); let person = "11111111-1111-4111-8111-000000020001"; seed_person(&client, person, "Example Singer", "manual"); let photo = seed_photo(&client, 'c'); let face = "11111111-1111-4111-8111-000000020002"; exec( &client, "INSERT INTO cotton_media_faces (id, workspace_id, record_kind, record_id, source, \ source_id, x, y, w, h, suggested_person_id, suggested_distance, created_at, updated_at) \ VALUES (?, ?, 'photo', ?, 'apple', 'example-face', 0.1, 0.1, 0.2, 0.2, ?, 0.2, ?, ?)", vec![text(face), text(&workspace(&client)), text(&photo), text(person), text(AT), text(AT)], ); let listed = ffi(&client, "records.list", json!({ "table": "face" })); assert_eq!(listed_ids(&listed), [face.to_string()]); let data = &listed["records"][0]["data"]; assert_eq!(data["question"], "Is this Example Singer?"); assert_eq!(data["likelihood"], "likely"); assert_eq!(data["photo_id"], json!(photo)); assert_eq!(data["suggested_person_id"], person); assert!(data["crop"].as_str().unwrap().ends_with(".jpg")); assert!(data.get("decision").is_none()); let got = ffi(&client, "records.get", json!({ "table": "face", "id": face })); assert_eq!(got["data"], *data); let answered = ffi( &client, "records.update", json!({ "table": "face", "id": face, "patch": { "decision": "yes" } }), ); assert_eq!(answered["record"]["data"]["decision"], "yes"); assert_eq!(answered["change"]["undoable"], false); assert_eq!(answered["change"]["byline"], "user"); assert_eq!(ffi(&client, "records.list", json!({ "table": "face" }))["total"], 0); ffi_refused(&client, "records.undo", json!({ "change_id": answered["change"]["id"] })); let refused = ffi_refused( &client, "records.create", json!({ "table": "face", "data": { "decision": "yes" } }), ); assert!(refused.contains("The Mac finds the faces"), "{refused}"); } /// RULE: "Same as …?" is listed through the generic verbs on the phone with where the person came from, and answered "different" through decide_person_suggestion, once. #[test] fn a_person_suggestion_is_answered_from_the_phone() { let (_dir, client) = phone(); let imported = "11111111-1111-4111-8111-000000030001"; let candidate = "11111111-1111-4111-8111-000000030002"; seed_person(&client, imported, "Example Neighbour", "apple_library"); seed_person_reaching( &client, candidate, "Example Neighbor", "manual", "+910000000002", "b@example.com", ); let suggestion = "11111111-1111-4111-8111-000000030003"; exec( &client, "INSERT INTO cotton_person_suggestions (id, workspace_id, person_id, candidate_id, reason, \ score, state, created_at, updated_at) VALUES (?, ?, ?, ?, 'name_fuzzy', 0.9, 'open', ?, ?)", vec![text(suggestion), text(&workspace(&client)), text(imported), text(candidate), text(AT), text(AT)], ); let listed = ffi(&client, "records.list", json!({ "table": "person_suggestion" })); let data = &listed["records"][0]["data"]; assert_eq!(data["question"], "Same as Example Neighbor?"); assert_eq!(data["note"], "Example Neighbour came from your Photos library"); assert_eq!(data["state"], "open"); let answered = ffi( &client, "records.update", json!({ "table": "person_suggestion", "id": suggestion, "patch": { "state": "different" } }), ); assert_eq!(answered["record"]["data"]["state"], "different"); assert_eq!(answered["change"]["undoable"], false); let again = ffi_refused( &client, "records.update", json!({ "table": "person_suggestion", "id": suggestion, "patch": { "state": "merged" } }), ); assert!(again.contains("already decided"), "{again}"); } /// RULE: A list asked by ids answers just those live records in the order asked and refuses paging beside them, because the app resolves a page's link titles by id and must never page a whole linked table to find a few rows. #[test] fn a_list_by_ids_answers_just_those_records_in_the_order_asked() { let (_dir, client) = phone(); let make = |title: &str| { id_of(&ffi( &client, "records.create", json!({ "table": "note", "data": { "title": title } }), )) }; let (first, second, gone) = (make("Example one"), make("Example two"), make("Example gone")); ffi(&client, "records.delete", json!({ "table": "note", "id": gone })); let listed = ffi( &client, "records.list", json!({ "table": "note", "ids": [second, "no-such-note", first, second, gone] }), ); assert_eq!( listed_ids(&listed), [second.clone(), first.clone()], "live records only, each once, in the order asked: {listed}" ); assert_eq!(listed["records"][0]["data"]["title"], "Example two"); assert_eq!(listed["next_page"], Value::Null); assert_eq!(listed["total"], 2); for (beside, value) in [("page", json!(50)), ("where", json!({ "title": "Example one" }))] { let mut request = json!({ "table": "note", "ids": [first] }); request[beside] = value; let refused = ffi_refused(&client, "records.list", request); assert!(refused.contains(beside), "{beside}: {refused}"); } let refused = ffi_refused(&client, "records.list", json!({ "table": "note", "ids": [] })); assert!(refused.contains("ids"), "{refused}"); } /// RULE: A repeating todo's rule is read by its id through records.list, because the app draws a todo's Repeat rule link with that title and a table it cannot read would fail every list holding a repeating todo. #[test] fn a_repeating_todos_rule_is_read_by_its_id() { let (_dir, client) = phone(); let workspace = workspace(&client); let rule = "11111111-1111-4111-8111-000000060001"; exec( &client, "INSERT INTO cotton_todo_recurrences (id, title, rrule, dtstart, created_at, updated_at, \ workspace_id) VALUES (?, 'Example water the ferns', 'FREQ=WEEKLY', '2026-10-01', ?, ?, ?)", vec![text(rule), text(AT), text(AT), text(&workspace)], ); let listed = ffi( &client, "records.list", json!({ "table": "todo_recurrence", "ids": [rule] }), ); assert_eq!(listed_ids(&listed), [rule.to_string()]); assert_eq!(listed["records"][0]["data"]["title"], "Example water the ferns"); } // ── records.command ───────────────────────────────────────────────────────── /// RULE: A command runs only when its table's built-in definition declares it, with the verb and arguments that definition binds, because the app names a command and never an engine verb. #[test] fn a_command_is_one_the_builtin_definition_declares() { let (_dir, client) = phone(); // "student" is a table a person defined: it has no commands to run. let refused = ffi_refused(&client, "records.command", json!({ "table": "student", "id": "s1", "command": "pin" })); assert!(refused.contains("only a table Cotton ships has commands"), "{refused}"); let refused = ffi_refused(&client, "records.command", json!({ "table": "thread", "id": "t1", "command": "send" })); assert!(refused.contains("no command \"send\""), "{refused}"); let refused = ffi_refused(&client, "records.command", json!({ "table": "thread", "command": "pin" })); assert!(refused.contains("needs a record id"), "{refused}"); // A declared command is first checked against the record it would act on // (its `when`), so an id naming no record is refused before any verb runs; // the verb with its id bound is exercised where a record exists, below. let refused = ffi_refused(&client, "records.command", json!({ "table": "thread", "id": "not-a-uuid", "command": "pin" })); assert!(refused.ends_with("is no longer here") && !refused.contains("not-a-uuid"), "{refused}"); } fn a_chat(client: &ClientController, thread: &str) { let workspace = workspace(client); exec( client, "INSERT INTO cotton_msg_threads (id, workspace_id, kind, title, created_at, updated_at) \ VALUES (?, ?, 'group', 'Example choir', ?, ?)", vec![text(thread), text(&workspace), text(AT), text(AT)], ); } /// RULE: A command that ran answers what happened and the command that takes it back; a one-word receipt names the record ("Pinned Example choir", undo "unpin"), and a command is refused on a record it is not offered on. #[test] fn a_command_answers_what_happened_and_how_to_take_it_back() { let (_dir, client) = phone(); let thread = "11111111-1111-4111-8111-000000060001"; a_chat(&client, thread); let run = |command: &str| call(&client, "records.command", &json!({ "table": "thread", "id": thread, "command": command })); let pinned = run("pin").expect("Pin runs on a chat not pinned"); assert_eq!(pinned["kind"], "update"); assert_eq!(pinned["receipt"], "Pinned Example choir"); assert_eq!(pinned["undo"], "unpin"); assert_eq!(pinned["answer"]["pinned"], true, "{pinned}"); let again = run("pin").expect_err("Pin is not offered on a pinned chat"); assert_eq!(again.code, "not_offered", "{again:?}"); assert!(again.message.contains("\"Pin\" is not offered"), "{again:?}"); let back = run(pinned["undo"].as_str().unwrap()).expect("the undo is a command of the same table"); assert_eq!(back["receipt"], "Unpinned Example choir"); assert_eq!(back["undo"], "pin"); // The quiet stamp a page runs on opening says nothing. let read = run("read").expect("Mark read"); assert_eq!(read["receipt"], Value::Null); } /// RULE: A chat's Archive and its Bring back each name the chat in the receipt ("Archived Example choir", "Moved Example choir back to your chats"), and each is the other's Undo. #[test] fn archiving_a_chat_and_bringing_it_back_name_the_chat() { let (_dir, client) = phone(); let thread = "11111111-1111-4111-8111-000000060002"; a_chat(&client, thread); let run = |command: &str| call(&client, "records.command", &json!({ "table": "thread", "id": thread, "command": command })); let archived = run("archive").expect("Archive runs on a chat in the list"); assert_eq!(archived["receipt"], "Archived Example choir", "{archived}"); assert_eq!(archived["undo"], "unarchive"); let back = run("unarchive").expect("Bring back runs on an archived chat"); assert_eq!(back["receipt"], "Moved Example choir back to your chats", "{back}"); assert_eq!(back["undo"], "archive"); } /// RULE: The one runner runs every kind and says what happened: the definition's receipt, else the command's label; open answers the record its link column holds and is refused while the column is empty. #[test] fn the_one_runner_runs_every_kind() { let (_dir, client) = phone(); let thread = "11111111-1111-4111-8111-000000060002"; a_chat(&client, thread); // A command with no receipt of its own answers its label. let mut chats = cotton_core::definitions::builtin_table_definition("thread").expect("chats").clone(); chats.commands.as_mut().unwrap().iter_mut().find(|command| command.id == "archive").unwrap().receipt = None; chats.validate().expect("a receipt is optional"); let archived = run_command(&client, &chats, thread, "archive").expect("archive"); assert_eq!(archived.receipt.as_deref(), Some("Archive")); assert_eq!(archived.undo.as_deref(), Some("unarchive")); assert_eq!(ffi(&client, "records.get", json!({ "table": "thread", "id": thread }))["data"]["archived"], true); // A link column opens its record; an empty one offers nowhere to go. let mut members = cotton_core::definitions::builtin_table_definition("thread_member").expect("members").clone(); members.commands = Some( serde_json::from_value(json!([ { "id": "chat", "label": "Open the chat", "kind": "open", "opens": "thread_id" }, { "id": "person", "label": "Open person", "kind": "open", "opens": "person_id" }, ])) .unwrap(), ); members.validate().expect("open commands on links"); let member = "11111111-1111-4111-8111-000000060003"; exec( &client, "INSERT INTO cotton_msg_thread_participants (id, thread_id, workspace_id, display_name, \ role, created_at) VALUES (?, ?, ?, 'Example Alto', 'admin', ?)", vec![text(member), text(thread), text(&workspace(&client)), text(AT)], ); let opened = run_command(&client, &members, member, "chat").expect("open a link"); assert_eq!(opened.open, Some(json!({ "table": "thread", "id": thread }))); assert_eq!((opened.receipt, opened.answer), (None, None)); let nowhere = run_command(&client, &members, member, "person").expect_err("nobody to open"); assert_eq!(nowhere.code, "not_offered"); } /// RULE: Every write the app makes answers its receipt's words with the change — "Added Call the plumber", "Done Call the plumber" — so no screen words a receipt itself. #[test] fn a_write_answers_its_receipts_words() { let (_dir, client) = phone(); let added = ffi(&client, "records.create", json!({ "table": "todo", "data": { "title": "Call the plumber" } })); assert_eq!(added["change"]["receipt"]["said"], "Added Call the plumber", "{added}"); assert_eq!(added["change"]["receipt"]["kind"], "added"); let id = added["record"]["id"].as_str().expect("the todo's id"); let done = ffi(&client, "records.update", json!({ "table": "todo", "id": id, "patch": { "status": "done" } })); assert_eq!(done["change"]["receipt"]["said"], "Done Call the plumber", "{done}"); assert_eq!(done["change"]["receipt"]["words"], json!([])); let renamed = ffi(&client, "records.update", json!({ "table": "todo", "id": id, "patch": { "title": "Call the plumber today" } })); assert_eq!(renamed["change"]["receipt"]["said"], "Edited Call the plumber today"); assert_eq!(renamed["change"]["receipt"]["words"][0]["before"], "Call the plumber"); } /// RULE: The phone's tick on a repeating todo clears its missed run as the tools do: the earlier open occurrences become missed, the receipt says "Done · n earlier missed cleared", and one Undo opens them all again. #[test] fn a_tick_on_the_phone_clears_the_missed_run() { let (_dir, client) = phone(); let workspace = workspace(&client); let rule = "11111111-1111-4111-8111-000000070001"; exec( &client, "INSERT INTO cotton_todo_recurrences (id, title, rrule, dtstart, created_at, updated_at, \ workspace_id) VALUES (?, 'Example water the ferns', 'FREQ=WEEKLY', '2026-09-01', ?, ?, ?)", vec![text(rule), text(AT), text(AT), text(&workspace)], ); let occurrences = [ ("11111111-1111-4111-8111-000000070002", "2026-09-01T09:00:00.000Z"), ("11111111-1111-4111-8111-000000070003", "2026-09-08T09:00:00.000Z"), ("11111111-1111-4111-8111-000000070004", "2026-09-15T09:00:00.000Z"), ]; for (id, at) in occurrences { exec( &client, "INSERT INTO cotton_todos (id, workspace_id, title, status, due_at, occurrence_at, \ recurrence_id, priority, created_at, updated_at) \ VALUES (?, ?, 'Example water the ferns', 'open', ?, ?, ?, 0, ?, ?)", vec![text(id), text(&workspace), text(at), text(at), text(rule), text(AT), text(AT)], ); } let status = |id: &str| ffi(&client, "records.get", json!({ "table": "todo", "id": id }))["data"]["status"].clone(); let latest = occurrences[2].0; let done = ffi(&client, "records.update", json!({ "table": "todo", "id": latest, "patch": { "status": "done" } })); assert_eq!(done["change"]["receipt"]["said"], "Done Example water the ferns · 2 earlier missed cleared", "{done}"); assert_eq!(status(occurrences[0].0), "missed"); assert_eq!(status(occurrences[1].0), "missed"); ffi(&client, "records.undo", json!({ "change_id": done["change"]["id"] })); for (id, _) in occurrences { assert_eq!(status(id), "open", "one Undo opens the whole run"); } } /// RULE: Every add carries Undo, and Undo of the person's own fresh add on this phone takes it back: the todo is removed as if it was never made, the receipt says Removed and its name, and nothing offers to bring it back. #[test] fn a_new_todo_is_taken_back_by_undo() { let (_dir, client) = phone(); let added = ffi(&client, "records.create", json!({ "table": "todo", "data": { "title": "Call the plumber" } })); assert_eq!(added["change"]["undoable"], true, "{added}"); assert_eq!(added["change"]["reason"], Value::Null); let undone = ffi(&client, "records.undo", json!({ "change_id": added["change"]["id"] })); assert_eq!(undone["record"], Value::Null, "{undone}"); assert_eq!(undone["change"]["verb"], "delete"); assert_eq!(undone["change"]["receipt"]["kind"], "removed"); assert_eq!(undone["change"]["receipt"]["said"], "Removed Call the plumber"); assert_eq!(undone["change"]["undoable"], false); let listed = ffi(&client, "records.list", json!({ "table": "todo" })); let titles: Vec<&str> = listed["records"].as_array().unwrap().iter().filter_map(|r| r["data"]["title"].as_str()).collect(); assert!(!titles.contains(&"Call the plumber"), "{listed}"); } /// RULE: An add that has changed since is not taken back: undoing a new todo that was edited is refused by its name and the todo keeps its edit, as every table whose Delete waits in the bin refuses it. #[test] fn a_new_todo_edited_since_is_not_undone() { let (_dir, client) = phone(); let added = ffi(&client, "records.create", json!({ "table": "todo", "data": { "title": "Call the plumber" } })); let id = added["record"]["id"].clone(); ffi(&client, "records.update", json!({ "table": "todo", "id": id, "patch": { "title": "Call the plumber on Monday" } })); let refused = ffi_refused(&client, "records.undo", json!({ "change_id": added["change"]["id"] })); assert!(refused.starts_with("Call the plumber on Monday has changed since"), "{refused}"); let kept = ffi(&client, "records.get", json!({ "table": "todo", "id": id })); assert_eq!(kept["data"]["title"], "Call the plumber on Monday", "{kept}"); } /// RULE: A todo added from the bar, with the day the sentence named, is the person's own add: its Undo erases it by the take-back and never leaves it under Dropped. #[test] fn a_bar_add_with_a_day_is_erased_by_undo_never_dropped() { let (_dir, client) = phone(); let added = ffi( &client, "records.create", json!({ "table": "todo", "data": { "title": "Sharpen the chisels", "due_at": "2026-10-09T09:00:00.000Z" } }), ); let undone = ffi(&client, "records.undo", json!({ "change_id": added["change"]["id"] })); assert_eq!(undone["change"]["receipt"]["said"], "Removed Sharpen the chisels", "{undone}"); let dropped = ffi(&client, "records.list", json!({ "table": "todo", "where": { "status": "dropped" } })); let titles: Vec<&str> = dropped["records"].as_array().unwrap().iter().filter_map(|r| r["data"]["title"].as_str()).collect(); assert!(!titles.contains(&"Sharpen the chisels"), "the todo was left under Dropped: {dropped}"); } // RULE: A planned list whose every record is past (Meetings: the newest yesterday) answers nothing coming and the whole past under earlier, so the app draws Earlier, never its empty words. /// RULE: A todo page's Drop runs update_todo through records.command and drops it as records.update does, its Undo the Reopen beside it; the page then offers Reopen in place of Done and Drop, which reopens it. Delete is its own act, into the bin. #[test] fn a_todo_pages_drop_is_a_command_that_drops_it() { let (_dir, client) = phone(); let todo = ffi(&client, "records.create", json!({ "table": "todo", "data": { "title": "Paint the shed" } })); let todo = todo["record"]["id"].as_str().unwrap().to_string(); let by_hand = ffi(&client, "records.create", json!({ "table": "todo", "data": { "title": "Sweep the yard" } })); let by_hand = by_hand["record"]["id"].as_str().unwrap().to_string(); ffi(&client, "records.update", json!({ "table": "todo", "id": by_hand, "patch": { "status": "dropped" } })); let page = ffi(&client, "records.page", json!({ "table": "todo", "id": todo })); assert_eq!(page["acts"]["away"]["id"], "delete", "{}", page["acts"]); let dropped = ffi(&client, "records.command", json!({ "table": "todo", "id": todo, "command": "drop" })); assert_eq!((dropped["kind"].as_str(), dropped["undo"].as_str()), (Some("update"), Some("take_up")), "Drop's way back is Reopen"); assert_eq!(dropped["receipt"], "Dropped Paint the shed"); let status = |id: &str| ffi(&client, "records.get", json!({ "table": "todo", "id": id }))["data"]["status"].clone(); assert_eq!(status(&todo), status(&by_hand), "Drop leaves the todo as the update by hand does"); assert_eq!(status(&todo), "dropped"); let page = ffi(&client, "records.page", json!({ "table": "todo", "id": todo })); assert_eq!(page["acts"], json!({ "main": null, "more": [{ "id": "set-date", "label": "Set date" }, { "id": "invite", "label": "People" }, { "id": "edit-notes", "label": "Notes" }, { "id": "take_up", "label": "Reopen" }], "away": { "id": "delete", "label": "Delete" } })); let refused = call(&client, "records.command", &json!({ "table": "todo", "id": todo, "command": "drop" })).unwrap_err(); assert_eq!(refused.code, "not_offered", "a dropped todo is not dropped again"); ffi(&client, "records.command", json!({ "table": "todo", "id": todo, "command": "take_up" })); assert_eq!(status(&todo), "open"); let page = ffi(&client, "records.page", json!({ "table": "todo", "id": todo })); assert_eq!(page["acts"]["main"], json!({ "id": "done", "label": "Mark done" })); } /// RULE: A note page's Delete (its away act) runs the generic delete through records.command and bins the note as records.delete does; its change is undone by records.undo, and the page then offers Delete again. #[test] fn a_note_pages_delete_is_a_command_that_bins_it() { let (_dir, client) = phone(); let note = ffi(&client, "records.create", json!({ "table": "note", "data": { "title": "Seed order", "body": "Beans, kale." } })); let note = note["record"]["id"].as_str().unwrap().to_string(); let by_hand = ffi(&client, "records.create", json!({ "table": "note", "data": { "title": "Shed list" } })); let by_hand = by_hand["record"]["id"].as_str().unwrap().to_string(); let deleted_by_hand = ffi(&client, "records.delete", json!({ "table": "note", "id": by_hand })); let page = ffi(&client, "records.page", json!({ "table": "note", "id": note })); // `more` offers Pin on a note not pinned (Unpin is not offered until it is). assert_eq!(page["acts"], json!({ "main": null, "more": [{ "id": "pin", "label": "Pin" }], "away": { "id": "delete", "label": "Delete" } })); let deleted = ffi(&client, "records.command", json!({ "table": "note", "id": note, "command": "delete" })); assert_eq!((deleted["kind"].as_str(), deleted["undo"].as_str()), (Some("delete"), None)); assert!(deleted["receipt"].as_str().is_some_and(|said| said.contains("Seed order")), "the receipt names the note: {deleted}"); let durable = phone_command_write(&deleted).expect("an undoable delete keeps its full write envelope"); assert!(durable.change.undoable); assert!(!durable.change.id.is_empty()); assert!(durable.change.before.is_some()); assert!(durable.change.after.is_none()); let answer = &deleted["answer"]; assert!(answer["record"]["deleted_at"].is_string(), "binned, as records.delete bins: {answer}"); assert_eq!(answer["change"]["kind"], deleted_by_hand["change"]["kind"], "the same change as the generic verb's"); let refused = call(&client, "records.page", &json!({ "table": "note", "id": note })).unwrap_err(); assert_eq!(refused.code, "record_not_found", "a deleted note's page is gone"); let bin = ffi(&client, "records.list", json!({ "table": "bin", "where": { "table": "note" } })); assert_eq!(bin["total"], 2, "both wait in the bin: {bin}"); ffi(&client, "records.undo", json!({ "change_id": answer["change"]["id"] })); let page = ffi(&client, "records.page", json!({ "table": "note", "id": note })); assert_eq!(page["acts"]["away"], json!({ "id": "delete", "label": "Delete" })); } /// RULE: A records.page of a record that is gone is refused as record_not_found, as records.get's is, and one without a table or an id is a bad request. #[test] fn a_gone_records_page_is_refused_by_name() { let (_dir, client) = phone(); let todo = ffi(&client, "records.create", json!({ "table": "todo", "data": { "title": "Gone soon" } })); let todo = todo["record"]["id"].as_str().unwrap().to_string(); let lesson = ffi(&client, "records.create", json!({ "table": "lesson", "data": { "title": "Gone soon" } })); let lesson = lesson["record"]["id"].as_str().unwrap().to_string(); ffi(&client, "records.delete", json!({ "table": "lesson", "id": lesson })); let refused = call(&client, "records.page", &json!({ "table": "lesson", "id": lesson })).unwrap_err(); assert_eq!(refused.code, "record_not_found", "{}", refused.message); assert_eq!(call(&client, "records.page", &json!({ "table": "todo" })).unwrap_err().code, "bad_request"); assert_eq!(call(&client, "records.page", &json!({ "id": todo })).unwrap_err().code, "bad_request"); } /// RULE: A record page's lists are what belongs to it — a count, at most ten rows each titled in words, and the read that opens the whole list — drawn from the definition's parts. #[test] fn a_records_page_lists_what_belongs_to_it() { let (_dir, client) = phone(); let mut teacher = student(); teacher["id"] = json!("teacher"); teacher["columns"] = json!([{ "key": "name", "type": "text", "required": true }, { "key": "subject", "type": "text" }, { "key": "school", "type": "text" }]); teacher["page"] = json!([{ "heading": null, "columns": ["name", "subject", "school"] }]); teacher["parts"] = json!({ "shape": "sheet", "head": { "facts": ["subject", "school"], "state": null }, "links": [], "body": null, "lists": [{ "table": "class_hour", "relation": "teacher", "heading": "Classes" }], "acts": { "main": null, "more": [], "away": null } }); define(&client, &teacher); let mut hour = lesson(); hour["id"] = json!("class_hour"); hour["columns"] = json!([{ "key": "title", "type": "text", "required": true }, { "key": "teacher", "type": "link", "link_to": "teacher" }]); hour["slip"] = json!({ "title": "title", "subtitle": null, "trailing": null, "photo": null, "toggle": null }); hour["order"] = Value::Null; hour["date"] = Value::Null; hour["page"] = json!([{ "heading": null, "columns": ["title"] }]); define(&client, &hour); let ines = ffi(&client, "records.create", json!({ "table": "teacher", "data": { "name": "Ines Moreau", "subject": "Cello", "school": "Harbour School" } })); let ines = ines["record"]["id"].as_str().unwrap().to_string(); ffi(&client, "records.create", json!({ "table": "teacher", "data": { "name": "Tomas Reyes", "subject": "Piano", "school": "Harbour School" } })); for at in 1..=12 { ffi(&client, "records.create", json!({ "table": "class_hour", "data": { "title": format!("Bowing, week {at}"), "teacher": ines } })); } let page = ffi(&client, "records.page", json!({ "table": "teacher", "id": ines })); assert_eq!(page["shape"], "sheet"); assert_eq!(page["head"]["title"], "Ines Moreau"); let classes = &page["lists"][0]; assert_eq!(classes["heading"], "Classes"); assert_eq!(classes["count"], 12); assert_eq!(classes["rows"].as_array().unwrap().len(), 10, "ten rows, the rest counted"); assert_eq!(classes["all"], json!({ "table": "class_hour", "where": { "teacher": ines } })); for row in classes["rows"].as_array().unwrap() { assert!(row["title"].as_str().unwrap().starts_with("Bowing, week"), "{row}"); assert_eq!(row["line"], Value::Null); } } /// RULE (owner, 25 Oct 2026, #77): memory has no review state. A memory the /// object sent with no `reviewed_at` is live, not waiting: its page offers no /// Approve and its heading stamps no status, and its card carries no state /// stamp. It is a row of the `memory` table the assistants write (2 Nov 2026): /// Memories' All lists it while it is active and Archived once it is not. #[test] fn a_memory_without_a_review_draws_no_review_stamp_and_no_approve() { let (_dir, client) = phone(); // The memory table as the object serves it: the personal kit's. let served = include_str!("../../../cotton-core/kits/personal/tables/memory.json"); exec(&client, "DELETE FROM cotton_table_definitions WHERE id = 'memory'", vec![]); define_raw(&client, "memory", served, false, false); let id = "aaaaaaaa-0000-4000-8000-0000000000a1"; exec( &client, "INSERT INTO cotton_memories (id, workspace_id, slug, title, body, status, visibility, origin_kind, origin_label, created_at, updated_at) \ VALUES (?, ?, 'an-invented-rule', 'An invented rule for a test', 'Its invented reason, a sentence long.', 'active', 'private', 'agent', 'Example assistant', \ '2026-10-01T00:00:00.000Z', '2026-10-01T00:00:00.000Z')", vec![SqlValue::Text(id.into()), SqlValue::Text(workspace(&client))], ); let record = ffi(&client, "records.get", json!({ "table": "memory", "id": id })); assert_eq!(record["data"]["title"], "An invented rule for a test", "{record}"); assert_eq!(record["data"]["status"], "active", "{record}"); let page = ffi(&client, "records.page", json!({ "table": "memory", "id": id })); let acts = page["acts"].to_string(); assert!(!acts.contains("approve") && !acts.contains("Approve"), "{acts}"); assert!(page["head"]["state"].is_null(), "the heading stamps no status: {}", page["head"]); let active = ffi(&client, "records.list", json!({ "table": "memory", "where": { "status": "active" } })); assert!(active.to_string().contains(id), "All lists the active memory: {active}"); let archived = ffi(&client, "records.list", json!({ "table": "memory", "where": { "status": "archived" } })); assert!(!archived.to_string().contains(id), "Archived does not: {archived}"); let tables = ffi(&client, "definitions.tables", json!({})); let memory = tables["definitions"].as_array().into_iter().flatten().find(|table| table["id"] == "memory").expect("the memory table"); assert_eq!(memory["card"]["face"], "memory", "{}", memory["card"]); let slots: Vec<&str> = memory["card"]["fields"].as_array().into_iter().flatten().filter_map(|field| field["slot"].as_str()).collect(); assert_eq!(slots, ["title", "body", "date"]); } /// A serving Mac that answers each call once, keeping what was sent. #[derive(Debug, Default)] struct FakeMac { seen: std::sync::Mutex>, } impl cotton_client::transport::ServerFetch for FakeMac { fn call( &self, request: cotton_client::transport::ClientRequest, ) -> Result { self.seen.lock().expect("the record").push(request); Ok(cotton_client::transport::ClientAnswer { status: 200, body: br#"{"repo":{"held":true}}"#.to_vec() }) } } /// A command's app methods: none answers here, so a method that reached this /// fake would be refused rather than run. impl AppMethods for FakeMac { fn call(&self, method: &str, _request: &Value) -> Result { Err(crate::methods::MethodError::new("unknown_method", format!("{method} is not answered by the fake Mac"))) } } /// RULE: Every method a command may run is an ffi method a module answers, and one off COMMAND_METHODS has none, so records.command dispatches nothing outside the allowlist. #[test] fn every_command_method_is_one_a_module_answers() { for method in cotton_core::definitions::COMMAND_METHODS { assert!(method_module(method).is_some(), "{method} has no module"); assert!( crate::methods::ALL_METHODS.contains(method), "{method} is not an ffi method" ); } for method in ["devices.list", "databases.leave", "records.update", "repo.merge"] { assert!(method_module(method).is_none(), "{method} is off the allowlist"); } } /// RULE: A picker populated from a native record is authority for that /// record alone; forged, missing, and malformed choices never reach a method. #[test] fn engine_owned_picker_choices_cannot_be_forged() { let data = serde_json::from_value(json!({"senders":["Alice","Bob"]})).unwrap(); assert_eq!(offered_choice(Some(&data), "senders", "Alice").unwrap(), "Alice"); assert!(offered_choice(Some(&data), "senders", "Charlie").is_err()); assert!(offered_choice(None, "senders", "Alice").is_err()); let malformed = serde_json::from_value(json!({"senders":["Alice",false]})).unwrap(); assert!(offered_choice(Some(&malformed), "senders", "Alice").is_err()); } /// RULE: A command naming a method off COMMAND_METHODS is refused by records.command before anything runs, even when its definition was never validated. #[test] fn a_command_method_off_the_allowlist_is_refused_before_it_runs() { let (_dir, client) = phone(); let mut imports = cotton_core::definitions::builtin_table_definition("message_import").expect("a kit table").clone(); let retry = imports.commands.as_mut().and_then(|commands| commands.iter_mut().find(|command| command.id == "retry")).expect("retry"); retry.method = Some("repo.merge".into()); retry.when = None; let mac = FakeMac::default(); let refused = run_command_with(&client, &imports, "some-import", "retry", None, &mac).expect_err("refused"); assert_eq!(refused.code, "write_refused"); assert!(mac.seen.lock().unwrap().is_empty(), "nothing reached the Mac"); } // CoreRecords.CommandOutcome.Answer decodes a WireWrite whenever `change` // exists. These are its required fields and typed row sides, never defaults. #[derive(Debug, serde::Deserialize)] struct PhoneCommandWrite { change: PhoneCommandChange, } #[derive(Debug, serde::Deserialize)] struct PhoneCommandChange { id: String, undoable: bool, before: Option>, after: Option>, } fn phone_command_write(outcome: &Value) -> Option { let answer = outcome.get("answer")?; answer.get("change")?; Some(serde_json::from_value(answer.clone()).expect("the phone must decode a complete WireWrite when change is present")) } // ── the assistant page's acts ─────────────────────────────────────────────── /// RULE: A note is pinned and unpinned from its page (board 11, "Edit Pin Delete"): `pin` is offered on a note not pinned and `unpin` on one that is, each writes the note's own `pinned` column through update_note, answers its receipt and names the other as its undo. #[test] fn a_note_is_pinned_and_unpinned_by_its_page_commands() { let (_dir, client) = phone(); let workspace = workspace(&client); let id = "11111111-1111-4111-8111-0000000d0001"; exec( &client, "INSERT INTO cotton_notes (id, workspace_id, kind, title, body, created_at, updated_at) \ VALUES (?, ?, 'note', 'Example allotment plan', '', ?, ?)", vec![ SqlValue::Text(id.into()), SqlValue::Text(workspace), SqlValue::Text("2026-09-20T09:15:00.000Z".into()), SqlValue::Text("2026-09-20T09:15:00.000Z".into()), ], ); let pinned = |client: &ClientController| { client .with_file(|file| { Ok(file .driver .get("SELECT pinned FROM cotton_notes WHERE id = ?", &[SqlValue::Text(id.into())]) .map_err(|error| error.to_string())? .and_then(|row| row.int("pinned"))) }) .expect("the read") }; assert_eq!(pinned(&client), Some(0), "a note starts unpinned"); ffi_refused(&client, "records.command", json!({ "table": "note", "id": id, "command": "unpin" })); let pin = ffi(&client, "records.command", json!({ "table": "note", "id": id, "command": "pin" })); assert_eq!(pin["undo"], "unpin"); assert!(pin["receipt"].as_str().is_some_and(|receipt| receipt.starts_with("Pinned")), "{pin}"); assert_eq!(pinned(&client), Some(1)); ffi_refused(&client, "records.command", json!({ "table": "note", "id": id, "command": "pin" })); let unpin = ffi(&client, "records.command", json!({ "table": "note", "id": id, "command": "unpin" })); assert_eq!(unpin["undo"], "pin"); assert_eq!(pinned(&client), Some(0)); } /// RULE: A story is kept and let go from its page (Stories ruling, note bce88213): `keep` is offered on a story not kept and `unkeep` on a kept one, each writes the story's own `kept` column, answers its receipt and names the other as its undo; nothing else on a story is written here. #[test] fn a_story_is_kept_and_let_go_by_its_page_commands() { let (_dir, client) = phone(); let workspace = workspace(&client); let id = "11111111-1111-4111-8111-0000000e0001"; exec( &client, "INSERT INTO cotton_stories (id, workspace_id, source, account, external_id, sender, sender_label, kind, caption, \ media_key, media_content_type, posted_at, expires_at, created_at) \ VALUES (?, ?, 'whatsapp', '15550009999@s.whatsapp.net', 'ST-EXAMPLE-1', '15550004242', 'Zorin Pell', 'image', \ 'Sunrise at the pier', ?, 'image/jpeg', '2026-09-20T09:15:00.000Z', '2026-09-21T09:15:00.000Z', '2026-09-20T09:15:00.000Z')", vec![ SqlValue::Text(id.into()), SqlValue::Text(workspace.clone()), SqlValue::Text(format!("{workspace}/messages/statuses/0000.jpg")), ], ); let listed = ffi(&client, "records.list", json!({ "table": "story" })); assert!(listed.to_string().contains("Sunrise at the pier"), "{listed}"); let kept = |client: &ClientController| { client .with_file(|file| { Ok(file .driver .get("SELECT kept FROM cotton_stories WHERE id = ?", &[SqlValue::Text(id.into())]) .map_err(|error| error.to_string())? .and_then(|row| row.int("kept"))) }) .expect("the read") }; assert_eq!(kept(&client), Some(0), "a story starts not kept"); ffi_refused(&client, "records.command", json!({ "table": "story", "id": id, "command": "unkeep" })); let keep = ffi(&client, "records.command", json!({ "table": "story", "id": id, "command": "keep" })); assert_eq!(keep["undo"], "unkeep"); assert!(keep["receipt"].as_str().is_some_and(|receipt| receipt.starts_with("Kept")), "{keep}"); assert_eq!(kept(&client), Some(1)); let unkeep = ffi(&client, "records.command", json!({ "table": "story", "id": id, "command": "unkeep" })); assert_eq!(unkeep["undo"], "keep"); assert_eq!(kept(&client), Some(0)); ffi_refused(&client, "records.update", json!({ "table": "story", "id": id, "patch": { "caption": "changed" } })); } /// Domains over canned rows — a domain held (`held`), one handed to another /// database (`handed`) and one only wanted (`wanted`) — answering /// `workspace.setReach` as the write does: its receipt and the way back. #[derive(Debug, Default)] struct FakeDomains { ran: std::sync::Mutex>, } impl AppMethods for FakeDomains { fn call(&self, method: &str, request: &Value) -> Result { self.ran.lock().unwrap().push((method.to_string(), request.clone())); Ok(json!({ "through": "direct", "address": request["address"], "receipt": "Reached directly \u{2014} which this version cannot open yet", "undo": { "method": "workspace.setReach", "args": { "through": "tailscale_funnel", "address": "study.tail1234.ts.net" } }, })) } fn answered_record(&self, table: &str, id: &str) -> Option { assert_eq!(table, "domain"); match id { "held" => Some(json!({ "name": "home.example.org", "registration": "succeeded" })), "handed" => Some(json!({ "name": "shop.example.org", "handed_to": "Example shop" })), "wanted" => Some(json!({ "name": "new.example.org", "registration": "wanted" })), _ => None, } } } /// RULE: A domain the household holds offers "Reach this household here" on its page, and the act is workspace.setReach { through: direct, address: that domain } — the write the serving Mac's own page makes — answered with that write's receipt and its way back to how the household was reached; a domain handed to another database, or only wanted, is not offered it. #[test] fn a_domain_the_household_holds_can_be_where_it_is_reached() { let (_dir, client) = phone(); let domain = super::records::carried_definition("domain").expect("Domains is carried"); let page = domain.page.iter().find(|section| section.heading.as_deref() == Some("Points to")).expect("the section"); assert!(page.commands.iter().flatten().any(|id| id == "reach_here"), "drawn under Points to"); let fake = FakeDomains::default(); let outcome = run_command_with(&client, &domain, "held", "reach_here", None, &fake).expect("reached here"); assert_eq!( *fake.ran.lock().unwrap(), vec![("workspace.setReach".to_string(), json!({ "through": "direct", "address": "home.example.org" }))] ); assert_eq!(outcome.receipt.as_deref(), Some("Reached directly \u{2014} which this version cannot open yet"), "the write's own receipt"); assert_eq!( outcome.undo_call, Some(json!({ "method": "workspace.setReach", "args": { "through": "tailscale_funnel", "address": "study.tail1234.ts.net" } })), "the way back is the write's own" ); assert_eq!(method_module("workspace.setReach"), Some(super::records::MethodModule::PageActs)); for id in ["handed", "wanted"] { let refused = run_command_with(&client, &domain, id, "reach_here", None, &fake).expect_err("not the household's to be reached at"); assert_eq!(refused.code, "not_offered", "{id}"); } assert_eq!(fake.ran.lock().unwrap().len(), 1, "nothing ran for a refused act"); } /// RULE: Nothing a person reads on a Domains page says "door" — not a column, a choice, a heading, an act, its receipt or question, nor the empty list — because the product's language retired the word; the row's internal value may keep it. #[test] fn the_domains_page_never_says_door() { let package = cotton_tools::connections::domains::package(); for table in &package.tables { let mut read: Vec = vec![table.name.clone(), table.plural.clone()]; for column in &table.columns { read.extend(column.name.clone()); read.extend(column.placeholder.clone()); read.extend(column.labels.iter().flat_map(|labels| labels.0.iter().map(|(_, label)| label.clone()))); } read.extend(table.page.iter().filter_map(|section| section.heading.clone())); for command in table.commands.iter().flatten() { read.push(command.label.clone()); read.extend(command.receipt.clone()); read.extend(command.confirm.clone()); } let surface = serde_json::to_value(table).expect("a definition"); for key in ["empty", "create"] { read.push(surface[key].to_string()); } for said in read { assert!(!said.to_lowercase().contains("door"), "{}: {said}", table.id); } } } /// RULE: A todo's people are edges the phone writes through records.link: naming a person who is not on it puts them on, naming them again takes them off, and the change says the people before and after (architect, r6: the people card is the pick sheet of people). #[test] fn a_todos_people_are_put_on_and_taken_off_by_link() { let (_dir, client) = phone(); let person = ffi( &client, "records.create", json!({ "table": "person", "data": { "full_name": "Example Person" } }), ); let person = person["record"]["id"].as_str().unwrap().to_string(); let todo = ffi( &client, "records.create", json!({ "table": "todo", "data": { "title": "Return the invented ladder" } }), ); let todo = todo["record"]["id"].as_str().unwrap().to_string(); let on = ffi( &client, "records.link", json!({ "table": "todo", "id": todo, "column": "people", "target_id": person }), ); assert_eq!(on["change"]["verb"], "link"); assert_eq!(on["record"]["data"]["people"], json!([person.clone()])); let off = ffi( &client, "records.link", json!({ "table": "todo", "id": todo, "column": "people", "target_id": person }), ); assert!( off["record"]["data"]["people"].as_array().is_none_or(|people| people.is_empty()), "named again, they are taken off: {}", off["record"]["data"]["people"] ); } // ── records.spoken ────────────────────────────────────────────────────────── fn boundary_list(handle: &mut crate::handle::CottonHandle, request: Value) -> Value { let method = std::ffi::CString::new("records.list").unwrap(); let body = std::ffi::CString::new(request.to_string()).unwrap(); // Exercise the C boundary and its envelope, exactly as CottonCore calls it. unsafe { let ptr = crate::ffi::cotton_call(handle, method.as_ptr(), body.as_ptr()); let answer = serde_json::from_slice(std::ffi::CStr::from_ptr(ptr).to_bytes()).unwrap(); crate::ffi::cotton_string_free(ptr); answer } } /// RULE: A real list refusal carries the core's reason through the FFI envelope, so the app can explain the failed read instead of saying only to try again. #[test] fn a_refused_list_carries_its_reason_through_ffi() { let (_dir, mut handle) = crate::fixture::synthetic_phone(); let request = json!({"table":"ride","page":-1}); let refused = crate::methods::dispatch(&handle, "records.list", &request).unwrap_err(); let answer = boundary_list(&mut handle, request); assert_eq!(answer["ok"], false); assert_eq!(answer["error"]["code"], "unreadable"); assert_eq!(answer["error"]["message"], refused.message); assert!(!refused.message.trim().is_empty()); assert_ne!(refused.message, cotton_core::failure::NOT_DONE); assert_ne!(refused.message, cotton_core::failure::NOT_READ); } // RULE: A package's declared act reaches the tray and records.command through the generic engine, while an undeclared native verb remains unavailable. #[test] fn package_act_is_dealt_and_run_by_records_command() { use base64::Engine; use cotton_core::definitions::{package::ToolPackage, TableDefinition, ToolDefinition}; let (_dir, client, _) = attached_on_a_clock(); let mut raw = student(); raw["id"] = json!("synthetic_act"); raw["acts"] = json!([{"id":"rename","label":"Rename","kind":"update","verb":"set","data":{"column":"name","value":"Changed by package"}}]); let table: TableDefinition = serde_json::from_value(raw).unwrap(); let tool: ToolDefinition = serde_json::from_value(json!({"id":"synthetic_acts","name":"Synthetic acts","tables":["synthetic_act"],"instructions":"Synthetic","engines":["rules@1"],"automations":[],"author":{"device":"synthetic","name":"Synthetic"},"signature":null})).unwrap(); let package = ToolPackage { board: None, tool, tables: vec![table], pictures: Default::default(), samples: Default::default() }; let bytes = cotton_core::definitions::package::encode_unsigned_package(&package).unwrap(); client.write("import_tool", json!({"bytes":base64::engine::general_purpose::STANDARD.encode(bytes)}).as_object().unwrap()).unwrap(); let made = ffi(&client, "records.create", json!({"table":"synthetic_act","data":{"name":"Synthetic"}})); let id = made["record"]["id"].clone(); let page = ffi(&client, "records.page", json!({"table":"synthetic_act","id":id})); assert!(page["acts"]["more"].as_array().unwrap().iter().any(|act| act["id"] == "rename")); let answer = ffi(&client, "records.command", json!({"table":"synthetic_act","id":id,"command":"rename"})); assert_eq!(answer["answer"]["record"]["data"]["name"], "Changed by package"); assert!(call(&client, "records.command", &json!({"table":"synthetic_act","id":id,"command":"delete_person"})).is_err()); } // RULE: The phone turns a numeric pick's text into a JSON number before writing; invalid text and out-of-range values never become act arguments. #[test] fn number_pick_crosses_the_phone_boundary_as_a_number() { let pick = serde_json::from_value(json!({"kind":"number","argument":"data.quantity","min":1,"max":5,"default":2})).unwrap(); for (text, value) in [("3", json!(3)), (" 2.5 ", json!(2.5))] { assert_eq!(super::records::picked_number(&pick, text).unwrap(), value); } for text in ["", "NaN", "Infinity", "null", "true", "\"2\"", "0", "6"] { assert!(super::records::picked_number(&pick, text).is_err()); } } // RULE: Phone and Mac preserve pick order and labels, send typed answers together, and execute a multi-pick act once. #[test] fn ordered_picks_cross_the_phone_boundary_together() { use base64::Engine; use cotton_core::definitions::{package::ToolPackage, TableDefinition, ToolDefinition}; let (_dir, client, _) = attached_on_a_clock(); let mut raw = student(); raw["id"] = json!("synthetic_act"); raw["columns"].as_array_mut().unwrap().push(json!({"key":"quantity","type":"number"})); raw["acts"] = json!([{"id":"copy","label":"Copy","kind":"create","verb":"create", "data":{"table":"synthetic_act","data":{}},"picks":[ {"kind":"text","argument":"data.name","label":"Customer"}, {"kind":"number","argument":"data.quantity","label":"Quantity","min":1,"max":5,"default":2}]}]); let table: TableDefinition = serde_json::from_value(raw).unwrap(); let tool: ToolDefinition = serde_json::from_value(json!({"id":"synthetic_acts","name":"Synthetic acts","tables":["synthetic_act"],"instructions":"Synthetic","engines":["rules@1"],"automations":[],"author":{"device":"synthetic","name":"Synthetic"},"signature":null})).unwrap(); let package = ToolPackage { board: None, tool, tables: vec![table], pictures: Default::default(), samples: Default::default() }; let bytes = cotton_core::definitions::package::encode_unsigned_package(&package).unwrap(); client.write("import_tool", json!({"bytes":base64::engine::general_purpose::STANDARD.encode(bytes)}).as_object().unwrap()).unwrap(); let made = ffi(&client, "records.create", json!({"table":"synthetic_act","data":{"name":"Synthetic"}})); let id = made["record"]["id"].clone(); let page = ffi(&client, "records.page", json!({"table":"synthetic_act","id":id})); assert!(page["acts"]["more"].as_array().unwrap().iter().any(|act| act["id"] == "copy")); let definitions = ffi(&client, "definitions.tables", json!({})); let table = definitions["definitions"].as_array().unwrap().iter().find(|table| table["id"] == "synthetic_act").unwrap(); let act = &table["acts"][0]; assert_eq!(act["picks"][0]["label"], "Customer"); assert_eq!(act["picks"][1]["kind"], "number"); for picked in [json!(["Synthetic", "6"]), json!(["Synthetic"]), json!("Synthetic")] { assert!(call(&client, "records.command", &json!({"table":"synthetic_act","id":id,"command":"copy","picked":picked})).is_err()); } let answer = ffi(&client, "records.command", json!({"table":"synthetic_act","id":id,"command":"copy","picked":["Synthetic copy","3"]})); assert_eq!(answer["answer"]["record"]["data"]["name"], "Synthetic copy"); assert_eq!(answer["answer"]["record"]["data"]["quantity"], 3); let listed = ffi(&client, "records.list", json!({"table":"synthetic_act"})); assert_eq!(listed["records"].as_array().unwrap().len(), 2); } // RULE: Yoga's renew act runs over the shipped package: a member renewed onto a plan holds that plan's classes, and the act is gone once the definition drops it. #[test] fn yoga_member_renew_runs_the_package_act() { let (_dir,client)=phone(); client.write("add_tool",json!({"tool_id":"yoga"}).as_object().unwrap()).unwrap(); let member=client.write("create_record",json!({"table":"yoga_member","data":{"name":"Synthetic member","currency":"USD"}}).as_object().unwrap()).unwrap(); let member=crate::authoring::own_answer(member); let id=member["record"]["id"].as_str().unwrap_or_else(||panic!("{member}")); let plan=client.write("create_record",json!({"table":"yoga_offer","data":{"name":"Synthetic two classes","kind":"classes","classes":2,"valid_days":30,"price":100,"currency":"USD"}}).as_object().unwrap()).unwrap(); let plan=crate::authoring::own_answer(plan); let plan=plan["record"]["id"].as_str().unwrap_or_else(||panic!("{plan}")).to_string(); call(&client,"records.command",&json!({"table":"yoga_member","id":id,"command":"renew","picked":plan})).unwrap(); client.with_file(|file| { let pack=file.driver.get("SELECT classes FROM cotton_yoga_pack WHERE member=?",&[id.to_owned().into()]).map_err(|e|e.to_string())?.unwrap(); assert_eq!(pack.int("classes"),Some(2)); Ok(()) }).unwrap(); exec(&client,"UPDATE cotton_table_definitions SET definition=json_remove(definition,'$.acts') WHERE id='yoga_member'",vec![]); assert!(call(&client,"records.command",&json!({"table":"yoga_member","id":id,"command":"renew","picked":plan})).is_err()); } // The phone's whole search reads an imported data-only table through its // definition, beside the built-in sections. #[test] fn find_reads_an_imported_table_through_its_definition() { use base64::Engine; use cotton_core::definitions::{package::ToolPackage, TableDefinition, ToolDefinition}; let (_dir, client, _) = attached_on_a_clock(); let mut raw = student(); raw["id"] = json!("synthetic_find"); let table: TableDefinition = serde_json::from_value(raw).unwrap(); let tool: ToolDefinition = serde_json::from_value(json!({"id":"synthetic_finds","name":"Synthetic finds","tables":["synthetic_find"],"instructions":"Synthetic","engines":[],"automations":[],"author":{"device":"synthetic","name":"Synthetic"},"signature":null})).unwrap(); let package = ToolPackage { board: None, tool, tables: vec![table], pictures: Default::default(), samples: Default::default() }; let bytes = cotton_core::definitions::package::encode_unsigned_package(&package).unwrap(); client.write("import_tool", json!({"bytes":base64::engine::general_purpose::STANDARD.encode(bytes)}).as_object().unwrap()).unwrap(); let made = ffi(&client, "records.create", json!({"table":"synthetic_find","data":{"name":"Quillon Marsh"}})); let entry = super::reads::read_for("read.find").expect("read.find is declared"); let answer = super::answer_read(&client, entry, json!({"query":"quillon"}).as_object().unwrap()).unwrap(); let hits = answer["defined"]["synthetic_find"]["hits"].as_array().unwrap_or_else(|| panic!("{answer}")); assert_eq!(hits.len(), 1); assert_eq!(hits[0]["id"], made["record"]["id"]); assert_eq!(hits[0]["title"], "Quillon Marsh"); // The section is named by the definition, never by the app. assert_eq!(answer["defined"]["synthetic_find"]["label"], "Students"); // An expanded section reads its next page by table, from an offset. ffi(&client, "records.create", json!({"table":"synthetic_find","data":{"name":"Quillon Reed"}})); let page = super::answer_read(&client, entry, json!({"query":"quillon","table":"synthetic_find","offset":1,"limit":1}).as_object().unwrap()).unwrap(); let section = &page["defined"]["synthetic_find"]; assert_eq!(section["hits"].as_array().map(Vec::len), Some(1), "{page}"); assert_eq!(section["total"], 2); assert_eq!(page["hits"], json!([])); } // RULE: a group deck's read (a view whose card is the group face) answers one // card per record its people place names, over every page of the view: the // student's name, then the lessons in the view's order, the latest three. #[test] fn a_group_view_deals_one_card_per_linked_record_over_every_page() { let (_dir, client) = phone(); let tool = json!({ "id": "lessons", "name": "Lessons", "picture": "tool-lessons", "tables": ["lesson", "student"], "instructions": "Teaching.", "automations": [], "author": { "device": "d1", "name": "A Teacher" }, "signature": null, "views": [{ "id": "all", "label": "All", "is_default": true, "read": { "table": "lesson" } }, { "id": "by_student", "label": "By student", "read": { "table": "lesson" }, "sort": { "column": "day", "descending": true }, "card": { "face": "group", "fields": [ { "slot": "people", "column": "student" }, { "slot": "title", "column": "title" }, { "slot": "date", "column": "day" } ] } }] }); exec( &client, "INSERT INTO cotton_tool_definitions (id, workspace_id, definition, created_at, updated_at) \ VALUES ('lessons', ?, ?, '2026-10-01T09:00:00.000Z', '2026-10-01T09:00:00.000Z')", vec![SqlValue::Text(workspace(&client)), SqlValue::Text(tool.to_string())], ); let student = |name: &str| { ffi(&client, "records.create", json!({ "table": "student", "data": { "name": name } }))["record"]["id"].as_str().unwrap().to_string() }; let (asha, ravi) = (student("Invented Asha"), student("Invented Ravi")); for (title, day, who) in [ ("Scales", "2026-10-01", &asha), ("Arpeggios", "2026-10-05", &asha), ("Chords", "2026-10-03", &ravi), ("Sight reading", "2026-10-07", &asha), ("Rhythm", "2026-10-09", &asha), ] { ffi(&client, "records.create", json!({ "table": "lesson", "data": { "title": title, "day": day, "student": who } })); } // A first page of two: the deal reads the rest itself. let request = json!({ "table": "lesson", "view": "lessons/by_student", "limit": 2, "page": 0 }); let mut definition = None; let answer = super::records::call_with_definition(&client, "records.list", &request, Some(&mut definition)).expect("the view's first page"); assert_eq!(answer["records"].as_array().unwrap().len(), 2); // The view's whole read, in its own order: what the deal follows. let whole = super::records::call_with_definition(&client, "records.list", &json!({ "table": "lesson", "view": "lessons/by_student", "limit": 20 }), None).unwrap(); let rows: Vec<(String, String)> = whole["records"] .as_array() .unwrap() .iter() .map(|row| (row["data"]["student"].as_str().unwrap().to_string(), row["data"]["title"].as_str().unwrap().to_string())) .collect(); let first = rows[0].0.clone(); let lines_of = |who: &str| rows.iter().filter(|(by, _)| by == who).map(|(_, title)| title.as_str()).take(3).collect::>(); let dealt = super::records::group_deck(&client, None, &request, &answer, definition.as_ref()) .expect("the deal") .expect("a group view is dealt"); assert_eq!(dealt["total"], 2); assert!(dealt["next_page"].is_null()); let cards: Vec<&Value> = dealt["records"].as_array().unwrap().iter().map(|record| &record["data"]["@card"]).collect(); assert_eq!(dealt["records"][0]["id"], json!(first), "the student of the view's first lesson first"); let asha_card = dealt["records"].as_array().unwrap().iter().find(|record| record["id"] == json!(asha)).unwrap(); let asha_card = &asha_card["data"]["@card"]; assert_eq!(asha_card["face"], "group"); assert_eq!(asha_card["fields"]["title"], "Invented Asha"); let titles: Vec<&str> = asha_card["fields"]["lines"].as_array().unwrap().iter().map(|line| line["title"].as_str().unwrap()).collect(); assert_eq!(titles, lines_of(&asha), "Asha's first three lessons in the view's order"); assert_eq!(asha_card["fields"]["more"], "+1"); assert!(asha_card["fields"]["lines"][0]["date"].is_string()); assert!(cards.iter().any(|card| card["fields"]["title"] == "Invented Ravi")); // Asked for its ids, the view answers its rows as ever. let by_ids = json!({ "table": "lesson", "view": "lessons/by_student", "ids": [asha] }); assert!(super::records::group_deck(&client, None, &by_ids, &answer, definition.as_ref()).unwrap().is_none()); } // RULE (owner, 27 Oct 2026): a transaction card says the account's balance // before and after it — the copy keeps the object's balance columns its // build's table lacks (`package_shape::add_served`), and the Money deck's // card reads them into its facts place under their labels. #[test] fn a_money_card_says_the_balance_the_copy_kept_for_the_object() { use cotton_store::schema::package_shape::{add_served, served_column}; let (_dir, client) = phone(); let id = "synthetic-served-movement"; exec( &client, "INSERT INTO cotton_money_transactions (id, workspace_id, occurred_on, description, status, amount_minor, amount_known, direction, currency, created_at, updated_at) \ VALUES (?, ?, '2026-10-20', 'Invented grocer', 'actual', 25000, 1, 'out', 'INR', '2026-10-20T09:00:00.000Z', '2026-10-20T09:00:00.000Z')", vec![SqlValue::Text(id.into()), SqlValue::Text(workspace(&client))], ); client .with_writer(|file| { let columns = [ served_column("balance_before_minor", "amount", false).map_err(|error| error.to_string())?, served_column("balance_after_minor", "amount", false).map_err(|error| error.to_string())?, ]; add_served(file.driver, "cotton_money_transactions", &columns).map_err(|error| error.to_string())?; // The object's balance, as the copy's pull leaves it on the row. file.driver .run("UPDATE cotton_money_transactions SET balance_before_minor = 120000, balance_after_minor = 95000 WHERE id = ?", &[SqlValue::Text(id.into())]) .map_err(|error| error.to_string())?; Ok(()) }) .expect("the copy keeps the object's balance"); // The Past deck's read, with the definition the deck draws its cards by. let mut viewed = None; let answer = super::records::call_with_definition(&client, "records.list", &json!({ "table": "transaction", "view": "money/past", "limit": 20 }), Some(&mut viewed)) .expect("the Past deck"); let record = answer["records"].as_array().and_then(|rows| rows.iter().find(|row| row["id"] == json!(id))).unwrap_or_else(|| panic!("{answer}")); assert_eq!(record["data"]["balance_before_minor"], json!(120000), "{record}"); assert_eq!(record["data"]["balance_after_minor"], json!(95000), "{record}"); // Its card, as the deck resolves it (`attach_cards`). let viewed = viewed.expect("the viewed definition"); let card = viewed.card.as_ref().expect("the Past view's card"); let now = chrono::DateTime::parse_from_rfc3339("2026-10-27T10:00:00+05:30").expect("an instant").with_timezone(&chrono::Utc); let cards = cotton_core::rules::shell_lines::LineSet::shipped("cards").expect("the card words"); let resolved = cotton_core::records::card::resolve( card, &viewed, id, record["data"].as_object().expect("data"), "Asia/Kolkata", now, cotton_core::records::page::Words::shipped(), &cards, cotton_core::records::card::Around::default(), ) .expect("a card"); let resolved = serde_json::to_value(resolved).expect("the card"); let facts = resolved["fields"]["facts"].as_array().unwrap_or_else(|| panic!("the card's facts: {resolved}")); let labels: Vec<&str> = facts.iter().filter_map(|fact| fact["label"].as_str()).collect(); assert_eq!(labels, vec!["Balance before", "Balance after"], "{resolved}"); assert!(facts.iter().all(|fact| fact["said"].as_str().is_some_and(|said| said.contains("1,200") || said.contains("950"))), "{facts:?}"); } /// RULE: Thread cards cross the phone boundary whole: only six recent /// visible notes, with the oldest visible year, even beyond the first page. #[test] fn thread_cards_carry_recent_messages_before_the_phone_draws_them() { let (_dir, handle) = crate::fixture::synthetic_phone(); let client = handle.client(); let workspace = workspace(&client); let thread = "11111111-1111-4111-8111-000000099001"; let empty = "11111111-1111-4111-8111-000000099002"; a_chat(&client, thread); a_chat(&client, empty); for n in 0..64 { let stamp = if n == 0 { "2020-01-01T00:00:00Z".to_string() } else { format!("2026-10-30T03:{:02}:00Z", n - 1) }; // Sixty-four rows also catch an oldest-page number mistaken for an offset. let stamp = if n >= 61 { format!("2026-10-30T04:0{}:00Z", n - 61) } else { stamp }; exec(&client, "INSERT INTO cotton_msg_messages (id, thread_id, workspace_id, direction, channel, origin, body, sent_at, created_at) VALUES (?, ?, ?, ?, 'cotton', 'live', ?, ?, ?)", vec![text(&format!("invented-m-{n:03}")), text(thread), text(&workspace), text(if n%2==1 {"out"} else {"in"}), text(&format!("Invented line {n}")), text(&stamp), text(&stamp)]); } exec(&client, "UPDATE cotton_msg_messages SET hidden_at = ? WHERE id = ?", vec![text(AT), text("invented-m-062")]); let started = std::time::Instant::now(); let got = crate::methods::dispatch(&handle, "records.get", &json!({"table":"thread", "id":thread})).unwrap(); eprintln!("complete thread card: {:?}", started.elapsed()); let history = &got["data"]["@card"]["thread"]; assert_eq!(history["earlier"].as_array().unwrap().len(), 5, "{got}"); assert_eq!(history["earlier"][0]["id"], "invented-m-057"); assert_eq!(history["last"]["id"], "invented-m-063"); assert_eq!(history["last"]["words"], "Invented line 63"); assert_eq!(history["last"]["mine"], true); assert!(history["count"].as_str().unwrap().ends_with("2020"), "{history}"); let listed = crate::methods::dispatch(&handle, "records.list", &json!({"table":"thread"})).unwrap(); let cards = listed["records"].as_array().unwrap(); let card = cards.iter().find(|card| card["id"] == thread).unwrap(); assert_eq!(card["data"]["@card"]["thread"], *history); let empty = cards.iter().find(|card| card["id"] == empty).unwrap(); assert_eq!(empty["data"]["@card"]["thread"]["earlier"], json!([])); assert!(empty["data"]["@card"]["thread"]["last"].is_null()); } #[test] fn account_cards_carry_their_current_month_statement_rows() { use cotton_store::schema::package_shape::{add_served, served_column}; let (_dir, handle) = crate::fixture::synthetic_phone(); let client = handle.client(); let account = "synthetic-statement-account"; exec(&client, "INSERT INTO cotton_money_accounts (id, workspace_id, kind, subtype, name, currency, created_at, updated_at) VALUES (?, ?, 'asset', 'bank', 'Synthetic savings', 'INR', '2026-10-01', '2026-10-01')", vec![text(account), text(&workspace(&client))]); let now = client.clock().now(); let today = cotton_core::records::page::Moment::now(now, client.time_zone().unwrap_or("Etc/UTC")).unwrap(); let (y, m, d) = cotton_core::transforms::zoned_clock::civil_from_days(today.day); let day = format!("{y:04}-{m:02}-{d:02}"); let transaction = "synthetic-statement-debit"; exec(&client, "INSERT INTO cotton_money_transactions (id,workspace_id,occurred_on,description,account_id,direction,amount_minor,amount_known,moves_money,status,currency,created_at,updated_at) VALUES (?, ?, ?, 'Synthetic groceries', ?, 'out', 190800, 1, 1, 'actual', 'INR', ?, ?)", vec![text(transaction), text(&workspace(&client)), text(&day), text(account), text(&day), text(&day)]); client.with_writer(|file| { add_served(file.driver, "cotton_money_accounts", &[served_column("balance_minor", "amount", false).unwrap()]).map_err(|e| e.to_string())?; file.driver.run("UPDATE cotton_money_accounts SET balance_minor=6775300 WHERE id=?", &[text(account)]).map_err(|e| e.to_string())?; add_served(file.driver, "cotton_money_transactions", &[served_column("balance_after_minor", "amount", false).unwrap()]).map_err(|e| e.to_string())?; file.driver.run("UPDATE cotton_money_transactions SET balance_after_minor=6775300 WHERE id=?", &[text(transaction)]).map_err(|e| e.to_string())?; Ok(()) }).unwrap(); let got = crate::methods::dispatch(&handle, "records.get", &json!({"table":"money_account","id":account})).unwrap(); assert_eq!(got["data"]["balance_minor"], 6775300, "the account keeps the Worker's balance, never a phone sum: {got}"); let rows = got["data"]["@card"]["fields"]["rows"].as_array().unwrap_or_else(|| panic!("{got}")); assert_eq!(rows.len(), 1, "{got}"); assert_eq!(rows[0]["narration"], "Synthetic groceries"); assert_eq!(rows[0]["debit"], "₹1,908"); assert_eq!(rows[0]["balance"], "₹67,753"); assert!(rows[0]["credit"].is_null()); } /// Cinemas' Watched reads by status, as the tool's instructions say: every /// watched film is on it, a film marked Watched without a day included (it /// vanished while Watched read the day), and no film still wanted. #[test] fn film_views_split_every_film_by_its_status() { let (_dir, client) = phone(); let mut films = Vec::new(); for (title, status, watched) in [ ("Synthetic unplayed film", "want_to_watch", None), ("Synthetic finished film", "watched", Some("2026-10-30")), ("Synthetic undated watched film", "watched", None), ] { let mut data = json!({"title":title,"kind":"film","status":status}); if let Some(day) = watched { data["watched_on"] = json!(day); } let made = ffi(&client, "records.create", json!({"table":"film","data":data})); films.push((made["record"]["id"].as_str().unwrap().to_string(), status)); } for (view, held) in [("watched", "watched")] { let answer = super::records::call_with_definition(&client, "records.list", &json!({"table":"film","view":format!("cinemas/{view}"),"limit":100}), None).unwrap(); let rows = answer["records"].as_array().unwrap(); for (id, status) in &films { assert_eq!(rows.iter().any(|row| row["id"] == *id), *status == held, "{view} / {status} {id}: {answer}"); } } } /// An object answering `object.act` as `fetch_add` does, or refusing a phone not signed in. #[derive(Debug, Default)] struct FakeObject { signed_out: bool, seen: std::sync::Mutex>, } impl AppMethods for FakeObject { fn call(&self, method: &str, request: &Value) -> Result { assert_eq!(method, "object.act"); self.seen.lock().expect("the record").push(request.clone()); if self.signed_out { return Err(crate::methods::MethodError::new(crate::phone::object_acts::SIGN_IN_FIRST, "Sign in first: this needs your account.")); } Ok(json!({ "fetch": "fetch-1", "made": { "table": "fetch", "id": "fetch-1" } })) } } /// RULE (6 Nov 2026): An article's Fetch sends the object's fetch_add the page's own link as its source, its title and what it wants, says its receipt, and lands on the download it made once sync brings it; on a phone not signed in it says the Downloads door's words. #[test] fn an_article_s_fetch_queues_its_link_and_lands_on_the_download() { let (_dir, client) = phone(); let path = cotton_store::manifest_dir().join("../cotton-core/kits/personal/tables/page.json"); let pages = cotton_core::definitions::TableDefinition::from_json(&std::fs::read_to_string(path).expect("the kit's page table")).expect("it reads"); let link = "https://video.example/watch?v=invented01"; let page = ffi(&client, "records.create", json!({ "table": "page", "data": { "url": link, "title": "An Invented Short" } })); let page = page["record"]["id"].as_str().expect("the page's id").to_string(); // The definitions the shell draws from hold both commands. let tables = ffi(&client, "definitions.tables", json!({})); let drawn = tables["definitions"].as_array().expect("definitions").iter().find(|table| table["id"] == "page").expect("page is drawn"); let ids: Vec<&str> = drawn["commands"].as_array().map(|commands| commands.iter().filter_map(|command| command["id"].as_str()).collect()).unwrap_or_default(); assert_eq!(ids, ["fetch", "fetch_sound", "star", "unstar", "archive", "open_original"], "{}", drawn["commands"]); // The phone's own definition offers both on the held card. let opened = crate::phone::opened::call(&client, &json!({ "table": "page", "id": page })).expect("shell.opened"); let offered: Vec<&str> = opened["acts"].as_array().expect("acts").iter().filter_map(|act| act["id"].as_str()).collect(); assert!(offered.contains(&"fetch") && offered.contains(&"fetch_sound"), "{opened}"); let object = FakeObject::default(); let fetched = run_command_with(&client, &pages, &page, "fetch_sound", None, &object).expect("Fetch the sound runs"); assert_eq!( object.seen.lock().unwrap().as_slice(), [json!({ "act": "fetch_add", "wants": "audio", "source": link, "title": "An Invented Short" })] ); assert_eq!(fetched.receipt.as_deref(), Some("The sound is queued for your Mac")); assert_eq!(fetched.open, Some(json!({ "table": "fetch", "id": "fetch-1", "by_sync": true }))); let refused = run_command_with(&client, &pages, &page, "fetch", None, &FakeObject { signed_out: true, ..Default::default() }) .expect_err("a phone not signed in fetches nothing"); assert_eq!(refused.code, crate::phone::object_acts::SIGN_IN_FIRST); assert_eq!(refused.message, "Sign in to fetch links on your Mac"); } /// RULE (362 walk, Downloads): A download's held acts follow its state: Cancel only while it waits, fetches or lands; Try again for a failed or cancelled one; Remove, last, for a done, failed or cancelled one. A cancelled row stands on its own Cancelled view (it neither landed nor failed: the person stopped it), and Remove takes it off All and Cancelled at once. #[test] fn a_downloads_acts_follow_its_state_and_remove_takes_it_off_the_views() { let (_dir, client) = phone(); let path = cotton_store::manifest_dir().join("../cotton-core/kits/personal/tables/fetch.json"); let fetches = cotton_core::definitions::TableDefinition::from_json(&std::fs::read_to_string(path).expect("the kit's fetch table")).expect("it reads"); let made = ffi(&client, "records.create", json!({ "table": "fetch", "data": { "source": "https://files.example/invented-short.epub" } })); let id = made["record"]["id"].as_str().expect("the download's id").to_string(); let acts = |state: &str| -> Vec { exec(&client, "UPDATE cotton_fetch SET state = ? WHERE id = ?", vec![text(state), text(&id)]); let opened = crate::phone::opened::call(&client, &json!({ "table": "fetch", "id": id })).expect("shell.opened"); opened["acts"].as_array().expect("acts").iter().filter_map(|act| act["id"].as_str().map(str::to_string)).filter(|act| ["cancel", "retry", "remove"].contains(&act.as_str())).collect() }; for state in ["queued", "fetching", "landing"] { assert_eq!(acts(state), ["cancel"], "{state}"); } assert_eq!(acts("done"), ["remove"]); assert_eq!(acts("failed"), ["retry", "remove"]); assert_eq!(acts("cancelled"), ["retry", "remove"]); let on = |view: &str| -> bool { let answer = super::records::call_with_definition(&client, "records.list", &json!({ "table": "fetch", "view": format!("downloads/{view}"), "limit": 100 }), None).expect("the view lists"); answer["records"].as_array().expect("records").iter().any(|row| row["id"] == id.as_str()) }; let views = ["all", "active", "done", "failed", "cancelled"]; let standing: Vec<&str> = views.into_iter().filter(|view| on(view)).collect(); assert_eq!(standing, ["all", "cancelled"]); let removed = run_command(&client, &fetches, &id, "remove").expect("Remove runs"); assert!(removed.receipt.as_deref().is_some_and(|said| said.starts_with("Removed")), "{:?}", removed.receipt); assert!(views.into_iter().all(|view| !on(view)), "a removed download stands on no view"); }