//! Folding one person into another — the DECISION, once, for every caller. //! The port of `packages/core/src/engine/people/merge.ts`. //! //! Why this lives in core: the MCP tool `merge_people` (the server) and the //! person page's **Merge** button (the phone) both fold a duplicate contact //! into a survivor. Two implementations of "what does the survivor end up //! with, and what is refused" would eventually disagree, and a disagreement //! there is a person's phone number quietly lost on one device and kept on the //! other. So the answer is computed HERE, from rows, and the callers only //! carry it out. //! //! What a plan IS: the refusals, the additive union patch for the survivor, //! the preserving comment's body, the device-card decision, the archive stamp, //! and [`person_repoints`] — what points at a person and has to be moved, //! derived from the database's definitions. //! //! What a plan is NOT: execution. Nothing here reads or writes anything; there //! is no store import and no clock — `now_ms` is passed in. The counts a //! caller reports (`repointed`) come from the writes it actually performed, //! not from here, because only the executor knows how many rows moved. //! //! **THE ORDER the executor must keep, and why.** Every write becomes an op //! the phone folds, so there is no transaction to hide behind: the order IS //! the safety, and it is the same order the server has always used. //! 1. Refusals — before anything moves. //! 2. The preserving comment — the duplicate's card is written onto the //! survivor BEFORE any of it is unioned or dropped, so what the duplicate //! said stays readable without an audit dig. //! 3. The union patch on the survivor. //! 4. The device card: the duplicate's link is CLEARED before the survivor //! claims it — one device contact belongs to one person by index, so the //! other order collides. //! 5. The repoints, in [`person_repoints`] order; each is idempotent (keyed //! on the duplicate), so a re-run converges. //! 6. The duplicate's archive, LAST. A failure at any earlier step therefore //! leaves both people present and the whole call retryable. use std::borrow::Cow; use serde::{Deserialize, Serialize}; use serde_json::{Map, Value}; use cotton_store::protocol::js::{json_stringify, to_iso_string}; use crate::definitions::{ColumnType, TableDefinition}; /// A person as a merge sees them — the columns the merge reads or unions, /// snake_case because that is how the row arrives from the file. /// /// `contact_source` and `created_at` are read by nothing here; they are kept /// because this is the row's shape and a caller mapping a person row should /// not have to remember which two columns to leave behind. #[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)] pub struct PersonMergeInput { pub id: String, pub full_name: String, pub phones: Vec, pub emails: Vec, pub org: Option, pub role_title: Option, pub city: Option, pub timezone: Option, pub birth_month: Option, pub birth_day: Option, pub birth_year: Option, pub summary: Option, pub summary_by: Option, pub summary_updated_at: Option, pub contact_source: String, pub device_contact_id: Option, /// The TypeScript's `unknown` — whatever the phone's mirror last wrote. pub device_contact_snapshot: Value, pub avatar_key: Option, pub archived_at: Option, pub created_at: String, } /// The claim-bearing money accounts each side already holds — read by the /// caller (one row per person per subtype is a unique index), decided here. #[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)] pub struct PersonMergeClaims { pub survivor: Vec, pub duplicate: Vec, } /// The literal `record_kind` of the preserving comment. /// /// The TypeScript's field type is the literal `"person"`, not the twelve-member /// `COMMENT_RECORD_KINDS` union — a merge writes onto a person and onto nothing /// else — so the port spells the literal and this file declares no wider union /// it does not use. #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] pub enum PersonMergeCommentRecordKind { #[serde(rename = "person")] Person, } /// The literal `author_kind` of the preserving comment: an agent wrote it, /// because a merge is something an assistant or a button did, never something /// the owner typed. #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] pub enum PersonMergeCommentAuthorKind { #[serde(rename = "agent")] Agent, } /// The comment written onto the survivor before anything moves. The caller /// adds its own scope (workspace) and identity (`author_label`); everything /// that makes it THIS comment is here. /// /// `parent_id` and `anchor` are typed as the unit, which serialises as `null` /// and can hold nothing else — the TypeScript's field types are the literal /// `null` for the same reason: a preserving comment is a root, and it points at /// no span of anything. #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct PersonMergeComment { pub record_kind: PersonMergeCommentRecordKind, pub record_id: String, pub parent_id: (), pub body: MergedCard, pub author_kind: PersonMergeCommentAuthorKind, pub anchor: (), } /// The preserving comment's body, as a typed fact: the duplicate's name and /// its card before the merge (`JSON.stringify`d). Said in the database's /// `people` lines (`kits/shell/lines/people.json`) where the comment is written. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct MergedCard { pub name: String, pub card: String, } impl MergedCard { /// The body in `rows`' words, the kit's for a line they have none of. pub fn say(&self, rows: &[crate::rules::shell_lines::LineRow]) -> String { crate::rules::shell_lines::resolve( "people", "merge.comment", rows, &[("name", &self.name), ("card", &self.card)], ) .unwrap_or_default() } } /// The clear that frees the unique index: both device-card columns to NULL. /// /// The fields are units, so `null` is the only value either can carry — the /// TypeScript's `{ device_contact_id: null; device_contact_snapshot: null }` is /// a literal type and this is its Rust spelling. Snake_case, because these are /// column names. #[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)] pub struct ClearDeviceCard { pub device_contact_id: (), pub device_contact_snapshot: (), } /// The survivor's claim of the duplicate's device card, snapshot included. #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct ClaimDeviceCard { pub device_contact_id: String, pub device_contact_snapshot: Value, } /// What happens to the duplicate's device (iPhone) contact link. /// /// - `None` — neither person was linked; nothing to do. /// - `Kept` — only the survivor was linked; their link stands untouched. /// - `Moved` — only the duplicate was linked: clear it, then claim it on the /// survivor, so the phone's next mirror pass rewrites that contact with the /// merged details instead of leaving an orphan card. /// - `Orphaned` — both were linked: the duplicate's link is cleared and its /// card stays on the phone until the owner removes it by hand (the mirror /// updates contacts and never deletes them). /// /// The TypeScript is one interface with three optional fields; Rust makes it an /// enum tagged on `outcome`, which serialises to exactly the same JSON and /// additionally makes the three illegal combinations (a `kept` carrying a /// patch, a `moved` naming an orphan, an `orphaned` claiming a card) /// unrepresentable rather than merely untested. #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[serde(tag = "outcome", rename_all = "snake_case")] pub enum PersonMergeDeviceCard { None, Kept, #[serde(rename_all = "camelCase")] Moved { /// Applied FIRST — the clear that frees the unique index. duplicate_patch: ClearDeviceCard, /// Applied second. survivor_patch: ClaimDeviceCard, }, #[serde(rename_all = "camelCase")] Orphaned { duplicate_patch: ClearDeviceCard, /// Reported back so the owner can find the card. orphaned_device_contact_id: String, }, } impl PersonMergeDeviceCard { /// The wire string the TypeScript's `outcome` field carries. pub const fn outcome(&self) -> &'static str { match self { PersonMergeDeviceCard::None => "none", PersonMergeDeviceCard::Kept => "kept", PersonMergeDeviceCard::Moved { .. } => "moved", PersonMergeDeviceCard::Orphaned { .. } => "orphaned", } } /// The clear to apply to the duplicate, where there is one. pub const fn duplicate_patch(&self) -> Option { match self { PersonMergeDeviceCard::Moved { duplicate_patch, .. } | PersonMergeDeviceCard::Orphaned { duplicate_patch, .. } => Some(*duplicate_patch), _ => None, } } } /// The duplicate's archive stamp. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct PersonMergeArchive { pub archived_at: String, } /// The whole plan. #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct PersonMergePlan { /// `Some` means: do nothing at all, and fail with this refusal, said in /// the database's `refusal` lines. pub refusal: Option, /// Additive union: arrays combine, empty survivor fields fill from the /// duplicate, a field the survivor holds is NEVER overwritten. An empty /// map means the survivor already carried everything. /// /// A `serde_json::Map` and not a struct, because it is a PATCH — the keys /// present are the statement, and the workspace turns on serde_json's /// `preserve_order` so it serialises in the TypeScript's own key order. pub survivor_patch: Map, /// `None` only when the plan is a refusal. pub preserving_comment: Option, pub device_card: PersonMergeDeviceCard, /// `None` when the duplicate is already archived — nothing left to stamp. pub archive_duplicate: Option, } /// How the executor moves a repoint. #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub enum PersonRepointKind { /// An UPDATE of `column` from the duplicate's id to the survivor's. Column, /// The id is DERIVED from the edge, so a repoint is /// upsert-the-new-fact + delete-the-old-row, and an edge between the two /// people themselves collapses rather than becoming a self-edge. Links, /// Derived id too; the survivor's own membership wins. ProjectLinks, /// Addressed by (record_kind, record_id); a plain repoint of `record_id`. Comments, } /// One thing that points at a person and must be moved to the survivor. /// /// Only the derivation of a new id is the executor's business. WHAT gets /// repointed is [`person_repoints`]: every person link the database's /// definitions declare, plus [`PERSON_STORAGE_REPOINTS`]. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct PersonRepoint { pub table: Cow<'static, str>, pub column: Cow<'static, str>, pub kind: PersonRepointKind, /// False for the tables with no `workspace_id`: person notes (their person /// IS their scope). pub workspace_scoped: bool, pub reason: Cow<'static, str>, } const fn storage( table: &'static str, column: &'static str, kind: PersonRepointKind, workspace_scoped: bool, reason: &'static str, ) -> PersonRepoint { PersonRepoint { table: Cow::Borrowed(table), column: Cow::Borrowed(column), kind, workspace_scoped, reason: Cow::Borrowed(reason), } } /// What points at a person in storage no definition column describes yet — /// each with why a definition cannot say it. Moved after the definitions' /// own links, in this order. pub const PERSON_STORAGE_REPOINTS: [PersonRepoint; 7] = [ storage( "cotton_msg_contacts", "person_id", PersonRepointKind::Column, true, "A phone handle that resolved to the duplicate is the survivor's handle; a message contact is engine storage under the thread table, with no definition of its own.", ), storage( "cotton_money_accounts", "counterparty_person_id", PersonRepointKind::Column, true, "The duplicate's ledgers become the survivor's — the claim collision was refused up front; Money ships no table definition yet.", ), storage( "cotton_money_transactions", "counterparty_person_id", PersonRepointKind::Column, true, "Who a transaction was with does not change because two cards became one; Money ships no table definition yet.", ), storage( "cotton_comments", "record_id", PersonRepointKind::Comments, true, "What was said about the duplicate was said about the survivor; a comment names any record by (kind, id), not by a link column.", ), storage( "cotton_links", "from_id", PersonRepointKind::Links, true, "Edges FROM the duplicate; the id is derived, so the row is re-minted and the old one deleted. Every `edges` link column is kept here.", ), storage( "cotton_links", "to_id", PersonRepointKind::Links, true, "Edges TO the duplicate; the person↔person edge between the two collapses instead of self-linking. Every `edges` link column is kept here.", ), storage( "cotton_project_links", "record_id", PersonRepointKind::ProjectLinks, true, "Project membership converges on the derived id; the survivor's own membership wins on collision.", ), ]; /// Person links a definition declares that a merge must NOT move, each with /// why: `(table id, column key, reason)`. pub const PERSON_LINKS_NOT_REPOINTED: [(&str, &str, &str); 2] = [ ( "person", "merged_into", "Where a merged-away person points: written by the merge itself, never moved by one. A kit column on the built-in person table, so a copy made before it holds no storage for it, and that must not refuse every merge there (seen on the Android emulator, 28 Nov 2026).", ), ( "thread_member", "person_id", "Worked out by the messages engine from the participant's contact; that contact's person (cotton_msg_contacts.person_id) is moved instead.", ), ]; /// The table every definition's person links point at. const PERSON_TABLE: &str = "person"; /// Why the repoints could not be worked out: a definition declares a person /// link this build cannot find in storage. A merge refuses rather than leave /// that link pointing at an archived card. #[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] pub enum PersonRepointError { #[error("{table}.{column} links to a person but no storage holds it — the merge is refused rather than leave it pointing at the duplicate")] NoStorage { table: String, column: String }, #[error("{table}: its storage could not be read: {cause}")] Storage { table: String, cause: String }, } /// Everything that points at a person, in the order the executor moves it: /// first every person link `definitions` declare (a tool a person imported /// included, so a new tool with a person link is moved with no code change), /// then [`PERSON_STORAGE_REPOINTS`]. /// /// A single-valued link is a column of the table's storage under its own key. /// A link kept as `edges` lives in `cotton_links`, and a `multiple` link that /// is not edges is worked out by its engine from other storage (only an /// engine may declare one), so neither adds an entry of its own. A computed /// link is stored nowhere. pub fn person_repoints( definitions: &[TableDefinition], ) -> Result, PersonRepointError> { let mut repoints: Vec = Vec::new(); for definition in definitions { // A view's rows are its source table's, whose own definition // declares the columns they are stored in. if definition.source.is_some() { continue; } for column in &definition.columns { if column.column_type != ColumnType::Link || column.link_to.as_deref() != Some(PERSON_TABLE) || column.computed.is_some() || column.edges == Some(true) || column.multiple == Some(true) || PERSON_LINKS_NOT_REPOINTED .iter() .any(|(table, key, _)| *table == definition.id && *key == column.key) { continue; } let tables = storage_of(definition)?; let Some(table) = tables .iter() .find(|table| table.columns.iter().any(|c| c.name == column.key)) else { return Err(PersonRepointError::NoStorage { table: definition.id.clone(), column: column.key.clone(), }); }; if repoints.iter().any(|r| r.table == table.name && r.column == column.key) { continue; } repoints.push(PersonRepoint { table: Cow::Owned(table.name.clone()), column: Cow::Owned(column.key.clone()), kind: PersonRepointKind::Column, workspace_scoped: table.columns.iter().any(|c| c.name == "workspace_id"), reason: Cow::Owned(format!( "{}'s {} links to a person (its definition says so).", definition.id, column.key )), }); } } for repoint in PERSON_STORAGE_REPOINTS { if !repoints.iter().any(|r| r.table == repoint.table && r.column == repoint.column) { repoints.push(repoint); } } Ok(repoints) } /// The storage a definition's columns live in: a built-in engine's compiled /// shape, or the tables a data-only definition derives. fn storage_of( definition: &TableDefinition, ) -> Result, PersonRepointError> { if definition.has_engine() { return Ok(cotton_store::schema::package_tables::compiled_shape(&definition.id) .map(<[_]>::to_vec) .unwrap_or_default()); } definition .physical_tables() .map_err(|error| PersonRepointError::Storage { table: definition.id.clone(), cause: error.to_string(), }) } /// Why a merge is refused before anything moves, as a typed fact; said to /// the assistant in the database's `refusal` lines (`merge.*`). #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub enum PersonMergeRefusal { /// The survivor is put away. ArchivedSurvivor, /// Money claims are one-row-per-person by a unique index; repointing a /// second claim of the same subtype would fail halfway through the merge. /// Refused up front — resolving two receivable ledgers is accounting, not /// contact cleanup. Each colliding subtype, in the duplicate's order. SharedClaims { subtypes: Vec }, } impl PersonMergeRefusal { /// The refusal in `rows`' words, the kit's for a line they have none of. #[must_use] pub fn say(&self, rows: &[crate::rules::shell_lines::LineRow]) -> String { let say = |line: &str, fills: &[(&str, &str)]| { crate::rules::shell_lines::resolve("refusal", line, rows, fills).unwrap_or_else(|| format!("refusal.{line}")) }; match self { PersonMergeRefusal::ArchivedSurvivor => say("merge.archived_survivor", &[]), PersonMergeRefusal::SharedClaims { subtypes } => { let joined = subtypes.join(&say("merge.and_a", &[])); say("merge.shared_claims", &[("subtypes", &joined)]) } } } } /// Why a plan could not be answered at all. /// /// The TypeScript has no such failure: `now.toISOString()` throws a /// `RangeError` on an unrepresentable instant, and a pure library here may not /// panic on caller-supplied data. `Display` is JavaScript's own sentence, so a /// handler can pass it straight to the error envelope. #[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] pub enum PersonMergeError { #[error("Invalid time value")] InvalidTimeValue(i64), } /// `!value` in JavaScript: absent OR the empty string. /// /// This is not pedantry — `org: ""` reaches these columns from an importer that /// wrote a blank field, and the TypeScript treats it as "the survivor has no /// org" and fills it. `Option::is_none` alone would leave the blank in place. fn truthy(value: &Option) -> bool { value.as_deref().is_some_and(|text| !text.is_empty()) } fn string_value(value: &Option) -> Value { match value { Some(text) => Value::String(text.clone()), None => Value::Null, } } fn number_value(value: Option) -> Value { match value { Some(number) => Value::Number(number.into()), None => Value::Null, } } /// The duplicate's card as it stood, for the preserving comment's body. fn card_before_merge(duplicate: &PersonMergeInput) -> Map { let mut original = Map::new(); original.insert("id".into(), Value::String(duplicate.id.clone())); original.insert("name".into(), Value::String(duplicate.full_name.clone())); if !duplicate.phones.is_empty() { original.insert("phones".into(), strings(&duplicate.phones)); } if !duplicate.emails.is_empty() { original.insert("emails".into(), strings(&duplicate.emails)); } if truthy(&duplicate.org) { original.insert("org".into(), string_value(&duplicate.org)); } if truthy(&duplicate.role_title) { // camelCase here and snake_case in the patch, deliberately: the card is // a JSON document a person reads, the patch is a row. original.insert("roleTitle".into(), string_value(&duplicate.role_title)); } if truthy(&duplicate.city) { original.insert("city".into(), string_value(&duplicate.city)); } if truthy(&duplicate.timezone) { original.insert("timezone".into(), string_value(&duplicate.timezone)); } if duplicate.birth_month.is_some() { let mut birthday = Map::new(); birthday.insert("month".into(), number_value(duplicate.birth_month)); // The day rides along even when it is null: the month is what gates the // whole trio, exactly as the TypeScript's `!== null` on the month does. birthday.insert("day".into(), number_value(duplicate.birth_day)); if let Some(year) = duplicate.birth_year { birthday.insert("year".into(), Value::Number(year.into())); } original.insert("birthday".into(), Value::Object(birthday)); } if truthy(&duplicate.summary) { original.insert("summary".into(), string_value(&duplicate.summary)); } original } fn strings(values: &[String]) -> Value { Value::Array(values.iter().cloned().map(Value::String).collect()) } /// The union, additive only. A field the survivor /// lacks is filled; the birthday trio and the summary-with-provenance move as /// one, and the avatar only when the survivor has neither key nor url. fn union_patch(survivor: &PersonMergeInput, duplicate: &PersonMergeInput) -> Map { let mut patch = Map::new(); // Phones and emails are not on the row since v90: they are the // duplicate's `cotton_person_handles` rows, which the executor repoints // to the survivor (`PERSON_REPOINTS`) — unique per handle, so the two // people never carried the same one and nothing needs a union here. if !truthy(&survivor.org) && truthy(&duplicate.org) { patch.insert("org".into(), string_value(&duplicate.org)); } if !truthy(&survivor.role_title) && truthy(&duplicate.role_title) { patch.insert("role_title".into(), string_value(&duplicate.role_title)); } if !truthy(&survivor.city) && truthy(&duplicate.city) { patch.insert("city".into(), string_value(&duplicate.city)); } if !truthy(&survivor.timezone) && truthy(&duplicate.timezone) { patch.insert("timezone".into(), string_value(&duplicate.timezone)); } if survivor.birth_month.is_none() && duplicate.birth_month.is_some() { patch.insert("birth_month".into(), number_value(duplicate.birth_month)); patch.insert("birth_day".into(), number_value(duplicate.birth_day)); patch.insert("birth_year".into(), number_value(duplicate.birth_year)); } if !truthy(&survivor.summary) && truthy(&duplicate.summary) { patch.insert("summary".into(), string_value(&duplicate.summary)); patch.insert("summary_by".into(), string_value(&duplicate.summary_by)); patch.insert( "summary_updated_at".into(), string_value(&duplicate.summary_updated_at), ); } if !truthy(&survivor.avatar_key) && truthy(&duplicate.avatar_key) { patch.insert("avatar_key".into(), string_value(&duplicate.avatar_key)); } patch } /// The device-card decision, as data. fn device_card_plan( survivor: &PersonMergeInput, duplicate: &PersonMergeInput, ) -> PersonMergeDeviceCard { if truthy(&survivor.device_contact_id) { let Some(duplicate_id) = duplicate .device_contact_id .clone() .filter(|id| !id.is_empty()) else { return PersonMergeDeviceCard::Kept; }; return PersonMergeDeviceCard::Orphaned { duplicate_patch: ClearDeviceCard::default(), orphaned_device_contact_id: duplicate_id, }; } let Some(duplicate_id) = duplicate .device_contact_id .clone() .filter(|id| !id.is_empty()) else { return PersonMergeDeviceCard::None; }; PersonMergeDeviceCard::Moved { duplicate_patch: ClearDeviceCard::default(), survivor_patch: ClaimDeviceCard { device_contact_id: duplicate_id, device_contact_snapshot: duplicate.device_contact_snapshot.clone(), }, } } fn refuse(refusal: PersonMergeRefusal) -> PersonMergePlan { PersonMergePlan { refusal: Some(refusal), survivor_patch: Map::new(), preserving_comment: None, device_card: PersonMergeDeviceCard::None, archive_duplicate: None, } } /// Decide the whole merge of `duplicate` into `survivor`. Pure: the caller /// reads the two rows (and each side's claim subtypes), then carries the plan /// out in the order documented at the top of this file. /// /// `claims` is required rather than optional on purpose: a caller that has not /// read the money side must say so with two empty lists, never by omission — /// an omitted argument that silently skips a refusal is exactly the kind of /// fallback that hides the problem. /// /// A refusal short-circuits: `refusal` non-null comes with an empty patch, no /// comment, `device_card == None` and no archive, so an executor that forgot to /// check it still cannot half-merge anything. /// /// `now_ms` is epoch milliseconds where the TypeScript takes a `Date`; the /// crate holds no clock, so the caller owns "now". The only `Err` is an instant /// JavaScript itself could not render. pub fn plan_person_merge( survivor: &PersonMergeInput, duplicate: &PersonMergeInput, now_ms: i64, claims: &PersonMergeClaims, ) -> Result { if truthy(&survivor.archived_at) { return Ok(refuse(PersonMergeRefusal::ArchivedSurvivor)); } let colliding: Vec = claims .duplicate .iter() .filter(|subtype| claims.survivor.contains(subtype)) .cloned() .collect(); if !colliding.is_empty() { return Ok(refuse(PersonMergeRefusal::SharedClaims { subtypes: colliding })); } let archive_duplicate = if truthy(&duplicate.archived_at) { None } else { Some(PersonMergeArchive { archived_at: to_iso_string(now_ms).ok_or(PersonMergeError::InvalidTimeValue(now_ms))?, }) }; Ok(PersonMergePlan { refusal: None, survivor_patch: union_patch(survivor, duplicate), preserving_comment: Some(PersonMergeComment { record_kind: PersonMergeCommentRecordKind::Person, record_id: survivor.id.clone(), parent_id: (), body: MergedCard { name: duplicate.full_name.clone(), card: json_stringify(&Value::Object(card_before_merge(duplicate))), }, author_kind: PersonMergeCommentAuthorKind::Agent, anchor: (), }), device_card: device_card_plan(survivor, duplicate), archive_duplicate, }) } #[cfg(test)] #[path = "merge_tests.rs"] mod tests;