//! `read.person`, over a real replica.//!//! Every fixture is synthetic — a person who does not exist, a number nobody//! answers, an invoice for nothing//! ([nothing-real-ever-goes-in-cotton-s-public-tree]).//!//! What these pin is the CLAUSES, because a clause quietly dropped in a port is//! a screen that shows somebody rows they had put away — and because the SQL//! here is written out rather than composed, so nothing but a test that runs it//! can tell whether a column name is real.//!//! They go through [`crate::phone::reads::read_for`], like `day_tests.rs`, and//! not through [`super::person`] directly: the `READS` entry landed on THIS//! branch (`reads.rs`), so the wiring is this lane's to prove. A test that//! called the function by name would pass over a read the app cannot reach.use serde_json::{json, Map, Value};usecrate::shell::client::phone_tests::{args, attached};usecrate::shell::client::ClientController;/// The read under test, reached the way the app reaches it — by METHOD NAME/// through `READS`, so a missing or misnamed entry is a red test rather than a/// screen that answers nothing.typeScreenQuery =fn(&crate::shell::file::ReadFile<'_>, &Map<String, Value>) -> Result<Value, String>;fn query() -> ScreenQuery {let entry = crate::phone::reads::read_for("read.person").expect("read.person is declared");match entry.source {crate::phone::reads::ReadSource::Query(query) => query, _ => panic!("read.person is not a query read"), }}fn read(client: &ClientController, args: &Map<String, Value>) -> Value { client .with_writer(|replica| query()(replica, args)) .unwrap_or_else(|reason| panic!("read.person answered: {reason}"))}fn refuse(client: &ClientController, args: &Map<String, Value>) -> String { client .with_writer(|replica| query()(replica, args)) .expect_err("the read was supposed to refuse")}fn sql(client: &ClientController, statement: &str) { client .with_writer(|replica| { replica .driver .run(&statement.replace("$WS", replica.workspace_id), &[]) .map(|_| ()) .map_err(|error| error.to_string()) }) .expect("the fixture lands");}/// A batch, for the one fixture that has to suspend a CHECK to write the row a/// broken build would have written.fn exec(client: &ClientController, statements: &str) { client .with_writer(|replica| { replica .driver .exec(&statements.replace("$WS", replica.workspace_id)) .map_err(|error| error.to_string()) }) .expect("the fixture lands");}/// The page's own person — never the fixture's `person-a`, so a test says what/// it put there and nothing else.const PERSON: &str = "per-page";fn a_person(client: &ClientController) { sql( client,"INSERT INTO cotton_people (id, workspace_id, full_name, org, city, created_at, updated_at) VALUES ('per-page', '$WS', 'QuietTester', 'NowhereLtd', 'Somewhere', '2026-09-01T00:00:00.000Z', '2026-09-01T00:00:00.000Z')", );// A phone is a handle row since v90. sql( client,"INSERT INTO cotton_person_handles (id, workspace_id, person_id, kind, value, normalised, source, created_at, updated_at) VALUES ('handle-per-page-phone', '$WS', 'per-page', 'phone', '+919000000001', '919000000001', 'manual', '2026-09-01T00:00:00.000Z', '2026-09-01T00:00:00.000Z')", );}fn only(client: &ClientController) -> Value { read(client, &args(&[("id", json!(PERSON))]))}fn ids(list: &Value) -> Vec<&str> { list.as_array() .expect("a list") .iter() .filter_map(|row| row["id"].as_str()) .collect()}// ── the person ──────────────────────────────────────────────────────────────#[test]fn a_person_who_is_not_there_is_null_and_an_archived_one_still_opens() {// `null` rather than a refusal: a stale deep link has to draw "gone", and// an error would make it draw a crash. And ARCHIVING is how somebody leaves// the DIRECTORY, not their own page — the read carries no `archived_at`// filter, so the page still opens with their whole history on it.let (_dir, client) = attached();let gone = read(&client, &args(&[("id", json!("per-absent"))])); assert_eq!(gone["person"], Value::Null); assert!(gone["personNotes"].as_array().expect("a list").is_empty());let archived = read(&client, &args(&[("id", json!("person-archived"))])); assert_eq!(archived["person"]["fullName"], json!("Alpaca Retired")); assert_eq!( archived["person"]["archivedAt"], json!("2026-09-02T00:00:00.000Z") );// And an id nobody passed is refused BY NAME rather than defaulted to// whoever the first row happens to be.let reason = refuse(&client, &Map::new()); assert!(reason.contains("`id`"), "{reason}");}#[test]fn the_gone_branch_answers_the_same_keys_as_the_found_one() {// THE RULE, and why it is a test rather than a habit. Swift's synthesized// `Decodable` calls `decode` — NOT `decodeIfPresent` — for a non-optional// stored property, so a default written beside the property is never// reached on an absent key: the decode THROWS. This branch was one key// short (`faceSuggestionPhotos`), so `PersonRead` threw `.keyNotFound` and// the "this person isn't here any more" screen came out as a load error// with a Try again that could never succeed.//// SORTED rather than in insertion order: the decoder does not care what// order the keys arrive in, so order is not the contract.let (_dir, client) = attached(); a_person(&client);let sorted = |value: &Value| -> Vec<String> {letmut names: Vec<String> = value .as_object() .expect("an object") .keys() .cloned() .collect(); names.sort(); names };let gone = read(&client, &args(&[("id", json!("per-absent"))]));let found = only(&client); assert_eq!(gone["person"], Value::Null); assert_eq!(sorted(&gone), sorted(&found));}#[test]fn half_a_birthday_refuses_rather_than_quietly_losing_the_other_half() {// `parseBirthday`'s drift discipline. The CHECK says both or neither, so a// row with one of them means something wrote past it — and dropping the// half that is there would lose a person's birthday without saying so.let (_dir, client) = attached(); a_person(&client); sql( &client,"INSERT INTO cotton_people (id, workspace_id, full_name, birth_month, birth_day, birth_year, created_at, updated_at) VALUES ('per-born', '$WS', 'DatedTester', 3, 14, 1990, '2026-09-01T00:00:00.000Z', '2026-09-01T00:00:00.000Z')", );let whole = read(&client, &args(&[("id", json!("per-born"))])); assert_eq!(whole["person"]["birthday"], json!({"month": 3, "day": 14, "year": 1990}));// Nobody's birthday is nothing at all, which is not the same as a broken one. assert_eq!(only(&client)["person"]["birthday"], Value::Null);// The CHECK is suspended for one statement on purpose: the whole question// is what this read does with a row that has ALREADY got past it — written// by a build whose constraint had moved, which is the only way one exists. exec( &client,"PRAGMA ignore_check_constraints = ON; INSERT INTO cotton_people (id, workspace_id, full_name, birth_month, created_at, updated_at) VALUES ('per-half', '$WS', 'HalfTester', 3, '2026-09-01T00:00:00.000Z', '2026-09-01T00:00:00.000Z'); PRAGMA ignore_check_constraints = OFF;", );let reason = refuse(&client, &args(&[("id", json!("per-half"))])); assert!(reason.contains("birth_month"), "{reason}");}// RULE (B1, 6 Nov 2026): a person whose birthday the object keeps whole — the month, day and year empty on a signed-in copy — shows it on their page, year or none; the phone's own month and day win where set.#[test]fn a_birthday_the_object_keeps_whole_shows_on_the_page() {use cotton_store::schema::package_shape::{add_served, served_column};let (_dir, client) = attached(); client .with_writer(|replica| {let column = served_column("birthday", "date", false).map_err(|error| error.to_string())?; add_served(replica.driver, "cotton_people", &[column]).map_err(|error| error.to_string()) }) .expect("the copy keeps the object's birthday"); sql( &client,"INSERT INTO cotton_people (id, workspace_id, full_name, birthday, created_at, updated_at) VALUES ('per-whole', '$WS', 'WholeTester', '1988-11-20', '2026-09-01T00:00:00.000Z', '2026-09-01T00:00:00.000Z'), ('per-yearless', '$WS', 'YearlessTester', '--03-02', '2026-09-01T00:00:00.000Z', '2026-09-01T00:00:00.000Z')", ); sql( &client,"INSERT INTO cotton_people (id, workspace_id, full_name, birth_month, birth_day, birthday, created_at, updated_at) VALUES ('per-both', '$WS', 'BothTester', 4, 2, '1988-11-20', '2026-09-01T00:00:00.000Z', '2026-09-01T00:00:00.000Z')", );let page = |id: &str| read(&client, &args(&[("id", json!(id))]))["person"]["birthday"].clone(); assert_eq!(page("per-whole"), json!({"month": 11, "day": 20, "year": 1988})); assert_eq!(page("per-yearless"), json!({"month": 3, "day": 2, "year": Value::Null})); assert_eq!(page("per-both"), json!({"month": 4, "day": 2, "year": Value::Null}));}// ── the notes, and the summary's staleness ──────────────────────────────────#[test]fn the_stream_is_this_person_s_own_notes_by_the_day_they_are_about() {// The order is `noted_at DESC` — the day the note is ABOUT, which an import// sets to long before the row was written. And the stream is scoped by// `person_id` alone: it is the only read on this page that is, because a// person note belongs to a person rather than to a workspace.//// The `noted_at IS NULL` term ahead of it is ported because the service// carries it and SQLite sorts NULLs FIRST — no row can exercise it while// the column is `NOT NULL`, and dropping it here would leave the day the// column loosens with every undated note above everything that happened// this week.let (_dir, client) = attached(); a_person(&client); sql( &client,"INSERT INTO cotton_person_notes (id, person_id, body, noted_at, created_at) VALUES ('pn-old', 'per-page', 'the older line', '2026-08-01T00:00:00.000Z', '2026-09-03T00:00:00.000Z'), ('pn-new', 'per-page', 'the newer line', '2026-09-01T00:00:00.000Z', '2026-09-01T00:00:00.000Z'), ('pn-elsewhere', 'person-a', 'somebody else''s line', '2026-09-09T00:00:00.000Z', '2026-09-09T00:00:00.000Z')", );let answer = only(&client); assert_eq!(ids(&answer["personNotes"]), vec!["pn-new", "pn-old"]); assert_eq!(answer["personNotes"][0]["body"], json!("the newer line"));}#[test]fn the_staleness_cue_counts_when_a_note_arrived_and_never_when_it_happened() {// `created_at`, never `noted_at`. An import writes an OLD `noted_at` with a// FRESH `created_at`, and the cue's question is "has material this summary// never saw reached me since" — which only arrival answers. Counting// `noted_at` here would report nothing at all after an import that just// brought in a year of somebody's history.let (_dir, client) = attached(); sql( &client,"INSERT INTO cotton_people (id, workspace_id, full_name, summary, summary_by, summary_updated_at, created_at, updated_at) VALUES ('per-page', '$WS', 'QuietTester', 'A synthetic paragraph.', 'user', '2026-09-05T00:00:00.000Z', '2026-09-01T00:00:00.000Z', '2026-09-01T00:00:00.000Z')", ); sql( &client,"INSERT INTO cotton_person_notes (id, person_id, body, noted_at, created_at) VALUES ('pn-imported', 'per-page', 'written years ago, filed today', '2019-04-04T00:00:00.000Z', '2026-09-06T00:00:00.000Z'), ('pn-before', 'per-page', 'already in the paragraph', '2026-09-01T00:00:00.000Z', '2026-09-01T00:00:00.000Z')", );let answer = only(&client); assert_eq!(answer["summary"]["summary"]["text"], json!("A synthetic paragraph.")); assert_eq!(answer["summary"]["summary"]["by"], json!("user"));// ONE arrival, and the noun is the person kind's own. assert_eq!(answer["summary"]["staleness"], json!({"count": 1, "noun": "note"}));}#[test]fn a_page_with_no_summary_says_nothing_rather_than_counting_to_zero() {// "Figure or silence": `staleness` is null, never `{count: 0}` — and the// count query is not run at all, because a page with nothing written on it// must not pay for a number nobody will see.let (_dir, client) = attached(); a_person(&client); sql( &client,"INSERT INTO cotton_person_notes (id, person_id, body, noted_at, created_at) VALUES ('pn-1', 'per-page', 'a line', '2026-09-01T00:00:00.000Z', '2026-09-01T00:00:00.000Z')", );let answer = only(&client); assert_eq!(answer["summary"]["summary"]["text"], Value::Null); assert_eq!(answer["summary"]["staleness"], Value::Null);}// ── the edges, and what they point at ───────────────────────────────────────#[test]fn an_edge_written_the_other_way_round_is_still_this_person_s() {// The two-direction OR. Which end of an edge a writer put the person on is// a fact about the writer, not about the person, and half the section would// vanish without it. `person_note` edges are dropped everywhere: those// notes are the stream above, and a second row would be one sentence twice.let (_dir, client) = attached(); a_person(&client); sql( &client,"INSERT INTO cotton_todos (id, workspace_id, title, status, due_at, created_at, updated_at) VALUES ('todo-owed', '$WS', 'Return the ladder', 'open', '2026-09-20T00:00:00.000Z', '2026-09-01T00:00:00.000Z', '2026-09-01T00:00:00.000Z')", ); sql( &client,"INSERT INTO cotton_person_notes (id, person_id, body, noted_at, created_at) VALUES ('pn-linked', 'per-page', 'a kept line', '2026-09-01T00:00:00.000Z', '2026-09-01T00:00:00.000Z')", ); sql( &client,"INSERT INTO cotton_links (id, workspace_id, from_kind, from_id, to_kind, to_id, created_at) VALUES ('lnk-forward', '$WS', 'person', 'per-page', 'todo', 'todo-owed', '2026-09-03T00:00:00.000Z'), ('lnk-backward', '$WS', 'note', 'note-a', 'person', 'per-page', '2026-09-02T00:00:00.000Z'), ('lnk-note', '$WS', 'person', 'per-page', 'person_note', 'pn-linked', '2026-09-01T00:00:00.000Z')", );let answer = only(&client);// Newest edge first. assert_eq!( ids(&answer["links"]), vec!["lnk-forward", "lnk-backward", "lnk-note"] );let facts = &answer["linkedRecordFacts"];// The backward edge resolved to the NOTE, not to the person it was written// from. assert_eq!(facts["lnk-backward"]["title"], json!("First")); assert_eq!(facts["lnk-forward"]["title"], json!("Return the ladder"));// And the person_note edge produced no fact at all. assert_eq!(facts.get("lnk-note"), None);}#[test]fn a_dated_todo_is_scheduled_an_undated_one_is_only_written_down() {// The two readings, and the whole reason `whenKind` exists: a `scheduled`// date can be in the FUTURE and must never go through the relative rule,// which reads "just now" for anything ahead of the clock.let (_dir, client) = attached(); a_person(&client); sql( &client,"INSERT INTO cotton_todos (id, workspace_id, title, status, due_at, created_at, updated_at) VALUES ('todo-dated', '$WS', 'Post the form', 'open', '2026-09-20T09:00:00.000Z', '2026-09-01T00:00:00.000Z', '2026-09-01T00:00:00.000Z'), ('todo-undated', '$WS', 'Someday', 'open', NULL, '2026-09-02T00:00:00.000Z', '2026-09-02T00:00:00.000Z')", ); sql( &client,"INSERT INTO cotton_links (id, workspace_id, from_kind, from_id, to_kind, to_id, created_at) VALUES ('lnk-dated', '$WS', 'person', 'per-page', 'todo', 'todo-dated', '2026-09-03T00:00:00.000Z'), ('lnk-undated', '$WS', 'person', 'per-page', 'todo', 'todo-undated', '2026-09-02T00:00:00.000Z')", );let facts = only(&client)["linkedRecordFacts"].clone(); assert_eq!(facts["lnk-dated"]["whenKind"], json!("scheduled")); assert_eq!(facts["lnk-dated"]["whenIso"], json!("2026-09-20T09:00:00.000Z")); assert_eq!(facts["lnk-undated"]["whenKind"], json!("made")); assert_eq!(facts["lnk-undated"]["whenIso"], json!("2026-09-02T00:00:00.000Z"));}#[test]fn a_linked_picture_carries_its_key_and_a_document_its_type_and_pages() {// The page draws a linked photo as a PRINT and a document as a SHEET with// its type typed on it — so the key (never the bytes) and the paper's kind// travel with the fact. A film carries its poster, never the film.let (_dir, client) = attached(); a_person(&client);let sha = "0".repeat(63) + "7"; sql( &client, &format!("INSERT INTO cotton_photos (id, workspace_id, key, sha256, content_type, size_bytes, taken_at, created_at, updated_at) VALUES ('photo:{sha}', '$WS', 'k/{sha}', '{sha}', 'image/jpeg', 1, '2026-08-01T00:00:00.000Z', '2026-09-01T00:00:00.000Z', '2026-09-01T00:00:00.000Z')" ), );let doc_sha = "a".repeat(64); sql( &client, &format!("INSERT INTO cotton_documents (id, workspace_id, title, original_name, mime, byte_size, sha256, storage_path, page_count, status_changed_at, doc_type, created_at, updated_at, status) VALUES ('doc-linked', '$WS', 'Lease', 'lease.pdf', 'application/pdf', 10, '{doc_sha}', 'docs/lease.pdf', 4, '2026-09-01T00:00:00.000Z', 'legal', '2026-09-01T00:00:00.000Z', '2026-09-01T00:00:00.000Z', 'ready')"), ); sql( &client, &format!("INSERT INTO cotton_links (id, workspace_id, from_kind, from_id, to_kind, to_id, created_at) VALUES ('lnk-photo', '$WS', 'person', 'per-page', 'photo', 'photo:{sha}', '2026-09-03T00:00:00.000Z'), ('lnk-doc', '$WS', 'document', 'doc-linked', 'person', 'per-page', '2026-09-02T00:00:00.000Z')"), );let facts = only(&client)["linkedRecordFacts"].clone(); assert_eq!(facts["lnk-photo"]["key"], json!(format!("k/{sha}"))); assert_eq!(facts["lnk-doc"]["docType"], json!("legal")); assert_eq!(facts["lnk-doc"]["pageCount"], json!(4));}#[test]fn a_record_that_is_gone_says_nothing() {// A record that has GONE simply answers nothing: an edge outlives what// it points at, and a person's page must still open.let (_dir, client) = attached(); a_person(&client); sql( &client,"INSERT INTO cotton_links (id, workspace_id, from_kind, from_id, to_kind, to_id, created_at) VALUES ('lnk-gone', '$WS', 'person', 'per-page', 'todo', 'todo-deleted', '2026-09-02T00:00:00.000Z')", );let answer = only(&client); assert_eq!(answer["linkedRecordFacts"].get("lnk-gone"), None);// The EDGE is still answered, though — the chip falls back to the bare// kind rather than disappearing. assert!(ids(&answer["links"]).contains(&"lnk-gone"));}// ── the todos section ───────────────────────────────────────────────────────#[test]fn the_todos_are_the_linked_ones_and_never_the_whole_workspace_pool() {// The app reads every todo in the file and filters on the client. The ids// are pushed down here instead — the same answer, without shipping a// person's whole todo list to draw the two owed with one human. `status !=// 'dropped'` comes with it: a todo somebody let go must not come back onto// their page. A DONE one travels, because the device leaves it in the// linked list, which is history with this person.let (_dir, client) = attached(); a_person(&client); sql( &client,"INSERT INTO cotton_todos (id, workspace_id, title, status, due_at, created_at, updated_at) VALUES ('todo-open', '$WS', 'Owed', 'open', '2026-09-20T00:00:00.000Z', '2026-09-01T00:00:00.000Z', '2026-09-01T00:00:00.000Z'), ('todo-done', '$WS', 'Already done', 'done', NULL, '2026-09-01T00:00:00.000Z', '2026-09-01T00:00:00.000Z'), ('todo-let-go', '$WS', 'Never mind', 'dropped', NULL, '2026-09-01T00:00:00.000Z', '2026-09-01T00:00:00.000Z'), ('todo-elsewhere', '$WS', 'Nothing to do with them', 'open', NULL, '2026-09-01T00:00:00.000Z', '2026-09-01T00:00:00.000Z')", ); sql( &client,"INSERT INTO cotton_links (id, workspace_id, from_kind, from_id, to_kind, to_id, created_at) VALUES ('lnk-open', '$WS', 'person', 'per-page', 'todo', 'todo-open', '2026-09-03T00:00:00.000Z'), ('lnk-done', '$WS', 'person', 'per-page', 'todo', 'todo-done', '2026-09-02T00:00:00.000Z'), ('lnk-let-go', '$WS', 'person', 'per-page', 'todo', 'todo-let-go', '2026-09-01T00:00:00.000Z')", );let answer = only(&client);let listed = ids(&answer["todos"]); assert!(listed.contains(&"todo-open"), "{listed:?}"); assert!(listed.contains(&"todo-done"), "{listed:?}"); assert!(!listed.contains(&"todo-let-go"), "{listed:?}");// The fixture's own three todos are in this workspace and none of them is// linked here — which is exactly what the narrowing is for. assert!(!listed.contains(&"todo-a"), "{listed:?}");}// ── the suggestions, and the directory that names them ──────────────────────#[test]fn a_question_from_either_side_is_asked_and_a_merged_pair_leaves_the_directory() {// The card belongs on BOTH people's pages, so the read matches either// column. And `archived_at IS NULL` on the directory is what stops the card// ever reading "Same as ?": a merge archives the imported side, so an// already-answered pair disappears rather than asking about somebody who is// no longer there.let (_dir, client) = attached(); a_person(&client); sql( &client,"INSERT INTO cotton_people (id, workspace_id, full_name, created_at, updated_at) VALUES ('per-other', '$WS', 'OtherTester', '2026-09-01T00:00:00.000Z', '2026-09-01T00:00:00.000Z')", ); sql( &client,"INSERT INTO cotton_person_suggestions (id, workspace_id, person_id, candidate_id, reason, score, state, decided_at, created_at, updated_at) VALUES ('sug-mine', '$WS', 'per-page', 'per-other', 'name_exact', 0.9, 'open', NULL, '2026-09-01T00:00:00.000Z', '2026-09-01T00:00:00.000Z'), ('sug-theirs', '$WS', 'per-other', 'per-page', 'name_fuzzy', 0.4, 'open', NULL, '2026-09-02T00:00:00.000Z', '2026-09-02T00:00:00.000Z'), ('sug-answered', '$WS', 'per-page', 'person-a', 'name_fuzzy', 0.99, 'different', '2026-09-03T00:00:00.000Z', '2026-09-03T00:00:00.000Z', '2026-09-03T00:00:00.000Z')", );let answer = only(&client);// Both sides, best score first — and the answered one is gone, however// confident it was. assert_eq!(ids(&answer["suggestions"]), vec!["sug-mine", "sug-theirs"]);let named: Vec<&str> = answer["people"] .as_array() .expect("a list") .iter() .filter_map(|row| row["id"].as_str()) .collect(); assert!(named.contains(&"per-other"), "{named:?}");// The fixture's archived person is NOT offered: a merged-away side must// disappear from the card instead of being named on it. assert!(!named.contains(&"person-archived"), "{named:?}");}// ── the projects ────────────────────────────────────────────────────────────#[test]fn an_archived_project_still_travels_so_its_membership_can_be_taken_off() {// The chips under the name draw only the ACTIVE projects — the device// filters — but the Projects sheet has to be able to unlink from an// archived one, and filtering here would make that membership impossible to// remove. `cotton_memory_projects` retires by `status`; it has no// `archived_at` column to filter on in the first place.let (_dir, client) = attached(); a_person(&client); sql( &client,"INSERT INTO cotton_project_links (id, workspace_id, project_id, record_kind, record_id, applied_by, created_at, updated_at) VALUES ('plink-live', '$WS', 'project-a', 'person', 'per-page', 'user', '2026-09-01T00:00:00.000Z', '2026-09-01T00:00:00.000Z'), ('plink-old', '$WS', 'project-old', 'person', 'per-page', 'user', '2026-09-02T00:00:00.000Z', '2026-09-02T00:00:00.000Z')", );let answer = only(&client);let listed = ids(&answer["projects"]); assert!(listed.contains(&"project-a"), "{listed:?}"); assert!(listed.contains(&"project-old"), "{listed:?}"); assert_eq!(ids(&answer["projectLinks"]), vec!["plink-live", "plink-old"]);// The note's own membership belongs to the note, never to this person. assert!(!ids(&answer["projectLinks"]).contains(&"link-a"));}// ── the calls ───────────────────────────────────────────────────────────────#[test]fn six_calls_come_back_for_a_section_that_draws_five() {// The sixth row is never drawn. It is how the section knows whether "See// all" has anything behind it, without a second query counting a log that// can hold a year of daily calls — which is also why the row shows no// count.let (_dir, client) = attached(); a_person(&client);for n in1..=8 { sql( &client, &format!("INSERT INTO cotton_call_log (id, workspace_id, source, external_id, provider, direction, outcome, started_at, duration_s, person_id, created_at, updated_at) VALUES ('call-{n}', '$WS', 'ios_call_history', 'ext-{n}', 'com.apple.telephony', 'in', 'answered', '2026-09-0{n}T10:00:00.000Z', 60, 'per-page', '2026-09-0{n}T10:00:00.000Z', '2026-09-0{n}T10:00:00.000Z')" ), ); } sql( &client,"INSERT INTO cotton_call_log (id, workspace_id, source, external_id, provider, direction, outcome, started_at, duration_s, person_id, created_at, updated_at) VALUES ('call-someone-else', '$WS', 'ios_call_history', 'ext-x', 'com.apple.telephony', 'out', 'missed', '2026-09-09T10:00:00.000Z', 0, 'person-a', '2026-09-09T10:00:00.000Z', '2026-09-09T10:00:00.000Z')", );let calls = only(&client)["calls"].clone();let listed = ids(&calls); assert_eq!(listed.len(), 6, "{listed:?}");// Newest first, and never somebody else's call. assert_eq!(listed[0], "call-8"); assert!(!listed.contains(&"call-someone-else"), "{listed:?}");}// ── the faces ───────────────────────────────────────────────────────────────#[test]fn only_the_faces_still_asking_come_back_nearest_first() {// `person_id IS NULL` is the whole question: a NAMED face is a fact, not a// suggestion, and answering one about a face the owner already settled// would ask them the same thing twice. A DISMISSED suggestion needs no// clause of its own — dismissing CLEARS `suggested_person_id`, which is// what the `IS NOT NULL` leg already refuses.let (_dir, client) = attached(); a_person(&client);let sha = |n: u8| "0".repeat(63) + &n.to_string();for n in1..=2u8 { sql( &client, &format!("INSERT INTO cotton_photos (id, workspace_id, key, sha256, content_type, size_bytes, taken_at, created_at, updated_at) VALUES ('photo:{s}', '$WS', 'k/{s}', '{s}', 'image/jpeg', 1, '2026-08-0{n}T00:00:00.000Z', '2026-09-01T00:00:00.000Z', '2026-09-01T00:00:00.000Z')", s = sha(n) ), ); } sql( &client, &format!("INSERT INTO cotton_media_faces (id, workspace_id, record_kind, record_id, source, source_id, x, y, w, h, person_id, suggested_person_id, suggested_distance, created_at, updated_at) VALUES ('face-near', '$WS', 'photo', 'photo:{a}', 'cotton', 's-1', 0.1, 0.1, 0.2, 0.2, NULL, 'per-page', 0.2, '2026-09-01T00:00:00.000Z', '2026-09-01T00:00:00.000Z'), ('face-far', '$WS', 'photo', 'photo:{b}', 'cotton', 's-2', 0.3, 0.3, 0.2, 0.2, NULL, 'per-page', 0.7, '2026-09-01T00:00:00.000Z', '2026-09-01T00:00:00.000Z'), ('face-named', '$WS', 'photo', 'photo:{a}', 'cotton', 's-3', 0.5, 0.5, 0.2, 0.2, 'per-page', NULL, NULL, '2026-09-01T00:00:00.000Z', '2026-09-01T00:00:00.000Z')", a = sha(1), b = sha(2) ), );let answer = only(&client); assert_eq!(ids(&answer["faceSuggestions"]), vec!["face-near", "face-far"]);// And the pictures they are in came back in ONE read, not one per row. assert_eq!(answer["faceSuggestionPhotos"].as_array().expect("a list").len(), 2);}// ── the conversation ────────────────────────────────────────────────────────#[test]fn a_thread_whose_contact_was_never_matched_is_still_found_by_the_number() {// A thread knows a CONTACT, and a contact may know a person. The link is// checked first and the PHONE second — a person whose number Cotton has but// whose contact was never matched still has a conversation, and hiding it// because a join column is null would be the page lying about its own data.// The number is normalised through the same rule `phone_e164` was written// with, so `+91 90000 00001` and `919000000001` are one number.let (_dir, client) = attached(); a_person(&client); sql( &client,"INSERT INTO cotton_msg_contacts (id, workspace_id, phone_e164, display_name, person_id, created_at, updated_at) VALUES ('contact-unmatched', '$WS', '919000000001', 'QuietTester', NULL, '2026-09-01T00:00:00.000Z', '2026-09-01T00:00:00.000Z')", ); sql( &client,"INSERT INTO cotton_msg_threads (id, workspace_id, contact_id, kind, last_message_at, last_message_preview, archived, created_at, updated_at) VALUES ('thread-theirs', '$WS', 'contact-unmatched', 'dm', '2026-09-08T10:00:00.000Z', 'see you then', 0, '2026-09-01T00:00:00.000Z', '2026-09-08T10:00:00.000Z')", );let thread = only(&client)["thread"].clone(); assert_eq!(thread["id"], json!("thread-theirs")); assert_eq!(thread["lastMessagePreview"], json!("see you then")); assert_eq!(thread["contactDisplayName"], json!("Quiet Tester"));}#[test]fn an_archived_conversation_and_a_group_are_never_this_person_s_card() {// The app reads the LIVE thread list; the archive is a separate place you// go. And a group carries no contact and belongs to no one person — a card// for one on somebody's page would be a private conversation that is not// private.let (_dir, client) = attached(); a_person(&client); sql( &client,"INSERT INTO cotton_msg_contacts (id, workspace_id, phone_e164, display_name, person_id, created_at, updated_at) VALUES ('contact-theirs', '$WS', '919000000002', 'QuietTester', 'per-page', '2026-09-01T00:00:00.000Z', '2026-09-01T00:00:00.000Z')", ); sql( &client,"INSERT INTO cotton_msg_threads (id, workspace_id, contact_id, kind, title, last_message_at, archived, created_at, updated_at) VALUES ('thread-put-away', '$WS', 'contact-theirs', 'dm', NULL, '2026-09-08T10:00:00.000Z', 1, '2026-09-01T00:00:00.000Z', '2026-09-08T10:00:00.000Z'), ('thread-group', '$WS', NULL, 'group', 'A synthetic group', '2026-09-09T10:00:00.000Z', 0, '2026-09-01T00:00:00.000Z', '2026-09-09T10:00:00.000Z')", ); assert_eq!(only(&client)["thread"], Value::Null);}#[test]fn an_imported_archive_arrives_read_and_never_lights_the_dot() {// `origin = 'live'` is load bearing: bring five years of WhatsApp history// into a conversation and every one of those rows is inbound and unread by// the cursor's reckoning — a three-digit badge on a thread nobody owes a// reply to. A row the person HID, and one before they cleared the chat, are// out for the same reason: the page must not count back what they made// disappear.let (_dir, client) = attached(); a_person(&client); sql( &client,"INSERT INTO cotton_msg_contacts (id, workspace_id, phone_e164, display_name, person_id, created_at, updated_at) VALUES ('contact-theirs', '$WS', '919000000003', 'QuietTester', 'per-page', '2026-09-01T00:00:00.000Z', '2026-09-01T00:00:00.000Z')", ); sql( &client,"INSERT INTO cotton_msg_threads (id, workspace_id, contact_id, kind, last_message_at, read_seq, cleared_before, archived, created_at, updated_at) VALUES ('thread-theirs', '$WS', 'contact-theirs', 'dm', '2026-09-08T10:00:00.000Z',10, '2026-09-02T00:00:00.000Z', 0, '2026-09-01T00:00:00.000Z', '2026-09-08T10:00:00.000Z')", ); sql( &client,"INSERT INTO cotton_msg_messages (id, thread_id, workspace_id, direction, channel, origin, body, sent_at, created_at, seq, hidden_at) VALUES ('msg-unread', 'thread-theirs', '$WS', 'in', 'cotton', 'live', 'are you free?', '2026-09-08T10:00:00.000Z', '2026-09-08T10:00:00.000Z', 11, NULL), ('msg-imported', 'thread-theirs', '$WS', 'in', 'whatsapp', 'imported', 'from the archive', '2026-09-08T09:00:00.000Z', '2026-09-08T09:00:00.000Z', 12, NULL), ('msg-hidden', 'thread-theirs', '$WS', 'in', 'cotton', 'live', 'deleted for me', '2026-09-08T09:30:00.000Z', '2026-09-08T09:30:00.000Z', 13, '2026-09-08T09:31:00.000Z'), ('msg-cleared', 'thread-theirs', '$WS', 'in', 'cotton', 'live', 'before the clear', '2026-09-01T09:00:00.000Z', '2026-09-01T09:00:00.000Z', 14, NULL), ('msg-read', 'thread-theirs', '$WS', 'in', 'cotton', 'live', 'already seen', '2026-09-07T09:00:00.000Z', '2026-09-07T09:00:00.000Z', 9, NULL)", );let thread = only(&client)["thread"].clone(); assert_eq!(thread["id"], json!("thread-theirs")); assert_eq!(thread["unreadCount"], json!(1));// The service is the NEWEST visible message's: the hidden one is newer// than the imported WhatsApp row but the person made it disappear. assert_eq!(thread["channel"], json!("cotton"));}#[test]fn the_thread_says_which_service_its_newest_message_came_over() {// The page's Message action hands off to WhatsApp for a WhatsApp// conversation and to Messages otherwise, so the read has to say which —// and a thread with no message yet says nothing rather than guessing.let (_dir, client) = attached(); a_person(&client); sql( &client,"INSERT INTO cotton_msg_contacts (id, workspace_id, phone_e164, display_name, person_id, created_at, updated_at) VALUES ('contact-theirs', '$WS', '919000000004', 'QuietTester', 'per-page', '2026-09-01T00:00:00.000Z', '2026-09-01T00:00:00.000Z')", ); sql( &client,"INSERT INTO cotton_msg_threads (id, workspace_id, contact_id, kind, last_message_at, archived, created_at, updated_at) VALUES ('thread-theirs', '$WS', 'contact-theirs', 'dm', '2026-09-08T10:00:00.000Z',0, '2026-09-01T00:00:00.000Z', '2026-09-08T10:00:00.000Z')", ); assert_eq!(only(&client)["thread"]["channel"], Value::Null); sql( &client,"INSERT INTO cotton_msg_messages (id, thread_id, workspace_id, direction, channel, origin, body, sent_at, created_at, seq) VALUES ('msg-old', 'thread-theirs', '$WS', 'in', 'sms', 'imported', 'an old text', '2026-08-01T10:00:00.000Z', '2026-08-01T10:00:00.000Z', 1), ('msg-new', 'thread-theirs', '$WS', 'in', 'whatsapp', 'imported', 'see you', '2026-09-08T10:00:00.000Z', '2026-09-08T10:00:00.000Z', 2)", ); assert_eq!(only(&client)["thread"]["channel"], json!("whatsapp"));}/// RULE: Between-us totals use only known actual one-row movements linked to/// this person, stay separate by currency, and a positive total says they owe.#[test]fn between_us_is_one_row_per_currency_and_positive_when_they_owe() {let (_dir, client) = attached(); a_person(&client); sql(&client, "INSERT INTO cotton_money_transactions (id, workspace_id, occurred_on, description, counterparty_person_id, amount_minor, amount_known, direction, currency, for_period, status, between_us, moves_money, created_at, updated_at) VALUES ('owed-inr', '$WS', '2026-10-01', 'Shared dinner', 'per-page', 5000, 1, 'out', 'INR', '2026-10', 'actual', 1, 0, '2026-10-01T00:00:00.000Z', '2026-10-01T00:00:00.000Z'), ('paid-inr', '$WS', '2026-10-02', 'Paid back', 'per-page', 1200, 1, 'in', 'INR', '2026-10', 'actual', 1, 1, '2026-10-02T00:00:00.000Z', '2026-10-02T00:00:00.000Z'), ('owed-eur', '$WS', '2026-10-03', 'Tickets', 'per-page', 700, 1, 'out', 'EUR', '2026-10', 'actual', 1, 0, '2026-10-03T00:00:00.000Z', '2026-10-03T00:00:00.000Z'), ('future', '$WS', '2026-10-04', 'Expected', 'per-page', 9999, 1, 'out', 'INR', '2026-10', 'expected', 1, 0, '2026-10-04T00:00:00.000Z', '2026-10-04T00:00:00.000Z'), ('unknown', '$WS', '2026-10-05', 'Unknown', 'per-page', NULL, 0, 'out', 'INR', '2026-10', 'actual', 1, 0, '2026-10-05T00:00:00.000Z', '2026-10-05T00:00:00.000Z'), ('elsewhere', '$WS', '2026-10-06', 'Not between us', 'per-page', 300, 1, 'out', 'INR', '2026-10', 'actual', 0, 1, '2026-10-06T00:00:00.000Z', '2026-10-06T00:00:00.000Z')"); assert_eq!( only(&client)["betweenUs"], json!([ {"currency": "EUR", "balanceMinor": 700}, {"currency": "INR", "balanceMinor": 3800}, ]) );}/// RULE: conversations are never merged across channels — a person with a WhatsApp DM and an Instagram DM has two conversations on their page, one per channel per counterpart.#[test]fn a_whatsapp_dm_and_an_instagram_dm_are_two_conversations() {let (_dir, client) = attached(); a_person(&client); sql( &client,"INSERT INTO cotton_msg_contacts (id, workspace_id, phone_e164, display_name, person_id, created_at, updated_at) VALUES ('contact-wa', '$WS', '919000000001', 'QuietTester', 'per-page', '2026-09-01T00:00:00.000Z', '2026-09-01T00:00:00.000Z'), ('contact-ig', '$WS', NULL, 'quiet.tester', 'per-page', '2026-09-01T00:00:00.000Z', '2026-09-01T00:00:00.000Z')", ); sql( &client,"INSERT INTO cotton_msg_threads (id, workspace_id, contact_id, kind, last_message_at, archived, created_at, updated_at) VALUES ('thread-wa', '$WS', 'contact-wa', 'dm', '2026-09-08T10:00:00.000Z',0, '2026-09-01T00:00:00.000Z', '2026-09-08T10:00:00.000Z'), ('thread-ig', '$WS', 'contact-ig', 'dm', '2026-09-09T10:00:00.000Z',0, '2026-09-01T00:00:00.000Z', '2026-09-09T10:00:00.000Z')", ); sql( &client,"INSERT INTO cotton_msg_messages (id, thread_id, workspace_id, direction, channel, origin, body, sent_at, created_at, seq) VALUES ('msg-wa', 'thread-wa', '$WS', 'in', 'whatsapp', 'live', 'hello', '2026-09-08T10:00:00.000Z', '2026-09-08T10:00:00.000Z', 1)", );let page = only(&client);let conversations = page["conversations"].as_array().expect("a list").clone();let chats: Vec<&str> = conversations.iter().filter_map(|row| row["chatId"].as_str()).collect(); assert_eq!(chats, vec!["thread-ig", "thread-wa"], "{page}"); assert_eq!(conversations[1]["channel"], json!("whatsapp")); assert!(conversations.iter().all(|row| row["kind"] == json!("dm")));// The page's one `thread` card is still a single chat, never a merge. assert!(page["thread"]["id"].as_str().is_some_and(|id| chats.contains(&id)), "{page}");}