Cotton code
580 lines · 22.3 KB · RustRaw
//! `read.record`'s conversation half — the re-ask gesture's read.//!//! Every fixture is invented: a note nobody wrote, a question nobody asked//! ([nothing-real-ever-goes-in-cotton-s-public-tree]).use serde_json::{json, Map, Value};use crate::shell::client::phone_tests::attached;use crate::shell::client::ClientController;fn read_record(client: &ClientController, kind: &str, id: &str) -> Value {    let entry = crate::phone::reads::read_for("read.record").expect("read.record is declared");    let mut args = Map::new();    args.insert("kind".to_string(), Value::from(kind));    args.insert("id".to_string(), Value::from(id));    crate::phone::answer_read(client, entry, &args)        .unwrap_or_else(|reason| panic!("read.record answered: {reason}"))}// W9-NOTE-11-03: the phone's device key identifies the writer on the wire,// not an assistant to credit on the note. Pin and its Undo must keep that// distinction in the same read that supplies the page's byline.#[test]fn owner_note_commands_keep_human_authorship_after_pin_and_undo() {    let (_dir, client) = attached();    let made = crate::phone::records::call(&client, "records.create", &json!({        "table": "note", "data": { "title": "Fern watering plan", "body": "Use the blue jug." }    })).expect("an owner creates a note");    let id = made["record"]["id"].as_str().expect("the note id");    for (command, pinned) in [("pin", true), ("unpin", false)] {        crate::phone::records::call(&client, "records.command", &json!({            "table": "note", "id": id, "command": command        })).expect("the page command and its inverse");        let read = read_record(&client, "note", id);        assert_eq!(read["author_kind"], "user", "{command} is the owner's act");        assert_eq!(read["author_label"], Value::Null, "{command} must not publish the device key as an assistant label");        assert_eq!(read["body"], "Use the blue jug.");        let record = crate::phone::records::call(&client, "records.get", &json!({ "table": "note", "id": id }))            .expect("the page reads the changed note");        assert_eq!(record["data"]["pinned"], pinned);    }}fn exec(client: &ClientController, sql: &str, params: &[&str]) {    client        .with_writer(|replica| {            let bound: Vec<rusqlite::types::Value> = params                .iter()                .map(|value| rusqlite::types::Value::Text((*value).to_string()))                .collect();            replica                .driver                .run(sql, &bound)                .map(|_| ())                .map_err(|error| error.to_string())        })        .expect("the seed");}fn workspace(client: &ClientController) -> String {    client        .with_writer(|replica| Ok(replica.workspace_id.to_string()))        .expect("the workspace id")}/// An assistant's answer note — an ORDINARY note with an agent byline, which is/// the whole reason this read grew a second half.fn seed_answer_note(client: &ClientController, id: &str) {    let workspace = workspace(client);    exec(        client,        "INSERT INTO cotton_notes (id, workspace_id, title, body, kind, author_kind, \         author_label, created_at, updated_at) \         VALUES (?, ?, ?, ?, 'note', 'agent', ?, ?, ?)",        &[            id,            &workspace,            "What the meter reading came to",            "Two hundred and eleven units since the last reading.",            "an assistant",            "2026-09-01T09:00:00.000Z",            "2026-09-01T09:00:00.000Z",        ],    );}/// One comment to seed. A struct rather than eight positional arguments, so a/// case reads as what it is saying.struct Say<'a> {    id: &'a str,    record_id: &'a str,    parent: Option<&'a str>,    body: &'a str,    author_kind: &'a str,    created_at: &'a str,    resolved_at: Option<&'a str>,}fn seed_comment(client: &ClientController, said: Say<'_>) {    let Say {        id,        record_id,        parent,        body,        author_kind,        created_at,        resolved_at,    } = said;    let workspace = workspace(client);    let parent_sql = parent.unwrap_or("");    let resolved_sql = resolved_at.unwrap_or("");    // `CHECK ((author_kind = 'agent') = (author_label IS NOT NULL))` — the    // column pair is the store's own rule: an agent comment is always signed    // and the owner's never is, because the owner is who is reading it.    let label = if author_kind == "agent" { "an assistant" } else { "" };    // And its twin: `CHECK ((author_kind = 'user') = (author_user_id IS NOT NULL))`.    // The owner's own comment names the owner; an agent's does not.    let user = if author_kind == "user" {"00000000-0000-4000-8000-000000000001".to_string()    } else {        String::new()    };    exec(        client,        "INSERT INTO cotton_comments (id, workspace_id, record_kind, record_id, parent_id, \         body, author_kind, author_label, author_user_id, resolved_at, resolved_by_kind, \         created_at, updated_at) \         VALUES (?, ?, 'note', ?, NULLIF(?, ''), ?, ?, NULLIF(?, ''), NULLIF(?, ''), \         NULLIF(?, ''), NULLIF(?, ''), ?, ?)",        &[            id,            &workspace,            record_id,            parent_sql,            body,            author_kind,            label,            &user,            resolved_sql,            // `CHECK ((resolved_at IS NULL) = (resolved_by_kind IS NULL))` — a            // settled thread always says WHO settled it.            if resolved_at.is_some() { "user" } else { "" },            created_at,            created_at,        ],    );}/// The record's own columns still arrive at the TOP level — the shape two/// screens already decode — and `threads` is beside them.#[test]fn the_record_is_unchanged_and_the_conversation_is_beside_it() {    let (_dir, client) = attached();    seed_answer_note(&client, "11111111-1111-4111-8111-00000000a001");    let answer = read_record(&client, "note", "11111111-1111-4111-8111-00000000a001");    assert_eq!(answer["id"], json!("11111111-1111-4111-8111-00000000a001"));    assert_eq!(answer["author_kind"], json!("agent"));    assert_eq!(        answer["threads"],        json!([]),        "a record nobody has commented on answers the EMPTY conversation, never a missing key"    );}/// A root carries its replies, oldest first, and a reply is never drawn as a/// root of its own.#[test]fn a_reply_belongs_to_its_root_and_is_not_a_thread_of_its_own() {    let (_dir, client) = attached();    seed_answer_note(&client, "11111111-1111-4111-8111-00000000a001");    seed_comment(        &client,        Say {            id: "11111111-1111-4111-8111-00000000b001",            record_id: "11111111-1111-4111-8111-00000000a001",            parent: None,            body: "Which meter did you read?",            author_kind: "user",            created_at: "2026-09-02T09:00:00.000Z",            resolved_at: None,        },    );    seed_comment(        &client,        Say {            id: "11111111-1111-4111-8111-00000000b002",            record_id: "11111111-1111-4111-8111-00000000a001",            parent: Some("11111111-1111-4111-8111-00000000b001"),            body: "The one by the stairs.",            author_kind: "agent",            created_at: "2026-09-02T10:00:00.000Z",            resolved_at: None,        },    );    let threads = read_record(&client, "note", "11111111-1111-4111-8111-00000000a001")["threads"].clone();    assert_eq!(threads.as_array().map(Vec::len), Some(1), "one thread");    assert_eq!(threads[0]["id"], json!("11111111-1111-4111-8111-00000000b001"));    assert_eq!(threads[0]["authorKind"], json!("user"));    assert_eq!(threads[0]["replies"][0]["id"], json!("11111111-1111-4111-8111-00000000b002"));    assert_eq!(        threads[0]["replies"][0]["authorKind"],        json!("agent"),        "WHO replied is the whole point: an assistant answering back is the re-ask completing"    );}/// `resolvedAt` travels as the INSTANT. A boolean would be the same fact with/// the only interesting half thrown away.#[test]fn a_settled_thread_says_when_it_was_settled() {    let (_dir, client) = attached();    seed_answer_note(&client, "11111111-1111-4111-8111-00000000a001");    seed_comment(        &client,        Say {            id: "11111111-1111-4111-8111-00000000b001",            record_id: "11111111-1111-4111-8111-00000000a001",            parent: None,            body: "This is out of date.",            author_kind: "user",            created_at: "2026-09-02T09:00:00.000Z",            resolved_at: Some("2026-09-03T09:00:00.000Z"),        },    );    let threads = read_record(&client, "note", "11111111-1111-4111-8111-00000000a001")["threads"].clone();    assert_eq!(threads[0]["resolvedAt"], json!("2026-09-03T09:00:00.000Z"));}/// `create_comment` writes the anchor as JSON text; a seed says the same thing/// the tool would have.fn pin(client: &ClientController, comment_id: &str, anchor: &str) {    exec(        client,        "UPDATE cotton_comments SET anchor = ? WHERE id = ?",        &[anchor, comment_id],    );}/// One comment on the answer note, with nothing said about where it points.fn seed_one(client: &ClientController, id: &str) {    seed_answer_note(client, "11111111-1111-4111-8111-00000000a001");    seed_comment(        client,        Say {            id,            record_id: "11111111-1111-4111-8111-00000000a001",            parent: None,            body: "This tile is the wrong wall.",            author_kind: "user",            created_at: "2026-09-02T09:00:00.000Z",            resolved_at: None,        },    );}fn thread_of(client: &ClientController) -> Value {    read_record(client, "note", "11111111-1111-4111-8111-00000000a001")["threads"][0].clone()}/// A PIN. The point is fractions of the picture, so the same pin lands in the/// same place on a phone, a Mac and a shared page — and the phone cannot draw/// one at all unless the whole anchor comes back.#[test]fn a_pin_on_a_picture_comes_back_whole() {    let (_dir, client) = attached();    let comment = "11111111-1111-4111-8111-00000000b010";    seed_one(&client, comment);    pin(        &client,        comment,        r#"{"attachment":{"kind":"photo","id":"photo:3f9a0000000000000000000000000000000000000000000000000000000000ab"},"x":0.42,"y":0.61}"#,    );    let anchor = thread_of(&client)["anchor"].clone();    assert_eq!(anchor["attachment"]["kind"], json!("photo"));    assert_eq!(        anchor["attachment"]["id"],        json!("photo:3f9a0000000000000000000000000000000000000000000000000000000000ab")    );    assert_eq!(anchor["x"], json!(0.42));    assert_eq!(anchor["y"], json!(0.61));}/// A TEXT anchor travels whole too, and not as a `quotedText` string: one/// shape for both kinds of anchor is what lets a screen ask which it is.#[test]fn a_text_anchor_travels_whole() {    let (_dir, client) = attached();    let comment = "11111111-1111-4111-8111-00000000b011";    seed_one(&client, comment);    pin(&client, comment, r#"{"quote":"two hundred and eleven units"}"#);    assert_eq!(        thread_of(&client)["anchor"],        json!({ "quote": "two hundred and eleven units" })    );}/// A comment anchored to nothing answers null, and a key that is always there.#[test]fn a_comment_with_no_anchor_answers_null() {    let (_dir, client) = attached();    seed_one(&client, "11111111-1111-4111-8111-00000000b012");    let thread = thread_of(&client);    assert_eq!(thread["anchor"], Value::Null);    assert!(        thread.as_object().is_some_and(|row| row.contains_key("anchor")),        "the key is part of the shape, never a missing one a decoder has to guess at"    );}/// The join is keyed on BOTH halves of the address. A comment on a different/// record — even one with the same id under another kind — is another/// conversation.#[test]fn the_conversation_is_this_records_and_no_other() {    let (_dir, client) = attached();    seed_answer_note(&client, "11111111-1111-4111-8111-00000000a001");    seed_answer_note(&client, "11111111-1111-4111-8111-00000000a002");    seed_comment(        &client,        Say {            id: "11111111-1111-4111-8111-00000000b003",            record_id: "11111111-1111-4111-8111-00000000a002",            parent: None,            body: "About the other one.",            author_kind: "user",            created_at: "2026-09-02T09:00:00.000Z",            resolved_at: None,        },    );    assert_eq!(read_record(&client, "note", "11111111-1111-4111-8111-00000000a001")["threads"], json!([]));    assert_eq!(        read_record(&client, "note", "11111111-1111-4111-8111-00000000a002")["threads"]            .as_array()            .map(Vec::len),        Some(1)    );}/// Threads come back oldest-first, which is reading order.#[test]fn threads_are_oldest_first() {    let (_dir, client) = attached();    seed_answer_note(&client, "11111111-1111-4111-8111-00000000a001");    seed_comment(        &client,        Say {            id: "11111111-1111-4111-8111-00000000b004",            record_id: "11111111-1111-4111-8111-00000000a001",            parent: None,            body: "Second.",            author_kind: "user",            created_at: "2026-09-04T09:00:00.000Z",            resolved_at: None,        },    );    seed_comment(        &client,        Say {            id: "11111111-1111-4111-8111-00000000b005",            record_id: "11111111-1111-4111-8111-00000000a001",            parent: None,            body: "First.",            author_kind: "user",            created_at: "2026-09-02T09:00:00.000Z",            resolved_at: None,        },    );    let threads = read_record(&client, "note", "11111111-1111-4111-8111-00000000a001")["threads"].clone();    assert_eq!(threads[0]["id"], json!("11111111-1111-4111-8111-00000000b005"));    assert_eq!(threads[1]["id"], json!("11111111-1111-4111-8111-00000000b004"));}// ── The argument spelling both halves must agree on ─────────────────────────/// **A read's arguments arrive nested OR flat, and mean the same thing.**////// The app sends `{"kind":"note","id":"…"}`; the boundary took/// `{"args":{…}}` only, from 4a onwards, so 26 of the 31 argument-taking read/// call sites were answering with an EMPTY map — and each read turned that into/// its own refusal, which each screen drew as "this isn't here any more" over a/// row the replica was holding. Measured on the simulator in 4k, on a note and/// on a todo.////// This case is the one that would have caught it: it drives BOTH spellings/// through `read_args`, the way `cotton_call` does, and asserts they answer the/// same record. A screen test could not — `ScriptedCore` answers by method name/// and never looks at the request.#[test]fn a_reads_arguments_may_be_nested_or_flat_and_mean_the_same_thing() {    let (_dir, client) = attached();    seed_answer_note(&client, "11111111-1111-4111-8111-00000000a001");    let entry = crate::phone::reads::read_for("read.record").expect("read.record is declared");    let flat = json!({ "kind": "note", "id": "11111111-1111-4111-8111-00000000a001" });    let nested = json!({ "args": { "kind": "note", "id": "11111111-1111-4111-8111-00000000a001" } });    let from_flat = crate::phone::answer_read(&client, entry, &crate::phone::read_args(&flat))        .expect("the flat spelling answers");    let from_nested = crate::phone::answer_read(&client, entry, &crate::phone::read_args(&nested))        .expect("the nested spelling answers");    assert_eq!(from_flat["id"], json!("11111111-1111-4111-8111-00000000a001"));    assert_eq!(        from_flat, from_nested,        "the two spellings are one request — an app that nests and an app that does not must \         get the same record"    );}/// A request that names NEITHER is still the empty map, and the read refuses in/// its own words rather than answering somebody else's row.#[test]fn a_request_with_no_arguments_at_all_is_still_refused_by_the_read() {    let (_dir, client) = attached();    let entry = crate::phone::reads::read_for("read.record").expect("read.record is declared");    let refusal = crate::phone::answer_read(&client, entry, &crate::phone::read_args(&json!({})))        .expect_err("a record read with no kind is a refusal");    assert!(        refusal.contains("kind"),        "the refusal names what is missing, and this one read `{refusal}`"    );}// ── The rule the module doc argues for, made a rule ─────────────────────────/// **A reply whose parent is gone is left out, not promoted to a root.**////// The module doc says so; nothing held it, and the `continue` that does it was/// never reached with an orphan in either direction. The simplification it/// guards against is a plausible one — "a reply with no parent must be a root"/// — and it compiles, passes every other case here, and draws somebody's/// follow-up sentence as the thing that OPENED the thread. Which is a person/// being quoted saying something they did not say.#[test]fn a_reply_whose_parent_is_gone_is_left_out_rather_than_drawn_as_the_thread() {    let (_dir, client) = attached();    seed_answer_note(&client, "11111111-1111-4111-8111-00000000a001");    // A whole thread that is fine, so the answer is not empty for some other    // reason.    seed_comment(        &client,        Say {            id: "11111111-1111-4111-8111-00000000b001",            record_id: "11111111-1111-4111-8111-00000000a001",            parent: None,            body: "Is that more than last month?",            author_kind: "user",            created_at: "2026-09-01T10:00:00.000Z",            resolved_at: None,        },    );    // And a reply pointing at a root that is not in the file.    //    // Getting one there takes deliberate work, and that is worth writing down:    // `create_comment` checks the parent, the table's own FOREIGN KEY refuses a    // dangling one, and its ON DELETE CASCADE takes the replies with the root.    // The one thing that switches those off is a MIGRATION rebuild step    // (`ForeignKeys::Off`), which is exactly where rows get moved between    // tables and a cascade does not fire. So the state is rare, not    // impossible — and the branch that handles it is one plausible    // simplification away from being deleted.    exec(&client, "PRAGMA foreign_keys = OFF", &[]);    seed_comment(        &client,        Say {            id: "11111111-1111-4111-8111-00000000b002",            record_id: "11111111-1111-4111-8111-00000000a001",            parent: Some("11111111-1111-4111-8111-00000000bdead"),            body: "It is, by about a fifth.",            author_kind: "agent",            created_at: "2026-09-01T10:05:00.000Z",            resolved_at: None,        },    );    exec(&client, "PRAGMA foreign_keys = ON", &[]);    let record = read_record(&client, "note", "11111111-1111-4111-8111-00000000a001");    let threads = record["threads"].as_array().expect("threads").clone();    assert_eq!(        threads.len(),        1,        "the orphan is not a second thread; got {threads:?}"    );    assert_eq!(        threads[0]["id"],        json!("11111111-1111-4111-8111-00000000b001")    );    assert_eq!(        threads[0]["replies"],        json!([]),        "and it is not adopted by the thread that is standing"    );    assert!(        !record.to_string().contains("It is, by about a fifth."),        "the orphan's words are left out entirely rather than drawn under \         somebody else's opening line"    );}/// A project, and one record filed into it.fn seed_project_link(client: &ClientController, record_kind: &str, record_id: &str) {    let workspace = workspace(client);    exec(        client,        "INSERT INTO cotton_memory_projects (id, workspace_id, slug, name, status, \         created_at, updated_at) VALUES (?, ?, 'garden-shed', 'Garden Shed', 'active', ?, ?)",        &[            "project-shed",            &workspace,            "2026-09-01T00:00:00.000Z",            "2026-09-01T00:00:00.000Z",        ],    );    exec(        client,        "INSERT INTO cotton_project_links (id, workspace_id, project_id, record_kind, \         record_id, applied_by, created_at, updated_at, pinned, position) \         VALUES ('link-shed', ?, 'project-shed', ?, ?, 'user', ?, ?, 0, 1.0)",        &[            &workspace,            record_kind,            record_id,            "2026-09-01T00:00:00.000Z",            "2026-09-01T00:00:00.000Z",        ],    );}/// The note sheet's kebab files a note into a project, and a screen has one/// read — so the roster and the note's own memberships ride on `read.record`.#[test]fn a_note_carries_the_roster_and_its_own_project_links() {    let (_dir, client) = attached();    let id = "11111111-1111-4111-8111-00000000b001";    seed_answer_note(&client, id);    seed_project_link(&client, "note", id);    let answer = read_record(&client, "note", id);    let roster = answer["projects"].as_array().expect("the roster");    assert!(        roster.iter().any(|project| project["slug"] == json!("garden-shed")),        "the roster names every project the sheet can offer: {roster:?}"    );    assert_eq!(answer["projectLinks"][0]["projectId"], json!("project-shed"));    assert_eq!(answer["projectLinks"][0]["recordKind"], json!("note"));}/// A journal page is read with `kind: note` — both live in `cotton_notes` — but/// its links are written under `journal`. The ROW's kind is the one asked, or a/// filed page would read as filed nowhere.#[test]fn a_journal_page_s_links_are_read_under_the_row_s_own_kind() {    let (_dir, client) = attached();    let id = "11111111-1111-4111-8111-00000000b002";    let workspace = workspace(&client);    exec(        &client,        "INSERT INTO cotton_notes (id, workspace_id, body, kind, journal_date, author_kind, \         created_at, updated_at) VALUES (?, ?, 'A quiet day.', 'journal', '2026-09-02', 'user', ?, ?)",        &[            id,            &workspace,            "2026-09-02T09:00:00.000Z",            "2026-09-02T09:00:00.000Z",        ],    );    seed_project_link(&client, "journal", id);    let answer = read_record(&client, "note", id);    assert_eq!(answer["projectLinks"].as_array().map(Vec::len), Some(1));    assert_eq!(answer["projectLinks"][0]["recordKind"], json!("journal"));}