Cotton code
813 lines · 45.8 KB · RustRaw
//! Each app's line about each person (`person_fact`, PEOPLE-DESIGN f.6): counted//! on the phone that holds the app's tables, written sealed, read by Contacts//! for its tiers and the person page, which never reads the apps' own tables.//!//! **Comms** counts the messages and calls of every one-to-one chat whose//! contact names a person (who(handle), derived as it is read): how many in//! all, in 90 days and this year, the last, whether he took part (wrote or//! called), and in how many of the last 8 weeks both sides did. A group chat//! counts for nobody: being in a group with someone is not talking to them.//!//! **Post** counts mail with a person: each mail in from an address that names one person, and each mail out to//! one (every `to` and `cc`). A list's mail, bulk mail and automatic replies count for nobody. He took part when he//! wrote; a week counts when both sides wrote in it, as in Comms.//!//! **Days** counts the events he shared with a person that have begun: everyone the event names (`people`) and every//! guest whose address or number names one person, each event once a person. One he declined counts for nobody. An//! event together is something he took part in; it has no weeks of both sides.//!//! **Albums** counts the photos a named face is in (`face.person_id`, PEOPLE-DESIGN f.1 "photos together, for named//! faces"): the person page says "In N of your photos". A photo is not an exchange, so it never lifts a tier by//! itself (`took_part` stays false).//!//! Every app's line is a recount from that app's own tables (one grouped query, never a walk per message), so a//! rebuild from nothing equals the running result. Lines are KEPT ([`COUNTED`]): a count after new rows recounts only//! the people those rows name; everyone is recounted once a day and when people or their handles change; each app//! counts in a transaction of its own, and until each held app has counted once the home says it is still sorting. A line whose app now finds nothing for that person is set aside//! (`deleted_at`), and comes back when there is something to count again.//!//! It runs after each sync pass and after Comms takes in what arrived (`chat.incoming`), at most every [`EVERY`],//! and on `contacts.facts` (any app may ask). A line is rewritten only//! when its numbers changed, so a quiet day writes nothing.use std::sync::Mutex;use std::time::{Duration, Instant};use rusqlite::types::Value as SqlValue;use serde_json::{json, Map, Value};use cotton_tools::mcp::dispatch::Ctx;use cotton_tools::mcp::handlers::common::{insert_row, update_row};use super::contacts_app::{held, FACTS};use super::cotton_chat::{rows, write, ws};use crate::methods::MethodError;use crate::shell::client::ClientController;/// How often a Comms refresh recounts.const EVERY: Duration = Duration::from_secs(60);const DAY_MS: i64 = 86_400_000;fn last_run() -> &'static Mutex<Option<Instant>> {    static LAST: std::sync::OnceLock<Mutex<Option<Instant>>> = std::sync::OnceLock::new();    LAST.get_or_init(|| Mutex::new(None))}/// After a Comms refresh: recount when the last count is older than [`EVERY`]. A count that fails is said in the log/// and tried at the next refresh; it never fails the refresh.pub(crate) fn after_refresh(client: &ClientController) {    {        let mut last = last_run().lock().unwrap_or_else(std::sync::PoisonError::into_inner);        if last.is_some_and(|at| at.elapsed() < EVERY) {            return;        }        *last = Some(Instant::now());    }    if let Err(error) = super::contacts_same::send_waiting(client) {        eprintln!("[contacts] a merge's server half was not sent this time: {}", error.message);    }    if let Err(error) = count(client) {        eprintln!("[contacts] Comms' lines about people were not counted this time: {}", error.message);        *last_run().lock().unwrap_or_else(std::sync::PoisonError::into_inner) = None;    }    // Same person? found here, off the screen, so the home and the pages open on pairs already found.    let _ = super::cotton_chat::read(client, "contacts.same.warm", |ctx| Ok(Value::from(super::contacts_same::count(ctx)?)));}/// `contacts.facts {}`: count every app's lines this copy can count, each app in a transaction of its own (so/// Contacts reads between them); answers how many lines changed.pub fn count(client: &ClientController) -> Result<Value, MethodError> {    // Merges queued for the object go first (signed in), so what syncs back is counted on the person it names.    super::contacts_same::send_waiting(client)?;    let mut changed = 0;    let mut moved = std::collections::HashSet::new();    for app in APPS {        let answer = write(client, "contacts.facts", |ctx| {            let (wrote, went) = count_app(ctx, app)?;            ctx.commit().map_err(|e| e.to_string())?;            Ok(json!([wrote, went]))        })?;        changed += answer[0].as_u64().unwrap_or(0);        if answer[1].as_bool() == Some(true) {            moved.insert(app);        }    }    // Groups are made from the same rows: looked for again only when their app's rows moved.    let groups = if moved.is_empty() {        Value::from(0)    } else {        write(client, "contacts.facts.groups", |ctx| {            let mut made = 0;            if moved.contains("comms") {                made += make_chat_groups(ctx)?;            }            if moved.contains("days") {                made += make_event_groups(ctx)?;            }            if moved.contains("post") {                made += make_domain_groups(ctx)?;            }            ctx.commit().map_err(|e| e.to_string())?;            Ok(Value::from(made))        })?    };    Ok(json!({ "changed": changed, "groups": groups }))}/// The apps whose lines Contacts keeps, in the order a first rebuild counts them.const APPS: [&str; 4] = ["comms", "post", "days", "albums"];/// What each app's lines were last counted from (phone-only: an underscore table never syncs): the last row of each/// table it reads (`mark`), the people and their handles as they were (`people`), and the day. Lines are KEPT: the/// next count recounts only the people rows past the mark name, and recounts everyone once a day (the windows move)/// or when people or their handles changed (a merge, an edit, a contact made).const COUNTED: &str = "_contacts_counted";fn ensure_counted(ctx: &mut Ctx<'_>) -> Result<(), String> {    ctx.db()        .run(&format!("CREATE TABLE IF NOT EXISTS {COUNTED} (app TEXT PRIMARY KEY, mark TEXT NOT NULL, people TEXT NOT NULL, day TEXT NOT NULL)"), &[])        .map(|_| ())        .map_err(|e| e.to_string())}fn last_row(ctx: &mut Ctx<'_>, table: &str) -> Result<i64, String> {    if !held(ctx, table) {        return Ok(0);    }    Ok(rows(ctx, &format!("SELECT coalesce(max(rowid), 0) AS n FROM {table}"), &[])?.first().map_or(0, |r| int_of(r, "n")))}/// The tables an app reads, as their last rows; `None` when this copy does not hold the app's tables.fn marks(ctx: &mut Ctx<'_>, app: &str) -> Result<Option<Vec<i64>>, String> {    let tables: &[&str] = match app {        "comms" => &["cotton_msg_messages", "cotton_call_log"],        "post" => &["cotton_emails"],        "days" => &["cotton_events", "cotton_event_attendees"],        _ => &["cotton_media_faces", "cotton_photos"],    };    if !held(ctx, FACTS) || !held(ctx, tables[0]) {        return Ok(None);    }    let mut out = Vec::new();    for table in tables {        out.push(last_row(ctx, table)?);    }    Ok(Some(out))}/// What an edit changes, where it is cheap to read: a mail binned (its own index), any event changed (a few/// thousand), a photo binned or a face named (a pass over tens of thousands, not hundreds). A message binned waits/// for the daily recount: reading for it is a walk over every message.fn edits(ctx: &mut Ctx<'_>, app: &str) -> Result<String, String> {    let sql = match app {        "post" => "SELECT count(*) AS k FROM cotton_emails WHERE workspace_id = ?1 AND trashed_at IS NOT NULL".to_string(),        "days" => "SELECT count(*) || ':' || coalesce(max(updated_at), '') AS k FROM cotton_events".to_string(),        "albums" => "SELECT (SELECT count(trashed_at) || ':' || coalesce(max(updated_at), '') FROM cotton_photos) || '|' || \                     (SELECT count(person_id) || ':' || coalesce(max(updated_at), '') FROM cotton_media_faces) AS k"            .to_string(),        _ => return Ok(String::new()),    };    let args = if sql.contains("?1") { vec![ws(ctx)] } else { Vec::new() };    Ok(rows(ctx, &sql, &args)?.first().and_then(|r| r.get("k")).map(|v| v.as_str().map_or_else(|| v.to_string(), str::to_string)).unwrap_or_default())}/// The people and their handles as a short signature: a count changes it, and so does any edit (`updated_at`).pub(crate) fn people_mark(ctx: &mut Ctx<'_>) -> Result<String, String> {    let mut parts = vec![        "(SELECT count(*) || ':' || coalesce(max(updated_at), '') || ':' || coalesce(sum(archived_at IS NOT NULL), 0) || ':' || coalesce(sum(trashed_at IS NOT NULL), 0) FROM cotton_people WHERE workspace_id = ?1)".to_string(),        "(SELECT count(*) || ':' || coalesce(max(updated_at), '') FROM cotton_person_handles WHERE workspace_id = ?1)".to_string(),    ];    if cotton_store::protocol::who::shared_held(ctx.db()) {        parts.push("(SELECT count(*) || ':' || coalesce(max(updated_at), '') FROM cotton_shared_handle WHERE workspace_id = ?1)".to_string());    }    if !held(ctx, "cotton_person_handles") {        parts.truncate(1);    }    let found = rows(ctx, &format!("SELECT {} AS mark", parts.join(" || '|' || ")), &[ws(ctx)])?;    Ok(found.first().and_then(|r| r.get("mark").and_then(Value::as_str)).unwrap_or_default().to_string())}/// The people the rows past `old` name, or `None` when the app is recounted whole (Days: a few thousand events).fn touched(ctx: &mut Ctx<'_>, app: &str, old: &[i64]) -> Result<Option<Vec<String>>, String> {    let (prelude, exchanges) = match app {        "comms" => comms_sql(ctx, &format!("AND m.rowid > {}", old[0]), &format!("AND l.rowid > {}", old.get(1).copied().unwrap_or(0))),        "post" => post_sql(ctx, &format!("AND m.rowid > {}", old[0])),        "albums" => (String::new(), format!("SELECT f.person_id AS person FROM cotton_media_faces f WHERE f.workspace_id = ?1 AND f.rowid > {}", old[0])),        _ => return Ok(None),    };    let with = if prelude.is_empty() { String::new() } else { format!("WITH {}", prelude.trim_end().trim_end_matches(',')) };    let found = rows(ctx, &format!("{with} SELECT DISTINCT x.person AS person FROM ({exchanges}) x WHERE x.person IS NOT NULL"), &[ws(ctx)])?;    Ok(Some(found.iter().filter_map(|r| r.get("person").and_then(Value::as_str).map(str::to_string)).collect()))}fn count_lines(ctx: &mut Ctx<'_>, app: &str, only: Option<&[String]>) -> Result<usize, String> {    match app {        "comms" => count_comms(ctx, only),        "post" => count_post(ctx, only),        "days" => count_days(ctx, only),        _ => count_albums(ctx, only),    }}/// One app's lines, kept: nothing when nothing is past its mark, only the people new rows name when the day and/// the people are as they were, else everyone. Answers the lines written and whether anything moved.fn count_app(ctx: &mut Ctx<'_>, app: &str) -> Result<(usize, bool), String> {    let Some(now_marks) = marks(ctx, app)? else { return Ok((0, false)) };    ensure_counted(ctx)?;    let day = iso(windows(ctx).0)[..10].to_string();    // An edit to rows already counted recounts the app whole, as a new day does.    let people = format!("{}#{}", people_mark(ctx)?, edits(ctx, app)?);    let stored = rows(ctx, &format!("SELECT mark, people, day FROM {COUNTED} WHERE app = ?"), &[SqlValue::Text(app.into())])?.into_iter().next();    let same_day = stored.as_ref().is_some_and(|r| r.get("day").and_then(Value::as_str) == Some(day.as_str()) && r.get("people").and_then(Value::as_str) == Some(people.as_str()));    let mut moved = true;    let wrote = if same_day {        let old: Vec<i64> = stored.as_ref().and_then(|r| r.get("mark").and_then(Value::as_str)).and_then(|m| serde_json::from_str(m).ok()).unwrap_or_default();        if old == now_marks {            moved = false;            0        } else if old.len() != now_marks.len() {            count_lines(ctx, app, None)?        } else {            match touched(ctx, app, &old)? {                Some(people) if people.is_empty() => 0,                Some(people) => count_lines(ctx, app, Some(&people))?,                None => count_lines(ctx, app, None)?,            }        }    } else {        count_lines(ctx, app, None)?    };    ctx.db()        .run(            &format!("INSERT OR REPLACE INTO {COUNTED} (app, mark, people, day) VALUES (?, ?, ?, ?)"),            &[SqlValue::Text(app.into()), SqlValue::Text(serde_json::to_string(&now_marks).unwrap_or_default()), SqlValue::Text(people), SqlValue::Text(day)],        )        .map_err(|e| e.to_string())?;    Ok((wrote, moved))}/// Whether some app this copy holds has never had its lines counted: the home says it is still sorting.pub(crate) fn sorting(ctx: &mut Ctx<'_>) -> Result<bool, String> {    let counted: std::collections::HashSet<String> = if held(ctx, COUNTED) {        rows(ctx, &format!("SELECT app FROM {COUNTED}"), &[])?.iter().filter_map(|r| r.get("app").and_then(Value::as_str).map(str::to_string)).collect()    } else {        Default::default()    };    for app in APPS {        if !counted.contains(app) && marks(ctx, app)?.is_some_and(|m| m[0] > 0) {            return Ok(true);        }    }    Ok(false)}fn iso(ms: i64) -> String {    chrono::DateTime::from_timestamp_millis(ms).unwrap_or_default().to_rfc3339_opts(chrono::SecondsFormat::Millis, true)}/// One app's lines: `found` rows of (person, n, n90, ny, took, last, w8), each written when its numbers changed;/// this app's other lines are set aside. Answers how many lines it wrote.fn write_lines(ctx: &mut Ctx<'_>, app: &str, kind: &str, found: Vec<Map<String, Value>>, only: Option<&[String]>) -> Result<usize, String> {    let now = windows(ctx).0;    let namespace = ctx.file.namespace().to_string();    let at = iso(now);    let mut wrote = 0;    let mut seen = std::collections::BTreeSet::new();    for row in found {        let Some(person) = row.get("person").and_then(Value::as_str).map(str::to_string) else { continue };        let id = cotton_core::cotton_rules::ids::derived_id("person_fact", &[&namespace, &person, app, kind]);        seen.insert(id.clone());        let line = [("count", int_of(&row, "n")), ("count_90d", int_of(&row, "n90")), ("count_year", int_of(&row, "ny")), ("weeks_8", int_of(&row, "w8"))];        let took = int_of(&row, "took") > 0;        let last = row.get("last").and_then(Value::as_str).map(str::to_string);        let had = rows(ctx, &format!("SELECT count, count_90d, count_year, weeks_8, took_part, last, deleted_at FROM {FACTS} WHERE id = ?"), &[SqlValue::Text(id.clone())])?.into_iter().next();        if let Some(had) = &had {            let live = had.get("deleted_at").is_none_or(Value::is_null);            let same = live && line.iter().all(|(k, v)| int_of(had, k) == *v) && (int_of(had, "took_part") > 0) == took && had.get("last").and_then(Value::as_str) == last.as_deref();            if same {                continue;            }        }        let mut patch = Map::new();        for (k, v) in line {            patch.insert(k.into(), Value::from(v));        }        patch.insert("took_part".into(), Value::from(took));        patch.insert("last".into(), last.map_or(Value::Null, Value::from));        patch.insert("counted_at".into(), Value::from(at.clone()));        patch.insert("updated_at".into(), Value::from(at.clone()));        if had.is_some() {            patch.insert("deleted_at".into(), Value::Null);            update_row(ctx, FACTS, &id, patch).map_err(|e| e.to_string())?;        } else {            patch.insert("workspace_id".into(), Value::from(ctx.workspace_id.to_string()));            patch.insert("person".into(), Value::from(person));            patch.insert("app".into(), Value::from(app));            patch.insert("kind".into(), Value::from(kind));            patch.insert("created_at".into(), Value::from(at.clone()));            insert_row(ctx, FACTS, &id, patch).map_err(|e| e.to_string())?;        }        wrote += 1;    }    // A line this app no longer finds anything for: set aside, so a recount from nothing gives the same lines.    // Counting only some people, only their lines can have gone stale.    let (among, mut args) = match only {        Some(only) => (" AND person IN (SELECT value FROM json_each(?))", vec![SqlValue::Text(serde_json::to_string(only).unwrap_or_default())]),        None => ("", Vec::new()),    };    args.splice(0..0, [ws(ctx), SqlValue::Text(app.into()), SqlValue::Text(kind.into())]);    let stale = rows(ctx, &format!("SELECT id FROM {FACTS} WHERE workspace_id = ? AND app = ? AND kind = ? AND deleted_at IS NULL{among}"), &args)?;    for row in stale {        let Some(id) = row.get("id").and_then(Value::as_str).map(str::to_string) else { continue };        if seen.contains(&id) {            continue;        }        let mut patch = Map::new();        patch.insert("deleted_at".into(), Value::from(at.clone()));        update_row(ctx, FACTS, &id, patch).map_err(|e| e.to_string())?;        wrote += 1;    }    Ok(wrote)}/// The windows every count uses: (now, 90 days back, the year's first day, 8 weeks back).fn windows(ctx: &Ctx<'_>) -> (i64, String, String, String) {    let now = cotton_tools::mcp::handlers::common::now_ms(ctx);    (now, iso(now - 90 * DAY_MS), format!("{}-01-01", &iso(now)[..4]), iso(now - 56 * DAY_MS))}/// The grouped line over `exchanges` (rows of person, direction 'in'|'out'|'with', at): as Comms counts. `prelude`/// is further CTEs the exchanges read (each ending in a comma); with `only`, the people asked for (`?9`, a JSON/// list). One pass over the exchanges: the weeks of both sides are grouped, never looked up again per person.fn grouped(prelude: &str, exchanges: &str, only: bool) -> String {    let only = if only { "AND x.person IN (SELECT value FROM json_each(?9))" } else { "" };    format!(        "WITH {prelude} e AS MATERIALIZED (SELECT x.person AS person, x.direction AS direction, x.at AS at FROM ({exchanges}) x WHERE x.person IS NOT NULL {only}), \           wk AS (SELECT person, strftime('%Y-%W', at) AS week FROM e WHERE at >= ?4 AND direction IN ('in', 'out') GROUP BY person, week HAVING COUNT(DISTINCT direction) = 2), \           w AS (SELECT person, COUNT(*) AS w8 FROM wk GROUP BY person) \         SELECT e.person AS person, COUNT(*) AS n, SUM(e.at >= ?2) AS n90, SUM(e.at >= ?3) AS ny, MAX(e.direction IN ('out', 'with')) AS took, MAX(e.at) AS last, \           coalesce(MAX(w.w8), 0) AS w8 \         FROM e LEFT JOIN w ON w.person = e.person GROUP BY e.person"    )}/// A grouped line's rows. Its parameters: `?1` the workspace, the three windows, `?5` now, `?9` the people asked/// for; as many as the statement names (SQLite counts up to the highest).fn run_grouped(ctx: &mut Ctx<'_>, sql: &str, only: Option<&[String]>) -> Result<Vec<Map<String, Value>>, String> {    let (now, d90, year, d56) = windows(ctx);    let mut args = vec![ws(ctx), SqlValue::Text(d90), SqlValue::Text(year), SqlValue::Text(d56)];    if sql.contains("?5") || only.is_some() {        args.push(SqlValue::Text(iso(now)));    }    if let Some(only) = only {        args.extend([SqlValue::Null, SqlValue::Null, SqlValue::Null, SqlValue::Text(serde_json::to_string(only).unwrap_or_default())]);    }    rows(ctx, sql, &args)}/// Each address a person's own handle holds, once, with the ONE person it names (who(handle)), as a CTE: what Post/// looks a mail's address up in, instead of asking who(handle) again for every mail.fn address_people(ctx: &mut Ctx<'_>, kind: &str) -> String {    let shared = cotton_store::protocol::who::shared_held(ctx.db());    let person = cotton_store::protocol::who::person_of_handle_sql(shared, "?1", &format!("'{kind}'"), "hv.value");    format!(        "hp_{kind} AS MATERIALIZED (SELECT hv.value AS value, {person} AS person FROM (SELECT DISTINCT normalised AS value FROM cotton_person_handles \           WHERE workspace_id = ?1 AND kind = '{kind}' AND trashed_at IS NULL) hv),"    )}/// Post's line per person: mail in from them, mail out to them. `newer` keeps only mail past a mark (`m.rowid > n`).fn post_sql(ctx: &mut Ctx<'_>, newer: &str) -> (String, String) {    let prelude = address_people(ctx, "email");    // Mail a person wrote, never a list's, bulk or an automatic answer.    let real = format!("m.workspace_id = ?1 AND m.trashed_at IS NULL AND coalesce(m.list_id, '') = '' \                AND lower(coalesce(m.precedence, '')) NOT IN ('bulk', 'list', 'junk') AND lower(coalesce(m.auto_submitted, 'no')) IN ('no', '') {newer}");    let exchanges = format!(        "SELECT h.person AS person, 'in' AS direction, m.sent_at AS at FROM cotton_emails m JOIN hp_email h ON h.value = lower(trim(m.from_email)) \           WHERE {real} AND coalesce(m.direction, 'in') = 'in' \         UNION ALL SELECT DISTINCT h.person AS person, 'out' AS direction, m.sent_at AS at FROM cotton_emails m, json_each(CASE WHEN json_valid(m.recipients) THEN m.recipients ELSE '[]' END) r \           JOIN hp_email h ON h.value = lower(trim(json_extract(r.value, '$.email'))) WHERE {real} AND m.direction = 'out'"    );    (prelude, exchanges)}pub(crate) fn count_post(ctx: &mut Ctx<'_>, only: Option<&[String]>) -> Result<usize, String> {    if !held(ctx, FACTS) || !held(ctx, "cotton_emails") || !held(ctx, "cotton_person_handles") {        return Ok(0);    }    let (prelude, exchanges) = post_sql(ctx, "");    let found = run_grouped(ctx, &grouped(&prelude, &exchanges, only.is_some()), only)?;    write_lines(ctx, "post", "mail", found, only)}/// Days' line per person: the events together that have begun.pub(crate) fn count_days(ctx: &mut Ctx<'_>, only: Option<&[String]>) -> Result<usize, String> {    if !held(ctx, FACTS) || !held(ctx, "cotton_events") {        return Ok(0);    }    let pairs = event_people_sql(ctx);    let exchanges = format!("SELECT t.person AS person, 'with' AS direction, t.at AS at FROM ({pairs}) t");    let found = run_grouped(ctx, &grouped("", &exchanges, only.is_some()), only)?;    write_lines(ctx, "days", "together", found, only)}/// Every (event, person, at, title) of an event together that has begun, as SQL over `?1` (the workspace) and `?5`/// (now): the event's people and its guests whose address or number names one person; never a declined event, a/// binned one or a person archived or binned.fn event_people_sql(ctx: &mut Ctx<'_>) -> String {    let shared = cotton_store::protocol::who::shared_held(ctx.db());    let guests = if held(ctx, "cotton_event_attendees") && held(ctx, "cotton_person_handles") {        // Neither an event nor a guest row carries a workspace: a copy holds one, the handles' (?1).        let by_mail = cotton_store::protocol::who::person_of_handle_sql(shared, "?1", "'email'", "lower(trim(g.email))");        let by_phone = cotton_store::protocol::who::person_of_handle_sql(shared, "?1", "'phone'", "g.phone");        let removed = if has_column(ctx, "cotton_event_attendees", "removed_at") { "AND g.removed_at IS NULL" } else { "" };        format!("UNION SELECT g.event_id AS event, COALESCE({by_mail}, {by_phone}) AS person FROM cotton_event_attendees g WHERE 1 = 1 {removed}")    } else {        String::new()    };    // The columns a Days copy gained over time (kit columns): an older copy counts with what it has.    let named = if has_column(ctx, "cotton_events", "people") {        "SELECT ev.id AS event, p.value AS person FROM cotton_events ev, json_each(CASE WHEN json_valid(ev.people) THEN ev.people ELSE '[]' END) p"    } else {        "SELECT NULL AS event, NULL AS person WHERE 0"    };    let declined = if has_column(ctx, "cotton_events", "my_response") { "AND coalesce(ev.my_response, '') <> 'declined'" } else { "" };    let binned = if has_column(ctx, "cotton_events", "trashed_at") { "AND ev.trashed_at IS NULL" } else { "" };    format!(        "SELECT t.event AS event, t.person AS person, ev.starts_at AS at, ev.title AS title FROM ({named} {guests}) t \           JOIN cotton_events ev ON ev.id = t.event JOIN cotton_people pp ON pp.id = t.person \         WHERE ev.starts_at <= ?5 {binned} {declined} AND pp.trashed_at IS NULL AND pp.archived_at IS NULL"    )}/// Groups Contacts makes from Days (PEOPLE-DESIGN f.2 "Events"): the same two to thirty people at three events or/// more become a group under the name those events most often carry, "at the same N events in Days". Made once/// (its origin keeps `events:<the people>`), and never again once he deleted it. Answers how many it made.pub(crate) fn make_event_groups(ctx: &mut Ctx<'_>) -> Result<usize, String> {    const ORIGIN: &str = "cotton_group_origin";    const MOST: usize = 30;    const TIMES: usize = 3;    if !held(ctx, ORIGIN) || !held(ctx, "cotton_events") || !held(ctx, "cotton_groups") {        return Ok(0);    }    let (now, ..) = windows(ctx);    let pairs = event_people_sql(ctx);    let found = rows(ctx, &format!("SELECT event, person, title FROM ({pairs}) ORDER BY event, person"), &[ws(ctx), SqlValue::Null, SqlValue::Null, SqlValue::Null, SqlValue::Text(iso(now))])?;    // Each event's people (sorted, so the same people are one key), and its title.    let mut events: std::collections::BTreeMap<String, (std::collections::BTreeSet<String>, String)> = std::collections::BTreeMap::new();    for row in found {        let (Some(event), Some(person)) = (row.get("event").and_then(Value::as_str), row.get("person").and_then(Value::as_str)) else { continue };        let entry = events.entry(event.to_string()).or_default();        entry.0.insert(person.to_string());        if let Some(title) = row.get("title").and_then(Value::as_str) {            entry.1 = title.trim().to_string();        }    }    let mut together: std::collections::BTreeMap<Vec<String>, Vec<String>> = std::collections::BTreeMap::new();    for (people, title) in events.into_values() {        if people.len() >= 2 && people.len() <= MOST {            together.entry(people.into_iter().collect()).or_default().push(title);        }    }    let mut made = 0;    for (people, titles) in together {        if titles.len() < TIMES {            continue;        }        // The name the events most often carry (the first in order on a tie); "Days" when none has one.        let mut tally: std::collections::BTreeMap<&str, usize> = std::collections::BTreeMap::new();        for t in titles.iter().filter(|t| !t.is_empty()) {            *tally.entry(t.as_str()).or_default() += 1;        }        let name = tally.iter().max_by(|a, b| a.1.cmp(b.1).then(b.0.cmp(a.0))).map(|(t, _)| t.to_string()).unwrap_or_else(|| "Days".to_string());        use sha2::Digest as _;        let key = format!("events:{}", hex::encode(&sha2::Sha256::digest(people.join(",").as_bytes())[..12]));        let reason = super::contacts_app::sf("groups.from_events", &[("count", &titles.len().to_string())]);        if put_app_group(ctx, &key, &name, &people, &reason)? {            made += 1;        }    }    Ok(made)}/// A group Contacts makes by itself, written as the groups tool writes a group of people: its id derived from `key`/// (two phones make one), its origin made_by app with `reason` and `from` = `key`. Nothing when that origin is/// already held: a group made once, even one he deleted since, is never made again. Answers whether it made it.fn put_app_group(ctx: &mut Ctx<'_>, key: &str, name: &str, members: &[String], reason: &str) -> Result<bool, String> {    const ORIGIN: &str = "cotton_group_origin";    if !rows(ctx, &format!("SELECT id FROM {ORIGIN} WHERE workspace_id = ? AND \"from\" = ?"), &[ws(ctx), SqlValue::Text(key.into())])?.is_empty() {        return Ok(false);    }    let namespace = ctx.file.namespace().to_string();    let group_id = cotton_core::cotton_rules::ids::derived_id("contact_group", &[&namespace, key]);    let at = iso(cotton_tools::mcp::handlers::common::now_ms(ctx));    if rows(ctx, "SELECT id FROM cotton_groups WHERE id = ?", &[SqlValue::Text(group_id.clone())])?.is_empty() {        let mut row = Map::new();        row.insert("id".into(), Value::from(group_id.clone()));        row.insert("table_id".into(), Value::from("person"));        row.insert("name".into(), Value::from(name));        insert_row(ctx, "cotton_groups", &group_id, row).map_err(|e| e.to_string())?;        for (place, member) in members.iter().enumerate() {            let id = cotton_store::protocol::derived_id::group_member_id(&group_id, member);            let mut patch = Map::new();            patch.insert("id".into(), Value::from(id.clone()));            patch.insert("group_id".into(), Value::from(group_id.clone()));            patch.insert("record_id".into(), Value::from(member.clone()));            patch.insert("place".into(), Value::from((place + 1) as f64));            patch.insert("created_at".into(), Value::from(at.clone()));            patch.insert("updated_at".into(), Value::from(at.clone()));            insert_row(ctx, "cotton_group_members", &id, patch).map_err(|e| e.to_string())?;        }    }    let origin = cotton_core::cotton_rules::ids::derived_id("group_origin", &[&namespace, &group_id]);    let mut patch = Map::new();    patch.insert("workspace_id".into(), Value::from(ctx.workspace_id.to_string()));    patch.insert("group_id".into(), Value::from(group_id));    patch.insert("made_by".into(), Value::from("app"));    patch.insert("reason".into(), Value::from(reason));    patch.insert("from".into(), Value::from(key));    patch.insert("created_at".into(), Value::from(at.clone()));    patch.insert("updated_at".into(), Value::from(at));    insert_row(ctx, ORIGIN, &origin, patch).map_err(|e| e.to_string())?;    Ok(true)}/// The domains anyone may hold an address at: never a workplace, never an organisation.const WEBMAIL: &[&str] = &[    "gmail.com", "googlemail.com", "outlook.com", "hotmail.com", "live.com", "msn.com", "yahoo.com", "yahoo.co.in", "yahoo.co.uk", "ymail.com",    "icloud.com", "me.com", "mac.com", "aol.com", "proton.me", "protonmail.com", "pm.me", "gmx.com", "gmx.net", "gmx.de", "mail.com", "zoho.com",    "rediffmail.com", "fastmail.com", "hey.com", "yandex.com", "yandex.ru", "qq.com", "163.com", "web.de", "tutanota.com",];fn domain_of(address: &str) -> Option<String> {    let domain = address.trim().rsplit_once('@')?.1.trim().trim_end_matches('.').to_lowercase();    (domain.contains('.') && !WEBMAIL.contains(&domain.as_str())).then_some(domain)}/// An organisation's name from its domain: the label before the public suffix, capitalised ("acme.example" →/// "Acme", "mail.acme.co.uk" → "Acme"). He renames it as he likes.pub(crate) fn organisation_name(domain: &str) -> String {    let labels: Vec<&str> = domain.split('.').filter(|l| !l.is_empty()).collect();    let second = ["co", "com", "org", "net", "ac", "gov", "edu"];    let at = if labels.len() >= 3 && second.contains(&labels[labels.len() - 2]) { labels.len() - 3 } else { labels.len().saturating_sub(2) };    let label = labels.get(at).copied().unwrap_or(domain);    let mut chars = label.chars();    chars.next().map(|c| c.to_uppercase().collect::<String>() + chars.as_str()).unwrap_or_default()}/// The organisation a domain made (`person_source` kind `mail_domain`), living or not; None when none was made.pub(crate) fn organisation_of(ctx: &mut Ctx<'_>, domain: &str) -> Result<Option<String>, String> {    if !held(ctx, super::contacts_app::SOURCES) {        return Ok(None);    }    Ok(rows(ctx, &format!("SELECT person FROM {} WHERE workspace_id = ? AND kind = 'mail_domain' AND source_id = ? ORDER BY first_seen LIMIT 1", super::contacts_app::SOURCES), &[ws(ctx), SqlValue::Text(domain.into())])?        .into_iter()        .next()        .and_then(|r| r.get("person").and_then(Value::as_str).map(str::to_string)))}/// What Contacts makes from Post's domains (PEOPLE-DESIGN f.2 "Work"): the domain of his own address that is no/// webmail makes Work, "people at <domain>", of the living people with an address there (two or more); every other/// such domain he wrote to someone at becomes an organisation (`kind = organisation`, the domain kept as its/// `mail_domain` source until person_handle takes a domain kind). Each is made once, with an id derived from the/// domain, so two phones make one and one he deleted is never made again. Answers how many it made.pub(crate) fn make_domain_groups(ctx: &mut Ctx<'_>) -> Result<usize, String> {    if !held(ctx, "cotton_emails") || !held(ctx, "cotton_person_handles") || !held(ctx, "cotton_group_origin") || !held(ctx, "cotton_groups") {        return Ok(0);    }    let own: std::collections::BTreeSet<String> = rows(ctx, "SELECT DISTINCT lower(coalesce(account, gmail_account)) AS a FROM cotton_emails WHERE workspace_id = ? AND coalesce(account, gmail_account) IS NOT NULL", &[ws(ctx)])?        .into_iter()        .filter_map(|r| r.get("a").and_then(Value::as_str).and_then(domain_of))        .collect();    let at = |domain: &str| format!("%@{domain}");    let mut made = 0;    for domain in &own {        let people: Vec<String> = rows(            ctx,            "SELECT DISTINCT h.person_id AS person FROM cotton_person_handles h JOIN cotton_people p ON p.id = h.person_id \             WHERE h.workspace_id = ? AND h.kind = 'email' AND h.normalised LIKE ? AND h.trashed_at IS NULL AND p.trashed_at IS NULL AND p.archived_at IS NULL ORDER BY h.person_id",            &[ws(ctx), SqlValue::Text(at(domain))],        )?        .into_iter()        .filter_map(|r| r.get("person").and_then(Value::as_str).map(str::to_string))        .collect();        if people.len() >= 2 && people.len() <= 200 {            let reason = super::contacts_app::sf("groups.from_domain", &[("domain", domain)]);            if put_app_group(ctx, &format!("work:{domain}"), &super::contacts_app::s("groups.work"), &people, &reason)? {                made += 1;            }        }    }    if !held(ctx, super::contacts_app::SOURCES) || !held(ctx, super::contacts_app::STATE) {        return Ok(made);    }    // The domains he wrote to someone at.    let wrote: std::collections::BTreeSet<String> = rows(        ctx,        "SELECT DISTINCT lower(trim(json_extract(r.value, '$.email'))) AS a FROM cotton_emails m, json_each(CASE WHEN json_valid(m.recipients) THEN m.recipients ELSE '[]' END) r \         WHERE m.workspace_id = ? AND m.direction = 'out' AND m.trashed_at IS NULL",        &[ws(ctx)],    )?    .into_iter()    .filter_map(|r| r.get("a").and_then(Value::as_str).and_then(domain_of))    .filter(|d| !own.contains(d))    .collect();    for domain in wrote {        if organisation_of(ctx, &domain)?.is_some() {            continue;        }        let anyone = !rows(            ctx,            "SELECT 1 AS one FROM cotton_person_handles h JOIN cotton_people p ON p.id = h.person_id WHERE h.workspace_id = ? AND h.kind = 'email' AND h.normalised LIKE ? AND h.trashed_at IS NULL AND p.trashed_at IS NULL LIMIT 1",            &[ws(ctx), SqlValue::Text(at(&domain))],        )?        .is_empty();        if !anyone {            continue;        }        let namespace = ctx.file.namespace().to_string();        let id = cotton_core::cotton_rules::ids::derived_id("organisation", &[&namespace, &domain]);        if rows(ctx, "SELECT id FROM cotton_people WHERE id = ?", &[SqlValue::Text(id.clone())])?.is_empty() {            let mut person = Map::new();            person.insert("full_name".into(), Value::from(organisation_name(&domain)));            person.insert("contact_source".into(), Value::from("manual"));            insert_row(ctx, "cotton_people", &id, person).map_err(|e| e.to_string())?;        }        let mut state = Map::new();        state.insert("kind".into(), Value::from("organisation"));        super::contacts_app::put_state(ctx, &id, state)?;        let source = cotton_core::cotton_rules::ids::derived_id("person_source", &[&namespace, "mail_domain", &domain]);        let now = iso(cotton_tools::mcp::handlers::common::now_ms(ctx));        let mut row = Map::new();        row.insert("workspace_id".into(), Value::from(ctx.workspace_id.to_string()));        row.insert("person".into(), Value::from(id));        row.insert("kind".into(), Value::from("mail_domain"));        row.insert("source_id".into(), Value::from(domain.clone()));        row.insert("name".into(), Value::from(domain.clone()));        row.insert("first_seen".into(), Value::from(now.clone()));        row.insert("created_at".into(), Value::from(now.clone()));        row.insert("updated_at".into(), Value::from(now));        insert_row(ctx, super::contacts_app::SOURCES, &source, row).map_err(|e| e.to_string())?;        made += 1;    }    Ok(made)}/// Albums' line per person: the photos a named face of theirs is in. Never "took part".pub(crate) fn count_albums(ctx: &mut Ctx<'_>, only: Option<&[String]>) -> Result<usize, String> {    if !held(ctx, FACTS) || !held(ctx, "cotton_media_faces") || !held(ctx, "cotton_photos") {        return Ok(0);    }    let exchanges = "SELECT DISTINCT f.person_id AS person, 'photo' AS direction, coalesce(ph.taken_at, ph.created_at) AS at, ph.id AS photo FROM cotton_media_faces f \           JOIN cotton_photos ph ON ph.id = f.record_id JOIN cotton_people pp ON pp.id = f.person_id \         WHERE f.workspace_id = ?1 AND f.record_kind = 'photo' AND f.person_id IS NOT NULL AND ph.trashed_at IS NULL AND pp.trashed_at IS NULL AND pp.archived_at IS NULL";    let found = run_grouped(ctx, &grouped("", exchanges, only.is_some()), only)?;    write_lines(ctx, "albums", "photos", found, only)}/// Whether this copy's `table` has `column` (a kit column a table gained later).fn has_column(ctx: &mut Ctx<'_>, table: &str, column: &str) -> bool {    rows(ctx, &format!("SELECT 1 AS one FROM pragma_table_info('{table}') WHERE name = ?"), &[SqlValue::Text(column.into())]).is_ok_and(|r| !r.is_empty())}fn int_of(row: &Map<String, Value>, key: &str) -> i64 {    row.get(key).and_then(|v| v.as_i64().or_else(|| v.as_f64().map(|f| f as i64))).unwrap_or(0)}/// Comms' exchanges: the one-to-one chats' messages and the calls, each by its chat contact, the contact named once/// (`cp`, who(handle) asked once a contact, never once a message). `newer` keeps only rows past the marks.fn comms_sql(ctx: &mut Ctx<'_>, newer_messages: &str, newer_calls: &str) -> (String, String) {    let person = cotton_store::protocol::who::contact_person_sql(cotton_store::protocol::who::shared_held(ctx.db()), "c");    let calls = if held(ctx, "cotton_call_log") {        format!("UNION ALL SELECT l.contact_id AS contact, l.direction AS direction, l.started_at AS at FROM cotton_call_log l WHERE l.workspace_id = ?1 AND l.contact_id IS NOT NULL {newer_calls}")    } else {        String::new()    };    let prelude = format!("cp AS MATERIALIZED (SELECT c.id AS contact, {person} AS person FROM cotton_msg_contacts c WHERE c.workspace_id = ?1),");    let exchanges = format!(        "SELECT cp.person AS person, x.direction AS direction, x.at AS at FROM (\           SELECT t.contact_id AS contact, m.direction AS direction, m.sent_at AS at FROM cotton_msg_messages m JOIN cotton_msg_threads t ON t.id = m.thread_id \             WHERE m.workspace_id = ?1 AND m.trashed_at IS NULL AND t.trashed_at IS NULL AND coalesce(t.kind, '') <> 'group' AND t.contact_id IS NOT NULL {newer_messages} \           {calls}) x JOIN cp ON cp.contact = x.contact"    );    (prelude, exchanges)}/// Comms' line per person. Answers how many lines it wrote.pub(crate) fn count_comms(ctx: &mut Ctx<'_>, only: Option<&[String]>) -> Result<usize, String> {    if !held(ctx, FACTS) || !held(ctx, "cotton_msg_messages") || !held(ctx, "cotton_msg_threads") {        return Ok(0);    }    let (prelude, exchanges) = comms_sql(ctx, "", "");    let found = run_grouped(ctx, &grouped(&prelude, &exchanges, only.is_some()), only)?;    write_lines(ctx, "comms", "talk", found, only)}/// Groups Contacts makes by itself (PEOPLE-DESIGN f.2): each group chat he took part in, of 30 people or fewer, whose/// members are his contacts, becomes a group under the chat's name, "from your … chat". Made once: its origin keeps/// the chat's key, and a group he deleted is never made again. Answers how many it made.pub(crate) fn make_chat_groups(ctx: &mut Ctx<'_>) -> Result<usize, String> {    const ORIGIN: &str = "cotton_group_origin";    const MOST: usize = 30;    if !held(ctx, ORIGIN) || !held(ctx, "cotton_msg_thread_participants") {        return Ok(0);    }    let person = cotton_store::protocol::who::contact_person_sql(cotton_store::protocol::who::shared_held(ctx.db()), "c");    let chats = rows(        ctx,        "SELECT t.id AS id, t.title AS title, (SELECT channel FROM cotton_msg_messages m WHERE m.thread_id = t.id LIMIT 1) AS channel FROM cotton_msg_threads t \         WHERE t.workspace_id = ? AND t.kind = 'group' AND t.trashed_at IS NULL AND coalesce(t.title, '') <> '' \           AND EXISTS (SELECT 1 FROM cotton_msg_messages m WHERE m.thread_id = t.id AND m.direction = 'out' AND m.trashed_at IS NULL)",        &[ws(ctx)],    )?;    let made: std::collections::HashSet<String> = rows(ctx, &format!("SELECT \"from\" AS key FROM {ORIGIN} WHERE workspace_id = ? AND \"from\" IS NOT NULL"), &[ws(ctx)])?        .into_iter()        .filter_map(|r| r.get("key").and_then(Value::as_str).map(str::to_string))        .collect();    let mut count = 0;    for chat in chats {        let (Some(id), Some(title)) = (chat.get("id").and_then(Value::as_str), chat.get("title").and_then(Value::as_str)) else { continue };        let key = format!("chat:{id}");        if made.contains(&key) {            continue;        }        let members: Vec<String> = rows(            ctx,            &format!(                "SELECT DISTINCT {person} AS person FROM cotton_msg_thread_participants tp JOIN cotton_msg_contacts c ON c.id = tp.contact_id \                 WHERE tp.thread_id = ? AND tp.left_at IS NULL AND coalesce(tp.is_self, 0) = 0"            ),            &[SqlValue::Text(id.to_string())],        )?        .into_iter()        .filter_map(|r| r.get("person").and_then(Value::as_str).map(str::to_string))        .collect();        if members.len() < 2 || members.len() > MOST {            continue;        }        let channel = match chat.get("channel").and_then(Value::as_str) {            Some("whatsapp") => "WhatsApp",            Some("sms") => "Messages",            _ => "Cotton",        };        let reason = super::contacts_app::sf("groups.from_chat", &[("name", title), ("channel", channel)]);        // Written as the groups tool writes a group of people, but here, where the chat is: a phone with Comms and        // no People tool still makes it. Its id is derived from the chat, so two phones make one group.        let namespace = ctx.file.namespace().to_string();        let group_id = cotton_core::cotton_rules::ids::derived_id("contact_group", &[&namespace, &key]);        let at = iso(cotton_tools::mcp::handlers::common::now_ms(ctx));        if rows(ctx, "SELECT id FROM cotton_groups WHERE id = ?", &[SqlValue::Text(group_id.clone())])?.is_empty() {            let mut row = Map::new();            row.insert("id".into(), Value::from(group_id.clone()));            row.insert("table_id".into(), Value::from("person"));            row.insert("name".into(), Value::from(title));            insert_row(ctx, "cotton_groups", &group_id, row).map_err(|e| e.to_string())?;            for (place, member) in members.iter().enumerate() {                let id = cotton_store::protocol::derived_id::group_member_id(&group_id, member);                let mut patch = Map::new();                patch.insert("id".into(), Value::from(id.clone()));                patch.insert("group_id".into(), Value::from(group_id.clone()));                patch.insert("record_id".into(), Value::from(member.clone()));                patch.insert("place".into(), Value::from((place + 1) as f64));                patch.insert("created_at".into(), Value::from(at.clone()));                patch.insert("updated_at".into(), Value::from(at.clone()));                insert_row(ctx, "cotton_group_members", &id, patch).map_err(|e| e.to_string())?;            }        }        let origin = cotton_core::cotton_rules::ids::derived_id("group_origin", &[&namespace, &group_id]);        if !rows(ctx, &format!("SELECT id FROM {ORIGIN} WHERE id = ?"), &[SqlValue::Text(origin.clone())])?.is_empty() {            continue;        }        let mut patch = Map::new();        patch.insert("workspace_id".into(), Value::from(ctx.workspace_id.to_string()));        patch.insert("group_id".into(), Value::from(group_id));        patch.insert("made_by".into(), Value::from("app"));        patch.insert("reason".into(), Value::from(reason));        patch.insert("from".into(), Value::from(key));        patch.insert("created_at".into(), Value::from(at.clone()));        patch.insert("updated_at".into(), Value::from(at));        insert_row(ctx, ORIGIN, &origin, patch).map_err(|e| e.to_string())?;        count += 1;    }    Ok(count)}/// Each part of a count, as (part, steps, ms): what the at-size test breaks a rebuild into.#[cfg(test)]pub(crate) fn tests_parts(ctx: &mut Ctx<'_>) -> Result<Vec<(String, u64, u128)>, String> {    let mut out = Vec::new();    let mut part = |name: &str, ctx: &mut Ctx<'_>, work: &mut dyn FnMut(&mut Ctx<'_>) -> Result<usize, String>| -> Result<(), String> {        let steps = cotton_store::driver::Driver::thread_steps();        let started = Instant::now();        work(ctx)?;        out.push((name.to_string(), cotton_store::driver::Driver::thread_steps() - steps, started.elapsed().as_millis()));        Ok(())    };    for app in APPS {        part(app, ctx, &mut |c| count_app(c, app).map(|(n, _)| n))?;    }    part("chat groups", ctx, &mut make_chat_groups)?;    part("event groups", ctx, &mut make_event_groups)?;    part("domain groups", ctx, &mut make_domain_groups)?;    Ok(out)}