Cotton code
636 lines · 30.3 KB · RustRaw
//! Same person? and merge, on this phone (PEOPLE-DESIGN b.3, f.3; PEOPLE BUILD 2//! items 2 and 4). The list is DERIVED each time from the evidence, ranked://! 1. a number or email both hold (a share: `shared_handle` beside the//!    holder's own `person_handle`);//! 2. the same address-book card on two contacts (`person_source.card_key`);//! 3. names alone (folded the same, or alike at 0.6 or more by//!    `cotton_rules::name_match`, within the same first word).//!//! Nothing is ever merged by itself. His "not the same" is kept//! (`person_pair`) and the pair is never asked again; "later" hides it for a//! week.//!//! **One merge** ([`merge_now`]), owned by the object (coordinator, 28 Nov 2026): the phone fills the survivor from//! the duplicate (sealed, `merge_union`) and queues `merge_people` for the object, which moves every link in one//! write and keeps the one record of what moved (`person_merge`). Until its answer syncs, the phone draws the merge//! from its queue (`_contacts_pending`, phone-only); after, from `person.merged_into`. **Unmerge** lets go of a merge//! the object never took, and otherwise queues `unmerge_people`. Signed out, the queue waits for sign-in and the//! merge reads as made meanwhile: nothing is lost and nothing is recorded twice.use std::collections::{BTreeMap, HashMap, HashSet};use rusqlite::types::Value as SqlValue;use serde_json::{json, Map, Value};use cotton_core::cotton_rules::name_match::{name_key, name_match_score};use cotton_tools::mcp::dispatch::Ctx;use cotton_tools::mcp::handlers::common::{insert_row, update_row};use super::contacts_app::{held, s, SOURCES};use super::cotton_chat::{read, rows, write, ws};use crate::methods::MethodError;use crate::shell::client::ClientController;pub const METHODS: &[&str] = &["contacts.same.list", "contacts.same", "contacts.same.pair", "contacts.merge", "contacts.unmerge"];const PAIRS: &str = "cotton_person_pair";const SHARED: &str = cotton_store::protocol::who::SHARED_TABLE;/// How long an Unmerge stays possible.const UNMERGE_DAYS: i64 = 30;/// How long "later" hides a pair.const LATER_DAYS: i64 = 7;/// A first-word bucket larger than this is not compared name by name (a very common first name says nothing).const BUCKET_MAX: usize = 60;const NAME_LIKE: f64 = 0.6;pub fn call(client: &ClientController, method: &str, request: &Value) -> Result<Value, MethodError> {    match method {        "contacts.same.list" => list(client),        "contacts.same" => answer(client, request),        "contacts.same.pair" => pair(client, request),        "contacts.merge" => merge_call(client, request),        "contacts.unmerge" => unmerge_call(client, request),        other => Err(MethodError::new("unknown_method", format!("{other} is not a Contacts method"))),    }}fn bad(why: &str) -> MethodError {    MethodError::new("bad_request", why)}fn text(value: &str) -> SqlValue {    SqlValue::Text(value.to_string())}fn str_of<'a>(row: &'a Map<String, Value>, key: &str) -> Option<&'a str> {    row.get(key).and_then(Value::as_str).filter(|v| !v.is_empty())}fn tool(error: cotton_tools::mcp::protocol::ToolFailure) -> String {    error.to_string()}fn now_ms(ctx: &Ctx<'_>) -> i64 {    cotton_tools::mcp::handlers::common::now_ms(ctx)}fn iso(ms: i64) -> String {    chrono::DateTime::from_timestamp_millis(ms).unwrap_or_default().to_rfc3339_opts(chrono::SecondsFormat::Millis, true)}fn ms_of(at: &str) -> Option<i64> {    chrono::DateTime::parse_from_rfc3339(at).ok().map(|t| t.timestamp_millis())}/// Why two contacts may be one, best first.#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]pub enum Why {    Number,    Email,    Source,    Name,}impl Why {    fn words(self) -> String {        s(match self {            Why::Number => "same.why_number",            Why::Email => "same.why_email",            Why::Source => "same.why_source",            Why::Name => "same.why_name",        })    }}/// A living contact as the list compares it.#[derive(Debug, Clone)]struct Living {    name: String,    reach: Vec<String>,    source: Option<String>,}fn living(ctx: &mut Ctx<'_>) -> Result<HashMap<String, Living>, String> {    let away = merged_away(ctx)?;    let people: Vec<Map<String, Value>> = rows(ctx, "SELECT p.id AS id, p.full_name AS name FROM cotton_people p WHERE p.workspace_id = ? AND p.trashed_at IS NULL AND p.archived_at IS NULL", &[ws(ctx)])?        .into_iter()        .filter(|r| str_of(r, "id").is_some_and(|id| !away.contains_key(id)))        .collect();    let mut out: HashMap<String, Living> = people        .into_iter()        .filter_map(|r| Some((str_of(&r, "id")?.to_string(), Living { name: str_of(&r, "name").unwrap_or_default().trim().to_string(), reach: Vec::new(), source: None })))        .collect();    for h in rows(ctx, "SELECT person_id AS person, value FROM cotton_person_handles WHERE workspace_id = ? AND trashed_at IS NULL ORDER BY kind DESC, position, value", &[ws(ctx)])? {        if let (Some(p), Some(v)) = (str_of(&h, "person"), str_of(&h, "value")) {            if let Some(l) = out.get_mut(p) {                l.reach.push(v.to_string());            }        }    }    if cotton_store::protocol::who::shared_held(ctx.db()) {        for h in rows(ctx, &format!("SELECT person, value FROM {SHARED} WHERE workspace_id = ? AND deleted_at IS NULL ORDER BY kind DESC, value"), &[ws(ctx)])? {            if let (Some(p), Some(v)) = (str_of(&h, "person"), str_of(&h, "value")) {                if let Some(l) = out.get_mut(p) {                    l.reach.push(v.to_string());                }            }        }    }    if held(ctx, SOURCES) {        for src in rows(ctx, &format!("SELECT person, kind FROM {SOURCES} WHERE workspace_id = ? AND deleted_at IS NULL ORDER BY first_seen"), &[ws(ctx)])? {            if let (Some(p), Some(k)) = (str_of(&src, "person"), str_of(&src, "kind")) {                if let Some(l) = out.get_mut(p) {                    l.source.get_or_insert_with(|| k.to_string());                }            }        }    }    Ok(out)}fn ordered(a: &str, b: &str) -> (String, String) {    if a <= b { (a.to_string(), b.to_string()) } else { (b.to_string(), a.to_string()) }}/// The pairs last found, by what they were found from: the home, every page and the list ask for them, and on a/// book of 1,500 the name comparisons alone are most of a second (CONTACTS AT SIZE). Found again only when the/// people, their handles and sources, the answers or a queued merge changed, or the day did (a "later" ends).fn found_last() -> &'static std::sync::Mutex<Option<(String, Vec<(String, String, Why)>)>> {    static LAST: std::sync::OnceLock<std::sync::Mutex<Option<(String, Vec<(String, String, Why)>)>>> = std::sync::OnceLock::new();    LAST.get_or_init(|| std::sync::Mutex::new(None))}/// What the pairs are found from, as a short signature.fn found_from(ctx: &mut Ctx<'_>) -> Result<String, String> {    let mut key = vec![ctx.file.namespace().to_string(), ctx.workspace_id.to_string(), iso(now_ms(ctx))[..10].to_string(), super::contacts_facts::people_mark(ctx)?];    for table in [PAIRS, SOURCES, PENDING] {        if held(ctx, table) {            let row = rows(ctx, &format!("SELECT count(*) || ':' || coalesce(max(rowid), 0) AS k FROM {table}"), &[])?;            key.push(row.first().and_then(|r| str_of(r, "k")).unwrap_or_default().to_string());            if table != PENDING {                let row = rows(ctx, &format!("SELECT coalesce(max(updated_at), '') AS k FROM {table}"), &[])?;                key.push(row.first().and_then(|r| str_of(r, "k")).unwrap_or_default().to_string());            }        }    }    Ok(key.join("|"))}/// Every Same person? pair still to ask, ranked, each with its best reason.fn pairs(ctx: &mut Ctx<'_>) -> Result<Vec<(String, String, Why)>, String> {    let key = found_from(ctx)?;    if let Some((had, found)) = found_last().lock().unwrap_or_else(std::sync::PoisonError::into_inner).as_ref() {        if had == &key {            return Ok(found.clone());        }    }    let found = pairs_now(ctx)?;    *found_last().lock().unwrap_or_else(std::sync::PoisonError::into_inner) = Some((key, found.clone()));    Ok(found)}fn pairs_now(ctx: &mut Ctx<'_>) -> Result<Vec<(String, String, Why)>, String> {    let people = living(ctx)?;    let mut found: BTreeMap<(String, String), Why> = BTreeMap::new();    let mut note = |a: &str, b: &str, why: Why| {        if a == b || !people.contains_key(a) || !people.contains_key(b) {            return;        }        let key = ordered(a, b);        let best = found.get(&key).map_or(why, |had| (*had).min(why));        found.insert(key, best);    };    if cotton_store::protocol::who::shared_held(ctx.db()) {        let shared = rows(            ctx,            &format!(                "SELECT s.person AS a, h.person_id AS b, s.kind AS kind FROM {SHARED} s JOIN cotton_person_handles h \                 ON h.workspace_id = s.workspace_id AND h.kind = s.kind AND h.normalised = s.normalised AND h.trashed_at IS NULL \                 WHERE s.workspace_id = ? AND s.deleted_at IS NULL"            ),            &[ws(ctx)],        )?;        for r in shared {            if let (Some(a), Some(b)) = (str_of(&r, "a"), str_of(&r, "b")) {                note(a, b, if str_of(&r, "kind") == Some("email") { Why::Email } else { Why::Number });            }        }    }    if held(ctx, SOURCES) && super::cotton_chat::holds(ctx, SOURCES, "card_key")? {        let same_card = rows(            ctx,            &format!(                "SELECT a.person AS a, b.person AS b FROM {SOURCES} a JOIN {SOURCES} b ON b.workspace_id = a.workspace_id AND b.card_key = a.card_key AND b.person > a.person \                 WHERE a.workspace_id = ? AND a.card_key IS NOT NULL AND a.deleted_at IS NULL AND b.deleted_at IS NULL"            ),            &[ws(ctx)],        )?;        for r in same_card {            if let (Some(a), Some(b)) = (str_of(&r, "a"), str_of(&r, "b")) {                note(a, b, Why::Source);            }        }    }    // Names alone: within each first word, folded alike.    let mut buckets: HashMap<String, Vec<(&String, &Living)>> = HashMap::new();    for (id, l) in &people {        let key = name_key(&l.name);        if let Some(first) = key.split(' ').next().filter(|f| f.chars().count() >= 2) {            buckets.entry(first.to_string()).or_default().push((id, l));        }    }    let mut by_name: Vec<(String, String)> = Vec::new();    for bucket in buckets.values().filter(|b| b.len() >= 2 && b.len() <= BUCKET_MAX) {        for i in 0..bucket.len() {            for j in i + 1..bucket.len() {                let (ia, la) = bucket[i];                let (ib, lb) = bucket[j];                let alike = name_key(&la.name) == name_key(&lb.name) || (la.name.contains(' ') && lb.name.contains(' ') && name_match_score(&la.name, &lb.name) >= NAME_LIKE);                if alike {                    by_name.push((ia.clone(), ib.clone()));                }            }        }    }    for (a, b) in by_name {        note(&a, &b, Why::Name);    }    // His answers.    let now = now_ms(ctx);    let mut answered: HashSet<(String, String)> = HashSet::new();    if held(ctx, PAIRS) {        for r in rows(ctx, &format!("SELECT a, b, answer, answered_at FROM {PAIRS} WHERE workspace_id = ? AND deleted_at IS NULL"), &[ws(ctx)])? {            let (Some(a), Some(b)) = (str_of(&r, "a"), str_of(&r, "b")) else { continue };            let still = match str_of(&r, "answer") {                Some("no") => true,                _ => str_of(&r, "answered_at").and_then(ms_of).is_some_and(|at| now - at < LATER_DAYS * 86_400_000),            };            if still {                answered.insert(ordered(a, b));            }        }    }    let mut out: Vec<(String, String, Why)> = found.into_iter().filter(|(k, _)| !answered.contains(k)).map(|((a, b), why)| (a, b, why)).collect();    out.sort_by(|x, y| x.2.cmp(&y.2).then_with(|| x.0.cmp(&y.0)).then_with(|| x.1.cmp(&y.1)));    Ok(out)}/// How many pairs are still to ask (the home's line).pub(crate) fn count(ctx: &mut Ctx<'_>) -> Result<usize, String> {    Ok(pairs(ctx)?.len())}fn side(id: &str, l: &Living) -> Value {    let from = match l.source.as_deref() {        Some("address_book") => s("person.from_contacts"),        Some("whatsapp") => s("person.from_whatsapp"),        Some("cotton") => s("person.from_cotton"),        Some("mail") => s("person.from_mail"),        Some("photos") => s("person.from_photos"),        Some("health") => s("person.from_health"),        _ => s("person.from_you"),    };    json!({ "id": id, "words": l.name, "detail": from, "initials": cotton_core::messages::app::lay::initials(&l.name), "reach": l.reach })}fn pair_json(a: &str, b: &str, why: Why, people: &HashMap<String, Living>) -> Option<Value> {    let (la, lb) = (people.get(a)?, people.get(b)?);    let act = |id: &str, words: &str, answer: &str| json!({ "id": id, "words": s(words), "call": { "method": "contacts.same", "request": { "a": a, "b": b, "answer": answer } } });    Some(json!({        "a": side(a, la),        "b": side(b, lb),        "why": why.words(),        "acts": [act("yes", "same.yes", "yes"), act("no", "same.no", "no"), act("later", "same.later", "later")],    }))}/// The pairs one contact is in, for its page.pub(crate) fn pairs_of(ctx: &mut Ctx<'_>, id: &str) -> Result<Vec<Value>, String> {    let all = pairs(ctx)?;    let mine: Vec<_> = all.into_iter().filter(|(a, b, _)| a == id || b == id).collect();    if mine.is_empty() {        return Ok(Vec::new());    }    let people = living(ctx)?;    Ok(mine        .iter()        .filter_map(|(a, b, why)| {            let other = if a == id { b } else { a };            let l = people.get(other)?;            Some(json!({ "words": l.name, "detail": why.words(), "call": { "method": "contacts.same.pair", "request": { "a": a, "b": b } } }))        })        .collect())}fn list(client: &ClientController) -> Result<Value, MethodError> {    read(client, "contacts.same.list", |ctx| {        let found = pairs(ctx)?;        let people = living(ctx)?;        let drawn: Vec<Value> = found.iter().filter_map(|(a, b, why)| pair_json(a, b, *why, &people)).collect();        Ok(json!({            "title": s("same.title"),            "count": drawn.len(),            "empty": drawn.is_empty().then(|| json!({ "title": s("same.empty_title"), "message": s("same.empty_message") })),            "pairs": drawn,        }))    })}fn pair(client: &ClientController, request: &Value) -> Result<Value, MethodError> {    let a = request.get("a").and_then(Value::as_str).ok_or_else(|| bad("a and b are the two contacts"))?.to_string();    let b = request.get("b").and_then(Value::as_str).ok_or_else(|| bad("a and b are the two contacts"))?.to_string();    read(client, "contacts.same.pair", |ctx| {        let why = pairs(ctx)?.into_iter().find(|(x, y, _)| (x == &a && y == &b) || (x == &b && y == &a)).map(|(_, _, w)| w).unwrap_or(Why::Name);        let people = living(ctx)?;        Ok(pair_json(&a, &b, why, &people).unwrap_or(Value::Null))    })}fn answer(client: &ClientController, request: &Value) -> Result<Value, MethodError> {    let a = request.get("a").and_then(Value::as_str).ok_or_else(|| bad("a and b are the two contacts"))?.to_string();    let b = request.get("b").and_then(Value::as_str).ok_or_else(|| bad("a and b are the two contacts"))?.to_string();    let said = request.get("answer").and_then(Value::as_str).ok_or_else(|| bad("answer is yes, no or later"))?.to_string();    if a == b {        return Err(bad("a and b are two different contacts"));    }    match said.as_str() {        "yes" => {            // The fuller contact is kept: one he keeps in Close, else the one with more ways to reach, else the longer name.            let (keep, drop) = read(client, "contacts.same.keep", |ctx| {                let weight = |ctx: &mut Ctx<'_>, id: &str| -> Result<(i64, usize, usize), String> {                    let pinned = super::contacts_app::state_of(ctx, id)?.map(|s| s.get("pinned").and_then(|v| v.as_i64().or(v.as_bool().map(i64::from))).unwrap_or(0)).unwrap_or(0);                    let handles = rows(ctx, "SELECT id FROM cotton_person_handles WHERE person_id = ? AND trashed_at IS NULL", &[text(id)])?.len();                    let name = rows(ctx, "SELECT full_name FROM cotton_people WHERE id = ?", &[text(id)])?.first().and_then(|r| str_of(r, "full_name")).map(|n| n.trim().chars().count()).unwrap_or(0);                    Ok((pinned, handles, name))                };                let (wa, wb) = (weight(ctx, &a)?, weight(ctx, &b)?);                Ok(if wb > wa { json!([b, a]) } else { json!([a, b]) })            })            .map(|v| (v[0].as_str().unwrap_or_default().to_string(), v[1].as_str().unwrap_or_default().to_string()))?;            merge_now(client, &keep, &drop)?;            Ok(json!({ "id": keep, "said": s("same.joined") }))        }        "no" | "later" => write(client, "contacts.same.answer", |ctx| {            remember_answer(ctx, &a, &b, &said)?;            ctx.commit().map_err(tool)?;            Ok(json!({ "said": if said == "no" { s("same.kept_apart") } else { String::new() } }))        }),        _ => Err(bad("answer is yes, no or later")),    }}// ── one merge: the object owns it (coordinator, 28 Nov 2026) ─────────────/// The phone's queue of merge acts not yet taken by the object: phone-only (an underscore table never syncs), so a/// merge made signed out, or offline, waits here and its view is drawn from it until the object's answer syncs.const PENDING: &str = "_contacts_pending";fn ensure_pending(ctx: &mut Ctx<'_>) -> Result<(), String> {    ctx.db()        .run(&format!("CREATE TABLE IF NOT EXISTS {PENDING} (id TEXT PRIMARY KEY, act TEXT NOT NULL, keep TEXT NOT NULL, drop_id TEXT, at TEXT NOT NULL, sent_at TEXT)"), &[])        .map(|_| ())        .map_err(|e| e.to_string())}fn pending(ctx: &mut Ctx<'_>) -> Result<Vec<Map<String, Value>>, String> {    if !held(ctx, PENDING) {        return Ok(Vec::new());    }    rows(ctx, &format!("SELECT * FROM {PENDING} ORDER BY at, id"), &[])}/// Who each merged-away contact went into, as this phone sees it now: a merge still queued here, else what the/// object wrote (`person.merged_into`, synced) while the duplicate is archived.pub(crate) fn merged_away(ctx: &mut Ctx<'_>) -> Result<HashMap<String, String>, String> {    let mut out = HashMap::new();    if super::cotton_chat::holds(ctx, "cotton_people", "merged_into")? {        for r in rows(ctx, "SELECT id, merged_into FROM cotton_people WHERE workspace_id = ? AND merged_into IS NOT NULL AND archived_at IS NOT NULL", &[ws(ctx)])? {            if let (Some(d), Some(k)) = (str_of(&r, "id"), str_of(&r, "merged_into")) {                out.insert(d.to_string(), k.to_string());            }        }    }    for r in pending(ctx)? {        if let (Some("merge"), Some(k), Some(d)) = (str_of(&r, "act"), str_of(&r, "keep"), str_of(&r, "drop_id")) {            out.insert(d.to_string(), k.to_string());        }    }    Ok(out)}/// The contacts merged into `keep` that this phone shows on its page meanwhile (their numbers and addresses).pub(crate) fn merged_into_keep(ctx: &mut Ctx<'_>, keep: &str) -> Result<Vec<String>, String> {    Ok(merged_away(ctx)?.into_iter().filter(|(_, k)| k == keep).map(|(d, _)| d).collect())}fn send(client: &ClientController, act: &str, args: Value) -> Result<Option<Value>, String> {    let Some(door) = client.object_door() else { return Ok(None) };    match door.address.send(        door.exchange.as_ref(),        "POST",        cotton_client::transport::object::routes::ACT,        cotton_client::transport::object::bearer(&door.credential),        Some(&json!({ "act": act, "args": args })),    ) {        Ok(answer) => Ok(Some(answer)),        Err(refusal) => {            let said = format!("{refusal:?}");            // Another phone sent it first, or nothing is left to undo: the object holds what this phone meant.            if said.contains("merged_away") || said.contains("nothing_to_unmerge") {                Ok(Some(Value::Null))            } else {                Err(said)            }        }    }}/// Send every queued act the object has not taken (signed in), repoint the sealed links the object names back in/// `left`, and let go of a sent merge once the object's own answer has synced here. Answers how many went.pub(crate) fn send_waiting(client: &ClientController) -> Result<usize, MethodError> {    let queued = read(client, "contacts.pending", |ctx| Ok(Value::from(pending(ctx)?.into_iter().map(Value::Object).collect::<Vec<_>>())))?;    let mut went = 0;    for row in queued.as_array().cloned().unwrap_or_default() {        let (Some(id), Some(act), Some(keep)) = (row["id"].as_str(), row["act"].as_str(), row["keep"].as_str()) else { continue };        let drop = row["drop_id"].as_str().unwrap_or_default().to_string();        let sent_before = row["sent_at"].as_str().is_some();        if !sent_before {            let args = if act == "merge" { json!({ "keep": keep, "drop": drop }) } else { json!({ "id": keep }) };            let name = if act == "merge" { "merge_people" } else { "unmerge_people" };            let answer = match send(client, name, args) {                Ok(Some(answer)) => answer,                Ok(None) => return Ok(went),                Err(why) => {                    eprintln!("[contacts] {name} did not reach the object this time: {why}");                    continue;                }            };            went += 1;            let (id, keep, drop, act) = (id.to_string(), keep.to_string(), drop.clone(), act.to_string());            write(client, "contacts.pending.sent", |ctx| {                if act == "merge" {                    repoint_left(ctx, &answer, &keep, &drop)?;                    ctx.db().run(&format!("UPDATE {PENDING} SET sent_at = ? WHERE id = ?"), &[text(&iso(now_ms(ctx))), text(&id)]).map_err(|e| e.to_string())?;                } else {                    ctx.db().run(&format!("DELETE FROM {PENDING} WHERE id = ?"), &[text(&id)]).map_err(|e| e.to_string())?;                }                ctx.commit().map_err(tool)?;                Ok(Value::Null)            })?;        }    }    // A sent merge whose duplicate the object has archived (its answer synced) is the object's now.    write(client, "contacts.pending.synced", |ctx| {        if !held(ctx, PENDING) {            return Ok(Value::Null);        }        ctx.db()            .run(                &format!("DELETE FROM {PENDING} WHERE act = 'merge' AND sent_at IS NOT NULL AND EXISTS (SELECT 1 FROM cotton_people p WHERE p.id = {PENDING}.drop_id AND p.archived_at IS NOT NULL)"),                &[],            )            .map_err(|e| e.to_string())?;        Ok(Value::Null)    })?;    Ok(went)}/// The links inside a seal the object could not read (`left`: "table.column"), moved here on the tables this copy/// holds, from the duplicate to the survivor.fn repoint_left(ctx: &mut Ctx<'_>, answer: &Value, keep: &str, drop: &str) -> Result<(), String> {    let left: Vec<String> = answer["left"].as_array().map(|l| l.iter().filter_map(Value::as_str).map(str::to_string).collect()).unwrap_or_default();    if left.is_empty() {        return Ok(());    }    let definitions = cotton_tools::definitions::shared_table_definitions(ctx).map_err(tool)?;    for definition in definitions.definitions.iter() {        for column in &definition.columns {            if !left.contains(&format!("{}.{}", definition.id, column.key)) {                continue;            }            let Some(store) = cotton_core::definitions::builtin_store_table(&definition.id).map(str::to_string).or_else(|| Some(format!("cotton_{}", definition.id))) else { continue };            let Ok(found) = rows(ctx, &format!("SELECT id FROM {store} WHERE {} = ?", column.key), &[text(drop)]) else { continue };            for row in found {                let Some(id) = str_of(&row, "id") else { continue };                let mut patch = Map::new();                patch.insert(column.key.clone(), Value::from(keep));                update_row(ctx, &store, id, patch).map_err(tool)?;            }        }    }    Ok(())}/// One merge on this phone: the sealed fill of the survivor here, and the act queued for the object, which moves/// every link and keeps the one record of what moved (`person_merge`). Sent at once when signed in.pub(crate) fn merge_now(client: &ClientController, keep: &str, drop: &str) -> Result<(), MethodError> {    if keep == drop {        return Err(bad("keep and drop are two different contacts"));    }    write(client, "contacts.merge", |ctx| {        if merged_away(ctx)?.contains_key(drop) || merged_away(ctx)?.contains_key(keep) {            return Err("one of them is already merged into someone".into());        }        cotton_tools::mcp::handlers::records_1::people::merge_union(ctx, keep, drop).map_err(tool)?;        // His Close pin and a kind he set carry over to the one kept.        if let Some(theirs) = super::contacts_app::state_of(ctx, drop)? {            let mine = super::contacts_app::state_of(ctx, keep)?;            let mut patch = Map::new();            let on = |row: &Map<String, Value>, k: &str| row.get(k).and_then(|v| v.as_i64().or(v.as_bool().map(i64::from))).unwrap_or(0) > 0;            if on(&theirs, "pinned") && !mine.as_ref().is_some_and(|m| on(m, "pinned")) {                patch.insert("pinned".into(), Value::from(true));            }            if let Some(kind) = str_of(&theirs, "kind").filter(|k| *k != "person") {                if mine.as_ref().and_then(|m| str_of(m, "kind")).is_none_or(|k| k == "person") {                    patch.insert("kind".into(), Value::from(kind));                }            }            if !patch.is_empty() {                super::contacts_app::put_state(ctx, keep, patch)?;            }        }        ensure_pending(ctx)?;        let id = cotton_core::cotton_rules::ids::derived_id("contacts_pending", &["merge", keep, drop]);        ctx.db()            .run(&format!("INSERT OR REPLACE INTO {PENDING} (id, act, keep, drop_id, at, sent_at) VALUES (?, 'merge', ?, ?, ?, NULL)"), &[text(&id), text(keep), text(drop), text(&iso(now_ms(ctx)))])            .map_err(|e| e.to_string())?;        ctx.commit().map_err(tool)?;        Ok(Value::Null)    })?;    send_waiting(client)?;    Ok(())}fn remember_answer(ctx: &mut Ctx<'_>, a: &str, b: &str, said: &str) -> Result<(), String> {    if !held(ctx, PAIRS) {        return Err("this copy does not hold Contacts' tables yet; sync once and try again".into());    }    let (x, y) = ordered(a, b);    let id = cotton_core::cotton_rules::ids::derived_id("person_pair", &[&ctx.file.namespace().to_string(), &x, &y]);    let now = iso(now_ms(ctx));    let mut patch = Map::new();    patch.insert("answer".into(), Value::from(said));    patch.insert("answered_at".into(), Value::from(now.clone()));    patch.insert("updated_at".into(), Value::from(now.clone()));    if rows(ctx, &format!("SELECT id FROM {PAIRS} WHERE id = ?"), &[text(&id)])?.is_empty() {        patch.insert("workspace_id".into(), Value::from(ctx.workspace_id.to_string()));        patch.insert("a".into(), Value::from(x));        patch.insert("b".into(), Value::from(y));        patch.insert("created_at".into(), Value::from(now));        insert_row(ctx, PAIRS, &id, patch).map_err(tool)?;    } else {        update_row(ctx, PAIRS, &id, patch).map_err(tool)?;    }    Ok(())}fn merge_call(client: &ClientController, request: &Value) -> Result<Value, MethodError> {    let keep = request.get("keep").and_then(Value::as_str).ok_or_else(|| bad("keep and drop are the two contacts"))?.to_string();    let drop = request.get("drop").and_then(Value::as_str).ok_or_else(|| bad("keep and drop are the two contacts"))?.to_string();    merge_now(client, &keep, &drop)?;    Ok(json!({ "id": keep, "said": s("same.joined") }))}/// Whether `id` took in someone it can still give back: a merge still queued, or one the object made in 30 days.pub(crate) fn can_unmerge(ctx: &mut Ctx<'_>, id: &str, now: i64) -> Result<bool, String> {    if pending(ctx)?.iter().any(|r| str_of(r, "act") == Some("merge") && str_of(r, "keep") == Some(id)) {        return Ok(true);    }    if !super::cotton_chat::holds(ctx, "cotton_people", "merged_into")? {        return Ok(false);    }    let since = iso(now - UNMERGE_DAYS * 86_400_000);    Ok(!rows(ctx, "SELECT id FROM cotton_people WHERE workspace_id = ? AND merged_into = ? AND archived_at >= ?", &[ws(ctx), text(id), text(&since)])?.is_empty())}fn unmerge_call(client: &ClientController, request: &Value) -> Result<Value, MethodError> {    let id = request.get("id").and_then(Value::as_str).ok_or_else(|| bad("id names the contact"))?.to_string();    let restored = write(client, "contacts.unmerge", |ctx| {        let drops = merged_into_keep(ctx, &id)?;        let queued: Vec<Map<String, Value>> = pending(ctx)?.into_iter().filter(|r| str_of(r, "act") == Some("merge") && str_of(r, "keep") == Some(&id)).collect();        // A merge the object never took is simply let go: nothing was moved anywhere.        let mut object_has = super::cotton_chat::holds(ctx, "cotton_people", "merged_into")?            && !rows(ctx, "SELECT id FROM cotton_people WHERE workspace_id = ? AND merged_into = ?", &[ws(ctx), text(&id)])?.is_empty();        for row in &queued {            object_has |= str_of(row, "sent_at").is_some();            ctx.db().run(&format!("DELETE FROM {PENDING} WHERE id = ?"), &[text(str_of(row, "id").unwrap_or_default())]).map_err(|e| e.to_string())?;        }        // He undid the join: the pair is not asked again (Not the same).        for d in &drops {            remember_answer(ctx, &id, d, "no")?;        }        if object_has {            ensure_pending(ctx)?;            let pid = cotton_core::cotton_rules::ids::derived_id("contacts_pending", &["unmerge", &id, &iso(now_ms(ctx))]);            ctx.db()                .run(&format!("INSERT INTO {PENDING} (id, act, keep, drop_id, at, sent_at) VALUES (?, 'unmerge', ?, NULL, ?, NULL)"), &[text(&pid), text(&id), text(&iso(now_ms(ctx)))])                .map_err(|e| e.to_string())?;        }        ctx.commit().map_err(tool)?;        Ok(Value::from(drops))    })?;    send_waiting(client)?;    let mut ids = vec![Value::from(id)];    ids.extend(restored.as_array().cloned().unwrap_or_default());    Ok(json!({ "ids": ids, "said": s("merge.unmerged") }))}