//! `list_people`, `create_person`, `update_person`, `merge_people`,//! `archive_person`, `unarchive_person` — the people block of//! `packages/server/src/mcp/records.ts`.//!//! `merge_people` is the one tool here that is mostly EXECUTION: the decision —//! the refusals, the additive union, the preserving comment, the device card//! and the list of what points at a person — is//! `cotton_core::rules::people::merge`, so the phone's Merge button and this//! tool can never reach different answers. What is left is the ORDER, and the//! order is the safety: refusals first, then the preserving comment, then the//! union, then the device card (clear before claim), then the repoints (each//! idempotent), and the duplicate's archive LAST — so a failure at any step//! leaves both people present and the call retryable.usecrate::mcp::handlers::records_1::person_handles::{ fill_phones_and_emails, handles_of, set_person_handles, Claimed,};use serde_json::{Map, Value};usecrate::mcp::writer::Retract;use cotton_core::constants::{MoneyAccountSubtype, SummaryKind};use cotton_core::rules::people::merge::{ person_repoints, plan_person_merge, PersonMergeClaims, PersonMergeDeviceCard, PersonMergeInput,PersonRepoint, PersonRepointKind,};use cotton_store::protocol::derived_id::{link_id_for, project_link_id, LinkRow};use rusqlite::types::ValueasSqlValue;use std::collections::{BTreeMap, BTreeSet};use cotton_core::rules::people::birthday as birthday_rule;use cotton_core::rules::people::handles::{HandleKind, HandleSource};usecrate::mcp::dispatch::{Ctx, ToolResult};usecrate::mcp::handlers::common::{ insert_row, maybe_row, now_iso, now_ms, or_null, put, rows, summary_out, text, update_row,Valid,};usecrate::mcp::handlers::records_1::validate::{ validate_create_person, validate_id, validate_list_people, validate_merge_people, validate_update_person, Birthday,};usecrate::mcp::handlers::tables::{byline, MADE_BYLINE};usecrate::mcp::protocol::ToolFailure;usecrate::mcp::read_db::{Filter, Order, Query};/// `phones` and `emails` are not columns since v90 — they are the person's/// handles (`person_handles::fill_phones_and_emails`), answered in the shape/// the columns had.const PERSON_LIST_COLUMNS: &[&str] = &["id","full_name","org","role_title","city","archived_at",];/// Every column a merge reads or unions — the whole identity, device link/// included.const PERSON_MERGE_COLUMNS: &[&str] = &["id","full_name","org","role_title","city","timezone","birth_month","birth_day","birth_year","summary","summary_by","summary_updated_at","contact_source","device_contact_id","device_contact_snapshot","avatar_key","archived_at","created_at",];// ── list_people ─────────────────────────────────────────────────────────────/// The order People's default view reads in — All: the people reached most/// recently first, the unreached after, ties by name — so `list_people`/// answers as the phone draws the list. A computed column is read from the/// device's index; while that is being worked out, or where the view says/// no order, the list reads by name.fn people_order(ctx: &Ctx<'_>, mut query: Query) -> Result<Query, ToolFailure> {let tables = crate::definitions::table_definitions(ctx)?;letSome(person) = tables.definitions.iter().find(|table| table.id == "person") else { returnOk(query) };letSome(sort) = person.tool.as_ref().and_then(|tool| tool.views.iter().find(|view| view.is_default)).and_then(|view| view.sort.clone()) else {returnOk(query); };let computed = |key: &str| person.column(key).is_some_and(|column| column.computed.is_some());if (computed(&sort.column) || sort.tie.as_deref().is_some_and(computed)) && !crate::derive::is_current(ctx.read.driver()).map_err(|error| ToolFailure::new(error.to_string()))? {returnOk(query); }for (column, descending) in std::iter::once((&sort.column, sort.descending == Some(true))).chain(sort.tie.iter().map(|tie| (tie, sort.tie_descends()))) {// Only a column the definition holds is named in SQL: the column was validated as an identifier.if person.column(column).is_none() { continue }let value = if computed(column) { format!("(SELECT value FROM _computed WHERE table_id = 'person' AND record_id = cotton_people.id AND key = '{column}')") } else { format!("\"{column}\"") }; query = query .order_by(&format!("NULLIF({value}, '') IS NULL"), Order::Composed) .order_by(&format!("NULLIF({value}, '') COLLATE NOCASE"), if descending { Order::ComposedDesc } else { Order::Composed }); }Ok(query)}/// The whole contact book, paged.////// `q` is a name SUBSTRING (SQLite LIKE, ASCII case-insensitive) —/// deliberately not FTS, whose whole-word matching is exactly what this tool/// exists to escape. `total` counts everything the filters admit, not the page,/// so "how many people" is answered in one call.pubfn list_people(ctx: &mutCtx<'_>, args: &Map<String, Value>) -> ToolResult {let args = validate_list_people(args)?;// Count and page reads carry IDENTICAL filters — built in one place so a// future filter cannot land on one read and skew `total` against the rows.let filtered = || {letmut query = Query::on("cotton_people");if !args.include_archived { query = query.filter(Filter::IsNull("archived_at".to_string())); }ifletSome(q) = &args.q { query = query.filter(Filter::Like("full_name".to_string(), format!("%{q}%"))); }ifletSome(source) = &args.source { query = query.eq("contact_source", source.clone()); } query };let total = rows(ctx, &filtered().columns(&["id"]))?.len() as i64;letmut page = rows( ctx, &people_order(ctx, filtered().columns(PERSON_LIST_COLUMNS))? .order_by("full_name", Order::Asc) .order_by("id", Order::Asc) .limit(args.limit + 1) .offset(args.offset), )?; fill_phones_and_emails(ctx, &mut page)?;let more = page.len() as i64 > args.limit;let people: Vec<Value> = page .into_iter() .take(args.limit as usize) .map(|row| {letmut item = Map::new(); item.insert("id".to_string(), or_null(text(&row, "id"))); item.insert("name".to_string(), or_null(text(&row, "full_name"))); item.insert("phones".to_string(), row.get("phones").cloned().unwrap_or(Value::Null), ); item.insert("emails".to_string(), row.get("emails").cloned().unwrap_or(Value::Null), ); put(&mut item, "org", text(&row, "org").map(Value::from)); put( &mut item,"roleTitle", text(&row, "role_title").map(Value::from), ); put(&mut item, "city", text(&row, "city").map(Value::from));if text(&row, "archived_at").is_some() { item.insert("archived".to_string(), Value::Bool(true)); }Value::Object(item) }) .collect();letmut out = Map::new(); out.insert("total".to_string(), Value::from(total)); out.insert("offset".to_string(), Value::from(args.offset)); out.insert("more".to_string(), Value::Bool(more)); out.insert("people".to_string(), Value::Array(people));// Which person is this database's own ("You"): the one read that tells// whether a merge left the workspace pointing at its survivor.let own = ctx .read .driver() .get("SELECT owner_person_id FROM cotton_workspaces WHERE id = ?", &[SqlValue::Text(ctx.workspace_id.to_string())], ) .map_err(|error| ToolFailure::new(error.to_string()))? .and_then(|row| row.text("owner_person_id").map(str::to_string)) .filter(|id| !id.is_empty()); put(&mut out, "ownPersonId", own.map(Value::from));Ok(Value::Object(out))}// ── create / update ─────────────────────────────────────────────────────────/// Whether this copy keeps the object's whole birthday beside the phone's/// parts: a copy signed in to an object (`rules::people::birthday`).fn whole_birthday_held(ctx: &Ctx<'_>) -> Valid<bool> { birthday_rule::whole_held(ctx.read.driver()).map_err(|error| ToolFailure::new(error.to_string()))}fn birthday_columns(ctx: &Ctx<'_>, patch: &mutMap<String, Value>, birthday: Option<Birthday>) -> Valid<()> {// The trio moves as one: a birthday is whole or absent, never a bare year. patch.insert("birth_month".to_string(), birthday.map_or(Value::Null, |b| Value::from(b.month)), ); patch.insert("birth_day".to_string(), birthday.map_or(Value::Null, |b| Value::from(b.day)), ); patch.insert("birth_year".to_string(), birthday .and_then(|b| b.year) .map_or(Value::Null, Value::from), );// A signed-in copy keeps the object's whole date too. Both forms move in// this one write, so what the phone pushes says the day it shows.if whole_birthday_held(ctx)? {let said = birthday.map(|b| birthday_rule::Birthday { month: b.month, day: b.day, year: b.year }.said()); patch.insert(birthday_rule::WHOLE_COLUMN.to_string(), said.map_or(Value::Null, Value::from)); }Ok(())}/// File a new person.////// Same-name creation is refused unless the caller said two different people/// really share the name — the message import matches senders to contacts by/// EXACT name, so an accidental duplicate quietly splits someone's history/// across two rows.pubfn create_person(ctx: &mutCtx<'_>, args: &Map<String, Value>) -> ToolResult {let args = validate_create_person(args)?;if !args.allow_duplicate_name {let existing = maybe_row( ctx, &Query::on("cotton_people") .columns(&["id", "full_name"]) .eq("full_name", args.full_name.clone()) .filter(Filter::IsNull("archived_at".to_string())), )?;ifletSome(existing) = existing {returnErr(ToolFailure::new(format!("a person named {} already exists (id {}) — update_person changes them; pass \ allowDuplicateName:true only if this is genuinely a second person", args.full_name, text(&existing, "id").unwrap_or_default() ))); } }let id = ctx.new_uuid();letmut patch = Map::new(); patch.insert("full_name".to_string(), Value::from(args.full_name)); patch.insert("org".to_string(), or_null(args.org)); patch.insert("role_title".to_string(), or_null(args.role_title)); patch.insert("city".to_string(), or_null(args.city));ifletSome(language) = args.language { patch.insert("language".into(), Value::from(language)); } patch.insert("timezone".to_string(), or_null(args.timezone)); birthday_columns(ctx, &mut patch, args.birthday)?; patch.insert("contact_source".to_string(), Value::from("manual")); insert_row(ctx, "cotton_people", &id, patch)?;// Each handle is refused when someone else carries it, before anything// is committed: a handle names one person.for (kind, values) in args.handles { set_person_handles(ctx, &id, kind, &values, HandleSource::Manual, Claimed::Refuse)?; } ctx.commit()?;// Someone who writes is a person now: their mail moves to People. resettle_senders(ctx, &id, &[])?;let row = maybe_row( ctx, &Query::on("cotton_people") .columns(&["id", "full_name", "org", "city"]) .eq("id", id.clone()), )? .ok_or_else(|| ToolFailure::new(format!("no person with id {id}")))?;Ok(Value::Object(with_handles(ctx, row)?))}/// The mail senders a person's addresses name — before this write and after/// it — settled again, so their threads move stacks at once (v107).fn resettle_senders(ctx: &mutCtx<'_>, person: &str, before: &[String]) -> Result<(), ToolFailure> {letmut addresses: BTreeSet<String> = before.iter().map(|address| address.to_lowercase()).collect(); addresses.extend(handles_of(ctx, person, HandleKind::Email)?.iter().map(|address| address.to_lowercase()));crate::mcp::handlers::emails::kinds::resettle(ctx, &addresses)?;Ok(())}pubfn update_person(ctx: &mutCtx<'_>, args: &Map<String, Value>) -> ToolResult {let args = validate_update_person(args)?;let emails_before = handles_of(ctx, &args.id, HandleKind::Email)?;// A rename gets the same duplicate guard as a create — a rename onto an// existing name makes every later same-name `create_person` call dangerous,// and quietly merges two people in the owner's eyes.ifletSome(full_name) = &args.full_name {if !args.allow_duplicate_name {let taken = maybe_row( ctx, &Query::on("cotton_people") .columns(&["id", "full_name"]) .eq("full_name", full_name.clone()) .filter(Filter::Ne("id".to_string(),SqlValue::Text(args.id.clone()), )) .filter(Filter::IsNull("archived_at".to_string())), )?;ifletSome(taken) = taken {returnErr(ToolFailure::new(format!("another person already carries the name {} (id {}) — pass \ allowDuplicateName:true only if the two really share it", full_name, text(&taken, "id").unwrap_or_default() ))); } } }let live = Query::on("cotton_people") .eq("id", args.id.clone()) .filter(Filter::IsNull("archived_at".to_string()));if maybe_row(ctx, &live)?.is_none() {returnErr(ToolFailure::new(format!("no live person with id {} (archived people are the owner's to edit)", args.id ))); }letmut patch = Map::new();ifletSome(full_name) = args.full_name { patch.insert("full_name".to_string(), Value::from(full_name)); }for (column, value) in [ ("org", args.org.patch_value()), ("role_title", args.role_title.patch_value()), ("city", args.city.patch_value()), ("timezone", args.timezone.patch_value()), ] {ifletSome(value) = value { patch.insert(column.to_string(), value); } }ifletSome(language) = args.language { patch.insert("language".into(), Value::from(language)); }ifletSome(birthday) = args.birthday { birthday_columns(ctx, &mut patch, birthday)?; }if args.clear_avatar {// Clearing the media-store object key removes the photo. patch.insert("avatar_key".to_string(), Value::Null); } update_row(ctx, "cotton_people", &args.id, patch)?;for (kind, values) in args.handles { set_person_handles(ctx, &args.id, kind, &values, HandleSource::Manual, Claimed::Refuse)?; }// Added after what the person holds NOW, read inside this write.for (kind, values) in args.adds {letmut whole = handles_of(ctx, &args.id, kind)?; whole.extend(values); set_person_handles(ctx, &args.id, kind, &whole, HandleSource::Manual, Claimed::Refuse)?; } ctx.commit()?; resettle_senders(ctx, &args.id, &emails_before)?;let row = maybe_row( ctx, &Query::on("cotton_people") .columns(&["id","full_name","org","role_title","city","summary","summary_by","summary_updated_at","timezone","birth_month","birth_day","birth_year", ]) .eq("id", args.id.clone()), )? .ok_or_else(|| ToolFailure::new(format!("no person with id {}", args.id)))?;let row = with_handles(ctx, row)?;// The same shape `get_record` answers with: ONE `summary` object carrying// its provenance, never three loose columns.let summary = summary_out(ctx, SummaryKind::Person, &args.id, &row)?;letmut out = row; out.remove("summary"); out.remove("summary_by"); out.remove("summary_updated_at"); put(&mut out, "summary", summary);Ok(Value::Object(out))}// ── archive / unarchive ─────────────────────────────────────────────────────fn archive_switch(ctx: &mutCtx<'_>, args: &Map<String, Value>, archiving: bool) -> ToolResult {let id = validate_id(args)?;let existing = maybe_row( ctx, &Query::on("cotton_people") .columns(&["id", "full_name", "archived_at"]) .eq("id", id.clone()), )? .ok_or_else(|| ToolFailure::new(format!("no person with id {id}")))?;let name = or_null(text(&existing, "full_name"));let archived = text(&existing, "archived_at").is_some();let key = if archiving {"alreadyArchived" } else {"alreadyLive" };if archived == archiving {letmut out = Map::new(); out.insert("id".to_string(), Value::from(id)); out.insert("name".to_string(), name); out.insert(key.to_string(), Value::Bool(true));returnOk(Value::Object(out)); }letmut patch = Map::new(); patch.insert("archived_at".to_string(),if archiving {Value::from(now_iso(ctx)) } else {Value::Null }, ); update_row(ctx, "cotton_people", &id, patch)?; ctx.commit()?;letmut out = Map::new(); out.insert("id".to_string(), Value::from(id)); out.insert("name".to_string(), name); out.insert(key.to_string(), Value::Bool(false));Ok(Value::Object(out))}pubfn archive_person(ctx: &mutCtx<'_>, args: &Map<String, Value>) -> ToolResult { archive_switch(ctx, args, true)}pubfn unarchive_person(ctx: &mutCtx<'_>, args: &Map<String, Value>) -> ToolResult { archive_switch(ctx, args, false)}// ── merge_people ────────────────────────────────────────────────────────────fn person_merge_input(row: &Map<String, Value>) -> PersonMergeInput {let list = |column: &str| -> Vec<String> { row.get(column) .and_then(Value::as_array) .map(|items| { items .iter() .filter_map(Value::as_str) .map(str::to_string) .collect() }) .unwrap_or_default() };let number = |column: &str| -> Option<i64> { row.get(column).and_then(Value::as_i64) };PersonMergeInput { id: text(row, "id").unwrap_or_default(), full_name: text(row, "full_name").unwrap_or_default(), phones: list("phones"), emails: list("emails"), org: text(row, "org"), role_title: text(row, "role_title"), city: text(row, "city"), timezone: text(row, "timezone"), birth_month: number("birth_month"), birth_day: number("birth_day"), birth_year: number("birth_year"), summary: text(row, "summary"), summary_by: text(row, "summary_by"), summary_updated_at: text(row, "summary_updated_at"), contact_source: text(row, "contact_source").unwrap_or_default(), device_contact_id: text(row, "device_contact_id"), device_contact_snapshot: row .get("device_contact_snapshot") .cloned() .unwrap_or(Value::Null), avatar_key: text(row, "avatar_key"), archived_at: text(row, "archived_at"), created_at: text(row, "created_at").unwrap_or_default(), }}fn read_person(ctx: &Ctx<'_>, id: &str, role: &str) -> Valid<Map<String, Value>> {let row = maybe_row( ctx, &Query::on("cotton_people") .columns(PERSON_MERGE_COLUMNS) .eq("id", id.to_string()), )? .ok_or_else(|| ToolFailure::new(format!("no person with id {id} ({role})")))?; with_handles(ctx, with_whole_birthday(ctx, id, row)?)}/// A person row's birthday parts by the one rule (`rules::people::birthday`):/// on a signed-in copy, a birthday the object keeps whole reads as parts, so a/// merge sees a birthday the person has, whichever form holds it.fn with_whole_birthday(ctx: &Ctx<'_>, id: &str, mut row: Map<String, Value>) -> Valid<Map<String, Value>> {if !whole_birthday_held(ctx)? {returnOk(row); }// Read straight from the copy: the whole date is a kit column this copy holds (`whole_birthday_held`), which the// build's compiled spec for `cotton_people` does not name, so a checked query refuses it (Android, 28 Nov 2026).let whole = ctx .db() .get(&format!("SELECT {column} AS whole FROM cotton_people WHERE id = ?", column = birthday_rule::WHOLE_COLUMN), &[SqlValue::Text(id.to_string())]) .map_err(|error| ToolFailure::new(error.to_string()))? .and_then(|found| found.text("whole").map(str::to_string));let part = |column: &str| row.get(column).and_then(Value::as_i64);let birthday = birthday_rule::Birthday::of(part("birth_month"), part("birth_day"), part("birth_year"), whole.as_deref()); row.insert("birth_month".into(), birthday.map_or(Value::Null, |b| Value::from(b.month))); row.insert("birth_day".into(), birthday.map_or(Value::Null, |b| Value::from(b.day))); row.insert("birth_year".into(), birthday.and_then(|b| b.year).map_or(Value::Null, Value::from));Ok(row)}/// A people row with its `phones` and `emails` lists, and since v90 its/// social handles (`instagram`, `facebook`, `linkedin`), off its handles.pub(crate) fn with_handles(ctx: &Ctx<'_>, row: Map<String, Value>) -> Valid<Map<String, Value>> {letmut rows = [row]; fill_phones_and_emails(ctx, &mut rows)?;let [mut row] = rows;let id = text(&row, "id").unwrap_or_default();for kind in [HandleKind::Instagram, HandleKind::Facebook, HandleKind::Linkedin] {let values = handles_of(ctx, &id, kind)?;if !values.is_empty() { row.insert(kind.as_str().to_string(), Value::Array(values.into_iter().map(Value::from).collect())); } }Ok(row)}/// Read the claim accounts before either person's references move. Removing/// the old ledger engine does not make a claim already in the file disappear.fn claims_of(ctx: &Ctx<'_>, person_id: &str) -> Valid<Vec<String>> {let subtypes = [MoneyAccountSubtype::Receivable,MoneyAccountSubtype::Payable,MoneyAccountSubtype::LentOut,MoneyAccountSubtype::Loan, ].into_iter().map(|subtype| SqlValue::Text(subtype.as_str().to_string())).collect();let query = Query::on("cotton_money_accounts") .columns(&["subtype"]) .eq("counterparty_person_id", person_id.to_string()) .filter(Filter::In("subtype".to_string(), subtypes));Ok(rows(ctx, &query)?.into_iter().filter_map(|row| text(&row, "subtype")).collect())}/// One merge is one transaction: every step below commits as it goes (a/// later step reads what an earlier one moved), and a refusal anywhere —/// the fold's included — rolls all of them back. On Mac 160 a merge refused/// at the money repoint had already moved the handles, the msg contacts and/// the workspace's owner (architect, 21 Oct 2026).pubfn merge_people(ctx: &mutCtx<'_>, args: &Map<String, Value>) -> ToolResult {crate::mcp::handlers::tables::atomically(ctx, |ctx| merge_people_in(ctx, args))}/// The phone's own part of a merge (CONTACTS-ANSWERS 5.1): the survivor filled from the duplicate, sealed, by the/// plan's union and its refusals. Nothing is repointed and nobody archived: the object does that in one write/// (`merge_people` on `/v1/act`), and its record of what moved is the one record of the merge.pubfn merge_union(ctx: &mutCtx<'_>, survivor_id: &str, duplicate_id: &str) -> Valid<()> {crate::mcp::handlers::tables::atomically(ctx, |ctx| {let survivor_row = read_person(ctx, survivor_id, "keep")?;let duplicate_row = read_person(ctx, duplicate_id, "drop")?;let survivor = person_merge_input(&survivor_row);let duplicate = person_merge_input(&duplicate_row);let claims = PersonMergeClaims { survivor: claims_of(ctx, &survivor.id)?, duplicate: claims_of(ctx, &duplicate.id)? };let plan = plan_person_merge(&survivor, &duplicate, now_ms(ctx), &claims).map_err(|error| ToolFailure::new(error.to_string()))?;ifletSome(refusal) = &plan.refusal {returnErr(ToolFailure::new(refusal.say(&crate::presentation::line_rows(ctx.read.driver(), ctx.workspace_id)))); } fill_survivor(ctx, &survivor.id, &plan.survivor_patch)?;Ok(()) })}/// Step 2 of a merge: the union, additive only, on the columns this copy's person storage holds.fn fill_survivor(ctx: &mutCtx<'_>, survivor: &str, survivor_patch: &Map<String, Value>) -> Valid<()> {if survivor_patch.is_empty() {returnOk(()); }letmut patch = survivor_patch.clone();// Only what this copy's person storage holds: a copy made before a kit column (`birthday`) fills the rest// when it gains it, and a merge is never refused for a column it has no place for (Android, 28 Nov 2026).let held: BTreeSet<String> = ctx .db() .all("SELECT name FROM pragma_table_info('cotton_people')", &[]) .map_err(|error| ToolFailure::new(error.to_string()))? .iter() .filter_map(|row| row.text("name").map(str::to_string)) .collect(); patch.retain(|column, _| held.contains(column));// A birthday the survivor takes moves both its forms, as every write does.if patch.contains_key("birth_month") {let part = |column: &str| patch.get(column).and_then(Value::as_i64);let taken = birthday_rule::Birthday::of(part("birth_month"), part("birth_day"), part("birth_year"), None) .map(|b| Birthday { month: b.month, day: b.day, year: b.year }); birthday_columns(ctx, &mut patch, taken)?; patch.retain(|column, _| held.contains(column)); }if !patch.is_empty() { update_row(ctx, "cotton_people", survivor, patch)?; } ctx.commit()?;Ok(())}fn merge_people_in(ctx: &mutCtx<'_>, args: &Map<String, Value>) -> ToolResult {let (survivor_id, duplicate_id) = validate_merge_people(args)?;let survivor_row = read_person(ctx, &survivor_id, "survivorId")?;let duplicate_row = read_person(ctx, &duplicate_id, "duplicateId")?;let survivor = person_merge_input(&survivor_row);let duplicate = person_merge_input(&duplicate_row);let claims = PersonMergeClaims { survivor: claims_of(ctx, &survivor.id)?, duplicate: claims_of(ctx, &duplicate.id)?, };let plan = plan_person_merge(&survivor, &duplicate, now_ms(ctx), &claims) .map_err(|error| ToolFailure::new(error.to_string()))?;ifletSome(refusal) = &plan.refusal {returnErr(ToolFailure::new(refusal.say(&crate::presentation::line_rows(ctx.read.driver(), ctx.workspace_id)))); }// What points at a person is what this database's definitions say links// to one — an imported tool's included — worked out before anything moves.let repoints = person_repoints(&crate::definitions::shared_table_definitions(ctx)?.definitions) .map_err(|error| ToolFailure::new(error.to_string()))?;// 1. Preserve the duplicate's card on the survivor BEFORE anything moves,// so what the duplicate said is readable after the merge without an audit// dig.ifletSome(comment) = &plan.preserving_comment {let id = ctx.new_uuid();letmut patch = Map::new(); patch.insert("record_kind".to_string(),Value::from( serde_json::to_value(comment.record_kind) .ok() .and_then(|value| value.as_str().map(str::to_string)) .unwrap_or_else(|| "person".to_string()), ), ); patch.insert("record_id".to_string(),Value::from(comment.record_id.clone()), ); patch.insert("parent_id".to_string(), Value::Null);let lines = crate::presentation::line_rows(ctx.read.driver(), ctx.workspace_id); patch.insert("body".to_string(), Value::from(comment.body.say(&lines))); patch.insert("author_kind".to_string(), Value::from("agent")); patch.insert("anchor".to_string(), Value::Null); patch.insert("author_label".to_string(), Value::from(ctx.agent)); insert_row(ctx, "cotton_comments", &id, patch)?; ctx.commit()?; }// 2. The union, additive only — computed by the plan, written here. fill_survivor(ctx, &survivor.id, &plan.survivor_patch)?;// 3. The device-book link. The clear must land before the claim — one// device contact belongs to one person by index, which is why the plan// hands them over in that order.let device_card = plan.device_card.outcome();if plan.device_card.duplicate_patch().is_some() {letmut patch = Map::new(); patch.insert("device_contact_id".to_string(), Value::Null); patch.insert("device_contact_snapshot".to_string(), Value::Null); update_row(ctx, "cotton_people", &duplicate.id, patch)?; ctx.commit()?; }ifletPersonMergeDeviceCard::Moved { survivor_patch, .. } = &plan.device_card {letmut patch = Map::new(); patch.insert("device_contact_id".to_string(),Value::from(survivor_patch.device_contact_id.clone()), ); patch.insert("device_contact_snapshot".to_string(), survivor_patch.device_contact_snapshot.clone(), ); update_row(ctx, "cotton_people", &survivor.id, patch)?; ctx.commit()?; }// 4. Repoints, walking core's `person_repoints`.letmut repointed: Map<String, Value> = Map::new();for repoint in &repoints {let moved = match repoint.kind {PersonRepointKind::Column => repoint_column(ctx, repoint, &survivor.id, &duplicate.id)?,PersonRepointKind::Comments => { repoint_comments(ctx, repoint, &survivor.id, &duplicate.id)? }PersonRepointKind::Links => repoint_links(ctx, repoint, &survivor.id, &duplicate.id)?,PersonRepointKind::ProjectLinks => { repoint_project_links(ctx, repoint, &survivor.id, &duplicate.id)? } };if moved > 0 {let total = repointed .get(repoint.table.as_ref()) .and_then(Value::as_i64) .unwrap_or(0) + moved; repointed.insert(repoint.table.to_string(), Value::from(total)); } }// 5. Only now, with nothing left pointing at them, the duplicate is put// away. Archived, never deleted.ifletSome(archive) = &plan.archive_duplicate {letmut patch = Map::new(); patch.insert("archived_at".to_string(),Value::from(archive.archived_at.clone()), ); update_row(ctx, "cotton_people", &duplicate.id, patch)?; ctx.commit()?; }let merged = maybe_row( ctx, &Query::on("cotton_people") .columns(&["id", "full_name", "org", "role_title", "city"]) .eq("id", survivor.id.clone()), )? .ok_or_else(|| ToolFailure::new(format!("no person with id {}", survivor.id)))?;let merged = with_handles(ctx, merged)?;letmut duplicate_out = Map::new(); duplicate_out.insert("id".to_string(), Value::from(duplicate.id)); duplicate_out.insert("name".to_string(), Value::from(duplicate.full_name)); duplicate_out.insert("archived".to_string(), Value::Bool(true));letmut out = Map::new(); out.insert("survivor".to_string(), Value::Object(merged)); out.insert("duplicate".to_string(), Value::Object(duplicate_out)); out.insert("repointed".to_string(), Value::Object(repointed)); out.insert("deviceCard".to_string(), Value::from(device_card));ifletPersonMergeDeviceCard::Orphaned { orphaned_device_contact_id, .. } = &plan.device_card { out.insert("orphanedDeviceContactId".to_string(),Value::from(orphaned_device_contact_id.clone()), ); }Ok(Value::Object(out))}/// A plain column: one write per row keyed on the duplicate, so a re-run finds/// nothing left to move.fn repoint_column( ctx: &mutCtx<'_>, repoint: &PersonRepoint, survivor_id: &str, duplicate_id: &str,) -> Valid<i64> {if repoint.table == HANDLES {return repoint_handles(ctx, survivor_id, duplicate_id); }if cotton_store::schema::specs::spec_for(&repoint.table).is_none() {return repoint_made_column(ctx, repoint, survivor_id, duplicate_id); }let query = Query::on(&repoint.table) .columns(&["id"]) .eq(&repoint.column, duplicate_id.to_string());let ids: Vec<String> = rows(ctx, &query)? .into_iter() .filter_map(|row| text(&row, "id")) .collect();for id in &ids {letmut patch = Map::new(); patch.insert(repoint.column.to_string(), Value::from(survivor_id)); update_row(ctx, &repoint.table, id, patch)?; } ctx.commit()?;Ok(ids.len() as i64)}/// A made table's link column (a tool a person imported): no typed spec/// knows it, so its rows are found by SQL over the definition's own/// identifiers and written as `update_record` writes one — the byline and/// the edited time move with the link.fn repoint_made_column( ctx: &mutCtx<'_>, repoint: &PersonRepoint, survivor_id: &str, duplicate_id: &str,) -> Valid<i64> {let quote = |name: &str| format!("\"{}\"", name.replace('"', "\"\""));letmut sql = format!("SELECT id FROM {} WHERE {} = ?1", quote(&repoint.table), quote(&repoint.column) );letmut params = vec![SqlValue::Text(duplicate_id.to_string())];if repoint.workspace_scoped { sql.push_str(" AND workspace_id = ?2"); params.push(SqlValue::Text(ctx.workspace_id.to_string())); }let ids: Vec<String> = ctx .db() .all(&sql, ¶ms) .map_err(|error| ToolFailure::new(error.to_string()))? .iter() .filter_map(|row| row.text("id").map(str::to_string)) .collect();for id in &ids {letmut patch = Map::new(); patch.insert(repoint.column.to_string(), Value::from(survivor_id)); patch.insert(MADE_BYLINE.to_string(), Value::from(byline(ctx))); patch.insert("updated_at".to_string(), Value::from(now_iso(ctx))); update_row(ctx, &repoint.table, id, patch)?; } ctx.commit()?;Ok(ids.len() as i64)}/// A person's handles, each list read by `position` (then `created_at`, `id`).const HANDLES: &str = "cotton_person_handles";/// The duplicate's handles move to the survivor AFTER the survivor's own, in/// their own order: each kind's list goes on from the survivor's last/// position. Moved as they stood, both lists start at 0, and the two tie on/// position — and on `created_at` when they were made together — so the/// merged list's order fell to the rows' random ids.fn repoint_handles(ctx: &mutCtx<'_>, survivor_id: &str, duplicate_id: &str) -> Valid<i64> {let held = |person: &str| {Query::on(HANDLES) .columns(&["id", "kind", "position"]) .eq("person_id", person.to_string()) .order_by("kind", Order::Asc) .order_by("position", Order::Asc) .order_by("created_at", Order::Asc) .order_by("id", Order::Asc) };letmut next: BTreeMap<String, i64> = BTreeMap::new();for row in rows(ctx, &held(survivor_id))? {let kind = text(&row, "kind").unwrap_or_default();let after = row.get("position").and_then(Value::as_i64).unwrap_or(0) + 1;let slot = next.entry(kind).or_insert(0); *slot = (*slot).max(after); }let moving = rows(ctx, &held(duplicate_id))?;for row in &moving {letSome(id) = text(row, "id") else { continue };let slot = next.entry(text(row, "kind").unwrap_or_default()).or_insert(0);letmut patch = Map::new(); patch.insert("person_id".to_string(), Value::from(survivor_id)); patch.insert("position".to_string(), Value::from(*slot)); *slot += 1; update_row(ctx, HANDLES, &id, patch)?; } ctx.commit()?;Ok(moving.len() as i64)}/// Comments address the person by (record_kind, record_id) with minted ids — a/// plain repoint, same as the columns above.fn repoint_comments( ctx: &mutCtx<'_>, repoint: &PersonRepoint, survivor_id: &str, duplicate_id: &str,) -> Valid<i64> {let query = Query::on(&repoint.table) .columns(&["id"]) .eq("record_kind", "person".to_string()) .eq(&repoint.column, duplicate_id.to_string());let ids: Vec<String> = rows(ctx, &query)? .into_iter() .filter_map(|row| text(&row, "id")) .collect();for id in &ids {letmut patch = Map::new(); patch.insert(repoint.column.to_string(), Value::from(survivor_id)); update_row(ctx, &repoint.table, id, patch)?; } ctx.commit()?;Ok(ids.len() as i64)}/// Record links carry DERIVED ids (the natural key IS the row), so a repoint is/// upsert-the-new-fact + delete-the-old-row. An edge between the two people/// themselves would become a self-edge — it is deleted, not moved. An edge into/// another file keeps its `to_database`: the file is part of the edge, and an/// edge whose `to` end is in another file names that file's record, not this/// person, so only an edge with no target file is repointed by its `to` end.fn repoint_links( ctx: &mutCtx<'_>, repoint: &PersonRepoint, survivor_id: &str, duplicate_id: &str,) -> Valid<i64> {let side_is_from = repoint.column == "from_id";let kind_column = if side_is_from { "from_kind" } else { "to_kind" };letmut query = Query::on(&repoint.table) .columns(&["id", "from_kind", "from_id", "to_kind", "to_id", "to_database"]) .eq(kind_column, "person".to_string()) .eq(&repoint.column, duplicate_id.to_string());if !side_is_from { query = query.filter(Filter::IsNull("to_database".to_string())); }let found = rows(ctx, &query)?;let moved = found.len() as i64;for row in found {let from_kind = text(&row, "from_kind").unwrap_or_default();let to_kind = text(&row, "to_kind").unwrap_or_default();let to_database = text(&row, "to_database");let from_id = if side_is_from { survivor_id.to_string() } else { text(&row, "from_id").unwrap_or_default() };let to_id = if side_is_from { text(&row, "to_id").unwrap_or_default() } else { survivor_id.to_string() };let self_edge = (from_kind == "person" && from_id == survivor_id) && (to_kind == "person" && to_id == survivor_id && to_database.is_none());if !self_edge {let id = link_id_for( &LinkRow { from_kind: &from_kind, from_id: &from_id, to_kind: &to_kind, to_id: &to_id, to_database: to_database.as_deref(), }, ctx.file.id(), );letmut patch = Map::new(); patch.insert("from_kind".to_string(), Value::from(from_kind)); patch.insert("from_id".to_string(), Value::from(from_id)); patch.insert("to_kind".to_string(), Value::from(to_kind)); patch.insert("to_id".to_string(), Value::from(to_id)); patch.insert("to_database".to_string(), to_database.map_or(Value::Null, Value::from), ); insert_row(ctx, &repoint.table, &id, patch)?; }let old = text(&row, "id").unwrap_or_default(); ctx.writer()?.retract(&repoint.table, &old, Retract::Relation); ctx.commit()?; }Ok(moved)}/// Project memberships converge on the derived id too. The survivor's own/// membership wins on collision (the write lands on the existing row).fn repoint_project_links( ctx: &mutCtx<'_>, repoint: &PersonRepoint, survivor_id: &str, duplicate_id: &str,) -> Valid<i64> {let query = Query::on(&repoint.table) .columns(&["id", "project_id", "note", "applied_by", "created_at"]) .eq("record_kind", "person".to_string()) .eq(&repoint.column, duplicate_id.to_string());let found = rows(ctx, &query)?;let moved = found.len() as i64;for row in found {let project_id = text(&row, "project_id").unwrap_or_default();let id = project_link_id(&project_id, "person", survivor_id);if maybe_row( ctx, &Query::on(&repoint.table) .columns(&["id"]) .eq("id", id.clone()), )? .is_none() {letmut patch = Map::new(); patch.insert("project_id".to_string(), Value::from(project_id)); patch.insert("record_kind".to_string(), Value::from("person")); patch.insert("record_id".to_string(), Value::from(survivor_id)); patch.insert("note".to_string(), or_null(text(&row, "note"))); patch.insert("applied_by".to_string(), or_null(text(&row, "applied_by"))); patch.insert("created_at".to_string(), or_null(text(&row, "created_at"))); insert_row(ctx, &repoint.table, &id, patch)?; }let old = text(&row, "id").unwrap_or_default(); ctx.writer()?.retract(&repoint.table, &old, Retract::Relation); ctx.commit()?; }Ok(moved)}// ── the owner's own verb (4e) ───────────────────────────────────────────────/// Rows per commit. `applyContactSync`'s own `SYNC_BATCH`, kept: a whole/// address book in one transaction is one op batch the size of the phone's/// contacts list, and the WhatsApp importer draws the line at the same number.const SYNC_BATCH: usize = 500;/// iOS stores a birthday with no year as 1604 (the Gregorian calendar's/// reference year) and some exports surface it. Any year at or below it is "no/// year", not somebody born in the 1600s — the phone's own `noYearCeiling`/// (`apps/cotton/Sources/CottonUI/Screens/Day/People/PeopleImportSheet.swift`),/// applied here too so the rule holds wherever the contact was/// composed.const NO_YEAR_CEILING: i64 = 1604;/// One contact as the phone reads it.structDeviceContactInput { device_contact_id: String, full_name: String, phones: Vec<String>, emails: Vec<String>, org: Option<String>, role_title: Option<String>, city: Option<String>, birthday: Option<Birthday>,}/// Dedupe + strip empties, preserving order — `contacts.ts::cleanStrings`.fn clean_strings(raw: Option<&Value>, key: &str) -> Valid<Vec<String>> {letSome(raw) = raw else {returnOk(Vec::new()); };if raw.is_null() {returnOk(Vec::new()); }letSome(list) = raw.as_array() else {returnErr(ToolFailure::new(format!("{key} is a list of text"))); };letmut out: Vec<String> = Vec::with_capacity(list.len());for entry in list {letSome(value) = entry.as_str() else {returnErr(ToolFailure::new(format!("{key} is a list of text"))); };let trimmed = value.trim();if !trimmed.is_empty() && !out.iter().any(|held| held == trimmed) { out.push(trimmed.to_string()); } }Ok(out)}/// The card's birthday, or NOTHING.////// A partial or out-of-range date is DROPPED and the contact is kept —/// `contacts.ts:30-37` decides exactly this way, and it is the difference/// between a person arriving without their birthday and a person not arriving/// at all. Deliberately NOT `validate::parse_birthday`, whose whole job is to/// refuse an assistant's malformed argument with a sentence: here the caller is/// the address book, and the address book is not correctable.fn lenient_birthday(raw: Option<&Value>) -> Option<Birthday> {let object = raw?.as_object()?;let whole = |key: &str| -> Option<i64> { object .get(key) .and_then(Value::as_f64) .filter(|value| value.fract() == 0.0 && value.is_finite()) .map(|value| value as i64) };let (month, day) = (whole("month")?, whole("day")?);if !(1..=12).contains(&month) || !(1..=31).contains(&day) {returnNone; }let year = whole("year").filter(|year| *year > NO_YEAR_CEILING);Some(Birthday { month, day, year })}fn device_contacts(args: &Map<String, Value>) -> Valid<Vec<DeviceContactInput>> {letSome(raw) = args.get("contacts") else {returnErr(ToolFailure::new("contacts is the batch the owner chose — pass [] to sync nothing", )); };letSome(list) = raw.as_array() else {returnErr(ToolFailure::new("contacts is a list of the phone's contacts")); };letmut out = Vec::with_capacity(list.len());for entry in list {letSome(object) = entry.as_object() else {returnErr(ToolFailure::new("each contact is an object with deviceContactId and fullName", )); };let required = |key: &str| -> Valid<String> {match object.get(key) {Some(Value::String(value)) if !value.trim().is_empty() => {Ok(value.trim().to_string()) } _ => Err(ToolFailure::new(format!("{key} is required on every contact — a card with no stable id and no name is \ noise in a directory somebody curates" ))), } };let optional = |key: &str| -> Valid<Option<String>> {match object.get(key) {None | Some(Value::Null) => Ok(None),Some(Value::String(value)) => {let trimmed = value.trim();Ok((!trimmed.is_empty()).then(|| trimmed.to_string())) }Some(_) => Err(ToolFailure::new(format!("{key} is text"))), } }; out.push(DeviceContactInput { device_contact_id: required("deviceContactId")?, full_name: required("fullName")?, phones: clean_strings(object.get("phones"), "phones")?, emails: clean_strings(object.get("emails"), "emails")?, org: optional("org")?, role_title: optional("roleTitle")?, city: optional("city")?, birthday: lenient_birthday(object.get("birthday")), }); }Ok(out)}/// What the phone showed, as the mirror will later compare against —/// `engine/contactSync.ts::nextSnapshot`, minus the photo it has not read.fn contact_snapshot(contact: &DeviceContactInput) -> Value {letmut snapshot = Map::new(); snapshot.insert("v".to_string(), Value::from(1)); snapshot.insert("fullName".to_string(), Value::from(contact.full_name.clone())); snapshot.insert("phones".to_string(),Value::Array(contact.phones.iter().cloned().map(Value::from).collect()), ); snapshot.insert("emails".to_string(),Value::Array(contact.emails.iter().cloned().map(Value::from).collect()), ); snapshot.insert("org".to_string(), or_null(contact.org.clone())); snapshot.insert("roleTitle".to_string(), or_null(contact.role_title.clone())); snapshot.insert("city".to_string(), or_null(contact.city.clone())); snapshot.insert("birthday".to_string(),match contact.birthday {None => Value::Null,Some(birthday) => {letmut out = Map::new(); out.insert("month".to_string(), Value::from(birthday.month)); out.insert("day".to_string(), Value::from(birthday.day)); out.insert("year".to_string(), birthday.year.map_or(Value::Null, Value::from), );Value::Object(out) } }, );// [contacts-import-brings-no-avatar] CLOSED 2026-09-12 — on the PHONE, not// here, and that is the right side of the boundary. A card's picture is// BYTES, and bytes do not cross this one: `sync_device_contacts` takes a// card's FIELDS. So the import sheet reads the picture off the address// book it is already holding open, stages a square, and calls// `capture.avatar` for each person this call just made// (`PeopleImportModel.bringFaces`).//// Both snapshot fields stay honestly null rather than absent: the snapshot// is what this call saw of the card, and it saw no picture — a snapshot// that omitted them would read to the mirror as "unknown" where the truth// is "we did not look". snapshot.insert("photoSha".to_string(), Value::Null); snapshot.insert("avatarKey".to_string(), Value::Null);Value::Object(snapshot)}/// A card's numbers and addresses as [`cotton_store::protocol::who`] matches them: each read with NO region guessed,/// so a number written without its country code is never matched by number (it names nobody here, and attaches/// nothing).fn card_matchables(contact: &DeviceContactInput) -> Vec<(&'static str, String)> {letmut out: Vec<(&'static str, String)> = Vec::new();for (kind, values) in [(HandleKind::Phone, &contact.phones), (HandleKind::Email, &contact.emails)] {for value in values {// A number is matched only as written with its country code: none is guessed for it.let international = value.trim_start().starts_with('+') || value.trim_start().starts_with("00");if kind == HandleKind::Phone && !international {continue; }ifletSome(key) = cotton_store::protocol::who::who_key(kind, value, None) {if !out.contains(&key) { out.push(key); } } } } out}/// What a card says, for [`crate::people_sources::card_key`]: its numbers and addresses read with no region guessed,/// a value that does not read kept as written (trimmed, lower-cased).fn card_said(contact: &DeviceContactInput) -> Vec<(&'static str, String)> {letmut out: Vec<(&'static str, String)> = Vec::new();for (kind, values) in [(HandleKind::Phone, &contact.phones), (HandleKind::Email, &contact.emails)] {for value in values {let said = cotton_store::protocol::who::who_key(kind, value, None) .map(|(_, v)| v) .unwrap_or_else(|| value.split_whitespace().collect::<String>().to_lowercase()); out.push((kind.as_str(), said)); } } out}fn folded(name: &str) -> String { cotton_core::cotton_rules::js::collapse_whitespace_and_trim(name).to_lowercase()}/// The person a card from the phone's contacts may be attached to WITHOUT asking (PEOPLE BUILD 1b): an import never/// merges two people by itself. Only when EVERY number and address of the card that can be matched names that one/// living person alone (who(handle): never a shared or archived holder), the card's name is theirs after folding, and/// no other card of this run holds any of those handles. Anything less makes the card a person of its own; the/// handles they share are kept as shared, the evidence "Same person?" reads.fn attach_target(ctx: &Ctx<'_>, contact: &DeviceContactInput, run_holds: &BTreeMap<(&'static str, String), usize>) -> Valid<Option<String>> {let matchables = card_matchables(contact);if matchables.is_empty() {returnOk(None); }letmut person: Option<cotton_store::protocol::who::Holder> = None;for key in &matchables {if run_holds.get(key).copied().unwrap_or(0) > 1 {returnOk(None); }let who = cotton_store::protocol::who::who(ctx.db(), ctx.workspace_id, key.0, &key.1).map_err(|error| ToolFailure::new(error.to_string()))?;letSome(holder) = who.one().cloned() else { returnOk(None) };match &person {Some(seen) if seen.id != holder.id => returnOk(None), _ => person = Some(holder), } }Ok(person.filter(|holder| folded(&holder.full_name) == folded(&contact.full_name)).map(|holder| holder.id))}/// A card's handles onto `person`: each one nobody holds is theirs; one another contact already holds (or a card/// earlier in this run took) is kept as SHARED on them, never dropped and never moved (PEOPLE BUILD 1b).fn card_handles_onto( ctx: &mutCtx<'_>, person: &str, contact: &DeviceContactInput, source: &str, claimed: &mut BTreeMap<(HandleKind, String), String>,) -> Valid<()> { hold_handles(ctx, person, &contact.phones, &contact.emails, Some(source), HandleSource::Contacts, claimed)}/// Give `person` these numbers and addresses (PEOPLE BUILD 1b): one nobody holds becomes theirs; one another/// living contact already holds is kept as SHARED (both keep it: a household landline, an office line), never/// refused and never taken. A value the one normaliser does not read is skipped. `claimed` carries what this run/// already handed out, so a batch sees its own writes.pubfn hold_handles( ctx: &mutCtx<'_>, person: &str, phones: &[String], emails: &[String], source: Option<&str>, how: HandleSource, claimed: &mut BTreeMap<(HandleKind, String), String>,) -> Valid<()> {usecrate::mcp::handlers::records_1::person_handles::handle_form;for (kind, values) in [(HandleKind::Phone, phones), (HandleKind::Email, emails)] {for value in values {letSome(normalised) = handle_form(ctx, kind, value) else { continue };let holder = match claimed.get(&(kind, normalised.clone())) {Some(holder) => Some(holder.clone()),None => ctx .db() .get("SELECT person_id FROM cotton_person_handles WHERE workspace_id = ? AND kind = ? AND normalised = ?", &[SqlValue::Text(ctx.workspace_id.to_string()), SqlValue::Text(kind.as_str().to_string()), SqlValue::Text(normalised.clone())], ) .map_err(|error| ToolFailure::new(error.to_string()))? .and_then(|row| row.text("person_id").map(str::to_string)), };match holder {Some(holder) if holder == person => {}Some(_) => crate::people_sources::share(ctx, person, kind.as_str(), value, &normalised, source)?,None => { claimed.insert((kind, normalised), person.to_string());crate::mcp::handlers::records_1::person_handles::add_person_handle(ctx, person, kind, value, how, None)?; } } } }Ok(())}/// `sync_device_contacts` — file a batch of the phone's own contacts as people.////// `packages/core/src/services/people.service.ts::applyContactSync`, insert/// half. THE IDENTITY SPINE: every row carries `device_contact_id`, which/// `uq_cotton_people_device_contact` makes unique, and a contact already on a/// row is SKIPPED. That is what makes a second run safe, what makes renaming/// somebody in Cotton harmless, and what lets `read.peopleImport` draw "already/// in People" — a name comparison could do none of the three.////// The pass guards against ITSELF as well as against the file: two entries/// sharing a `deviceContactId` in one call would hit the unique index and the/// fold refuses the whole batch, so a single malformed pair would otherwise/// lose the entire sync. The TypeScript says the same thing at the same place.////// WHY IT IS THE OWNER'S AND NOT AN ASSISTANT'S. The address book lives on the/// owner's phone: there is no reading of it an assistant could do, and a verb/// that mints people from a list it was handed is the owner's own act of/// deciding who joins their directory. So it lands on/// [`crate::mcp::protocol::McpScope::Owner`].////// WHAT IT DELIBERATELY DOES NOT DO. No avatars (see [`contact_snapshot`]), and/// no UPDATE half — `applyContactSync` also patches people already linked when/// the phone's card has drifted, which is the contact MIRROR, a surface the/// phone does not draw yet. `updated` and `missing` are therefore absent from/// the answer rather than reported as zero: a caller must not read "0 updated"/// as "nothing had drifted".pubfn sync_device_contacts(ctx: &mutCtx<'_>, args: &Map<String, Value>) -> ToolResult {let contacts = device_contacts(args)?;// ONE column, not the whole row: this runs over every linked person, and a// full row would decode phones, emails and the snapshot of each — thousands// of parses to build a set of ids. The TypeScript's own reason, kept.let existing = rows( ctx, &Query::on("cotton_people") .columns(&["id", "device_contact_id"]) .filter(Filter::NotNull("device_contact_id".to_string())), )?;let legacy: BTreeMap<String, String> = existing .iter() .filter_map(|row| Some((text(row, "device_contact_id")?, text(row, "id")?))) .collect();let device = crate::people_sources::this_device(ctx)?;letmut inserted_ids: Vec<String> = Vec::new();letmut attached: Vec<String> = Vec::new();letmut seen: BTreeSet<String> = BTreeSet::new();// This run's own handles, which the file does not show until the batch commits.letmut claimed: BTreeMap<(HandleKind, String), String> = BTreeMap::new();// How many cards of this run carry each matchable handle: a handle two cards hold attaches neither.letmut run_holds: BTreeMap<(&'static str, String), usize> = BTreeMap::new();for contact in &contacts {for key in card_matchables(contact) { *run_holds.entry(key).or_insert(0) += 1; } }// How many cards of this run say the same thing so far: the n-th is told apart from the first.letmut said_before: BTreeMap<String, usize> = BTreeMap::new();let namespace = ctx.file.namespace().to_string();letmut skipped: i64 = 0;letmut pending = 0usize;for contact in &contacts {if !seen.insert(contact.device_contact_id.clone()) { skipped += 1;continue; }let said = card_said(contact);let first_key = crate::people_sources::card_key(&namespace, &contact.full_name, &said, 0);let nth = {let count = said_before.entry(first_key).or_insert(0); *count += 1; *count - 1 };let card_key = crate::people_sources::card_key(&namespace, &contact.full_name, &said, nth);// PEOPLE BUILD 1: the source first. A card this device already brought in is its contact's, whatever he// renamed or merged since.let card = crate::people_sources::Source::address_book(&device, &contact.device_contact_id, &contact.full_name).keyed(card_key.clone());ifcrate::people_sources::person_of(ctx, &card)?.is_some() { skipped += 1;continue; }// A card brought in before sources were kept carries its id on the person.ifletSome(person) = legacy.get(&contact.device_contact_id) {crate::people_sources::record(ctx, person, &card)?; skipped += 1;continue; }// PEOPLE BUILD 1b: the same card on another of his phones (it says exactly the same thing) is that contact.let source_id = card.id(&namespace);ifletSome(person) = crate::people_sources::person_of_card(ctx, &card_key)? {crate::people_sources::record(ctx, &person, &card)?; card_handles_onto(ctx, &person, contact, &source_id, &mut claimed)?; attached.push(person); pending += 1;continue; }// A card every matchable handle of which names one living person alone, under their name, is that person.ifletSome(person) = attach_target(ctx, contact, &run_holds)? {crate::people_sources::record(ctx, &person, &card)?; card_handles_onto(ctx, &person, contact, &source_id, &mut claimed)?; attached.push(person); pending += 1;continue; }// A person of its own. The id is the card's (what it says), so two phones bringing the same card in at once// make one person; a person under that id already in the bin leaves a new one to a fresh id.let derived = cotton_core::cotton_rules::ids::derived_id("person", &[&namespace, "address_book", &card_key]);let taken = ctx .db() .get("SELECT trashed_at, archived_at FROM cotton_people WHERE id = ?", &[SqlValue::Text(derived.clone())]) .map_err(|error| ToolFailure::new(error.to_string()))?;ifletSome(row) = &taken {if row.text("trashed_at").is_none() && row.text("archived_at").is_none() {// Made by another phone, its source not here yet: the same card.crate::people_sources::record(ctx, &derived, &card)?; card_handles_onto(ctx, &derived, contact, &source_id, &mut claimed)?; attached.push(derived); pending += 1;continue; } }let id = if taken.is_some() { ctx.new_uuid() } else { derived };letmut patch = Map::new(); patch.insert("full_name".to_string(), Value::from(contact.full_name.clone())); patch.insert("org".to_string(), or_null(contact.org.clone())); patch.insert("role_title".to_string(), or_null(contact.role_title.clone())); patch.insert("city".to_string(), or_null(contact.city.clone())); birthday_columns(ctx, &mut patch, contact.birthday)?; patch.insert("timezone".to_string(), Value::Null); patch.insert("contact_source".to_string(), Value::from("import")); patch.insert("device_contact_id".to_string(),Value::from(contact.device_contact_id.clone()), ); patch.insert("device_contact_snapshot".to_string(), contact_snapshot(contact), ); insert_row(ctx, "cotton_people", &id, patch)?;crate::people_sources::record(ctx, &id, &card)?;// A number another contact holds (a household landline, an office line) is kept as shared on this one too. card_handles_onto(ctx, &id, contact, &source_id, &mut claimed)?; inserted_ids.push(id); pending += 1;if pending >= SYNC_BATCH { ctx.commit()?; pending = 0; } }// The run's line in the Imports tool's history (`cotton_imports`).crate::imports::record( ctx,crate::imports::ImportSource::Contacts,"Phone contacts", inserted_ids.len() as i64, skipped, )?; ctx.commit()?;// Read back in input order, and a row that failed to land is left out// rather than invented — `inserted` counts what the FILE holds, which is// why the TypeScript answers `people.length` and not `insertedIds.length`.//// CAMEL CASE, like `toIPerson` and like `read.peopleImport`'s own rows: the// same person read two ways would be two shapes for one thing.letmut people: Vec<Value> = Vec::with_capacity(inserted_ids.len());for id in &inserted_ids {let row = maybe_row( ctx, &Query::on("cotton_people") .columns(&["id", "full_name", "org", "city", "device_contact_id"]) .eq("id", id.clone()), )?;letSome(row) = row else { continue };let row = with_handles(ctx, row)?;letmut out = Map::new(); out.insert("id".to_string(), or_null(text(&row, "id"))); out.insert("name".to_string(), or_null(text(&row, "full_name"))); out.insert("phones".to_string(), row.get("phones").cloned().unwrap_or_else(|| Value::Array(Vec::new())), ); out.insert("emails".to_string(), row.get("emails").cloned().unwrap_or_else(|| Value::Array(Vec::new())), ); out.insert("org".to_string(), or_null(text(&row, "org"))); out.insert("city".to_string(), or_null(text(&row, "city"))); out.insert("deviceContactId".to_string(), or_null(text(&row, "device_contact_id")), ); people.push(Value::Object(out)); }letmut out = Map::new(); out.insert("inserted".to_string(), Value::from(people.len() as i64)); out.insert("attached".to_string(), Value::from(attached.len() as i64)); out.insert("skipped".to_string(), Value::from(skipped)); out.insert("people".to_string(), Value::Array(people));Ok(Value::Object(out))}