//! The generic record verbs (store v47) — `list_records`, //! `get_record_by_table`, `create_record`, `update_record`, `delete_record`, //! `reorder_records`, `link_records` and `undo` — driven end to end through //! the dispatcher, on a table a person defined AND on todos. //! //! The user tables are two synthetic ones, "student" and "lesson", written as //! table-definition rows the way an imported tool writes them. Every value is //! invented ([nothing-real-ever-goes-in-cotton-s-public-tree]). mod support; use std::collections::BTreeMap; use cotton_store::meta::Meta; use rusqlite::types::Value as SqlValue; use serde_json::{json, Value}; use support::harness::{synthetic_uuid, Harness}; use support::mcp::{call_tool, call_tool_as_owner, call_tool_raw, mint_token}; const NOW: &str = "2026-10-01T09:00:00.000Z"; // RULE: Everything’s native last-change read spans the whole live table, keeps note and journal distinct, and excludes binned rows. #[test] fn everything_latest_change_is_native_whole_table_metadata() { let (h, secret) = harness(); let text = |value: &str| SqlValue::Text(value.to_string()); for (id, kind, at, binned) in [ ("note:old", "note", "2026-10-01T09:00:00Z", None), ("note:latest", "note", "2026-10-06T09:00:00Z", None), ("note:binned", "note", "2026-10-07T09:00:00Z", Some(NOW)), ("journal:latest", "journal", "2026-10-08T09:00:00Z", None), ] { h.run("INSERT INTO cotton_notes (id, workspace_id, kind, title, body, created_at, updated_at, trashed_at) VALUES (?, ?, ?, 'Synthetic', 'Words', ?, ?, ?)", &[text(id), text(&h.workspace_id), text(kind), text(NOW), text(at), binned.map_or(SqlValue::Null, text)]); } let answer = call(&h, &secret, "list_records", json!({"table":"note", "last_changed":true})); assert_eq!(answer["last_changed"], "2026-10-06T09:00:00.000Z", "{answer}"); assert!(answer.get("records").is_none(), "metadata does not read record bodies"); let empty = call(&h, &secret, "list_records", json!({"table":"student", "last_changed":true})); assert!(empty["last_changed"].is_null(), "{empty}"); let student = call(&h, &secret, "create_record", json!({"table":"student", "data":{"name":"A synthetic student"}})); let changed = call(&h, &secret, "list_records", json!({"table":"student", "last_changed":true})); assert_eq!(changed["last_changed"], student["record"]["updated_at"]); assert!(changed["last_changed"].is_string()); let refusal = refused(&h, &secret, "list_records", json!({"table":"student", "last_changed":true, "query":"missing"})); assert!(refusal.contains("whole table"), "{refusal}"); } // RULE: Everything counts the list's whole visible set without constructing email bodies or thread pages; a limit-one list caused a 30-second LARGE timeout. 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 account_fixture() -> Value { json!({ "id": "account_fixture", "name": "Account fixture", "plural": "Account fixtures", "picture": null, "builtin": false, "engine": null, "columns": [ { "key": "number", "type": "account_number", "required": true }, { "key": "label", "type": "text" } ], "title": "number", "date": null, "project": null, "order": null, "slip": { "title": "number", "subtitle": null, "trailing": null, "photo": null, "toggle": null }, "tile": { "face": "slip-list" }, "page": [ { "heading": null, "columns": ["number"] } ], "instructions": "Synthetic account-number safety fixture." }) } 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": "starts", "type": "time" }, { "key": "level", "type": "choice", "choices": ["beginner", "advanced"] }, { "key": "fee", "type": "amount" }, { "key": "student", "type": "link", "link_to": "student" }, { "key": "project", "type": "link", "link_to": "project" }, { "key": "paid", "type": "bool" }, { "key": "position", "type": "number" } ], "title": "title", "date": "day", "project": "project", "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." }) } fn define(h: &Harness, definition: &Value) { h.run( "INSERT INTO cotton_table_definitions (id, workspace_id, definition, builtin, created_at, updated_at) \ VALUES (?, ?, ?, 0, ?, ?)", &[ SqlValue::Text(definition["id"].as_str().unwrap().to_string()), SqlValue::Text(h.workspace_id.clone()), SqlValue::Text(definition.to_string()), SqlValue::Text(NOW.to_string()), SqlValue::Text(NOW.to_string()), ], ); } fn harness() -> (Harness, String) { let mut h = Harness::new(); let secret = mint_token(&mut h, &["read", "write"], "Claude"); define(&h, &student()); define(&h, &lesson()); (h, secret) } fn call(h: &Harness, secret: &str, tool: &str, args: Value) -> Value { call_tool(h, secret, tool, args) } fn refused(h: &Harness, secret: &str, tool: &str, args: Value) -> String { let answer = call_tool_raw(h, secret, tool, args); assert!( answer.is_error, "{tool} was expected to refuse: {}", answer.text ); answer.text } fn new_student(h: &Harness, secret: &str, name: &str) -> String { let out = call( h, secret, "create_record", json!({ "table": "student", "data": { "name": name } }), ); out["record"]["id"].as_str().unwrap().to_string() } fn new_lesson(h: &Harness, secret: &str, data: Value) -> Value { call( h, secret, "create_record", json!({ "table": "lesson", "data": data }), ) } fn changes(h: &Harness) -> i64 { h.count("SELECT count(*) AS c FROM cotton_changes", &[]) } // ── create, read, list ────────────────────────────────────────────────────── /// RULE: An account number is stored whole for matching, but generic reads and search expose only its ending so middle digits cannot leave the store. #[test] fn generic_account_number_reads_and_search_use_only_the_ending() { let (h, secret) = harness(); define(&h, &account_fixture()); let wrote = call(&h, &secret, "create_record", json!({"table":"account_fixture", "data":{"number":"12345678901234"}})); let id = wrote["record"]["id"].as_str().unwrap(); let read = call(&h, &secret, "get_record_by_table", json!({"table":"account_fixture", "id":id})); let listed = call(&h, &secret, "list_records", json!({"table":"account_fixture"})); for answer in [&wrote, &read, &listed] { assert!(!answer.to_string().contains("12345678901234"), "{answer}"); assert!(answer.to_string().contains("1234"), "{answer}"); } assert_eq!(read["data"]["number"], "1234", "{read}"); assert_eq!(listed["records"][0]["data"]["number"], "1234", "{listed}"); let group = call(&h, &secret, "create_group", json!({"table":"account_fixture", "name":"Synthetic accounts", "records":[id]})); let groups = call(&h, &secret, "list_groups", json!({"table":"account_fixture"})); let members = call(&h, &secret, "list_records", json!({"table":"account_fixture", "where":{"group":group["group"]["id"]}})); for answer in [&group, &groups, &members] { assert!(!answer.to_string().contains("12345678901234"), "{answer}"); } assert_eq!(groups["groups"][0]["top"][0]["data"]["number"], "1234", "{groups}"); assert_eq!(members["records"][0]["data"]["number"], "1234", "{members}"); call(&h, &secret, "update_record", json!({"table":"account_fixture", "id":id, "patch":{"label":"Synthetic current account"}})); assert_eq!(h.one("SELECT number FROM cotton_account_fixture WHERE id = ?", &[SqlValue::Text(id.into())]).unwrap()["number"], "12345678901234", "a projected read never overwrites the stored number"); let by_middle = call(&h, &secret, "list_records", json!({"table":"account_fixture", "query":"5678"})); assert_eq!(by_middle["total"], 0, "{by_middle}"); let search = call(&h, &secret, "search_records", json!({"query":"5678"})); assert!(!search["records"].as_array().unwrap().iter().any(|hit| hit["table"] == "account_fixture"), "{search}"); let search = call(&h, &secret, "search_records", json!({"query":"current"})); let hit = search["records"].as_array().unwrap().iter().find(|hit| hit["table"] == "account_fixture").unwrap(); assert_eq!(hit["title"], "1234", "{search}"); let changed = call(&h, &secret, "update_record", json!({"table":"account_fixture", "id":id, "patch":{"number":"11112222335678"}})); assert_eq!(changed["record"]["data"]["number"], "5678", "{changed}"); let undone = call(&h, &secret, "undo", json!({"change_id":changed["change"]["id"]})); assert_eq!(undone["record"]["data"]["number"], "1234", "{undone}"); assert!(!undone.to_string().contains("12345678901234"), "{undone}"); assert!(!undone.to_string().contains("11112222335678"), "{undone}"); assert_eq!(h.one("SELECT number FROM cotton_account_fixture WHERE id = ?", &[SqlValue::Text(id.into())]).unwrap()["number"], "12345678901234"); } /// RULE: A record created in a table a person defined reads back with every value in its column's encoding, and its change carries the caller's byline. #[test] fn a_user_table_record_is_created_and_read_back() { let (h, secret) = harness(); let ravi = new_student(&h, &secret, "Ravi"); let out = new_lesson( &h, &secret, json!({ "title": "Scales", "notes": "Slow tempo", "day": "2026-10-02", "starts": "16:30", "level": "beginner", "fee": 150_000, "student": ravi, "paid": false }), ); let change = &out["change"]; assert_eq!(change["verb"], "create"); assert_eq!(change["byline"], "Claude", "the connection's own name"); assert_eq!(change["table"], "lesson"); assert_eq!(change["before"], Value::Null); assert_eq!(change["after"]["fee"], 150_000); let id = out["record"]["id"].as_str().unwrap(); assert_eq!(change["record_id"], id); let read = call( &h, &secret, "get_record_by_table", json!({ "table": "lesson", "id": id }), ); assert_eq!(read["table"], "lesson"); assert_eq!(read["data"]["title"], "Scales"); assert_eq!(read["data"]["day"], "2026-10-02"); assert_eq!(read["data"]["starts"], "16:30"); assert_eq!(read["data"]["fee"], 150_000); assert_eq!(read["data"]["student"], ravi); assert_eq!(read["data"]["paid"], false); assert_eq!(read["deleted_at"], Value::Null); assert_eq!(read["byline"], "Claude"); assert_eq!(changes(&h), 2, "the student and the lesson"); } #[test] fn a_list_filters_by_query_and_pages_by_offset() { let (h, secret) = harness(); for title in ["Major scales", "Minor scales", "Arpeggios"] { new_lesson(&h, &secret, json!({ "title": title })); } let all = call(&h, &secret, "list_records", json!({ "table": "lesson" })); assert_eq!(all["records"].as_array().unwrap().len(), 3); assert_eq!(all["next_page"], Value::Null); let found = call( &h, &secret, "list_records", json!({ "table": "lesson", "query": "SCALES major" }), ); assert_eq!(found["records"].as_array().unwrap().len(), 1); assert_eq!(found["records"][0]["data"]["title"], "Major scales"); let first = call( &h, &secret, "list_records", json!({ "table": "lesson", "limit": 2 }), ); assert_eq!(first["records"].as_array().unwrap().len(), 2); assert_eq!(first["next_page"], 2); let second = call( &h, &secret, "list_records", json!({ "table": "lesson", "limit": 2, "page": 2 }), ); assert_eq!(second["records"].as_array().unwrap().len(), 1); assert_eq!(second["next_page"], Value::Null); } // ── update, link, delete, reorder, and their undo ─────────────────────────── /// RULE: An update records only the columns it changed, and undoing it puts exactly those columns back. #[test] fn an_update_records_what_changed_and_undo_puts_it_back() { let (h, secret) = harness(); let made = new_lesson(&h, &secret, json!({ "title": "Scales", "fee": 100 })); let id = made["record"]["id"].as_str().unwrap().to_string(); let out = call( &h, &secret, "update_record", json!({ "table": "lesson", "id": id, "patch": { "fee": 200, "notes": "Faster" } }), ); assert_eq!(out["change"]["verb"], "update"); // The record's edited time rides on `before`, so an Undo can put it back. assert_eq!( out["change"]["before"], json!({ "fee": 100, "notes": null, "updated_at": made["record"]["updated_at"] }) ); assert_eq!( out["change"]["after"], json!({ "fee": 200, "notes": "Faster" }) ); assert_eq!(out["record"]["data"]["fee"], 200); let undone = call( &h, &secret, "undo", json!({ "change_id": out["change"]["id"] }), ); assert_eq!(undone["undone"]["undone_by"], undone["change"]["id"]); assert_eq!(undone["change"]["verb"], "update"); assert_eq!( undone["record"]["data"], json!({ "title": "Scales", "fee": 100 }) ); } #[test] fn a_create_is_undone_by_a_delete_and_a_delete_by_a_restore() { let (h, secret) = harness(); let created = new_lesson(&h, &secret, json!({ "title": "Scales" })); let id = created["record"]["id"].as_str().unwrap().to_string(); let undone = call( &h, &secret, "undo", json!({ "change_id": created["change"]["id"] }), ); assert_eq!(undone["change"]["verb"], "delete"); assert!( undone["record"]["deleted_at"].is_string(), "kept, with deleted_at set" ); assert_eq!( call(&h, &secret, "list_records", json!({ "table": "lesson" }))["records"], json!([]) ); // Undoing the undo brings it back at its own id. let back = call( &h, &secret, "undo", json!({ "change_id": undone["change"]["id"] }), ); assert_eq!(back["change"]["verb"], "restore"); assert_eq!(back["record"]["id"], id); assert_eq!(back["record"]["deleted_at"], Value::Null); let deleted = call( &h, &secret, "delete_record", json!({ "table": "lesson", "id": id }), ); assert_eq!(deleted["change"]["verb"], "delete"); assert_eq!(deleted["change"]["before"], json!({ "title": "Scales", "updated_at": back["record"]["updated_at"] })); assert_eq!(deleted["change"]["after"], Value::Null); let restored = call( &h, &secret, "undo", json!({ "change_id": deleted["change"]["id"] }), ); assert_eq!(restored["change"]["verb"], "restore"); assert_eq!(restored["record"]["data"], json!({ "title": "Scales" })); } #[test] fn a_link_checks_its_target_and_undoes_to_the_previous_value() { let (h, secret) = harness(); let ravi = new_student(&h, &secret, "Ravi"); let meera = new_student(&h, &secret, "Meera"); let made = new_lesson(&h, &secret, json!({ "title": "Scales", "student": ravi })); let id = made["record"]["id"].as_str().unwrap().to_string(); let linked = call( &h, &secret, "link_records", json!({ "table": "lesson", "id": id, "column": "student", "target_id": meera }), ); assert_eq!(linked["change"]["verb"], "link"); assert_eq!(linked["change"]["before"], json!({ "student": ravi, "updated_at": made["record"]["updated_at"] })); assert_eq!(linked["change"]["after"], json!({ "student": meera })); let text = refused( &h, &secret, "link_records", json!({ "table": "lesson", "id": id, "column": "student", "target_id": "no-such-student" }), ); assert!(text.contains("there is no student"), "{text}"); let text = refused( &h, &secret, "link_records", json!({ "table": "lesson", "id": id, "column": "title", "target_id": meera }), ); assert!(text.contains("is not a link column"), "{text}"); let undone = call( &h, &secret, "undo", json!({ "change_id": linked["change"]["id"] }), ); assert_eq!(undone["record"]["data"]["student"], ravi); let cleared = call( &h, &secret, "link_records", json!({ "table": "lesson", "id": id, "column": "student", "target_id": null }), ); assert_eq!(cleared["change"]["after"], json!({ "student": null })); } /// RULE: A reorder numbers the listed records from one, records each one's old and new position, and undoing it puts every position back. #[test] fn a_reorder_is_recorded_and_undone() { let (h, secret) = harness(); let ids: Vec = ["A", "B", "C"] .iter() .map(|title| { new_lesson(&h, &secret, json!({ "title": title }))["record"]["id"] .as_str() .unwrap() .to_string() }) .collect(); let first = call( &h, &secret, "reorder_records", json!({ "table": "lesson", "ids": [ids[2], ids[0], ids[1]] }), ); assert_eq!(first["change"]["verb"], "reorder"); assert_eq!(first["change"]["record_id"], Value::Null); assert_eq!(first["record"], Value::Null); assert_eq!(first["change"]["after"][&ids[2]], 1.0); assert_eq!(first["change"]["before"][&ids[2]], Value::Null); let order = |h: &Harness| -> Vec { call(h, &secret, "list_records", json!({ "table": "lesson" }))["records"] .as_array() .unwrap() .iter() .map(|r| r["data"]["title"].as_str().unwrap().to_string()) .collect() }; assert_eq!(order(&h), ["C", "A", "B"]); let second = call( &h, &secret, "reorder_records", json!({ "table": "lesson", "ids": [ids[1], ids[0], ids[2]] }), ); assert_eq!(order(&h), ["B", "A", "C"]); call( &h, &secret, "undo", json!({ "change_id": second["change"]["id"] }), ); assert_eq!(order(&h), ["C", "A", "B"]); } // ── refusals ──────────────────────────────────────────────────────────────── /// RULE: A generic write is refused with a plain reason for an unknown table, an unknown column, a value of the wrong type or a fractional amount, and nothing is written. #[test] fn bad_writes_are_refused_in_plain_words() { let (h, secret) = harness(); let before = changes(&h); let text = refused( &h, &secret, "create_record", json!({ "table": "spaceship", "data": { "title": "x" } }), ); // A table no tool here draws is the typed refusal, never a guess. assert_eq!(text, cotton_core::definitions::no_tool_draws_this_table(&[])); // RULE: the no-tool refusal is line `refusal.definition.no_tool_draws_this_table`, never a sentence in Rust — a // database that rewords it says its own words, and the refusal carries its typed kind, so the server // knows it by the kind and never by words a database may change. let words = "Nothing here draws that table yet."; h.run("UPDATE cotton_lines SET words = ? WHERE \"set\" = 'refusal' AND line = 'definition.no_tool_draws_this_table'", &[SqlValue::Text(words.into())]); let text = refused(&h, &secret, "list_records", json!({ "table": "spaceship" })); assert_eq!(text, words); let failure = h.with(|db| cotton_tools::definitions::no_tool_draws(db, &h.workspace_id)); assert_eq!((failure.message(), failure.kind()), (words, Some(cotton_core::definitions::NO_TOOL_DRAWS_THIS_TABLE))); let text = refused( &h, &secret, "create_record", json!({ "table": "lesson", "data": { "title": "x", "colour": "red" } }), ); assert_eq!(text, "Lessons have no column \"colour\""); let text = refused( &h, &secret, "create_record", json!({ "table": "lesson", "data": { "title": "x", "day": "tomorrow" } }), ); assert!(text.contains("a date written YYYY-MM-DD"), "{text}"); let text = refused( &h, &secret, "create_record", json!({ "table": "lesson", "data": { "title": "x", "fee": 12.5 } }), ); assert!(text.contains("never rounded"), "{text}"); let text = refused( &h, &secret, "create_record", json!({ "table": "lesson", "data": { "title": "x", "level": "expert" } }), ); assert!(text.contains("beginner, advanced"), "{text}"); let text = refused( &h, &secret, "create_record", json!({ "table": "lesson", "data": { "notes": "no title" } }), ); assert_eq!(text, "\"title\" is required"); assert_eq!(changes(&h), before, "a refusal writes nothing"); assert_eq!(h.count("SELECT count(*) AS c FROM cotton_lesson", &[]), 0); } /// RULE: A table with no manual order refuses a reorder in plain words. #[test] fn a_table_without_an_order_refuses_a_reorder() { let (h, secret) = harness(); let ravi = new_student(&h, &secret, "Ravi"); let text = refused( &h, &secret, "reorder_records", json!({ "table": "student", "ids": [ravi] }), ); assert_eq!( text, "Students have no manual order, so they cannot be reordered" ); } /// RULE: A change is undone once; a second undo of the same change is refused. #[test] fn undoing_twice_is_refused() { let (h, secret) = harness(); let created = new_lesson(&h, &secret, json!({ "title": "Scales" })); call( &h, &secret, "undo", json!({ "change_id": created["change"]["id"] }), ); let text = refused( &h, &secret, "undo", json!({ "change_id": created["change"]["id"] }), ); assert_eq!(text, "this change was already undone"); } /// RULE: An undo is refused when a later change touched the same field, so it never overwrites the later edit. #[test] fn undo_after_a_later_edit_of_the_same_field_is_refused() { let (h, secret) = harness(); let id = new_lesson(&h, &secret, json!({ "title": "Scales", "fee": 100 }))["record"]["id"] .as_str() .unwrap() .to_string(); let first = call( &h, &secret, "update_record", json!({ "table": "lesson", "id": id, "patch": { "fee": 200 } }), ); call( &h, &secret, "update_record", json!({ "table": "lesson", "id": id, "patch": { "fee": 300 } }), ); let text = refused( &h, &secret, "undo", json!({ "change_id": first["change"]["id"] }), ); assert!(text.contains("has changed since"), "{text}"); // A later edit of ANOTHER field does not stand in the way. let other = call( &h, &secret, "update_record", json!({ "table": "lesson", "id": id, "patch": { "notes": "x" } }), ); call( &h, &secret, "update_record", json!({ "table": "lesson", "id": id, "patch": { "title": "Scales II" } }), ); let undone = call( &h, &secret, "undo", json!({ "change_id": other["change"]["id"] }), ); assert_eq!(undone["record"]["data"]["notes"], Value::Null); assert_eq!(undone["record"]["data"]["title"], "Scales II"); } /// RULE: An undo puts back only the keys its change still holds; a key a later write has taken since stays as that write left it and is named in the answer. #[test] fn undo_does_not_revert_a_key_another_write_has_since_taken() { let (h, secret) = harness(); let id = new_lesson(&h, &secret, json!({ "title": "Scales", "fee": 100 }))["record"]["id"] .as_str() .unwrap() .to_string(); let both = call( &h, &secret, "update_record", json!({ "table": "lesson", "id": id, "patch": { "title": "Scales II", "fee": 200 } }), ); call( &h, &secret, "update_record", json!({ "table": "lesson", "id": id, "patch": { "fee": 300 } }), ); let undone = call(&h, &secret, "undo", json!({ "change_id": both["change"]["id"] })); assert_eq!(undone["record"]["data"]["title"], "Scales", "the key the change still holds goes back"); assert_eq!(undone["record"]["data"]["fee"], 300, "the later write's key stays"); assert_eq!(undone["taken"], json!(["fee"])); // Undone once: the key the undo left is not a second chance. let text = refused(&h, &secret, "undo", json!({ "change_id": both["change"]["id"] })); assert_eq!(text, "this change was already undone"); } /// RULE: A create the generic verbs do not take on a built-in table is refused in words that say where it is made, while reading it still works. #[test] fn a_read_only_builtin_refuses_writes_and_still_reads() { let (h, secret) = harness(); let text = refused( &h, &secret, "create_record", json!({ "table": "secret", "data": { "name": "A login" } }), ); assert_eq!( text, "A password is saved with its value on the Passwords screen, never written here" ); let listed = call(&h, &secret, "list_records", json!({ "table": "secret" })); assert_eq!(listed["records"], json!([])); } /// RULE: A password's delete moves it to the bin and says so ("Moved Router to the bin" (the Bin's tile on Home, the default)); its Undo takes it back out with every field and its edited time as they were. #[test] fn a_passwords_delete_moves_it_to_the_bin_and_undo_takes_it_back() { let (h, secret) = harness(); let id = "a0000000-0000-4000-8000-000000000003"; seed_secret(&h, id, None); let read = |h: &Harness| call(h, &secret, "get_record_by_table", json!({ "table": "secret", "id": id })); let was = read(&h); let gone = call(&h, &secret, "delete_record", json!({ "table": "secret", "id": id })); assert_eq!(gone["change"]["receipt"]["said"], "Moved Router to the bin"); assert_eq!(gone["change"]["undoable"], true, "{gone}"); let listed = call(&h, &secret, "list_records", json!({ "table": "secret" })); assert_eq!(listed["records"], json!([]), "a binned password is not listed"); let bin = call(&h, &secret, "list_bin", json!({ "kind": "secret" })); assert!(bin.to_string().contains(id), "the bin lists it: {bin}"); assert!(!bin.to_string().contains("sealed-bytes"), "{bin}"); let undone = call(&h, &secret, "undo", json!({ "change_id": gone["change"]["id"] })); assert_eq!(undone["change"]["receipt"]["said"], "Put back Router"); let listed = call(&h, &secret, "list_records", json!({ "table": "secret" })); assert_eq!(listed["records"].as_array().map(Vec::len), Some(1), "{listed}"); let bin = call(&h, &secret, "list_bin", json!({ "kind": "secret" })); assert!(!bin.to_string().contains(id), "out of the bin: {bin}"); let back = read(&h); assert_eq!(back["data"], was["data"], "every field as it was"); assert_eq!(back["data"]["updated_at"], NOW, "its edited time back"); let sealed = h.count( "SELECT count(*) FROM cotton_secrets WHERE id = ? AND value_enc = 'sealed-bytes' AND trashed_at IS NULL", &[SqlValue::Text(id.into())], ); assert_eq!(sealed, 1, "the sealed value never moved"); } // ── todos, through their own tools ────────────────────────────────────────── /// RULE: A todo written through the generic verbs is written by the todo tools themselves, and its update can be undone. #[test] fn a_todo_is_created_updated_and_undone_through_its_own_tools() { let (h, secret) = harness(); let created = call( &h, &secret, "create_record", json!({ "table": "todo", "data": { "title": "Buy strings", "due_at": "2026-10-03T10:00:00.000Z" } }), ); assert_eq!(created["change"]["verb"], "create"); let id = created["record"]["id"].as_str().unwrap().to_string(); assert_eq!(created["record"]["data"]["status"], "open"); // The todo tool's own reader sees it: one writer, whatever door. let own = call( &h, &secret, "get_record", json!({ "kind": "todo", "id": id }), ); assert_eq!( own["title"].as_str().or(own["todo"]["title"].as_str()), Some("Buy strings") ); let done = call( &h, &secret, "update_record", json!({ "table": "todo", "id": id, "patch": { "status": "done" } }), ); assert_eq!(done["change"]["before"]["status"], "open"); assert_eq!(done["change"]["after"]["status"], "done"); assert!( done["change"]["after"]["completed_at"].is_string(), "the todo tool stamped it" ); let undone = call( &h, &secret, "undo", json!({ "change_id": done["change"]["id"] }), ); assert_eq!(undone["record"]["data"]["status"], "open"); assert!( undone["record"]["data"].get("completed_at").is_none(), "cleared by the todo tool again" ); let listed = call( &h, &secret, "list_records", json!({ "table": "todo", "query": "strings" }), ); assert_eq!(listed["records"][0]["id"], id); // Undoing the add takes the todo back (R4: every add carries Undo). call( &h, &secret, "undo", json!({ "change_id": created["change"]["id"] }), ); let after = call( &h, &secret, "list_records", json!({ "table": "todo", "query": "strings" }), ); assert_eq!(after["records"].as_array().map(Vec::len), Some(0), "{after}"); } #[test] fn a_todo_column_cotton_sets_itself_is_refused() { let (h, secret) = harness(); let created = call( &h, &secret, "create_record", json!({ "table": "todo", "data": { "title": "Tune" } }), ); let id = created["record"]["id"].as_str().unwrap(); let text = refused( &h, &secret, "update_record", json!({ "table": "todo", "id": id, "patch": { "completed_at": "2026-10-01T09:00:00.000Z" } }), ); assert_eq!( text, "Todos cannot set \"completed_at\" through the generic verbs; Cotton sets it itself" ); } /// RULE: A built-in whose own tool is the owner's app's alone stays that way through the generic verbs. #[test] fn an_owner_only_builtin_write_stays_owner_only() { let (h, secret) = harness(); // A chat's delete archives it through `set_thread_archived`, an owner-only tool. let chat = "c0000000-0000-4000-8000-0000000000c1"; h.run( "INSERT INTO cotton_msg_threads (id, workspace_id, kind, title, created_at, updated_at) \ VALUES (?, ?, 'group', 'Example walkers', ?, ?)", &[ SqlValue::Text(chat.into()), SqlValue::Text(h.workspace_id.clone()), SqlValue::Text(NOW.into()), SqlValue::Text(NOW.into()), ], ); let text = refused(&h, &secret, "delete_record", json!({ "table": "thread", "id": chat })); assert_eq!(text, "only the owner's own app can do this to chats"); let answer = call_tool_as_owner(&h, "device:phone", "delete_record", json!({ "table": "thread", "id": chat })); assert!(!answer.is_error, "{}", answer.text); assert_eq!(answer.json()["change"]["byline"], "user", "the owner's own app writes as the user"); } // ── sync ──────────────────────────────────────────────────────────────────── /// RULE: A user-table record and its change reach another copy of the database by ordinary sync, value for value. #[test] fn a_record_and_its_change_sync_to_another_copy() { let (h, secret) = harness(); let created = new_lesson( &h, &secret, json!({ "title": "Scales", "fee": 150_000, "day": "2026-10-02" }), ); let id = created["record"]["id"].as_str().unwrap().to_string(); let other = cotton_store::test_template::create_workspace_in_memory_for_test(&Meta { workspace_id: h.workspace_id.clone(), owner_id: h.owner_id.clone(), device_id: format!("device:{}", synthetic_uuid("phone")), last_server_seq: 0, last_hlc: None, }) .expect("a second copy"); other .run( // Another copy of the SAME file: its identity (kind, namespace) // is the original's, which the fold refuses to see changed. "INSERT INTO cotton_workspaces (id, name, owner_user_id, kind, namespace, created_at, _hlc) \ VALUES (?, ?, ?, 'personal', ?, ?, '')", &[ SqlValue::Text(h.workspace_id.clone()), SqlValue::Text("Cotton".into()), SqlValue::Text(h.owner_id.clone()), SqlValue::Text(h.workspace_id.clone()), SqlValue::Text(NOW.into()), ], ) .expect("the workspace row"); // The harness writes its definitions raw, so no receipt carries them: the // copy is given them the same way, and steps to the tables they declare. for definition in [student(), lesson()] { other .run( "INSERT INTO cotton_table_definitions (id, workspace_id, definition, builtin, created_at, updated_at) VALUES (?, ?, ?, 0, ?, ?)", &[ SqlValue::Text(definition["id"].as_str().unwrap().to_string()), SqlValue::Text(h.workspace_id.clone()), SqlValue::Text(definition.to_string()), SqlValue::Text(NOW.into()), SqlValue::Text(NOW.into()), ], ) .expect("the definition"); } cotton_store::schema::package_shape::step_file(&other).expect("steps"); // The copy asks page by page, as a device does, until nothing is left. let mut seen = BTreeMap::new(); loop { let page = h.with(|db| cotton_store::exchange::answer(db, &seen, 5_000).expect("answers")); let folded = cotton_store::fold::fold_ops(&other, &page.ops).expect("folds"); assert!(folded.rejected.is_empty(), "{:?}", folded.rejected); seen = page.cursors; if !page.has_more { break; } } let read = |db: &cotton_store::Driver, sql: &str, key: &str| -> cotton_store::Row { db.get(sql, &[SqlValue::Text(key.to_string())]) .expect("reads") .expect("the row") }; for (sql, key) in [ ("SELECT * FROM cotton_lesson WHERE id = ?", id.as_str()), ( "SELECT id, record_id, verb, byline, before, after, _hlc FROM cotton_changes WHERE id = ?", created["change"]["id"].as_str().unwrap(), ), ] { let here = h.with(|db| read(db, sql, key)); assert_eq!(read(&other, sql, key).columns(), here.columns(), "{sql}"); } } // ── review fixes: atomic plans, hostile definitions, visibility, the bin ──── /// RULE: A record's write and its change row commit together — a write refused after the record's own step leaves neither. #[test] fn a_write_and_its_change_commit_together() { let (h, secret) = harness(); // A todo whose FIRST step (create_todo) succeeds and whose second // (update_todo, for the priority) refuses: the first step is rolled back. let before = changes(&h); let text = refused( &h, &secret, "create_record", json!({ "table": "todo", "data": { "title": "Tune", "priority": 5 } }), ); assert!(text.contains("priority"), "{text}"); assert_eq!(h.count("SELECT count(*) AS c FROM cotton_todos", &[]), 0, "no half-made todo"); assert_eq!(changes(&h), before); // And every successful write has exactly one change row per record verb. let created = new_lesson(&h, &secret, json!({ "title": "Scales" })); let id = created["record"]["id"].as_str().unwrap(); assert_eq!( h.count( "SELECT count(*) AS c FROM cotton_changes WHERE record_id = ?", &[SqlValue::Text(id.to_string())] ), 1 ); } /// RULE: A table definition that does not validate — a column key with a quote in it — is refused whole, and no key of it ever reaches SQL. #[test] fn a_hostile_definition_is_refused_not_queried() { let (h, secret) = harness(); let mut hostile = lesson(); hostile["id"] = json!("hostile"); hostile["columns"][1]["key"] = json!("notes') OR 1=1 --"); define(&h, &hostile); for tool in ["list_records", "create_record"] { let text = refused( &h, &secret, tool, json!({ "table": "hostile", "query": "x", "data": { "title": "x" } }), ); assert!(text.starts_with("the definition of table \"hostile\" cannot be read"), "{text}"); } } /// RULE: A built-in is read through the definition the app ships, never a synced row's columns, and a sensitive column is never answered. #[test] fn a_builtin_reads_the_shipped_definition_and_never_a_sealed_value() { let (h, secret) = harness(); // A synced row claiming the secret table carries its sealed value. let mut widened = serde_json::from_str::( cotton_core::definitions::BUILTIN_DEFINITION_FILES .iter() .find(|(id, _)| *id == "secret") .unwrap() .1, ) .unwrap(); widened["columns"] .as_array_mut() .unwrap() .push(json!({ "key": "value_enc", "type": "text" })); // The kit's passwords tool already holds the row: it is widened in place. h.run( "UPDATE cotton_table_definitions SET definition = ?, builtin = 1, updated_at = ? \ WHERE id = 'secret' AND workspace_id = ?", &[ SqlValue::Text(widened.to_string()), SqlValue::Text(NOW.into()), SqlValue::Text(h.workspace_id.clone()), ], ); assert_eq!(h.count("SELECT count(*) AS c FROM cotton_table_definitions WHERE id = 'secret' AND builtin = 1", &[]), 1, "the secret row was widened"); seed_secret(&h, "a0000000-0000-4000-8000-000000000001", None); seed_secret(&h, "a0000000-0000-4000-8000-000000000002", Some(NOW)); let listed = call(&h, &secret, "list_records", json!({ "table": "secret" })); let records = listed["records"].as_array().unwrap(); assert_eq!(records.len(), 1, "the binned password is left out: {records:?}"); assert_eq!(records[0]["data"]["name"], "Router"); assert!(records[0]["data"].get("value_enc").is_none(), "never the sealed value"); assert!(records[0]["data"].get("hint").is_none()); let binned = call( &h, &secret, "get_record_by_table", json!({ "table": "secret", "id": "a0000000-0000-4000-8000-000000000002" }), ); assert_eq!(binned["deleted_at"], NOW, "a binned row reads as deleted"); } fn seed_secret(h: &Harness, id: &str, trashed_at: Option<&str>) { h.run( "INSERT INTO cotton_secrets (id, workspace_id, kind, name, value_enc, hint, trashed_at, created_at, updated_at) \ VALUES (?, ?, 'login', 'Router', 'sealed-bytes', 'ab12', ?, ?, ?)", &[ SqlValue::Text(id.into()), SqlValue::Text(h.workspace_id.clone()), trashed_at.map_or(SqlValue::Null, |at| SqlValue::Text(at.into())), SqlValue::Text(NOW.into()), SqlValue::Text(NOW.into()), ], ); } /// RULE: A message the owner hid, or one its thread cleared away, is not answered by the generic reads at all. #[test] fn hidden_and_cleared_messages_are_not_read() { let (h, secret) = harness(); let thread = "b0000000-0000-4000-8000-000000000001"; h.run( "INSERT INTO cotton_msg_threads (id, workspace_id, kind, title, cleared_before, created_at, updated_at) \ VALUES (?, ?, 'group', 'Band', '2026-09-02T00:00:00.000Z', ?, ?)", &[ SqlValue::Text(thread.into()), SqlValue::Text(h.workspace_id.clone()), SqlValue::Text(NOW.into()), SqlValue::Text(NOW.into()), ], ); for (id, sent_at, hidden) in [ ("m-cleared", "2026-09-01T10:00:00.000Z", None), ("m-hidden", "2026-09-03T10:00:00.000Z", Some(NOW)), ("m-visible", "2026-09-04T10:00:00.000Z", None), ] { h.run( "INSERT INTO cotton_msg_messages (id, thread_id, workspace_id, direction, channel, origin, body, sent_at, created_at, hidden_at) \ VALUES (?, ?, ?, 'in', 'whatsapp', 'imported', 'invented words', ?, ?, ?)", &[ SqlValue::Text(id.into()), SqlValue::Text(thread.into()), SqlValue::Text(h.workspace_id.clone()), SqlValue::Text(sent_at.into()), SqlValue::Text(NOW.into()), hidden.map_or(SqlValue::Null, |at: &str| SqlValue::Text(at.into())), ], ); } let listed = call(&h, &secret, "list_records", json!({ "table": "message" })); let ids: Vec<&str> = listed["records"].as_array().unwrap().iter().map(|r| r["id"].as_str().unwrap()).collect(); assert_eq!(ids, ["m-visible"]); for gone in ["m-cleared", "m-hidden"] { let text = refused(&h, &secret, "get_record_by_table", json!({ "table": "message", "id": gone })); assert!(text.contains("is no longer here"), "{text}"); } } /// GUARD: a binned record of a made table names its kind, and a record its table titles by a date says the day as a date. /// RULE: a binned record's card carries its kind and its name — the table's own name, typed, and a date title as a typed date the Bin says in words, never the stored ISO text alone (292, walker291: a Records card read only '2026-12-14'). #[test] fn a_binned_made_record_names_its_kind_and_its_day() { let (h, secret) = harness(); define(&h, &json!({ "id": "sleep_night", "name": "Night", "plural": "Nights", "picture": null, "builtin": false, "engine": null, "columns": [ { "key": "night", "type": "date", "required": true }, { "key": "hours", "type": "number" } ], "title": "night", "date": "night", "project": null, "order": null, "slip": { "title": "night", "subtitle": null, "trailing": null, "photo": null, "toggle": null }, "tile": { "face": "slip-list" }, "page": [ { "heading": null, "columns": ["night", "hours"] } ], "instructions": "Synthetic date-titled fixture." })); let lesson = new_lesson(&h, &secret, json!({ "title": "Scales" }))["record"]["id"].as_str().unwrap().to_string(); let night = call(&h, &secret, "create_record", json!({ "table": "sleep_night", "data": { "night": "2026-12-14" } }))["record"]["id"] .as_str().unwrap().to_string(); call(&h, &secret, "delete_record", json!({ "table": "lesson", "id": lesson })); call(&h, &secret, "delete_record", json!({ "table": "sleep_night", "id": night })); let page = call(&h, &secret, "list_records", json!({ "table": "bin" })); let row = |id: &str| page["records"].as_array().unwrap().iter().find(|row| row["id"] == id).expect("in the bin")["data"].clone(); let lesson = row(&lesson); assert_eq!(lesson["title"], "Scales"); assert_eq!(lesson["table_name"], "Lesson", "the card says what kind of record it was"); let night = row(&night); assert_eq!(night["table_name"], "Night"); assert_eq!(night["title_at"], "2026-12-14", "the day is a typed date the Bin says in words"); assert_ne!(night["title"], "2026-12-14", "never the stored ISO text as the card's name"); } /// RULE: A deleted record of a table a person defined waits in the one bin, comes back through restore_from_bin, and only empty_bin erases it with its change rows. #[test] fn a_deleted_user_record_goes_through_the_bin() { let (h, secret) = harness(); let id = new_lesson(&h, &secret, json!({ "title": "Scales" }))["record"]["id"].as_str().unwrap().to_string(); call(&h, &secret, "delete_record", json!({ "table": "lesson", "id": id })); let bin = call(&h, &secret, "list_bin", json!({})); let entry = bin["entries"].as_array().unwrap().iter().find(|e| e["id"] == id).expect("in the bin"); assert_eq!(entry["kind"], "record"); assert_eq!(entry["table"], "lesson"); assert_eq!(entry["title"], "Scales"); assert_eq!(bin["counts"]["record"], 1); assert_eq!(call(&h, &secret, "list_bin", json!({ "kind": "record" }))["entries"].as_array().unwrap().len(), 1); let restored = call(&h, &secret, "restore_from_bin", json!({ "kind": "record", "id": id })); assert_eq!(restored["restored"], true); assert_eq!(call(&h, &secret, "list_records", json!({ "table": "lesson" }))["records"].as_array().unwrap().len(), 1); assert_eq!( h.count("SELECT count(*) AS c FROM cotton_changes WHERE record_id = ? AND verb = 'restore'", &[SqlValue::Text(id.clone())]), 1, "the restore is a change like any other" ); call(&h, &secret, "delete_record", json!({ "table": "lesson", "id": id })); let owner = call_tool_as_owner(&h, "device:phone", "empty_bin", json!({})).json(); assert_eq!(owner["erased"]["record"], 1); assert_eq!(h.count("SELECT count(*) AS c FROM cotton_lesson WHERE id = ?", &[SqlValue::Text(id.clone())]), 0); assert_eq!( h.count("SELECT count(*) AS c FROM cotton_changes WHERE record_id = ?", &[SqlValue::Text(id.clone())]), 0, "no change row still holding its values" ); } // ── where ─────────────────────────────────────────────────────────────────── fn titles(listed: &Value) -> Vec { let mut out: Vec = listed["records"] .as_array() .unwrap() .iter() .map(|record| record["data"]["title"].as_str().unwrap_or_default().to_string()) .collect(); out.sort(); out } fn list_where(h: &Harness, secret: &str, table: &str, filter: Value) -> Value { call( h, secret, "list_records", json!({ "table": table, "where": filter }), ) } /// RULE: `where` on a table a person defined keeps the records whose columns hold a value, any of several values, or anything at all — the order column included — together with search and paging. #[test] fn a_where_narrows_a_user_table_by_value_values_and_presence() { let (h, secret) = harness(); new_lesson( &h, &secret, json!({ "title": "Scales", "level": "beginner", "paid": true, "fee": 100, "position": 1 }), ); new_lesson( &h, &secret, json!({ "title": "Arpeggios", "level": "advanced", "paid": false, "fee": 200, "notes": "Hands apart" }), ); new_lesson(&h, &secret, json!({ "title": "Sight reading", "level": "advanced" })); let advanced = list_where(&h, &secret, "lesson", json!({ "level": "advanced" })); assert_eq!(titles(&advanced), ["Arpeggios", "Sight reading"]); let paid = list_where(&h, &secret, "lesson", json!({ "paid": true })); assert_eq!(titles(&paid), ["Scales"]); let unpaid = list_where(&h, &secret, "lesson", json!({ "paid": false })); assert_eq!(titles(&unpaid), ["Arpeggios"], "false is a value, not absence"); let fees = list_where(&h, &secret, "lesson", json!({ "fee": { "values": [100, 200, 300] } })); assert_eq!(titles(&fees), ["Arpeggios", "Scales"]); // `not`: a value none of these; a lesson with no fee holds no value. let not_scales = list_where(&h, &secret, "lesson", json!({ "fee": { "not": [100] } })); assert_eq!(titles(¬_scales), ["Arpeggios"]); let noted = list_where(&h, &secret, "lesson", json!({ "notes": { "present": true } })); assert_eq!(titles(¬ed), ["Arpeggios"]); let bare = list_where(&h, &secret, "lesson", json!({ "notes": { "present": false } })); assert_eq!(titles(&bare), ["Scales", "Sight reading"]); let placed = list_where(&h, &secret, "lesson", json!({ "position": { "present": true } })); assert_eq!(titles(&placed), ["Scales"], "the order column, stored outside data"); let both = list_where( &h, &secret, "lesson", json!({ "level": "advanced", "notes": { "present": false } }), ); assert_eq!(titles(&both), ["Sight reading"], "every entry must hold"); let searched = call( &h, &secret, "list_records", json!({ "table": "lesson", "query": "reading", "where": { "level": "advanced" } }), ); assert_eq!(titles(&searched), ["Sight reading"]); let first = call( &h, &secret, "list_records", json!({ "table": "lesson", "limit": 1, "where": { "level": "advanced" } }), ); assert_eq!(first["next_page"], 1); let second = call( &h, &secret, "list_records", json!({ "table": "lesson", "limit": 1, "page": 1, "where": { "level": "advanced" } }), ); assert_eq!(second["next_page"], Value::Null); assert_ne!(first["records"][0]["id"], second["records"][0]["id"]); } /// RULE: `where {within_days: n}` keeps the records whose date is no more than n days back from now, or later — on a table a person defined and on a built-in's stored date alike — and a built-in narrowed by its engine refuses it. #[test] fn a_where_within_days_keeps_the_recent_dates() { let (h, secret) = harness(); let at = |back: i64| chrono::Utc::now() - chrono::Duration::days(back); let day = |back: i64| at(back).format("%Y-%m-%d").to_string(); let instant = |back: i64| at(back).format("%Y-%m-%dT%H:%M:%S.000Z").to_string(); for (title, back) in [("Today", 0), ("Three days back", 3), ("A month back", 30), ("Next week", -7)] { new_lesson(&h, &secret, json!({ "title": title, "day": day(back) })); call(&h, &secret, "create_record", json!({ "table": "todo", "data": { "title": title, "due_at": instant(back) } })); } new_lesson(&h, &secret, json!({ "title": "Undated" })); let week = list_where(&h, &secret, "lesson", json!({ "day": { "within_days": 7 } })); assert_eq!(titles(&week), ["Next week", "Three days back", "Today"]); let todos = list_where(&h, &secret, "todo", json!({ "due_at": { "within_days": 7 } })); assert_eq!(titles(&todos), ["Next week", "Three days back", "Today"], "a built-in's stored date, in SQL"); let refused = refused(&h, &secret, "list_records", json!({ "table": "lesson", "where": { "title": { "within_days": 7 } } })); assert!(refused.contains("within_days narrows only a date column"), "{refused}"); } /// RULE: `where {on: "today"}` keeps the records whose date is today in the workspace's zone (or the zone and today the read names), and `{on: "this_day"}` the ones on today's month and day in an earlier year (a journal's Today and On this day), in SQL on a table a person defined; an undated record is on no day, and a column that is no date refuses it. #[test] fn a_where_on_keeps_today_or_this_day_in_earlier_years() { let (h, secret) = harness(); // The read names its today and zone, as the phone's do. let today = chrono::NaiveDate::from_ymd_opt(2026, 11, 13).unwrap(); use chrono::Datelike; // A 29 February has no day in most earlier years: it is left out then. let years_back = |years: i32| chrono::NaiveDate::from_ymd_opt(today.year() - years, today.month(), today.day()).map(|day| day.format("%Y-%m-%d").to_string()); let yesterday = (today - chrono::Duration::days(1)).format("%Y-%m-%d").to_string(); new_lesson(&h, &secret, json!({ "title": "Today", "day": today.format("%Y-%m-%d").to_string() })); new_lesson(&h, &secret, json!({ "title": "Yesterday", "day": yesterday })); let mut earlier = Vec::new(); for (title, years) in [("A year ago", 1), ("Five years ago", 5)] { if let Some(day) = years_back(years) { new_lesson(&h, &secret, json!({ "title": title, "day": day })); earlier.push(title); } } new_lesson(&h, &secret, json!({ "title": "Undated" })); let on = |filter: Value| call(&h, &secret, "list_records", json!({ "table": "lesson", "where": filter, "today": "2026-11-13", "timezone": "Asia/Kolkata" })); let todays = on(json!({ "day": { "on": "today" } })); assert_eq!(titles(&todays), ["Today"]); let this_day = on(json!({ "day": { "on": "this_day" } })); earlier.sort(); assert_eq!(titles(&this_day), earlier, "today's month and day, earlier years only"); let refused = refused(&h, &secret, "list_records", json!({ "table": "lesson", "where": { "title": { "on": "today" } } })); assert!(refused.contains("on narrows only a date column"), "{refused}"); } /// RULE: `where {at_most: n}` / `{at_least: n}` keeps the records whose number is no more, or no less, than n, in SQL on a table a person defined; a record holding no number is in no bound, and a column that is not a number refuses it. #[test] fn a_where_bound_keeps_the_numbers_on_its_side() { let (h, secret) = harness(); for (title, minutes) in [("Quick", json!(20)), ("Half hour", json!(30)), ("Slow", json!(95)), ("Odd", json!(12.5))] { new_lesson(&h, &secret, json!({ "title": title, "position": minutes })); } new_lesson(&h, &secret, json!({ "title": "Untimed" })); let quick = list_where(&h, &secret, "lesson", json!({ "position": { "at_most": 30 } })); assert_eq!(titles(&quick), ["Half hour", "Odd", "Quick"]); let long = list_where(&h, &secret, "lesson", json!({ "position": { "at_least": 30 } })); assert_eq!(titles(&long), ["Half hour", "Slow"]); let refused = refused(&h, &secret, "list_records", json!({ "table": "lesson", "where": { "title": { "at_most": 7 } } })); assert!(refused.contains("at_most and at_least narrow only a number column"), "{refused}"); } /// RULE: A `where` naming a column the table does not have, a value its column cannot hold, a shape it does not spell, or a built-in column the engine cannot narrow by is refused — never ignored. #[test] fn a_where_that_cannot_be_answered_is_refused() { let (h, secret) = harness(); new_lesson(&h, &secret, json!({ "title": "Scales" })); let refuse = |table: &str, filter: Value| { refused( &h, &secret, "list_records", json!({ "table": table, "where": filter }), ) }; assert_eq!( refuse("lesson", json!({ "colour": "red" })), "Lessons have no column \"colour\"" ); assert!(refuse("lesson", json!({ "level": "expert" })).contains("\"expert\" is not one")); assert!(refuse("lesson", json!({ "level": null })).contains("present")); assert!(refuse("lesson", json!({ "level": [] })).contains("values")); assert!(refuse("lesson", json!({ "level": ["expert"] })).contains("\"expert\" is not one")); assert!(refuse("lesson", json!("beginner")).starts_with("where")); // A built-in: a column it does not have. assert_eq!( refuse("todo", json!({ "nope": "x" })), "Todos have no column \"nope\"" ); } /// RULE: `where` on a built-in's stored column filters the engine's own rows in SQL. #[test] fn a_where_narrows_a_builtin_by_a_stored_column() { let (h, secret) = harness(); for title in ["Buy strings", "Tune the piano"] { call(&h, &secret, "create_record", json!({ "table": "todo", "data": { "title": title } })); } let done = call( &h, &secret, "create_record", json!({ "table": "todo", "data": { "title": "Book the hall", "status": "done" } }), ); assert_eq!(done["record"]["data"]["status"], "done"); let open = list_where(&h, &secret, "todo", json!({ "status": "open" })); assert_eq!(titles(&open), ["Buy strings", "Tune the piano"]); let either = list_where(&h, &secret, "todo", json!({ "status": { "values": ["done", "dropped"] } })); assert_eq!(titles(&either), ["Book the hall"]); let not_open = list_where(&h, &secret, "todo", json!({ "status": { "not": ["open"] } })); assert_eq!(titles(¬_open), ["Book the hall"], "a built-in's stored column, in SQL"); let undated = list_where(&h, &secret, "todo", json!({ "due_at": { "present": false } })); assert_eq!(undated["records"].as_array().unwrap().len(), 3); } /// RULE: `where people` narrows todos, notes and events to the ones linked with that person — whichever way round the link was made — and events also to the ones a contact of theirs is a guest of, because a person's page lists and counts them by this narrowing. #[test] fn a_where_people_narrows_todos_notes_and_events_to_a_persons_links() { let (h, secret) = harness(); let ws = SqlValue::Text(h.workspace_id.clone()); let at = SqlValue::Text(NOW.to_string()); let text = |value: &str| SqlValue::Text(value.to_string()); for (id, name, emails) in [ ("person:a", "Asha Rao", &["Asha@Example.test"][..]), ("person:b", "Bilal Khan", &[][..]), ] { h.run( "INSERT INTO cotton_people (id, workspace_id, full_name, created_at, updated_at) VALUES (?, ?, ?, ?, ?)", &[text(id), ws.clone(), text(name), at.clone(), at.clone()], ); // An email is a handle row since v90. for (position, email) in emails.iter().enumerate() { h.run( "INSERT INTO cotton_person_handles (id, workspace_id, person_id, kind, value, normalised, source, position, created_at, updated_at) VALUES (?, ?, ?, 'email', ?, ?, 'manual', ?, ?, ?)", &[ text(&format!("handle-{id}-{position}")), ws.clone(), text(id), text(email), text(&email.to_lowercase()), SqlValue::Integer(position as i64), at.clone(), at.clone(), ], ); } } let todo = call(&h, &secret, "create_record", json!({ "table": "todo", "data": { "title": "Ring Asha" } })) ["record"]["id"] .as_str() .unwrap() .to_string(); let note = |id: &str, title: &str| { h.run( "INSERT INTO cotton_notes (id, workspace_id, title, body, created_at, updated_at) VALUES (?, ?, ?, '', ?, ?)", &[text(id), ws.clone(), text(title), at.clone(), at.clone()], ); id.to_string() }; let linked_note = note(&synthetic_uuid("people-note-linked"), "Asha's recipe"); let loose_note = note(&synthetic_uuid("people-note-loose"), "Nobody's note"); let link = |serial: u8, from: (&str, &str), to: (&str, &str)| { h.run( "INSERT INTO cotton_links (id, workspace_id, from_kind, from_id, to_kind, to_id, created_at) VALUES (?, ?, ?, ?, ?, ?, ?)", &[text(&format!("link:{serial}")), ws.clone(), text(from.0), text(from.1), text(to.0), text(to.1), at.clone()], ); }; link(1, ("todo", &todo), ("person", "person:a")); // the record names the person link(2, ("person", "person:a"), ("note", &linked_note)); // the person names the record let calendar = synthetic_uuid("people-calendar"); let event = synthetic_uuid("people-event"); h.run( "INSERT INTO cotton_collections (id, workspace_id, kind, name, created_at) VALUES (?, ?, 'calendar', 'Family', ?)", &[text(&calendar), ws.clone(), at.clone()], ); h.run( "INSERT INTO cotton_events (id, collection_id, title, starts_at, created_at, updated_at) \ VALUES (?, ?, 'Recital', '2026-10-05T17:30:00.000Z', ?, ?)", &[text(&event), text(&calendar), at.clone(), at.clone()], ); h.run( "INSERT INTO cotton_event_attendees (id, event_id, email, created_at, updated_at) VALUES ('guest:1', ?, 'asha@example.test', ?, ?)", &[text(&event), at.clone(), at], ); let ids = |table: &str, person: &str| -> Vec { list_where(&h, &secret, table, json!({ "people": person }))["records"] .as_array() .unwrap() .iter() .map(|record| record["id"].as_str().unwrap().to_string()) .collect() }; assert_eq!(ids("todo", "person:a"), [todo.clone()]); assert_eq!(ids("note", "person:a"), [linked_note.clone()], "not {loose_note}"); assert_eq!(ids("event", "person:a"), [event.clone()], "a guest by one of her addresses"); for table in ["todo", "note", "event"] { assert!(ids(table, "person:b").is_empty(), "nothing of {table} is Bilal's"); } let unlinked = list_where(&h, &secret, "note", json!({ "people": { "present": false } })); let unlinked: Vec<&str> = unlinked["records"].as_array().unwrap().iter().map(|r| r["id"].as_str().unwrap()).collect(); assert!(unlinked.contains(&loose_note.as_str()) && !unlinked.contains(&linked_note.as_str()), "{unlinked:?}"); } /// The ids a `where` keeps, in the order listed. fn ids_where(h: &Harness, secret: &str, table: &str, filter: Value) -> Vec { list_where(h, secret, table, filter)["records"] .as_array() .unwrap() .iter() .map(|record| record["id"].as_str().unwrap().to_string()) .collect() } /// RULE: An email conversation's `people` are the people one of whose addresses (in any letter case) wrote or was written to in it, and `where people` lists it by them, because a person's page lists their mail by this. #[test] fn an_email_threads_people_are_its_participants_by_address_and_where_people_finds_it() { let (h, secret) = harness(); let ws = SqlValue::Text(h.workspace_id.clone()); let at = SqlValue::Text(NOW.to_string()); let text = |value: &str| SqlValue::Text(value.to_string()); for (id, name, emails) in [ ("person:a", "Alice Kumar", &["Alice@Acme.COM"][..]), ("person:b", "Bilal Khan", &["bilal@example.test"][..]), ] { h.run( "INSERT INTO cotton_people (id, workspace_id, full_name, created_at, updated_at) VALUES (?, ?, ?, ?, ?)", &[text(id), ws.clone(), text(name), at.clone(), at.clone()], ); // An email is a handle row since v90. for (position, email) in emails.iter().enumerate() { h.run( "INSERT INTO cotton_person_handles (id, workspace_id, person_id, kind, value, normalised, source, position, created_at, updated_at) VALUES (?, ?, ?, 'email', ?, ?, 'manual', ?, ?, ?)", &[ text(&format!("handle-{id}-{position}")), ws.clone(), text(id), text(email), text(&email.to_lowercase()), SqlValue::Integer(position as i64), at.clone(), at.clone(), ], ); } } call( &h, &secret, "ingest_emails", json!({ "emails": [{ "threadKey": "gmail:acme-contract", "subject": "Re: Acme contract", "sentAt": "2026-08-20T10:00:00.000Z", "body": "Sending over the revised contract.", "messageId": "", "from": { "email": "alice@acme.com", "name": "Alice Kumar" }, "to": [{ "email": "owner@example.com" }], }], }), ); let thread = h .one("SELECT id FROM cotton_email_threads LIMIT 1", &[]) .and_then(|row| row.get("id").and_then(Value::as_str).map(str::to_string)) .expect("the conversation"); let read = call(&h, &secret, "get_record_by_table", json!({ "table": "email_thread", "id": thread })); let people = read["data"]["people"].as_array().unwrap_or_else(|| panic!("the conversation names its people: {read}")); assert!(people.contains(&json!("person:a")) && !people.contains(&json!("person:b")), "{read}"); assert_eq!(ids_where(&h, &secret, "email_thread", json!({ "people": "person:a" })), [thread.clone()]); assert!(ids_where(&h, &secret, "email_thread", json!({ "people": "person:b" })).is_empty(), "nothing of Bilal's"); } // ── thoughts ──────────────────────────────────────────────────────────────── const CAPTURED: &str = "2026-09-20T08:00:00.000Z"; /// RULE: A list page answers every record's pictures, each record its own, in its own order. #[test] fn a_list_answers_each_records_pictures_from_one_read() { let (h, secret) = harness(); let first = seed_photo(&h, 'e'); let second = seed_photo(&h, 'f'); let mut notes = Vec::new(); for (title, pictures) in [ ("Two pictures", json!([{ "kind": "photo", "id": second }, { "kind": "photo", "id": first, "caption": "c" }])), ("One picture", json!([{ "kind": "photo", "id": first }])), ("No pictures", json!([])), ] { let note = call( &h, &secret, "create_record", json!({ "table": "note", "data": { "title": title, "body": "b" } }), ); let id = note["record"]["id"].as_str().unwrap().to_string(); if !pictures.as_array().unwrap().is_empty() { call( &h, &secret, "update_record", json!({ "table": "note", "id": id, "patch": { "attachments": pictures } }), ); } notes.push(id); } let listed = call(&h, &secret, "list_records", json!({ "table": "note" })); let records = listed["records"].as_array().unwrap(); assert_eq!(records.len(), 3); for record in records { let id = record["id"].as_str().unwrap(); let one = call(&h, &secret, "get_record_by_table", json!({ "table": "note", "id": id })); assert_eq!(record["data"].get("attachments"), one["data"].get("attachments"), "{id}"); } let by_id = |id: &str| records.iter().find(|r| r["id"] == id).unwrap()["data"].clone(); assert_eq!( by_id(¬es[0])["attachments"], json!([ { "kind": "photo", "id": second, "caption": null }, { "kind": "photo", "id": first, "caption": "c" } ]) ); assert_eq!(by_id(¬es[1])["attachments"], json!([{ "kind": "photo", "id": first, "caption": null }])); assert!(by_id(¬es[2]).get("attachments").is_none()); } fn seed_photo(h: &Harness, letter: char) -> String { let hash: String = std::iter::repeat_n(letter, 64).collect(); let id = format!("photo:{hash}"); h.run( "INSERT INTO cotton_photos (id, workspace_id, key, sha256, content_type, size_bytes, taken_at, \ created_at, updated_at) VALUES (?, ?, ?, ?, 'image/png', 4096, ?, ?, ?)", &[ SqlValue::Text(id.clone()), SqlValue::Text(h.workspace_id.clone()), SqlValue::Text(format!("{}/photos/{hash}.png", h.workspace_id)), SqlValue::Text(hash), SqlValue::Text(CAPTURED.to_string()), SqlValue::Text(CAPTURED.to_string()), SqlValue::Text(CAPTURED.to_string()), ], ); id } /// RULE: A note's pictures are written through `update_record {attachments}` by the engine's own attachment write, read back under `attachments` in the order given, and undone to the list before. #[test] fn a_note_takes_its_pictures_through_update_record() { let (h, secret) = harness(); let first = seed_photo(&h, 'a'); let second = seed_photo(&h, 'b'); let note = call( &h, &secret, "create_record", json!({ "table": "note", "data": { "title": "Practice log", "body": "Scales daily" } }), ); let note_id = note["record"]["id"].as_str().unwrap().to_string(); assert!(note["record"]["data"].get("attachments").is_none(), "no pictures, no key"); for (table, id) in [("note", note_id.as_str())] { let written = call( &h, &secret, "update_record", json!({ "table": table, "id": id, "patch": { "attachments": [ { "kind": "photo", "id": second, "caption": "where it jumps" }, { "kind": "photo", "id": first } ] } }), ); let wanted = json!([ { "kind": "photo", "id": second, "caption": "where it jumps" }, { "kind": "photo", "id": first, "caption": null } ]); assert_eq!(written["record"]["data"]["attachments"], wanted, "{table}"); assert_eq!(written["change"]["before"]["attachments"], Value::Null, "{table}"); let read = call(&h, &secret, "get_record_by_table", json!({ "table": table, "id": id })); assert_eq!(read["data"]["attachments"], wanted, "{table}"); // A caption cleared and the order swapped, then undone back. let moved = call( &h, &secret, "update_record", json!({ "table": table, "id": id, "patch": { "attachments": [ { "kind": "photo", "id": first }, { "kind": "photo", "id": second, "caption": null } ] } }), ); assert_eq!( moved["record"]["data"]["attachments"], json!([ { "kind": "photo", "id": first, "caption": null }, { "kind": "photo", "id": second, "caption": null } ]), "{table}" ); let undone = call(&h, &secret, "undo", json!({ "change_id": moved["change"]["id"] })); assert_eq!(undone["record"]["data"]["attachments"], wanted, "{table}: the caption came back"); // A picture the database does not hold refuses the whole write. let text = refused( &h, &secret, "update_record", json!({ "table": table, "id": id, "patch": { "attachments": [ { "kind": "photo", "id": format!("photo:{}", "c".repeat(64)) } ] } }), ); assert!(!text.is_empty(), "{table}"); let cleared = call( &h, &secret, "update_record", json!({ "table": table, "id": id, "patch": { "attachments": null } }), ); assert!(cleared["record"]["data"].get("attachments").is_none(), "{table}"); } // A table whose engine keeps no pictures refuses the key. let todo = call(&h, &secret, "create_record", json!({ "table": "todo", "data": { "title": "x" } })); let text = refused( &h, &secret, "update_record", json!({ "table": "todo", "id": todo["record"]["id"], "patch": { "attachments": [] } }), ); assert_eq!(text, "Todos have no column \"attachments\""); } /// RULE: Every list answers how many records the whole list holds — the same filters, no page's bounds — on a table a person defined and on a built-in alike. #[test] fn a_list_answers_its_whole_count_beside_the_page() { let (h, secret) = harness(); for (title, level) in [("Scales", "beginner"), ("Arpeggios", "beginner"), ("Fugue", "advanced")] { new_lesson(&h, &secret, json!({ "title": title, "level": level })); } let page = call(&h, &secret, "list_records", json!({ "table": "lesson", "limit": 1 })); assert_eq!(page["records"].as_array().unwrap().len(), 1); assert_eq!(page["total"], 3); let narrowed = call( &h, &secret, "list_records", json!({ "table": "lesson", "where": { "level": "beginner" }, "query": "a", "limit": 1 }), ); assert_eq!(narrowed["total"], 2, "the where and the query count, the limit does not"); for title in ["One", "Two"] { call(&h, &secret, "create_record", json!({ "table": "todo", "data": { "title": title } })); } let todos = call(&h, &secret, "list_records", json!({ "table": "todo", "limit": 1, "page": 1 })); assert_eq!(todos["total"], 2); assert_eq!(todos["next_page"], Value::Null); let none = call(&h, &secret, "list_records", json!({ "table": "lesson", "query": "zzz" })); assert_eq!(none["total"], 0); } /// RULE: A secret's once-only copy is persisted through the generic update with a byline, and neither another update nor Undo can reset its reveal metadata. #[test] fn secret_reveal_once_is_consumed_atomically_and_cannot_be_undone() { let (h, secret) = harness(); let mut definition = student(); definition["id"] = json!("code_credential"); definition["columns"].as_array_mut().unwrap().extend([ json!({"key":"token","type":"text","secret":true,"reveal":{"once":true,"expires":60}}), json!({"key":"reveal_count","type":"number"}), json!({"key":"last_revealed","type":"date"}), ]); define(&h, &definition); let created = call(&h, &secret, "create_record", json!({"table":"code_credential","data":{"name":"Example","token":"synthetic"}})); let id = &created["record"]["id"]; let patch = json!({"reveal_count":1,"last_revealed":"2026-10-02T09:00:00Z"}); let copied = call(&h, &secret, "update_record", json!({"table":"code_credential","id":id,"patch":patch})); assert!(copied["change"]["byline"].is_string()); for patch in [patch, json!({"reveal_count":0}), json!({"last_revealed":null}), json!({"reveal_count":2,"last_revealed":"2026-10-03T09:00:00Z"})] { let out = call_tool_raw(&h, &secret, "update_record", json!({"table":"code_credential","id":id,"patch":patch})); assert!(out.is_error, "{}", out.text); } let undone = call_tool_raw(&h, &secret, "undo", json!({"change_id":copied["change"]["id"]})); assert!(undone.is_error, "{}", undone.text); let read = call(&h, &secret, "get_record_by_table", json!({"table":"code_credential","id":id})); assert_eq!(read["data"]["reveal_count"], 1); } // ── news editions ─────────────────────────────────────────────────────────── fn news_zone(h: &Harness, zone: &str) { h.run( "INSERT INTO cotton_news_settings (workspace_id, timezone, created_at, updated_at) \ VALUES (?, ?, ?, ?)", &[ SqlValue::Text(h.workspace_id.clone()), SqlValue::Text(zone.to_string()), SqlValue::Text(NOW.to_string()), SqlValue::Text(NOW.to_string()), ], ); } // ── days, not instants, where the person meant a day ──────────────────────── /// RULE: A todo due on a day with no stated hour reads back as that bare day ("2026-10-04"), never as the workspace's midnight instant — a phone in another zone drew that instant as the evening before; a due with an hour stays an instant. #[test] fn a_day_only_due_reads_as_the_day_whatever_zone_the_phone_is_in() { let (h, secret) = harness(); news_zone(&h, "Asia/Kolkata"); let day = call( &h, &secret, "create_record", json!({ "table": "todo", "data": { "title": "Water the plants", "due_at": "2026-10-04" } }), ); let day_id = day["record"]["id"].as_str().unwrap().to_string(); // Stored as midnight in Kolkata, as the todo engine has always stored a day. let own = call(&h, &secret, "get_record", json!({ "kind": "todo", "id": day_id })); assert_eq!(own["due_at"], "2026-10-03T18:30:00.000Z", "{own}"); // Read through the generic verbs: the day, so no device can shift it. let read = call(&h, &secret, "get_record_by_table", json!({ "table": "todo", "id": day_id })); assert_eq!(read["data"]["due_at"], "2026-10-04", "{read}"); let timed = call( &h, &secret, "create_record", json!({ "table": "todo", "data": { "title": "Call the plumber", "due_at": "2026-10-05T04:30:00.000Z" } }), ); let timed_id = timed["record"]["id"].as_str().unwrap().to_string(); let read = call(&h, &secret, "get_record_by_table", json!({ "table": "todo", "id": timed_id })); assert_eq!(read["data"]["due_at"], "2026-10-05T04:30:00.000Z", "{read}"); } /// RULE: An all-day event reads back as the days it covers ("2026-10-15" to "2026-10-16"), never as the workspace's midnight and last-millisecond instants that showed a clock on a phone in another zone. #[test] fn an_all_day_event_reads_as_its_days() { let (h, secret) = harness(); news_zone(&h, "Asia/Kolkata"); // An event is filed in the workspace's default calendar. h.run( "INSERT INTO cotton_collections (id, workspace_id, kind, name, is_default, created_at) \ VALUES (?, ?, 'calendar', 'Personal', 1, ?)", &[ SqlValue::Text(synthetic_uuid("calendar")), SqlValue::Text(h.workspace_id.clone()), SqlValue::Text(NOW.to_string()), ], ); let made = call( &h, &secret, "create_record", json!({ "table": "event", "data": { "title": "Diwali", "starts_at": "2026-10-15T03:00:00.000Z", "ends_at": "2026-10-16T03:00:00.000Z", "all_day": true } }), ); let id = made["record"]["id"].as_str().unwrap().to_string(); let read = call(&h, &secret, "get_record_by_table", json!({ "table": "event", "id": id })); assert_eq!(read["data"]["starts_at"], "2026-10-15", "{read}"); assert_eq!(read["data"]["ends_at"], "2026-10-16", "{read}"); assert_eq!(read["data"]["all_day"], true); let timed = call( &h, &secret, "create_record", json!({ "table": "event", "data": { "title": "Dentist", "starts_at": "2026-10-15T09:30:00.000Z" } }), ); let id = timed["record"]["id"].as_str().unwrap().to_string(); let read = call(&h, &secret, "get_record_by_table", json!({ "table": "event", "id": id })); assert_eq!(read["data"]["starts_at"], "2026-10-15T09:30:00.000Z", "{read}"); } /// RULE: A list of work still to do (a table with `upcoming`) reads what is coming soonest first, then the undated, then the late — read newest first, a todo 200 days late sat on the last page and Today began at "31 days late". #[test] fn an_upcoming_list_reads_soonest_first_and_the_undated_last() { let (h, secret) = harness(); news_zone(&h, "Asia/Kolkata"); for (title, due) in [ ("Later", json!("2026-12-01")), ("Owed", json!("2026-01-10")), ("Someday", Value::Null), ("Soon", json!("2026-10-05T04:30:00.000Z")), ] { let mut data = json!({ "title": title }); if !due.is_null() { data["due_at"] = due; } call(&h, &secret, "create_record", json!({ "table": "todo", "data": data })); } let listed = call(&h, &secret, "list_records", json!({ "table": "todo" })); let titles: Vec<&str> = listed["records"] .as_array() .unwrap() .iter() .map(|record| record["data"]["title"].as_str().unwrap()) .collect(); assert_eq!(titles, ["Soon", "Later", "Someday", "Owed"], "{listed}"); } /// RULE: A built-in table with no date column lists in the order its definition's sort names — people by name whatever their capitals, pictures newest first — because the app draws pages as they come. #[test] fn a_table_with_no_date_lists_in_its_definitions_sort_order() { let (h, secret) = harness(); for name in ["zoe Adams", "Bea", "alan"] { call(&h, &secret, "create_record", json!({ "table": "person", "data": { "full_name": name } })); } let listed = call(&h, &secret, "list_records", json!({ "table": "person" })); let names: Vec<&str> = listed["records"] .as_array() .unwrap() .iter() .map(|record| record["data"]["full_name"].as_str().unwrap()) .collect(); assert_eq!(names, ["alan", "Bea", "zoe Adams"], "{listed}"); // Seeded oldest-made last, so neither the made time nor the insert order is the answer. for (letter, taken) in [('a', "2026-03-01T10:00:00.000Z"), ('b', "2026-09-01T10:00:00.000Z"), ('c', "2026-06-01T10:00:00.000Z")] { let id = seed_photo(&h, letter); h.run( "UPDATE cotton_photos SET taken_at = ? WHERE id = ?", &[SqlValue::Text(taken.to_string()), SqlValue::Text(id)], ); } let listed = call(&h, &secret, "list_records", json!({ "table": "photo" })); let taken: Vec<&str> = listed["records"] .as_array() .unwrap() .iter() .map(|record| record["data"]["taken_at"].as_str().unwrap()) .collect(); assert_eq!(taken.len(), 3, "{listed}"); assert!(taken.windows(2).all(|pair| pair[0] > pair[1]), "pictures read newest first: {taken:?}"); assert!(taken[0].starts_with("2026-09"), "{taken:?}"); } /// RULE: A built-in's sort wins over its date — chats pins first then newest — except where a list of work still to do reads as its day plan, and a list split into days pages by its date. #[test] fn sort_wins_over_date_except_a_day_plan() { let (h, secret) = harness(); let ids = |listed: &Value| -> Vec { listed["records"].as_array().unwrap().iter().map(|record| record["id"].as_str().unwrap().to_string()).collect() }; // Chats: the pins first, newest pin first; then the rest by their last line, newest first. let mut chats = Vec::new(); for (n, (pinned, last)) in [ (None, "2026-09-30T10:00:00.000Z"), (Some("2026-09-01T10:00:00.000Z"), "2026-09-29T10:00:00.000Z"), (None, "2026-09-10T10:00:00.000Z"), (Some("2026-09-20T10:00:00.000Z"), "2026-08-01T10:00:00.000Z"), ] .iter() .enumerate() { let id = synthetic_uuid(&format!("chat-{n}")); h.run( "INSERT INTO cotton_msg_threads (id, workspace_id, kind, title, pinned_at, last_message_at, created_at, updated_at) \ VALUES (?, ?, 'group', ?, ?, ?, ?, ?)", &[ SqlValue::Text(id.clone()), SqlValue::Text(h.workspace_id.clone()), SqlValue::Text(format!("Example chat {n}")), pinned.map_or(SqlValue::Null, |at| SqlValue::Text(at.to_string())), SqlValue::Text(last.to_string()), SqlValue::Text(NOW.to_string()), SqlValue::Text(NOW.to_string()), ], ); chats.push(id); } let listed = call(&h, &secret, "list_records", json!({ "table": "thread" })); assert_eq!(ids(&listed), [chats[3].clone(), chats[1].clone(), chats[0].clone(), chats[2].clone()], "{listed}"); // Todos: still the day plan, whatever a sort would say. news_zone(&h, "Asia/Kolkata"); for (title, due) in [("Later", "2026-12-01"), ("Owed", "2026-01-10"), ("Soon", "2026-10-05T04:30:00.000Z")] { call(&h, &secret, "create_record", json!({ "table": "todo", "data": { "title": title, "due_at": due } })); } let listed = call(&h, &secret, "list_records", json!({ "table": "todo" })); let titles: Vec<&str> = listed["records"].as_array().unwrap().iter().map(|record| record["data"]["title"].as_str().unwrap()).collect(); assert_eq!(titles, ["Soon", "Later", "Owed"], "{listed}"); // Events: split into days, paged from today — what is coming soonest first, then the past newest first, never the oldest event ever. h.run( "INSERT INTO cotton_collections (id, workspace_id, kind, name, is_default, created_at) \ VALUES (?, ?, 'calendar', 'Personal', 1, ?)", &[SqlValue::Text(synthetic_uuid("calendar")), SqlValue::Text(h.workspace_id.clone()), SqlValue::Text(NOW.to_string())], ); for (title, at) in [("Old", "2025-01-01T10:00:00.000Z"), ("Next", "2026-10-09T10:00:00.000Z"), ("Recent", "2026-09-20T10:00:00.000Z")] { call(&h, &secret, "create_record", json!({ "table": "event", "data": { "title": title, "starts_at": at } })); } let listed = call(&h, &secret, "list_records", json!({ "table": "event" })); let titles: Vec<&str> = listed["records"].as_array().unwrap().iter().map(|record| record["data"]["title"].as_str().unwrap()).collect(); // The clock reads 8 September: 20 September is still to come. assert_eq!(titles, ["Recent", "Next", "Old"], "{listed}"); } /// RULE: A password's expiry reads back as a day and a card's as its month ("2027-11"), never as an instant a phone draws with a clock ("Runs out Mon, 8 Nov 2027 · 2:30 PM"); a day written in (UTC midnight) stays that day. #[test] fn a_cards_expiry_reads_as_its_month_and_any_other_as_its_day() { let (h, secret) = harness(); news_zone(&h, "Asia/Kolkata"); let mut ids = Vec::new(); for (name, kind, expires) in [ ("Everyday debit", "card", "2027-11-08T09:00:00.000Z"), ("Passport", "identity", "2027-11-08T00:00:00.000Z"), ("Weather key", "api_key", "2027-11-08T20:00:00.000Z"), ] { let id = synthetic_uuid(name); h.run( "INSERT INTO cotton_secrets (id, workspace_id, kind, name, expires_at, created_at, updated_at) \ VALUES (?, ?, ?, ?, ?, ?, ?)", &[ SqlValue::Text(id.clone()), SqlValue::Text(h.workspace_id.clone()), SqlValue::Text(kind.to_string()), SqlValue::Text(name.to_string()), SqlValue::Text(expires.to_string()), SqlValue::Text(NOW.to_string()), SqlValue::Text(NOW.to_string()), ], ); ids.push(id); } let read = |id: &str| call(&h, &secret, "get_record_by_table", json!({ "table": "secret", "id": id })); assert_eq!(read(&ids[0])["data"]["expires_at"], "2027-11", "a card runs out in a month"); assert_eq!(read(&ids[1])["data"]["expires_at"], "2027-11-08", "a day written in stays that day"); // 20:00 UTC is 01:30 the next morning in Kolkata, the workspace's day. assert_eq!(read(&ids[2])["data"]["expires_at"], "2027-11-09"); } /// RULE: A list of work still to do reads as a day plan — today first, then what is coming soonest first, then the undated, then every late record newest first — so its first page holds today and the days ahead however much is late. #[test] fn an_upcoming_list_reads_today_then_what_is_coming_then_the_late() { let (h, secret) = harness(); news_zone(&h, "Asia/Kolkata"); // The harness's clock reads 8 September. for (title, due) in [ ("Someday", Value::Null), ("Late long ago", json!("2026-01-10")), ("Soon", json!("2026-10-05T04:30:00.000Z")), ("Late lately", json!("2026-09-05")), ("Today", json!("2026-09-08")), ] { let mut data = json!({ "title": title }); if !due.is_null() { data["due_at"] = due; } call(&h, &secret, "create_record", json!({ "table": "todo", "data": data })); } let listed = call(&h, &secret, "list_records", json!({ "table": "todo" })); let titles: Vec<&str> = listed["records"] .as_array() .unwrap() .iter() .map(|record| record["data"]["title"].as_str().unwrap()) .collect(); assert_eq!(titles, ["Today", "Soon", "Someday", "Late lately", "Late long ago"], "{listed}"); } /// RULE: The All deck reads by relevance — every late todo first (newest late first, as the Late view reads), then today, then the days ahead soonest first, then later, the undated and the done — because a deck shows one card at a time and what is owed comes before what is coming (architect, 22 Oct 2026, build 3's walk). The view says so (`lead`), so the whole read without it still holds today on its first page. #[test] fn the_all_deck_reads_late_then_today_then_what_is_soon() { let (h, secret) = harness(); news_zone(&h, "Asia/Kolkata"); // The harness's clock reads 8 September. for (title, due) in [ ("Someday", Value::Null), ("Tomorrow", json!("2026-09-09")), ("Late long ago", json!("2026-01-10")), ("Later", json!("2026-10-05T04:30:00.000Z")), ("Late lately", json!("2026-09-05")), ("Today", json!("2026-09-08")), ("In three days", json!("2026-09-11")), ] { let mut data = json!({ "title": title }); if !due.is_null() { data["due_at"] = due; } call(&h, &secret, "create_record", json!({ "table": "todo", "data": data })); } seed_todo(&h, "Done", "done", Some("2026-09-07"), None); let listed = call(&h, &secret, "list_records", json!({ "table": "todo", "view": "todos/all" })); let titles: Vec<&str> = listed["records"] .as_array() .unwrap() .iter() .map(|record| record["data"]["title"].as_str().unwrap()) .collect(); assert_eq!( titles, ["Late lately", "Late long ago", "Today", "Tomorrow", "In three days", "Later", "Someday", "Done"], "{listed}" ); } // ── the day plan's sections, on the reader's day ──────────────────────────── /// The harness's clock (8 September, 10:00 UTC) moved to 1 October, 09:00 /// UTC — 14:30 in Kolkata. fn to_first_of_october(h: &Harness) { h.clock.advance(chrono::Duration::hours(22 * 24 + 23)); } /// One todo written straight into its table: a status, a due and a snooze. fn seed_todo(h: &Harness, label: &str, status: &str, due: Option<&str>, snoozed: Option<&str>) -> String { let id = synthetic_uuid(label); let at = |value: Option<&str>| value.map_or(SqlValue::Null, |v| SqlValue::Text(v.to_string())); let completed = if status == "done" { SqlValue::Text(NOW.to_string()) } else { SqlValue::Null }; h.run( "INSERT INTO cotton_todos (id, workspace_id, title, status, due_at, snoozed_until, completed_at, created_at, updated_at) \ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)", &[ SqlValue::Text(id.clone()), SqlValue::Text(h.workspace_id.clone()), SqlValue::Text(label.to_string()), SqlValue::Text(status.to_string()), at(due), at(snoozed), completed, SqlValue::Text(NOW.to_string()), SqlValue::Text(NOW.to_string()), ], ); id } /// `late` open todos, one a day back from 30 September, each at 10:00 UTC. fn seed_late(h: &Harness, late: i64) { let last = chrono::NaiveDate::from_ymd_opt(2026, 9, 30).unwrap(); for n in 0..late { let day = last - chrono::Duration::days(n); seed_todo(h, &format!("Late {n}"), "open", Some(&format!("{day}T10:00:00.000Z")), None); } } /// The clock reads 1 October, 14:30 in Kolkata: two today, 120 late plus one /// whose snooze ended, three on the days ahead (one carried there by a /// snooze), one later, two undated, one done that was due a month ago, one /// dropped. fn seed_day_plan(h: &Harness) { to_first_of_october(h); news_zone(h, "Asia/Kolkata"); seed_late(h, 120); seed_todo(h, "Today morning", "open", Some("2026-10-01T03:00:00.000Z"), None); seed_todo(h, "Today evening", "open", Some("2026-10-01T12:00:00.000Z"), None); seed_todo(h, "Snooze ended", "open", Some("2026-09-25T10:00:00.000Z"), Some("2026-09-28T10:00:00.000Z")); seed_todo(h, "Tomorrow", "open", Some("2026-10-02T05:00:00.000Z"), None); seed_todo(h, "Snoozed to Saturday", "open", Some("2026-09-20T10:00:00.000Z"), Some("2026-10-03T05:00:00.000Z")); seed_todo(h, "Monday", "open", Some("2026-10-05T04:30:00.000Z"), None); seed_todo(h, "November", "open", Some("2026-11-01T04:30:00.000Z"), None); seed_todo(h, "Someday", "open", None, None); seed_todo(h, "Some other day", "open", None, None); seed_todo(h, "Done long ago", "done", Some("2026-09-01T10:00:00.000Z"), None); seed_todo(h, "Dropped", "dropped", Some("2026-09-02T10:00:00.000Z"), None); } fn titles_of(listed: &Value) -> Vec { listed["records"].as_array().unwrap().iter().map(|r| r["data"]["title"].as_str().unwrap().to_string()).collect() } /// RULE: A list of todos answers `sections` with every count true over the whole table on the reader's day — today, late, each of the next seven days, later, undated, done, dropped — never the rows one page loaded, and a done todo with a past due date is never late. #[test] fn an_upcoming_list_counts_every_section_truly() { let (h, secret) = harness(); seed_day_plan(&h); let listed = call(&h, &secret, "list_records", json!({ "table": "todo", "limit": 10, "timezone": "Asia/Kolkata" })); assert_eq!(listed["records"].as_array().unwrap().len(), 10); assert_eq!(listed["total"], 131, "{listed}"); assert_eq!( listed["sections"], json!([ { "key": "today", "count": 2 }, { "key": "late", "count": 121 }, { "key": "day", "day": "2026-10-02", "count": 1 }, { "key": "day", "day": "2026-10-03", "count": 1 }, { "key": "day", "day": "2026-10-05", "count": 1 }, { "key": "later", "count": 1 }, { "key": "undated", "count": 2 }, { "key": "done", "count": 1 }, { "key": "dropped", "count": 1 }, ]), ); // A search counts the same way: the sections honour `query`. let searched = call(&h, &secret, "list_records", json!({ "table": "todo", "query": "Snooze ended" })); assert_eq!(searched["sections"], json!([{ "key": "late", "count": 1 }]), "{searched}"); } /// RULE: A read with `section` answers only that section's records, in its own order — late newest first, a day ahead soonest first — paged as usual with total its count, and a section the table does not have is refused. #[test] fn a_section_reads_only_its_own_rows() { let (h, secret) = harness(); seed_day_plan(&h); let late = call(&h, &secret, "list_records", json!({ "table": "todo", "section": "late", "limit": 50 })); assert_eq!(late["total"], 121, "{late}"); assert_eq!(late["next_page"], 50); let titles = titles_of(&late); assert_eq!(titles.len(), 50); assert_eq!(&titles[..2], ["Late 0", "Late 1"], "late reads newest first"); assert!(!titles.iter().any(|t| t.starts_with("Done") || t.starts_with("Today")), "{titles:?}"); let rest = call(&h, &secret, "list_records", json!({ "table": "todo", "section": "late", "page": 100, "limit": 50 })); assert_eq!(titles_of(&rest).len(), 21); assert_eq!(titles_of(&rest).last().map(String::as_str), Some("Late 119"), "the oldest debt last"); let saturday = call(&h, &secret, "list_records", json!({ "table": "todo", "section": "day", "day": "2026-10-03" })); assert_eq!(titles_of(&saturday), ["Snoozed to Saturday"], "{saturday}"); assert_eq!(saturday["total"], 1); let today = call(&h, &secret, "list_records", json!({ "table": "todo", "section": "today" })); assert_eq!(titles_of(&today), ["Today morning", "Today evening"]); assert_eq!(titles_of(&call(&h, &secret, "list_records", json!({ "table": "todo", "section": "later" }))), ["November"]); assert_eq!(titles_of(&call(&h, &secret, "list_records", json!({ "table": "todo", "section": "done" }))), ["Done long ago"]); assert_eq!(titles_of(&call(&h, &secret, "list_records", json!({ "table": "todo", "section": "undated" }))).len(), 2); let refusal = refused(&h, &secret, "list_records", json!({ "table": "todo", "section": "day" })); assert!(refusal.contains("needs day"), "{refusal}"); let refusal = refused(&h, &secret, "list_records", json!({ "table": "todo", "section": "day", "day": "2026-12-25" })); assert!(refusal.contains("next 7 days"), "{refusal}"); let refusal = refused(&h, &secret, "list_records", json!({ "table": "todo", "section": "coming" })); assert!(refusal.contains("today, late, day, later, undated, done, dropped"), "{refusal}"); let refusal = refused(&h, &secret, "list_records", json!({ "table": "student", "section": "late" })); assert!(refusal.contains("not read in sections"), "{refusal}"); } /// RULE: However many todos are late, the first page of the list holds today and the days ahead — hundreds late once pushed tomorrow's todo to page eighty, reachable only by search. #[test] fn the_first_page_holds_today_and_the_days_ahead() { let (h, secret) = harness(); to_first_of_october(&h); news_zone(&h, "Asia/Kolkata"); seed_late(&h, 300); seed_todo(&h, "Tomorrow", "open", Some("2026-10-02T05:00:00.000Z"), None); seed_todo(&h, "Today", "open", Some("2026-10-01T12:00:00.000Z"), None); seed_todo(&h, "Next week", "open", Some("2026-10-07T05:00:00.000Z"), None); seed_todo(&h, "Someday", "open", None, None); let listed = call(&h, &secret, "list_records", json!({ "table": "todo", "limit": 50 })); let titles = titles_of(&listed); assert_eq!(&titles[..5], ["Today", "Tomorrow", "Next week", "Someday", "Late 0"], "{titles:?}"); assert_eq!(listed["sections"][1], json!({ "key": "late", "count": 300 })); } /// RULE: Today and late are judged on the reader's day, in the reader's zone (`today`, else `timezone`), never the workspace's: one todo is today in Auckland and late in Los Angeles at the same instant, and a todo due on a day with no hour is that day everywhere. #[test] fn late_is_judged_by_the_readers_day() { let (h, secret) = harness(); to_first_of_october(&h); news_zone(&h, "Asia/Kolkata"); // 1 October 09:00 UTC: 22:00 on the 1st in Auckland, 02:00 on the 1st in Los Angeles. seed_todo(&h, "Evening of the 30th, UTC", "open", Some("2026-09-30T20:00:00.000Z"), None); // A day with no hour: the workspace's midnight, read as 1 October. call(&h, &secret, "create_record", json!({ "table": "todo", "data": { "title": "The first", "due_at": "2026-10-01" } })); let sections = |args: Value| call(&h, &secret, "list_records", args)["sections"].clone(); assert_eq!( sections(json!({ "table": "todo", "timezone": "Pacific/Auckland" })), json!([{ "key": "today", "count": 2 }]), ); assert_eq!( sections(json!({ "table": "todo", "timezone": "America/Los_Angeles" })), json!([{ "key": "today", "count": 1 }, { "key": "late", "count": 1 }]), ); // The reader's own day outranks its zone's: a phone already on the 2nd. assert_eq!( sections(json!({ "table": "todo", "timezone": "Pacific/Auckland", "today": "2026-10-02" })), json!([{ "key": "late", "count": 2 }]), ); } /// RULE: A todo due late yesterday in a half-hour zone is late, not today: a reader in Kolkata (+05:30) on a workspace in Nairobi (+03:00) finds one due at 22:30 and one at 23:45 of the day before under Late — the walk of 5 Oct found two of them under Today. #[test] fn late_yesterday_in_a_half_hour_zone_is_late() { let (h, secret) = harness(); to_first_of_october(&h); news_zone(&h, "Africa/Nairobi"); // 30 September 22:30 and 23:45 in Kolkata; 1 October 14:30 there now. seed_todo(&h, "Half past ten last night", "open", Some("2026-09-30T17:00:00.000Z"), None); seed_todo(&h, "Quarter to midnight last night", "open", Some("2026-09-30T18:15:00.000Z"), None); call(&h, &secret, "create_record", json!({ "table": "todo", "data": { "title": "Written at 22:30", "due_at": "2026-09-30T17:00:00.000Z" } })); call(&h, &secret, "create_record", json!({ "table": "todo", "data": { "title": "Written at 23:45, offset", "due_at": "2026-09-30T23:45:00+05:30" } })); // Nairobi's midnight of the 1st (02:30 on the 1st in Kolkata) is today. seed_todo(&h, "Midnight in Nairobi", "open", Some("2026-09-30T21:00:00.000Z"), None); let sections = |args: Value| call(&h, &secret, "list_records", args)["sections"].clone(); let want = json!([{ "key": "today", "count": 1 }, { "key": "late", "count": 4 }]); assert_eq!(sections(json!({ "table": "todo", "timezone": "Asia/Kolkata" })), want); // As the phone asks: its own day beside its zone, one section at a time. let phone = json!({ "table": "todo", "timezone": "Asia/Kolkata", "today": "2026-10-01", "section": "today", "limit": 50 }); let listed = call(&h, &secret, "list_records", phone); assert_eq!(listed["sections"], want, "{listed}"); assert_eq!(titles_of(&listed), ["Midnight in Nairobi"], "{listed}"); } /// RULE: A calendar opens on today: its read comes today and after soonest first, then the past newest first, and answers sections coming and earlier so the past can stand behind one Earlier link — read latest first, it opened on 2 December. #[test] fn a_calendar_opens_on_today_and_keeps_the_past_behind_earlier() { let (h, secret) = harness(); to_first_of_october(&h); news_zone(&h, "Asia/Kolkata"); h.run( "INSERT INTO cotton_collections (id, workspace_id, kind, name, is_default, created_at) \ VALUES (?, ?, 'calendar', 'Personal', 1, ?)", &[SqlValue::Text(synthetic_uuid("calendar")), SqlValue::Text(h.workspace_id.clone()), SqlValue::Text(NOW.to_string())], ); for (title, at) in [ ("Far", "2026-12-02T10:00:00.000Z"), ("Old", "2025-01-01T10:00:00.000Z"), ("Next", "2026-10-09T10:00:00.000Z"), ("This morning", "2026-10-01T03:00:00.000Z"), ("Recent", "2026-09-20T10:00:00.000Z"), ] { call(&h, &secret, "create_record", json!({ "table": "event", "data": { "title": title, "starts_at": at } })); } let listed = call(&h, &secret, "list_records", json!({ "table": "event", "timezone": "Asia/Kolkata" })); assert_eq!(titles_of(&listed), ["This morning", "Next", "Far", "Recent", "Old"], "{listed}"); assert_eq!(listed["sections"], json!([{ "key": "coming", "count": 3 }, { "key": "earlier", "count": 2 }])); let first = call(&h, &secret, "list_records", json!({ "table": "event", "limit": 2 })); assert_eq!(titles_of(&first), ["This morning", "Next"], "page one opens on today"); let earlier = call(&h, &secret, "list_records", json!({ "table": "event", "section": "earlier" })); assert_eq!(titles_of(&earlier), ["Recent", "Old"]); assert_eq!(earlier["total"], 2); } /// RULE: A repeating event stands in the Calendar at its next occurrence from today, each later one its own row (`@`); a series that has ended stays where it last was — filed by its first start, a weekly meeting on today was under a day weeks gone. #[test] fn a_repeating_event_stands_on_its_next_occurrence() { let (h, secret) = harness(); to_first_of_october(&h); news_zone(&h, "Asia/Kolkata"); h.run( "INSERT INTO cotton_collections (id, workspace_id, kind, name, is_default, created_at) \ VALUES (?, ?, 'calendar', 'Personal', 1, ?)", &[SqlValue::Text(synthetic_uuid("calendar")), SqlValue::Text(h.workspace_id.clone()), SqlValue::Text(NOW.to_string())], ); for (title, at, rrule) in [ // Thursdays at 10:00 in Kolkata since 3 September; 1 October is a Thursday. ("Team catch-up", "2026-09-03T04:30:00.000Z", Some("FREQ=WEEKLY")), ("Rent due", "2026-08-20T04:30:00.000Z", Some("FREQ=MONTHLY")), ("Old class", "2026-06-01T04:30:00.000Z", Some("FREQ=WEEKLY;COUNT=3")), ("Recent", "2026-09-20T10:00:00.000Z", None), ] { let mut data = json!({ "title": title, "starts_at": at }); if let Some(rrule) = rrule { data["rrule"] = Value::from(rrule); } call(&h, &secret, "create_record", json!({ "table": "event", "data": data })); } let listed = call(&h, &secret, "list_records", json!({ "table": "event", "timezone": "Asia/Kolkata" })); assert_eq!(titles_of(&listed)[..4], ["Team catch-up", "Team catch-up", "Team catch-up", "Rent due"], "{listed}"); let first = &listed["records"][0]; assert_eq!(first["data"]["starts_at"], "2026-10-01T04:30:00.000Z", "{first}"); assert_eq!(first["data"]["day"], "2026-10-01", "the slip stands under today: {first}"); // A series standing on a day after its first start is that day: its id // names it, so "Only this one" reaches it (architect 2005, sev 1). let (series, on) = first["id"].as_str().unwrap().split_once('@').expect("the next occurrence names its day"); assert_eq!(on, "2026-10-01T04:30:00.000Z", "{first}"); let second = &listed["records"][1]; assert_eq!(second["id"], format!("{series}@2026-10-08T04:30:00.000Z"), "{second}"); assert_eq!(second["data"]["day"], "2026-10-08", "{second}"); assert_eq!(listed["records"][3]["data"]["starts_at"], "2026-10-20T04:30:00.000Z"); let sections = listed["sections"].as_array().unwrap(); assert_eq!(sections[0]["key"], "coming"); assert!(sections[0]["count"].as_i64().unwrap() > 2, "later occurrences are counted: {sections:?}"); assert_eq!(sections[1], json!({ "key": "earlier", "count": 2 })); let earlier = call(&h, &secret, "list_records", json!({ "table": "event", "section": "earlier", "timezone": "Asia/Kolkata" })); assert_eq!(titles_of(&earlier), ["Recent", "Old class"]); let coming = call(&h, &secret, "list_records", json!({ "table": "event", "section": "coming", "timezone": "Asia/Kolkata", "limit": 4 })); assert_eq!(titles_of(&coming), ["Team catch-up", "Team catch-up", "Team catch-up", "Rent due"]); } /// RULE: A list's search box reads its last word as the start of one, so an event today is found while its name is still being typed ("dent" finds the Dentist); the words before it are whole. #[test] fn a_list_search_finds_a_word_being_typed() { let (h, secret) = harness(); to_first_of_october(&h); h.run( "INSERT INTO cotton_collections (id, workspace_id, kind, name, is_default, created_at) \ VALUES (?, ?, 'calendar', 'Personal', 1, ?)", &[SqlValue::Text(synthetic_uuid("calendar")), SqlValue::Text(h.workspace_id.clone()), SqlValue::Text(NOW.to_string())], ); for (title, at) in [("Dentist", "2026-10-01T11:00:00.000Z"), ("Dinner at ours", "2026-10-01T14:00:00.000Z")] { call(&h, &secret, "create_record", json!({ "table": "event", "data": { "title": title, "starts_at": at } })); } let found = |words: &str| titles_of(&call(&h, &secret, "list_records", json!({ "table": "event", "query": words }))); assert_eq!(found("dent"), ["Dentist"]); assert_eq!(found("dentist"), ["Dentist"]); assert_eq!(found("dinner at o"), ["Dinner at ours"]); assert!(found("din at").is_empty(), "only the last word is a prefix"); } /// RULE: A generic verb on a built-in leaves ONE history row per action — its own — never a second one minted for the engine's act (slice 6b-2). #[test] fn a_generic_verb_on_a_builtin_leaves_one_history_row_per_action() { let (h, secret) = harness(); let rows_for = |id: &str| { h.count( "SELECT count(*) AS c FROM cotton_changes WHERE record_id = ?", &[SqlValue::Text(id.to_string())], ) }; let created = call( &h, &secret, "create_record", json!({ "table": "todo", "data": { "title": "Tune the cello" } }), ); let id = created["record"]["id"].as_str().unwrap().to_string(); assert_eq!(rows_for(&id), 1, "the create"); let done = call( &h, &secret, "update_record", json!({ "table": "todo", "id": id, "patch": { "status": "done" } }), ); assert_eq!(rows_for(&id), 2, "the update"); call(&h, &secret, "undo", json!({ "change_id": done["change"]["id"] })); assert_eq!(rows_for(&id), 3, "the undo"); } #[test] fn keyed_settings_use_the_same_row_on_repeated_ordinary_creates() { let (h, secret) = harness(); let mut definition: Value = serde_json::from_str(include_str!("../../cotton-core/kits/personal/tables/face_settings.json")).unwrap(); definition["id"] = json!("synthetic_face_settings"); define(&h, &definition); let write = |face: &str| call(&h, &secret, "create_record", json!({"table":"synthetic_face_settings", "data":{"table":"person", "face":face}})); let first = write("person"); assert_eq!(first["record"]["id"], "person", "the copy mints the key the object keeps"); let second = write("person.rolodex"); assert_eq!(second["record"]["id"], "person"); assert_eq!(second["record"]["data"]["face"], "person.rolodex"); let rows = call(&h, &secret, "list_records", json!({"table":"synthetic_face_settings"})); assert_eq!(rows["records"].as_array().unwrap().len(), 1); refused(&h, &secret, "update_record", json!({"table":"synthetic_face_settings", "id":"person", "patch":{"table":"book"}})); let held = call(&h, &secret, "get_record_by_table", json!({"table":"synthetic_face_settings", "id":"person"})); assert_eq!(held["data"]["table"], "person"); }