Cotton code
304 lines · 15.6 KB · RustRaw
//! Undo of an add (architect's ruling, 5 Oct 2026): the person's own fresh//! add is TAKEN BACK — erased on every device as if it was never made, with//! the receipt "Removed <name>" — when the same person at the same device//! made the record, nothing has changed it since, and the add's own receipt//! asks. Otherwise its Undo puts the record away in the table's own state.//! Driven end to end through the dispatcher; the store's half is//! `cotton-store/tests/take_back.rs`.//!//! Every value is invented ([nothing-real-ever-goes-in-cotton-s-public-tree]).mod support;use rusqlite::types::Value as SqlValue;use serde_json::{json, Value};use support::harness::Harness;use support::mcp::{call_tool, call_tool_as_owner, mint_token};const PHONE: &str = "device:phone";const TABLET: &str = "device:tablet";fn harness() -> (Harness, String) {    let mut h = Harness::new();    let secret = mint_token(&mut h, &["read", "write"], "Claude");    (h, secret)}fn at(h: &Harness, device: &str, tool: &str, args: Value) -> Value {    let answer = call_tool_as_owner(h, device, tool, args);    assert!(!answer.is_error, "{tool} refused: {}", answer.text);    answer.json()}fn owner(h: &Harness, tool: &str, args: Value) -> Value {    at(h, PHONE, tool, args)}fn add_todo(h: &Harness, title: &str) -> (Value, String) {    let added = owner(h, "create_record", json!({ "table": "todo", "data": { "title": title } }));    let id = added["record"]["id"].as_str().expect("the todo's id").to_string();    (added, id)}fn undo(h: &Harness, change: &Value) -> Value {    owner(h, "undo", json!({ "change_id": change["change"]["id"] }))}fn count(h: &Harness, sql: &str, id: &str) -> i64 {    h.count(sql, &[SqlValue::Text(id.to_string())])}fn gone_reason(h: &Harness, table: &str, id: &str) -> Option<String> {    h.one(        "SELECT reason FROM _gone WHERE tbl = ? AND row_id = ?",        &[SqlValue::Text(table.to_string()), SqlValue::Text(id.to_string())],    )    .and_then(|row| row["reason"].as_str().map(str::to_string))}/// The record stayed, moved to the bin, by an Undo that is itself undoable.fn assert_binned(h: &Harness, undone: &Value, id: &str, why: &str) {    assert_eq!(undone["change"]["verb"], "delete", "{why}: {undone}");    assert_eq!(undone["change"]["undoable"], true, "{why}: {undone}");    assert_eq!(count(h, "SELECT count(*) AS c FROM cotton_todos WHERE id = ? AND trashed_at IS NOT NULL", id), 1, "{why}: the todo is not in the bin");    assert_eq!(gone_reason(h, "cotton_todos", id), None, "{why}: the todo was erased");}/// RULE: Undo of the person's own fresh add takes it back: the record is erased with reason taken_back, the receipt says Removed and its name, offers no Undo, and no change row is left.#[test]fn undo_of_a_fresh_add_removes_the_record() {    let (h, _) = harness();    let (added, id) = add_todo(&h, "Call the plumber");    assert_eq!(added["change"]["undoable"], true, "{added}");    let undone = undo(&h, &added);    assert_eq!(undone["record"], Value::Null, "{undone}");    assert_eq!(undone["change"]["verb"], "delete");    assert_eq!(undone["change"]["receipt"]["kind"], "removed");    assert_eq!(undone["change"]["undoable"], false, "a taken-back add offers no Undo");    assert_eq!(undone["change"]["reason"], Value::Null, "and never says it cannot be undone");    assert_eq!(count(&h, "SELECT count(*) AS c FROM cotton_todos WHERE id = ?", &id), 0);    assert_eq!(gone_reason(&h, "cotton_todos", &id).as_deref(), Some("taken_back"));    assert_eq!(count(&h, "SELECT count(*) AS c FROM cotton_changes WHERE record_id = ?", &id), 0, "a change row outlived the record");    assert_eq!(count(&h, "SELECT count(*) AS c FROM _writes WHERE instr(CAST(bytes AS TEXT), ?) > 0", &id), 0, "a receipt still names the record");}/// RULE: An add made by an assistant is never taken back, and neither is one whose Undo an assistant asks: the todo is moved to the bin.#[test]fn an_assistants_add_or_undo_puts_the_record_away() {    let (h, secret) = harness();    // Made by the assistant, undone by the person.    let added = call_tool(&h, &secret, "create_record", json!({ "table": "todo", "data": { "title": "Order the tiles" } }));    let id = added["record"]["id"].as_str().unwrap().to_string();    assert_binned(&h, &undo(&h, &added), &id, "made by an assistant");    // Made by the person, undone by the assistant.    let (added, id) = add_todo(&h, "Measure the wall");    let undone = call_tool(&h, &secret, "undo", json!({ "change_id": added["change"]["id"] }));    assert_binned(&h, &undone, &id, "asked by an assistant");}/// RULE: An add is taken back only on the device it was made on: its Undo asked at another of the person's devices moves the record to the bin.#[test]fn an_add_undone_at_another_device_is_put_away() {    let (h, _) = harness();    let (added, id) = add_todo(&h, "Water the ferns");    let undone = at(&h, TABLET, "undo", json!({ "change_id": added["change"]["id"] }));    assert_binned(&h, &undone, &id, "asked at another device");}/// RULE: An add that was edited, linked or given a child record since is never taken back: on a table whose Delete waits in the bin an Undo that would overwrite a later edit is refused by the record's name and the record stays as it now stands, and one whose row is unchanged moves it to the bin with what hangs off it.#[test]fn an_add_changed_since_is_not_undone() {    let refused = |h: &Harness, added: &Value, id: &str, title: &str, why: &str| {        let answer = call_tool_as_owner(h, PHONE, "undo", json!({ "change_id": added["change"]["id"] }));        assert!(answer.is_error && answer.text.starts_with(title) && answer.text.contains("changed since"), "{why}: {}", answer.text);        let live = "SELECT count(*) AS c FROM cotton_todos WHERE id = ? AND trashed_at IS NULL";        assert_eq!(count(h, live, id), 1, "{why}: the todo left");    };    // An edit.    let (h, _) = harness();    let (added, id) = add_todo(&h, "Call the plumber");    owner(&h, "update_record", json!({ "table": "todo", "id": id, "patch": { "title": "Call the plumber on Monday" } }));    refused(&h, &added, &id, "Call the plumber on Monday", "edited since");}/// The verbs that add a record and answer its create change: the add's receipt, with the Undo this file tests.const ANSWERS_A_CHANGE: &[&str] = &["add_photo", "add_sender_to_people", "create_record", "create_project", "create_album", "create_group"];/// The add verbs that do not answer a create change yet, each an assistant's own verb whose add the app makes through `create_record`. The list may only shorten.const NOT_YET: &[&str] = &[    "append_journal", "create_event", "create_link",    "create_money_account", "create_note",    "create_person", "create_secret", "create_session",    "create_todo", "log_session", "record_transaction",];/// Verbs the scan's prefixes catch that add no record: `add_tool` holds a tool in the database, a definition row with no receipt of its own.const ADDS_NO_RECORD: &[&str] = &["add_tool"];/// RULE: Any verb that adds a record answers its create change, so every add shows the same receipt and its Undo is asked one way; a new add verb that does not is a defect.#[test]fn every_verb_that_adds_a_record_answers_a_create_change() {    let adds: Vec<&str> = cotton_tools::mcp::catalogue::TOOLS        .iter()        .map(|tool| tool.name)        .filter(|name| ["create_", "record_", "add_", "append_", "log_"].iter().any(|prefix| name.starts_with(prefix)))        .filter(|name| !ADDS_NO_RECORD.contains(name))        .collect();    let unlisted: Vec<&&str> = adds.iter().filter(|name| !ANSWERS_A_CHANGE.contains(name) && !NOT_YET.contains(name)).collect();    assert!(unlisted.is_empty(), "an add verb that answers no create change: {unlisted:?} — answer tables::record_added as `change`");    for listed in ANSWERS_A_CHANGE.iter().chain(NOT_YET) {        assert!(adds.contains(listed), "{listed} is listed and is no add verb of the catalogue");    }}/// RULE: Undo of an archive restores the note or person without leaving its archive stamp set.#[test]fn undo_of_an_archive_puts_the_record_back() {    let (h, _) = harness();    for (table, data, _name) in [        ("note", json!({ "title": "Spare key under the blue pot" }), "Spare key under the blue pot"),        ("person", json!({ "full_name": "Sela Porchwalker" }), "Sela Porchwalker"),    ] {        let added = owner(&h, "create_record", json!({ "table": table, "data": data }));        let id = added["record"]["id"].as_str().unwrap().to_string();        let archived = owner(&h, "update_record", json!({ "table": table, "id": id, "patch": { "archived_at": "2026-10-05T07:40:00.000Z" } }));        assert_eq!(archived["change"]["undoable"], true, "{archived}");        let undone = undo(&h, &archived);        assert_eq!(undone["record"]["data"].get("archived_at").filter(|at| !at.is_null()), None, "{table} stayed archived: {undone}");    }}/// RULE: A refused Undo is a sentence that names the record by its name, never by its id.#[test]fn a_refused_undo_names_the_record_never_its_id() {    let (h, _) = harness();    let added = owner(&h, "create_record", json!({ "table": "note", "data": { "title": "Spare key under the blue pot" } }));    let id = added["record"]["id"].as_str().unwrap().to_string();    let renamed = owner(&h, "update_record", json!({ "table": "note", "id": id, "patch": { "title": "Spare key under the red pot" } }));    owner(&h, "update_record", json!({ "table": "note", "id": id, "patch": { "title": "Spare key under the green pot" } }));    let refused = call_tool_as_owner(&h, PHONE, "undo", json!({ "change_id": renamed["change"]["id"] }));    assert!(refused.is_error, "{}", refused.text);    assert!(refused.text.contains("Spare key under the green pot"), "{}", refused.text);    assert!(!refused.text.contains(&id), "a refusal printed a record id: {}", refused.text);}// ── an Undo leaves no trace: the record's edited time ──────────────────────/// A while later on the harness's clock, so a write stamps a new edited time.fn later(h: &Harness) {    h.clock.advance(chrono::Duration::minutes(7));}fn edited_at(h: &Harness, table: &str, id: &str) -> Value {    h.one(&format!("SELECT updated_at FROM {table} WHERE id = ?"), &[SqlValue::Text(id.to_string())])        .and_then(|row| row.get("updated_at").cloned())        .expect("the row's edited time")}fn author(h: &Harness, id: &str) -> Value {    h.one("SELECT author_kind, author_label FROM cotton_notes WHERE id = ?", &[SqlValue::Text(id.to_string())])        .map(Value::Object)        .expect("the note's author")}/// Two notes, the first written before the second: the first's id.fn two_notes(h: &Harness) -> String {    let first = owner(h, "create_record", json!({ "table": "note", "data": { "title": "Spare key under the blue pot" } }));    later(h);    owner(h, "create_record", json!({ "table": "note", "data": { "title": "Bike shed hinges" } }));    later(h);    first["record"]["id"].as_str().expect("the note's id").to_string()}fn first_note(h: &Harness) -> String {    let listed = owner(h, "list_records", json!({ "table": "note" }));    listed["records"][0]["id"].as_str().expect("a listed note").to_string()}/// RULE: An archive and its Undo leave no trace — the note keeps its own edited time and author, so it is not lifted to the top of Home — by the archive column and by delete_record alike.#[test]fn undo_of_an_archive_keeps_the_notes_edited_time() {    for route in ["update", "delete"] {        let (h, _) = harness();        let id = two_notes(&h);        let (was, by) = (edited_at(&h, "cotton_notes", &id), author(&h, &id));        let archived = match route {            "update" => owner(&h, "update_record", json!({ "table": "note", "id": id, "patch": { "archived_at": "2026-10-05T07:40:00.000Z" } })),            _ => owner(&h, "delete_record", json!({ "table": "note", "id": id })),        };        later(&h);        undo(&h, &archived);        assert_eq!(edited_at(&h, "cotton_notes", &id), was, "{route}: the Undo stamped the note now");        assert_eq!(author(&h, &id), by, "{route}: the Undo signed the note");        assert_ne!(first_note(&h), id, "{route}: the Undo lifted the note to the top");    }}/// RULE: Undo of a note's edit puts its edited time back as it was before the edit, and an Undo of that Undo gives the edit's time back.#[test]fn undo_of_a_note_edit_keeps_its_edited_time() {    let (h, _) = harness();    let id = two_notes(&h);    let (was, by) = (edited_at(&h, "cotton_notes", &id), author(&h, &id));    let edited = owner(&h, "update_record", json!({ "table": "note", "id": id, "patch": { "title": "Spare key under the red pot" } }));    let edit_time = edited_at(&h, "cotton_notes", &id);    later(&h);    let undone = undo(&h, &edited);    assert_eq!(undone["record"]["data"]["title"], "Spare key under the blue pot", "{undone}");    assert_eq!(edited_at(&h, "cotton_notes", &id), was);    assert_eq!(author(&h, &id), by, "the Undo changed who wrote the note");    assert_ne!(first_note(&h), id);    later(&h);    owner(&h, "undo", json!({ "change_id": undone["change"]["id"] }));    assert_eq!(edited_at(&h, "cotton_notes", &id), edit_time, "the Undo of the Undo stamped the note now");}/// RULE: Undo of an edit to a record of a table a person made puts its edited time back as it was before the edit.#[test]fn undo_of_a_made_tables_edit_keeps_its_edited_time() {    let (h, _) = harness();    let kite = json!({        "id": "kite", "name": "Kite", "plural": "Kites", "picture": null,        "builtin": false, "engine": null,        "columns": [ { "key": "name", "type": "text", "required": true }, { "key": "colour", "type": "text" } ],        "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", "colour"] } ],        "instructions": "A kite."    });    h.run(        "INSERT INTO cotton_table_definitions (id, workspace_id, definition, builtin, created_at, updated_at) \         VALUES ('kite', ?, ?, 0, '2026-10-01T09:00:00.000Z', '2026-10-01T09:00:00.000Z')",        &[SqlValue::Text(h.workspace_id.clone()), SqlValue::Text(kite.to_string())],    );    let made = owner(&h, "create_record", json!({ "table": "kite", "data": { "name": "Red diamond" } }));    let id = made["record"]["id"].as_str().expect("the kite's id").to_string();    later(&h);    let was = edited_at(&h, "cotton_kite", &id);    let coloured = owner(&h, "update_record", json!({ "table": "kite", "id": id, "patch": { "colour": "Red" } }));    let coloured_time = edited_at(&h, "cotton_kite", &id);    later(&h);    let named = owner(&h, "update_record", json!({ "table": "kite", "id": id, "patch": { "name": "Big red diamond" } }));    let named_time = edited_at(&h, "cotton_kite", &id);    later(&h);    let undone = undo(&h, &named);    assert_eq!(undone["record"]["data"]["name"], "Red diamond", "{undone}");    assert_eq!(undone["record"]["data"].get("updated_at"), None, "the edited time went into the record's data");    assert_ne!(coloured_time, named_time);    assert_eq!(edited_at(&h, "cotton_kite", &id), coloured_time, "the Undo stamped the record now");    later(&h);    undo(&h, &coloured);    assert_eq!(edited_at(&h, "cotton_kite", &id), was, "the Undo stamped the record now");    // Deleted and brought back by Undo, it keeps its time too.    later(&h);    let deleted = owner(&h, "delete_record", json!({ "table": "kite", "id": id }));    later(&h);    undo(&h, &deleted);    assert_eq!(edited_at(&h, "cotton_kite", &id), was);}