Cotton code
1117 lines · 50.3 KB · RustRaw
//! `/people/person/[id]` — one human, as ONE answer.//!//! The page asks fourteen questions, and every one of them is a read of the//! same file: the person, the//! notes kept about them, every edge `cotton_links` holds, the Photos//! importer's open "Same as …?" questions, the directory that names the other//! side of one, the summary and how stale it is, the projects they are in, the//! open todos linked to them, their recent calls, the faces waiting to be//! confirmed, their conversation and//! what each linked record is called. A phone that made fourteen round trips//! for one screen would paint it in fourteen stages; this read is the same//! answers, once.//!//! It is a PORT, clause for clause, of `[id].tsx` and the services under it —//! `peopleService`, `linksService`, `personSuggestionsService`,//! `summariesService`, `memoriesService.listProjects`,//! `projectsService.listLinksForRecord`, `todosService.listTodos`,//! `callLogService.listCalls`, `mediaFacesService.listFaceSuggestions`,//! `messagesService.listThreads`//! — and the clause comments say which clause is load bearing and why. A clause//! quietly dropped in a port is a screen that shows somebody rows they had put//! away, or a page that says "Same as ?" about a person who no longer exists.//!//! Three of those fourteen are NARROWED here rather than restated: the app//! reads the whole todo pool, the whole thread list and every open claim in the//! workspace and then filters in JavaScript, because a service that already//! existed answered a bigger question. The predicate is pushed into SQL//! instead — the same answer, without shipping every todo, every conversation//! and every debt a person has to draw one page of them. Each says so where it//! happens.//!//! Two decisions travel WITH the prose rather than being made here. A note's//! display title is `stripMarkdown`'s first line and a capture's is//! `splitTitleNotes`', and neither rule has a Rust twin: computing one here//! would be a second answer to what a record is called, exactly what//! [`super::day::journal`] refuses when it hands a page's body over whole. So//! those two kinds carry their prose and the device applies its own rule.//!//! One rule runs through all of it: **an empty answer and a failed read are//! different facts**. A query that cannot run returns `Err`; nothing answers an//! empty list to hide a failure. The single exception is stated where it lives://! a person who is not there answers `null`, because a stale deep link must//! draw "gone" and never a crash.use rusqlite::types::Value as SqlValue;use serde_json::{json, Map, Value};use crate::shell::file::ReadFile;use cotton_core::constants::SummaryKind;use cotton_core::rules::summaries::{staleness_from, ISummary, SummaryRead};use cotton_core::rules::people::birthday::{columns_sql, whole_held, Birthday, PEOPLE_TABLE};use cotton_store::driver::Row;// A JSON text column that holds a LIST, read as one. THE one reading, declared// beside the alarms list in `day.rs` and imported here rather than restated:// `phones` and `emails` are read in both files, and three different readings of// those two columns landed in one PR before this import existed.use super::day;use super::day::json_list;/// The workspace id as a bound parameter — every read here is scoped to the one/// file this phone holds.////// A twin of [`super::day`]'s, copied rather than promoted on purpose: `day.rs`/// and `reads.rs` are being edited on the lane beside this one, and a shared/// private helper would put both lanes in the same bytes for four lines.fn workspace(replica: &ReadFile<'_>) -> SqlValue {    SqlValue::Text(replica.workspace_id.to_string())}/// A required id argument, refused by name rather than defaulted.fn id_arg(args: &Map<String, Value>, what: &str) -> Result<String, String> {    args.get("id")        .and_then(Value::as_str)        .map(str::trim)        .filter(|id| !id.is_empty())        .map(str::to_string)        .ok_or_else(|| format!("`id` is the {what} to read"))}/// One bound id.fn text(value: &str) -> SqlValue {    SqlValue::Text(value.to_string())}/// `?,?,?` for an `IN` list of `count` bound values.////// Written rather than composed from the ids themselves: an id in this file is/// the owner's own data and never goes into SQL as a literal.fn placeholders(count: usize) -> String {    vec!["?"; count].join(",")}/// A trimmed column, or `None` when it is absent or blank.////// `title?.trim() || fallback` appears on five kinds in `resolveFacts`, and/// "the owner typed only spaces" has to read as "they named nothing" on all/// five or the row draws a blank caption.fn trimmed(raw: Option<&str>) -> Option<&str> {    raw.map(str::trim).filter(|value| !value.is_empty())}/// The amounts one person and the owner owe each other, one currency at a/// time. A positive balance means the person owes the owner: money lent out/// is an `out` row, money borrowed is an `in` row.fn between_us(replica: &ReadFile<'_>, person_id: &str) -> Result<Vec<Value>, String> {    let counterparty = cotton_store::soft_refs::soft_value("t.counterparty_person_id", "cotton_people");    let rows = replica.driver.all(        &format!("SELECT currency, SUM(CASE direction WHEN 'out' THEN amount_minor ELSE -amount_minor END) AS balance_minor           FROM cotton_money_transactions t          WHERE workspace_id = ? AND {counterparty} = ?            AND between_us = 1 AND status = 'actual' AND amount_known = 1 AND trashed_at IS NULL            AND amount_minor IS NOT NULL AND currency IS NOT NULL          GROUP BY currency ORDER BY currency ASC"),        &[workspace(replica), text(person_id)],    ).map_err(|error| error.to_string())?;    Ok(rows        .into_iter()        .filter_map(|row| {            Some(json!({                "currency": row.text("currency")?,                "balanceMinor": row.int("balance_minor")?,            }))        })        .collect())}// ── the person ──────────────────────────────────────────────────────────────/// The birthday triple as one fact — `parseBirthday`'s own discipline.////// Half a birthday means the CHECK moved (or something wrote past it), and/// quietly dropping it would lose a person's birthday without saying so. The/// TypeScript THROWS; this refuses the read, which is the same fact reaching/// the same screen.////// Past that floor, the birthday is `cotton_core::rules::people::birthday`'s/// one rule: the three columns where set, else the date a signed-in copy/// keeps whole from the object — what the views and the reminders answer.fn birthday(row: &Row) -> Result<Value, String> {    let (month, day) = (row.int("birth_month"), row.int("birth_day"));    if month.is_some() != day.is_some() {        return Err(format!(            "Unexpected value for cotton_people.birth_month/birth_day: {{\"month\":{month:?},\"day\":{day:?}}}. Both must be set, or neither."        ));    }    Ok(Birthday::of_row(row).map_or(Value::Null, |birthday| json!({        "month": birthday.month,        "day": birthday.day,        "year": birthday.year,    })))}/// The columns the page draws a person with — `toIPerson`, minus one.////// `device_contact_snapshot` is deliberately NOT here. It is the address-book/// mirror's own working state, no part of this page renders it, and reading it/// would mean porting `parseDeviceContactSnapshot`'s refusal — whose whole/// purpose is to stop the SYNC path treating a snapshot it cannot read as/// absent. A display read that refuses on it would take the person's page down/// for a fact the page never shows./// `phones` and `emails` are read off `cotton_person_handles` (v90) in the/// shape the columns had, so the page's answer did not change./// The birthday's columns are [`columns_sql`]'s, `whole_held` saying whether/// this copy keeps the object's whole date.fn person_columns(whole_held: bool) -> String {    format!(        "id, workspace_id, full_name, {}, org, role_title, city, \     summary, summary_by, summary_updated_at, contact_source, device_contact_id, {}, \     timezone, avatar_key, archived_at, created_at, updated_at",        cotton_core::rules::people::handles::phones_and_emails_sql("cotton_people.id"),        columns_sql(PEOPLE_TABLE, whole_held)    )}/// One person as the page renders them.fn person_out(row: &Row) -> Result<Value, String> {    Ok(json!({        "id": row.text("id"),        "workspaceId": row.text("workspace_id"),        "fullName": row.text("full_name"),        "phones": json_list(row.text("phones")),        "emails": json_list(row.text("emails")),        "org": row.text("org"),        "roleTitle": row.text("role_title"),        "city": row.text("city"),        // The person row's own copy, which `peopleKeys` can lag an assistant's        // write by. The SUMMARY block reads the `summary` field below instead        // (R68) — this one travels because the edit sheet's remount key is        // `updatedAt` beside the summary's stamp, and because the app's model        // carries it.        "summary": row.text("summary"),        "summaryBy": row.text("summary_by"),        "summaryUpdatedAt": row.text("summary_updated_at"),        "contactSource": row.text("contact_source"),        // `null` is what "Cotton made this person by hand" looks like, and it        // is the whole condition for the "Add to iPhone" menu item.        "deviceContactId": row.text("device_contact_id"),        "birthday": birthday(row)?,        "timezone": row.text("timezone"),        "avatarKey": row.text("avatar_key"),        "archivedAt": row.text("archived_at"),        "createdAt": row.text("created_at"),        "updatedAt": row.text("updated_at"),    }))}// ── the linked records ──────────────────────────────────────────────────────/// One edge, reduced to the record on the OTHER end of it.struct LinkRef {    /// The edge's own id — the stable row key, since one record can link twice.    link_id: String,    kind: String,    id: String,}/// `linkedRecordsForPerson` — the record on the other end of every edge/// touching this person.////// `person_note` edges are DROPPED, everywhere: a person's own notes render as/// the notes stream above, and a second row for one would be the same sentence/// twice on one page.fn link_refs(rows: &[Row], person_id: &str) -> Vec<LinkRef> {    rows.iter()        .filter_map(|row| {            let from_kind = row.text("from_kind")?;            let from_id = row.text("from_id")?;            let is_from = from_kind == "person" && from_id == person_id;            let (kind, id) = if is_from {                (row.text("to_kind")?, row.text("to_id")?)            } else {                (from_kind, from_id)            };            if kind == "person_note" {                return None;            }            Some(LinkRef {                link_id: row.text("id")?.to_string(),                kind: kind.to_string(),                id: id.to_string(),            })        })        .collect()}/// What ONE linked record is called and when it was — `resolveFacts`, kind by/// kind.////// Two readings run through the whole table, and the difference is what a row/// draws:////// * `"scheduled"` is a date that can be in the FUTURE — a todo's due date, an///   event's start — and must never go through the app's relative rule, which///   reads "just now" for anything ahead of the clock;/// * `"made"` is always behind us: when the thing was written, taken, posted or///   held.////// A record that has GONE answers nothing at all and its chip falls back to the/// bare kind. That is not an error and must never become one: an edge outlives/// the record it points at, and a person's page must still open.fn record_fact(replica: &ReadFile<'_>, reference: &LinkRef) -> Result<Option<Value>, String> {    let id = text(&reference.id);    let one = |sql: &str| -> Result<Option<Row>, String> {        replica            .driver            .get(sql, std::slice::from_ref(&id))            .map_err(|error| error.to_string())    };    let fact = match reference.kind.as_str() {        "todo" => {            let Some(row) = one("SELECT title, due_at, created_at FROM cotton_todos WHERE id = ? AND trashed_at IS NULL")?            else {                return Ok(None);            };            // A DATED todo is a thing on a day; an undated one is only a thing            // somebody wrote down, so it states when it was written.            match row.text("due_at") {                Some(due) => json!({ "title": row.text("title"), "whenIso": due, "whenKind": "scheduled" }),                None => json!({                    "title": row.text("title"),                    "whenIso": row.text("created_at"),                    "whenKind": "made",                }),            }        }        "event" => {            // The CONTAINER, and only here: since the flattening an event is            // the one kind that still lives in one, and the row reads "Event in            // Family" when the file knows the calendar's name. A `LEFT JOIN`            // rather than an inner one — a calendar since deleted must not take            // the event's own caption with it.            let Some(row) = one(                "SELECT e.title AS title, e.starts_at AS starts_at, c.name AS container                   FROM cotton_events e                   LEFT JOIN cotton_collections c ON c.id = e.collection_id                  WHERE e.id = ? AND e.trashed_at IS NULL",            )?            else {                return Ok(None);            };            json!({                "title": row.text("title"),                "container": row.text("container"),                "whenIso": row.text("starts_at"),                "whenKind": "scheduled",            })        }        "note" => {            let Some(row) = one("SELECT title, body, created_at FROM cotton_notes WHERE id = ? AND trashed_at IS NULL")?            else {                return Ok(None);            };            // The BODY travels and the title is not derived here. A note filed            // from a capture carries no title of its own and borrows its first            // line — after `stripMarkdown`, at sixty units — and that rule is            // the device's. Computing it here would be a second answer to what            // a note is called.            json!({                "title": trimmed(row.text("title")),                "body": row.text("body").unwrap_or_default(),                "whenIso": row.text("created_at"),                "whenKind": "made",            })        }        "person" => {            let Some(row) = one("SELECT full_name, created_at FROM cotton_people WHERE id = ?")?            else {                return Ok(None);            };            json!({                "title": row.text("full_name"),                "whenIso": row.text("created_at"),                "whenKind": "made",            })        }        "transaction" => {            let Some(row) = one(                "SELECT description, occurred_on FROM cotton_money_transactions WHERE id = ?",            )?            else {                return Ok(None);            };            // `occurred_on`, never `created_at`: backdating a payment must move            // it on this list too, or the person's page disagrees with the            // register about when they paid.            json!({                "title": row.text("description"),                "whenIso": row.text("occurred_on"),                "whenKind": "made",            })        }        "document" => {            let Some(row) = one(                "SELECT title, original_name, document_date, created_at, doc_type, page_count                   FROM cotton_documents                  WHERE id = ? AND trashed_at IS NULL",            )?            else {                return Ok(None);            };            // The day the paper is ABOUT — a statement's month, a contract's            // date — falling back to when it was filed only when the paper            // never said. The file's own name stands in until the profile pass            // names it.            json!({                "title": trimmed(row.text("title")).or_else(|| row.text("original_name")),                "whenIso": row.text("document_date").or_else(|| row.text("created_at")),                "whenKind": "made",                // What KIND of paper it is and how many pages: the person page                // draws a document as a sheet with its type line typed on it.                "docType": row.text("doc_type"),                "pageCount": row.int("page_count"),            })        }        "photo" => {            let Some(row) = one("SELECT caption, taken_at, key FROM cotton_photos WHERE id = ? AND trashed_at IS NULL")?            else {                return Ok(None);            };            // `taken_at`, never `created_at`: the row is written when the            // media-index sweep reaches the picture, which can be months after            // the afternoon in it.            // The object KEY travels so the page can draw the picture as a            // print: bytes never cross, the device asks `media.ensure` for a            // path to it, exactly as the photo library's tiles do.            json!({                "title": trimmed(row.text("caption")),                "whenIso": row.text("taken_at"),                "whenKind": "made",                "key": row.text("key"),            })        }        "video" => {            let Some(row) =                one("SELECT caption, taken_at, poster_key FROM cotton_videos WHERE id = ? AND trashed_at IS NULL")?            else {                return Ok(None);            };            // A film's POSTER, never the film — a print is a still.            json!({                "title": trimmed(row.text("caption")),                "whenIso": row.text("taken_at"),                "whenKind": "made",                "posterKey": row.text("poster_key"),            })        }        // Every kind `cotton_links` admits is above. `person_note` never        // reaches here (`link_refs` drops it), and a kind a later schema adds        // falls to the bare label rather than to a query against a table this        // build has never heard of.        _ => return Ok(None),    };    Ok(Some(fact))}// ── the conversation ────────────────────────────────────────────────────────/// EVERY conversation with the person — one chat per channel per/// counterpart, never merged (owner ruling 7 Oct 2026, note 1e50d25b): their/// direct chats on each channel (WhatsApp, Instagram, iMessage …, matched/// exactly as [`thread`] matches: the contact naming them, else a contact/// naming nobody that carries one of their numbers) and the groups they are/// a member of. Each is `{channel, chatId, lastAt, kind}`, freshest first;/// `channel` is the newest message's, null for a chat with no message yet.fn conversations(replica: &ReadFile<'_>, person_id: &str, phones: &Value) -> Result<Value, String> {    let numbers: Vec<String> = phones        .as_array()        .map(Vec::as_slice)        .unwrap_or_default()        .iter()        .filter_map(Value::as_str)        .filter_map(cotton_core::import::phone::normalize_phone)        .collect();    // The contact's person, derived by who(handle) (PEOPLE BUILD 1).    let person = cotton_store::protocol::who::contact_person_sql(cotton_store::protocol::who::shared_held(&replica.driver), "c");    let nobody = format!("{person} IS NULL");    let phone_leg = if numbers.is_empty() {        String::new()    } else {        format!(" OR ({nobody} AND c.phone_e164 IN ({}))", placeholders(numbers.len()))    };    let mut params = vec![workspace(replica), text(person_id)];    params.extend(numbers.iter().map(|number| text(number)));    params.push(text(person_id));    let rows = replica        .driver        .all(            &format!(                "SELECT t.id AS id, t.kind AS kind, t.last_message_at AS last_at,                        (SELECT m.channel FROM cotton_msg_messages m                          WHERE m.thread_id = t.id AND m.hidden_at IS NULL                          ORDER BY m.sent_at DESC LIMIT 1) AS channel                   FROM cotton_msg_threads t                  WHERE t.workspace_id = ?                    AND t.archived = 0                    AND ((t.kind = 'dm' AND EXISTS (                            SELECT 1 FROM cotton_msg_contacts c                             WHERE c.id = t.contact_id AND ({person} = ?{phone_leg})))                      OR (t.kind = 'group' AND EXISTS (                            SELECT 1 FROM cotton_msg_thread_participants tp                              JOIN cotton_msg_contacts c ON c.id = tp.contact_id                             WHERE tp.thread_id = t.id AND tp.left_at IS NULL AND {person} = ?)))                  ORDER BY (t.last_message_at IS NULL) ASC, t.last_message_at DESC, t.id ASC"            ),            &params,        )        .map_err(|error| error.to_string())?;    Ok(Value::Array(        rows.iter()            .map(|row| {                json!({                    "channel": row.text("channel"),                    "chatId": row.text("id"),                    "lastAt": row.text("last_at"),                    "kind": row.text("kind"),                })            })            .collect(),    ))}/// This person's chat, if one exists.////// `threadForPerson`, with its predicate pushed into SQL: the app calls/// `listThreads` for the whole workspace — six queries, unread counts and/// channel badges for every conversation in the file — to find ONE thread.////// The rules it encodes, each of them load bearing:////// * a thread does not know a person, it knows a CONTACT, so the join is///   through `cotton_msg_contacts.person_id` FIRST;/// * and only THEN the phone. 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///   match is on `normalize_phone` — the port of `normalizeContactPhone`, so a///   handle and `phone_e164` can never disagree about what a number is;/// * a contact that ALREADY names a different person is not theirs, which is///   why the phone leg is `person_id IS NULL`;/// * GROUP threads never match — they carry no contact and belong to no one///   person;/// * `archived = 0`: the app reads the live list, and the archive is a separate///   place you go. An archived conversation draws no card;/// * the freshest `last_message_at` wins, NULLs last (SQLite sorts them first),///   with the id as the tie-break so the same file answers the same thread///   twice.fn thread(replica: &ReadFile<'_>, person_id: &str, phones: &Value) -> Result<Value, String> {    let numbers: Vec<String> = phones        .as_array()        .map(Vec::as_slice)        .unwrap_or_default()        .iter()        .filter_map(Value::as_str)        .filter_map(cotton_core::import::phone::normalize_phone)        .collect();    // The contact's person, derived by who(handle) (PEOPLE BUILD 1).    let person = cotton_store::protocol::who::contact_person_sql(cotton_store::protocol::who::shared_held(&replica.driver), "c");    let phone_leg = if numbers.is_empty() {        String::new()    } else {        // A contact naming a person who is gone names no one: its number is        // free to be this person's.        format!(" OR ({person} IS NULL AND c.phone_e164 IN ({}))", placeholders(numbers.len()))    };    let mut params = vec![workspace(replica), text(person_id)];    params.extend(numbers.iter().map(|number| text(number)));    let row = replica        .driver        .get(            &format!(                "SELECT t.id AS id, t.last_message_at AS last_message_at,                        t.last_message_preview AS last_message_preview,                        c.display_name AS contact_display_name,                        c.phone_e164 AS contact_phone_e164                   FROM cotton_msg_threads t                   JOIN cotton_msg_contacts c ON c.id = t.contact_id                  WHERE t.workspace_id = ?                    AND t.archived = 0                    AND t.kind = 'dm'                    AND ({person} = ?{phone_leg})                  ORDER BY (t.last_message_at IS NULL) ASC, t.last_message_at DESC, t.id ASC                  LIMIT 1"            ),            &params,        )        .map_err(|error| error.to_string())?;    let Some(row) = row else {        // No thread, no card. There is no owner-side "start a chat" path in        // this app, so a link for somebody Cotton has never heard from would        // lead nowhere — silence is the honest state.        return Ok(Value::Null);    };    let thread_id = row.text("id").unwrap_or_default().to_string();    // Unread = LIVE inbound rows past the thread's read cursor. `origin =    // 'live'` is load bearing: an imported archive arrives READ, and counting    // five years of WhatsApp history as unread would put a three-digit badge on    // a conversation nobody owes a reply to. `seq IS NOT NULL` because a row    // the server has not numbered is one nobody else has seen; `hidden_at` and    // `cleared_before` because a row the person made disappear must not be    // counted back onto their page.    let unread = replica        .driver        .get(            "SELECT COUNT(*) AS n               FROM cotton_msg_messages m               JOIN cotton_msg_threads t ON t.id = m.thread_id              WHERE m.workspace_id = ?                AND m.thread_id = ?                AND m.direction = 'in' AND m.origin = 'live'                AND m.seq IS NOT NULL AND m.seq > t.read_seq                AND m.hidden_at IS NULL AND m.trashed_at IS NULL                AND (t.cleared_before IS NULL OR m.sent_at > t.cleared_before)",            &[workspace(replica), text(&thread_id)],        )        .map_err(|error| error.to_string())?        .and_then(|row| row.int("n"))        .unwrap_or(0);    // Which service the conversation is on, read off its NEWEST message — the    // index on `(thread_id, sent_at DESC)` answers it in one seek. The page's    // Message action hands off to that app (WhatsApp for a WhatsApp thread,    // Messages otherwise); Cotton itself sends nothing. `null` for a thread    // with no message yet.    let channel = replica        .driver        .get(            "SELECT channel FROM cotton_msg_messages              WHERE thread_id = ? AND hidden_at IS NULL AND trashed_at IS NULL              ORDER BY sent_at DESC              LIMIT 1",            &[text(&thread_id)],        )        .map_err(|error| error.to_string())?        .and_then(|row| row.text("channel").map(str::to_string));    Ok(json!({        "id": thread_id,        "channel": channel,        "lastMessageAt": row.text("last_message_at"),        // Whole, never clipped: `previewOf` flattens and clamps at 90 on the        // device, and clipping here would be a second answer to how long a        // preview is.        // The slip's own line: Markdown read as prose, a marker in its words.        "lastMessagePreview": row            .text("last_message_preview")            .filter(|line| !line.trim().is_empty())            .map(|line| cotton_core::messages::display::list_line(Some(line))),        "unreadCount": unread,        "contactDisplayName": row.text("contact_display_name"),        // The card's lead falls back to the contact's own line when a thread        // was created before its first message, and that line is the number.        "contactPhoneE164": row.text("contact_phone_e164"),    }))}// ── the page ────────────────────────────────────────────────────────────────/// `/people/person/[id]` — the person page's fourteen queries as one answer.////// Everything the screen draws, in one object: the person and the quiet facts/// under their name, the "Same as …?" questions the Photos importer left, how/// to reach them, their chat, their recent calls, the open todos owed with/// them, the faces waiting to be/// confirmed, the summary and its staleness cue, the notes kept about them, the/// projects they are in, and every linked record with what it is called.////// **A person who is not there answers `null` and the rest answers empty.** A/// stale deep link must draw "gone", and a refusal would make it draw a crash —/// the same reading [`super::day::event`] takes of an event that has been/// deleted. **An ARCHIVED person still answers their row**: archiving takes/// somebody out of the directory, not off their own page, and the screen has/// their history to show either way.pub fn person(replica: &ReadFile<'_>, args: &Map<String, Value>) -> Result<Value, String> {    let id = id_arg(args, "person")?;    // NO `archived_at IS NULL`, and no workspace clause either: this is the    // page's own row, addressed by its primary key, exactly as `getPerson` is.    let held = whole_held(replica.driver).map_err(|error| error.to_string())?;    let row = replica        .driver        .get(            &format!("SELECT {} FROM cotton_people WHERE id = ?", person_columns(held)),            &[text(&id)],        )        .map_err(|error| error.to_string())?;    let Some(row) = row else {        return Ok(json!({            "person": Value::Null,            "personNotes": [],            "links": [],            "linkedRecordFacts": {},            "suggestions": [],            "people": [],            "summary": Value::Null,            "projects": [],            "projectLinks": [],            "todos": [],            "calls": [],            "faceSuggestions": [],            // EVERY key the found branch emits, including this one. Swift's            // synthesized `Decodable` calls `decode`, not `decodeIfPresent`,            // for a non-optional stored property, so a default is never reached            // on an absent key: `faceSuggestionPhotos: [FacePhoto] = []` threw            // `.keyNotFound` here and the "this person isn't here any more"            // screen came out as a load failure with a Try again that could            // never succeed. The two branches emit the same key SET, and            // `person_tests.rs` asserts it rather than trusting this comment.            "faceSuggestionPhotos": [],            "thread": Value::Null,            "conversations": [],            "betweenUs": [],        }));    };    let person = person_out(&row)?;    // The context stream, newest first. `noted_at IS NULL` FIRST in the sort is    // load bearing: SQLite sorts NULLs first, so without it every undated note    // would sit above every dated one.    let notes = replica        .driver        .all(            "SELECT id, person_id, body, noted_at, created_at               FROM cotton_person_notes              WHERE person_id = ?              ORDER BY noted_at IS NULL, noted_at DESC",            &[text(&id)],        )        .map_err(|error| error.to_string())?;    // Every edge touching this person, in EITHER direction — the two-direction    // OR is load bearing, because an edge may be written either way round and    // the writer's choice is not a fact about the person.    let link_rows = replica        .driver        .all(            "SELECT id, workspace_id, from_kind, from_id, to_kind, to_id, created_at               FROM cotton_links              WHERE (from_kind = ? AND from_id = ?)                 OR (to_kind = ? AND to_id = ?)              ORDER BY created_at DESC",            &[text("person"), text(&id), text("person"), text(&id)],        )        .map_err(|error| error.to_string())?;    let refs = link_refs(&link_rows, &id);    let mut facts = Map::new();    for reference in &refs {        if let Some(fact) = record_fact(replica, reference)? {            facts.insert(reference.link_id.clone(), fact);        }    }    // The open questions about who this person even IS, from EITHER side: the    // card belongs on both people's pages, and which of the two the Photos    // importer made is a fact of the row rather than of who is looking.    let suggestions = replica        .driver        .all(            "SELECT id, workspace_id, person_id, candidate_id, reason, score, state,                    decided_at, created_at, updated_at               FROM cotton_person_suggestions              WHERE state = 'open' AND (person_id = ? OR candidate_id = ?)              ORDER BY score DESC, created_at DESC, id ASC",            &[text(&id), text(&id)],        )        .map_err(|error| error.to_string())?;    // The directory, which is how the other side of a suggestion gets a NAME.    // `archived_at IS NULL` is load bearing: a merge archives the imported    // side, so an already-merged pair disappears from the card rather than    // rendering "Same as ?" — which is worse than silence. Two columns and no    // more, because naming the other side is all this page asks of it.    let directory = replica        .driver        .all(            "SELECT id, full_name FROM cotton_people              WHERE workspace_id = ? AND archived_at IS NULL              ORDER BY full_name ASC",            &[workspace(replica)],        )        .map_err(|error| error.to_string())?;    // The summary, under the summary layer's OWN root (R68) — the block reads    // this and the edit sheet is SEEDED from it, never from `person.summary`,    // whose cache entry can lag an assistant's write.    //    // The staleness count is `created_at`, never `noted_at`: the question is    // "has material this summary never saw ARRIVED since", and an import writes    // an old `noted_at` with a fresh `created_at`. The `>` is pushed into SQL    // as a COUNT, the same way the server's twin does it, and the read is    // SKIPPED entirely when nothing has been written — a page with no summary    // must not pay for a count nobody will see.    let summary_updated_at = row.text("summary_updated_at").filter(|at| !at.is_empty());    let arrivals = match summary_updated_at {        None => 0,        Some(at) => replica            .driver            .get(                "SELECT COUNT(*) AS n FROM cotton_person_notes                  WHERE person_id = ? AND created_at > ?",                &[text(&id), text(at)],            )            .map_err(|error| error.to_string())?            .and_then(|row| row.int("n"))            .unwrap_or(0),    };    let summary = SummaryRead {        summary: ISummary {            kind: SummaryKind::Person,            id: id.clone(),            text: row.text("summary").map(str::to_string),            by: row.text("summary_by").map(str::to_string),            updated_at: summary_updated_at.map(str::to_string),        },        // `staleness_from`, not a count of its own: "figure or silence" and the        // NOUN are one decision, and the app's cue reads the same function.        staleness: staleness_from(SummaryKind::Person, arrivals),    };    // ARCHIVED PROJECTS INCLUDED. The chips under the name draw only the active    // ones — the device filters — but the Projects sheet on this page has to be    // able to UNLINK from an archived project, and filtering here would make    // that membership impossible to remove. `cotton_memory_projects` retires by    // `status`, not by an `archived_at` stamp; it has no such column.    //    // ONE reading of the pair, shared with the other four detail reads —    // `day::record_projects` is where it lives, and this page was the original    // it was lifted from. Two copies is how the membership note came to be read    // on none of the five: the sheet is kind-agnostic and its rows must be too.    let (projects, project_links) = day::record_projects(replica, "person", &id)?;    // The todos linked to them. `listTodos` is the whole workspace pool of    // open and done todos, filtered to this person's edges on the client; the    // ids are pushed down here instead — the same answer, without shipping    // every todo a person has to draw the few owed with one human. The    // `due_at IS NULL` half of its ORDER BY comes along, for the reason the    // notes' does: SQLite would otherwise put every undated todo first.    //    // DONE rows travel. The device promotes only the OPEN ones into the Todos    // section and leaves the rest in the linked list, which is history with    // this person and is what that section is for.    let todo_ids: Vec<&str> = refs        .iter()        .filter(|reference| reference.kind == "todo")        .map(|reference| reference.id.as_str())        .collect();    let todos = if todo_ids.is_empty() {        Vec::new()    } else {        let mut params = vec![workspace(replica)];        params.extend(todo_ids.iter().map(|id| text(id)));        replica            .driver            .all(                &format!(                    "SELECT id, title, status, due_at, recurrence_id, created_at                       FROM cotton_todos                      WHERE workspace_id = ? AND trashed_at IS NULL AND status IN ('open', 'done')                        AND id IN ({})                      ORDER BY due_at IS NULL, due_at ASC, created_at ASC",                    placeholders(todo_ids.len())                ),                &params,            )            .map_err(|error| error.to_string())?    };    // Their recent calls. SIX rows for a section that shows FIVE: the sixth 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. It is    // never drawn — and it is why the section shows no COUNT, since "6" over a    // log of two hundred is wrong in exactly the direction that makes somebody    // stop looking.    let calls = cotton_tools::mcp::handlers::calls::read_calls_for_person(        replica.driver,replica.workspace_id,&id,    ).map_err(|error|error.to_string())?.into_iter().take(6).collect::<Vec<_>>();    // "Is this <name>?" — the faces the Mac thinks show them, waiting for a yes    // or a no. `person_id IS NULL` is the whole question (a named face is a    // fact, not a suggestion), and a DISMISSED suggestion needs no clause of    // its own because dismissing CLEARS `suggested_person_id`. Nearest first.    let face_rows = replica        .driver        .all(            "SELECT id, record_kind, record_id, x, y, w, h, suggested_person_id,                    suggested_distance               FROM cotton_media_faces              WHERE workspace_id = ?                AND person_id IS NULL                AND suggested_person_id IS NOT NULL                AND suggested_person_id = ?                AND record_id NOT IN (SELECT id FROM cotton_photos WHERE trashed_at IS NOT NULL UNION ALL SELECT id FROM cotton_videos WHERE trashed_at IS NOT NULL)              ORDER BY suggested_distance ASC, record_id ASC, id ASC",            &[workspace(replica), text(&id)],        )        .map_err(|error| error.to_string())?;    // The pictures those faces are in — ONE read for all of them, never a query    // per row. A face whose picture has gone still answers its row; the tile is    // simply absent, exactly as the app's `photos.get(...) ?? null` leaves it.    // DEDUPED, because two suggested faces can be in one picture and `faces.ts`    // dedupes before it asks — an `IN` list naming the same id twice is one row    // back and one wasted placeholder, but the list is what the next reader    // copies.    let mut photo_ids: Vec<&str> = Vec::new();    for row in &face_rows {        if row.text("record_kind") != Some("photo") {            continue;        }        if let Some(record_id) = row.text("record_id") {            if !photo_ids.contains(&record_id) {                photo_ids.push(record_id);            }        }    }    let photos = if photo_ids.is_empty() {        Vec::new()    } else {        let mut params = vec![workspace(replica)];        params.extend(photo_ids.iter().map(|id| text(id)));        replica            .driver            .all(                &format!(                    // `mediaFilters.ts:151-159`'s own order. Nothing on this                    // page reads the list in order — the tiles are looked up by                    // the face's `record_id` — but an unordered read is a                    // clause dropped in a port, and the next consumer would                    // inherit the loss rather than the rule.                    "SELECT id, key, content_type, preview, taken_at FROM cotton_photos                      WHERE workspace_id = ? AND trashed_at IS NULL AND id IN ({})                      ORDER BY taken_at DESC, id ASC",                    placeholders(photo_ids.len())                ),                &params,            )            .map_err(|error| error.to_string())?    };    let phones = person["phones"].clone();    Ok(json!({        "person": person,        "personNotes": notes            .iter()            .map(|row| json!({                "id": row.text("id"),                "personId": row.text("person_id"),                "body": row.text("body"),                "notedAt": row.text("noted_at"),                "createdAt": row.text("created_at"),            }))            .collect::<Vec<Value>>(),        "links": link_rows            .iter()            .map(|row| json!({                "id": row.text("id"),                "workspaceId": row.text("workspace_id"),                "fromKind": row.text("from_kind"),                "fromId": row.text("from_id"),                "toKind": row.text("to_kind"),                "toId": row.text("to_id"),                "createdAt": row.text("created_at"),            }))            .collect::<Vec<Value>>(),        // Keyed by the EDGE's id, not the record's: one record can link twice,        // and the row key has to be the edge or the two collapse.        "linkedRecordFacts": Value::Object(facts),        "suggestions": suggestions            .iter()            .map(|row| json!({                "id": row.text("id"),                "workspaceId": row.text("workspace_id"),                "personId": row.text("person_id"),                "candidateId": row.text("candidate_id"),                "reason": row.text("reason"),                "score": row.real("score"),                "state": row.text("state"),                "decidedAt": row.text("decided_at"),                "createdAt": row.text("created_at"),                "updatedAt": row.text("updated_at"),            }))            .collect::<Vec<Value>>(),        "people": directory            .iter()            .map(|row| json!({ "id": row.text("id"), "fullName": row.text("full_name") }))            .collect::<Vec<Value>>(),        "summary": serde_json::to_value(&summary).map_err(|error| error.to_string())?,        "projects": projects,        "projectLinks": project_links,        "todos": todos            .iter()            .map(|row| json!({                "id": row.text("id"),                "title": row.text("title"),                "status": row.text("status"),                "dueAt": row.text("due_at"),                // The repeat mark on the row — a materialised occurrence draws                // it, a one-off does not.                "recurrenceId": row.text("recurrence_id"),                "createdAt": row.text("created_at"),            }))            .collect::<Vec<Value>>(),        "calls": calls            .iter()            .map(|row| json!({                "id": row.get("id"),                "direction": row.get("direction"),                "outcome": row.get("outcome"),                "startedAt": row.get("started_at"),                "durationS": row.get("duration_s").cloned().unwrap_or(json!(0)),                // What a call-back dials. Null for a call the log recorded                // without one, and the row then offers no call-back at all.                "handle": row.get("handle"),                "provider": row.get("provider"),                "personId": row.get("person_id"),                "contactId": row.get("contact_id"),                "live":row.get("live"),"kind":row.get("kind"),"endedAt":row.get("ended_at"),"meeting":row.get("meeting"),            }))            .collect::<Vec<Value>>(),        "faceSuggestions": face_rows            .iter()            .map(|row| json!({                "id": row.text("id"),                "recordKind": row.text("record_kind"),                "recordId": row.text("record_id"),                // The box, so the row can crop the face out of the picture.                "x": row.real("x"),                "y": row.real("y"),                "w": row.real("w"),                "h": row.real("h"),                "suggestedPersonId": row.text("suggested_person_id"),                "suggestedDistance": row.real("suggested_distance"),            }))            .collect::<Vec<Value>>(),        "faceSuggestionPhotos": photos            .iter()            .map(|row| json!({                "id": row.text("id"),                "key": row.text("key"),                "contentType": row.text("content_type"),                "preview": row.text("preview"),                "takenAt": row.text("taken_at"),            }))            .collect::<Vec<Value>>(),        "thread": thread(replica, &id, &phones)?,        "conversations": conversations(replica, &id, &phones)?,        "betweenUs": between_us(replica, &id)?,    }))}// Gated on the FEATURE as well as on `test`: the fixture helper these use// (`shell::client::phone_tests`) is itself phone-only, so a host-flavoured// `cargo test` would fail to resolve it — which is exactly what// `pnpm rust:verify` caught.#[cfg(test)]#[path = "person_tests.rs"]mod tests;// ── the directory ───────────────────────────────────────────────────────────/// The columns `/people` draws a row with.////// `timezone` and `avatar_key` are here and `list_people`'s/// answer does not carry them — that is the point of the read being its own/// query rather than the tool's list. The row wants the person's local clock/// and their face; the ledger carried both as PORT GAPs/// (`people-row-has-no-local-clock`) for exactly as long as the screen was/// reading an assistant's answer to a different question.fn person_listing_columns() -> String {    format!(        "id, full_name, {}, org, role_title, city, timezone, avatar_key",        cotton_core::rules::people::handles::phones_and_emails_sql("cotton_people.id")    )}/// `read.people` — **the WHOLE address book, in one answer.**////// ## Why this is not `list_people`////// It was, until a directory of about 1,900 people drew fifty of them. The tool/// pages (`bounded_limit(args, 50, 200)`) and it is right to: an assistant's/// context is finite, and a tool that answers two thousand rows into a model's/// window spends someone's money on rows nobody asked for. **A screen is the/// other case entirely.** The file is one person's, it is on this device, and/// the list the screen is drawing IS the set — so the honest answer is all of/// it, and the page size was never a fact about the person's address book. The/// rule, written down: Cotton note "The phone and Mac app — how a screen is built", "a screen's list read/// answers the whole set".////// ## Why there is no `q`////// Because the screen holds the whole set already, and a filter over a list you/// are holding beats a round trip per keystroke — with no second answer to/// "who are my people", which is the thing a query-parameterised read would/// mint. The substring reading (name, org and city, case-insensitively) stays/// where it was, in `PersonFacts.filter`, and it is CORRECT there now in a way/// it never was over a page of fifty.////// This is also why the read does not go to `fts_people`. FTS matches whole/// words with an optional prefix: it finds "Karaka" for "kar" and cannot find/// it for "rak", and it indexes no `org` and no `city`. Adopting it would have/// narrowed what the search already found and called it an optimisation.////// `total` and `more` are still in the answer, and `more` is always `false`:/// they are the shape the screen decodes, and saying "there is no more" is a/// fact this read can now state rather than a field it has to drop.pub fn people(replica: &ReadFile<'_>, _args: &Map<String, Value>) -> Result<Value, String> {    // NO LIMIT and no OFFSET — see the doc comment. The ORDER is the tool's,    // because the screen's order is not what changed: name first, then the id    // so two people who share a name hold a stable place between reads.    let rows = replica        .driver        .all(            &format!(                "SELECT {}                   FROM cotton_people                  WHERE workspace_id = ? AND archived_at IS NULL                  ORDER BY full_name ASC, id ASC",                person_listing_columns()            ),            &[workspace(replica)],        )        .map_err(|error| error.to_string())?;    let people: Vec<Value> = rows        .iter()        .map(|row| {            json!({                "id": row.text("id"),                // `name`, not `fullName` — the key `PersonListing` decodes, kept                // from the tool's answer so the screen's type did not have to                // change with its read.                "name": row.text("full_name"),                "phones": json_list(row.text("phones")),                "emails": json_list(row.text("emails")),                "org": trimmed(row.text("org")),                "roleTitle": trimmed(row.text("role_title")),                "city": trimmed(row.text("city")),                "timezone": trimmed(row.text("timezone")),                // Both, unreconciled, for the same reason the person page sends                // both: the renderer prefers the key and falls back to the url.                "avatarKey": trimmed(row.text("avatar_key")),            })        })        .collect();    Ok(json!({        "total": people.len(),        "offset": 0,        "more": false,        "people": people,    }))}