//! Is this imported person the same person we already have? — names only, //! pure, and in core, so the Mac importer, the server and the app all answer //! alike (spec 2026-09-05-cotton-people-suggestions-design.md §D3). The port of //! `packages/core/src/engine/people/nameMatch.ts`. //! //! The shape of the rule, and what each part defends: //! //! **NAMES ONLY.** A person imported from the Apple Photos library carries a //! name and nothing else — the importer writes no phone and no email for one, //! and a handle match is `resolveContact`'s job. So this file compares names //! and refuses to pretend it knows more. //! //! **A SUGGESTION, NEVER A MERGE.** Every score here ends up on an OPEN //! `cotton_person_suggestions` row the owner decides. Two people with the same //! name are two people until they say otherwise, so the scores are tuned to //! ask rather than to be right: a missed ask costs a duplicate in the People //! list, a wrong automatic merge would cost someone's records. //! //! **ONE KEY, DERIVED THE SAME WAY EVERY TIME.** [`name_key`] is NFKD, //! combining marks stripped, lowercased, punctuation turned into spaces, //! whitespace collapsed. That is what makes "Zoë" and "Zoe", "Ravi K." and //! "Ravi K", "O'Brien" and "O Brien" the same question. It is deliberately //! stronger than the importer's `normaliseName` (trim + collapse + lowercase), //! which decides the automatic unique-exact rule: this file only ever //! proposes, so it can afford to fold more together. //! //! **THREE RULES, EACH WITH A WRITTEN WEIGHT, BEST WINS.** They are ordered by //! how much of the name they actually agree on: //! - (a) token subset — 0.8, scaled by how much of the longer name is //! shared. "Ravi" beside "Ravi Kumar", or the same tokens reordered. //! - (b) first token equal plus a last-token initial — 0.75. "Ravi K" beside //! "Ravi Kumar": common in a photo library, where the label is whatever //! was typed on the phone. //! - (c) same token count, tokens within one edit — 0.7, less 0.05 per token //! that differs. This is the typo/transcription rule ("Kumaar"/"Kumar"); //! an accent is already gone in the key. //! //! **AN INITIAL IS NOT A NAME.** A whole name of one token of two characters //! or fewer ("K", "AB") matches nothing but an identical key. Otherwise every //! "K" in a library would be proposed against every surname starting with K. //! //! **SHORT TOKENS MUST BE EXACT.** The edit-distance licence starts at four //! characters, because one edit inside a three-letter token is most of the //! token: "Mum"/"Mom" and "Ben"/"Ken" are different people, "Kumaar"/"Kumar" //! is one person typed twice. //! //! **DETERMINISTIC OUTPUT.** Ties break on `person_id` ascending, so the same //! input yields the same suggestions on the Mac, the server and the phone, and //! a re-import refreshes rather than reshuffles. //! //! ## What this port had to be careful about //! //! Everything here is string arithmetic, which is where a port drifts. Three //! rules held throughout: //! //! - **Lengths are UTF-16 code units**, because JavaScript's are. `"🎉".length` //! is 2, so [`edit_distance`] works over `encode_utf16` and not over `char`s //! — a `char`-based distance answers 1 for `("🎉", "a")` where JavaScript //! answers 2, and the four-character floor in rule (c) would admit tokens //! the TypeScript refuses. //! - **The whitespace class is the ECMAScript one**, spelled out in //! `cotton_store::protocol::js`. JS `\s` includes U+FEFF and excludes //! U+0085; Rust's `\s` does the opposite. A name pasted out of a spreadsheet //! with a BOM in it keys differently under the wrong class. //! - **`to_lowercase` is relied on to be the full Unicode mapping**, which is //! what JavaScript's `String.prototype.toLowerCase` is too — including the //! Greek final-sigma context rule (`ΟΔΥΣΣΕΥΣ` → `οδυσσευς`, with ς only at //! the end). That agreement is pinned by vector rather than assumed. use std::collections::HashSet; use std::sync::LazyLock; use regex::Regex; use serde::{Deserialize, Serialize}; use unicode_normalization::UnicodeNormalization; use crate::js::collapse_whitespace_and_trim; use crate::js_number::math_round; /// The weight of the token-subset rule (a), before the shared-token scaling. const TOKEN_SUBSET_WEIGHT: f64 = 0.8; /// The floor for a one-token name inside a two-token name ("Ravi" ⊂ "Ravi /// Kumar"). The scaling alone would put it at 0.4 and it would never be asked; /// a given name matching half of a two-part name is exactly the question this /// design exists to ask, so it is pinned to the threshold. const TOKEN_SUBSET_HALF_NAME_FLOOR: f64 = 0.6; /// The weight of the initial rule (b) — "Ravi K" beside "Ravi Kumar". const INITIAL_WEIGHT: f64 = 0.75; /// The weight of the near-token rule (c), before the per-token penalty. const NEAR_TOKEN_WEIGHT: f64 = 0.7; /// How much rule (c) loses for each aligned token that is not identical. const NEAR_TOKEN_PENALTY: f64 = 0.05; /// Tokens shorter than this must be equal; longer ones may differ by one edit. /// In UTF-16 code units, like `String.prototype.length`. const NEAR_TOKEN_MIN_LENGTH: usize = 4; /// A whole name of one token this short or shorter is an initial, not a name. const INITIAL_ONLY_MAX_LENGTH: usize = 2; /// The score a candidate must reach to be proposed at all. 0.6 is exactly the /// one-token-inside-a-two-token-name floor, so "Ravi" beside "Ravi Kumar" is /// asked and a single token inside a three-part name (0.27) is not. pub const SUGGEST_MIN_SCORE: f64 = 0.6; /// How many candidates one imported person may be asked about. Three fits the /// person page's card stack and keeps a common given name from turning into a /// screen of questions; past the third, the name is too common for a name-only /// rule to be deciding anything. pub const SUGGEST_MAX_CANDIDATES: usize = 3; // Why a candidate was proposed: the keys were equal, or a rule fired. // // The TypeScript spells this union twice — once locally as // `PersonMatchReason`, once in `constants.ts` as `PERSON_SUGGESTION_REASONS`, // which mirrors the `cotton_person_suggestions.reason` CHECK. They are the // same two strings and this port keeps only the constants' one, so a value // that reaches the column cannot have been minted from a second declaration. string_enum! { /// `PERSON_SUGGESTION_REASONS` — why a person suggestion was raised. /// /// Mirrors the CHECKs on `cotton_person_suggestions` (schema v44, v90). A /// suggestion is found by NAME and nothing else — never acted on alone — /// and this module is what scores it. PersonSuggestionReason { /// Two or more people share the name and the importer could not choose. NameExact => "name_exact", /// The names are close but not equal ("Ravi K" beside "Ravi Kumar"). NameFuzzy => "name_fuzzy", /// A message contact known only by a handle (an Instagram sender) /// whose name matches a person's: "is this them?" (schema v90). Never /// raised by `name_match`, which compares people with people. HandleName => "handle_name", } } pub use PersonSuggestionReason as PersonMatchReason; /// One candidate worth asking the owner about. #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct PersonMatch { pub person_id: String, /// 0 … 1, where 1 is an equal name key. pub score: f64, pub reason: PersonMatchReason, } /// The two columns this engine reads off a person row. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct PersonNamed { pub id: String, pub name: String, } /// The threshold and cap [`suggest_person_matches`] runs with. /// /// `None` in either field means the module's own default, which is the /// TypeScript's `??`. Rust has no default arguments, so the caller passes /// `SuggestPersonMatchesOptions::default()` where the TypeScript passes /// nothing. #[derive(Debug, Clone, Copy, Default, PartialEq)] pub struct SuggestPersonMatchesOptions { pub min_score: Option, /// A cap of 0 answers nothing at all. The TypeScript guards `max <= 0` /// because a JavaScript caller can pass a negative; `usize` makes that /// unrepresentable and 0 is the reachable spelling of the same intent. pub max: Option, } /// Punctuation AND symbols: `&` is punctuation, `+` is a math symbol. /// /// The TypeScript's pattern carries the `u` flag, so `\p{P}` and `\p{S}` are /// Unicode general categories on both sides. The two implementations read /// their own copy of the UCD, so a category reassignment between Unicode /// versions is the one way they could ever disagree here — the vectors pin the /// characters a name actually contains. static PUNCTUATION: LazyLock = LazyLock::new(|| Regex::new(r"[\p{P}\p{S}]").expect("a valid pattern")); /// The comparable form of a name: NFKD, combining marks stripped, lowercased, /// every punctuation or symbol character turned into a space, whitespace /// collapsed, trimmed. Empty in, empty out. /// /// The order is load-bearing and is the TypeScript's: decomposing FIRST is /// what turns `é` into `e` + U+0301 so the mark strip can eat it, and /// lowercasing AFTER the strip is why `İstanbul` keys as `istanbul` (NFKD /// gives `I` + U+0307, the dot is a combining mark, and what is left lowers to /// a plain `i`). /// /// Only U+0300–U+036F — the Combining Diacritical Marks block — is stripped, /// exactly as the TypeScript does: a Devanagari or Thai name keeps its marks, /// because there they are letters and not decoration. pub fn name_key(name: &str) -> String { let decomposed: String = name.nfkd().collect(); let unmarked: String = decomposed .chars() .filter(|ch| !matches!(ch, '\u{300}'..='\u{36f}')) .collect(); let lowered = unmarked.to_lowercase(); let spaced = PUNCTUATION.replace_all(&lowered, " "); // `.replace(/\s+/g, " ").trim()` in the ECMAScript whitespace class. collapse_whitespace_and_trim(&spaced) } /// The key's tokens. An empty key has no tokens. pub fn name_tokens(name: &str) -> Vec { let key = name_key(name); if key.is_empty() { return Vec::new(); } key.split(' ').map(str::to_string).collect() } /// The UTF-16 length JavaScript's `String.prototype.length` reports. fn utf16_len(text: &str) -> usize { text.encode_utf16().count() } /// Damerau–Levenshtein, optimal string alignment: insertions, deletions, /// substitutions and the transposition of two ADJACENT characters each cost 1. /// Optimal string alignment (no substring edited twice) is enough here — /// everything this file admits is one edit away — and it is small and exact. /// /// The unit of edit is a UTF-16 CODE UNIT, because the TypeScript indexes with /// `a[i - 1]` and measures with `.length`. An astral character is therefore two /// edits away from nothing, which is why `edit_distance("🎉", "a")` is 2 and /// not 1. pub fn edit_distance(a: &str, b: &str) -> usize { if a == b { return 0; } let left: Vec = a.encode_utf16().collect(); let right: Vec = b.encode_utf16().collect(); if left.is_empty() { return right.len(); } if right.is_empty() { return left.len(); } // (a.length + 1) × (b.length + 1) rows, kept as three rolling ones. let mut two_ago: Vec = Vec::new(); let mut previous: Vec = (0..=right.len()).collect(); for i in 1..=left.len() { let mut current = vec![0usize; right.len() + 1]; current[0] = i; for j in 1..=right.len() { let cost = usize::from(left[i - 1] != right[j - 1]); let mut best = (current[j - 1] + 1) // insertion .min(previous[j] + 1) // deletion .min(previous[j - 1] + cost); // substitution if i > 1 && j > 1 && left[i - 1] == right[j - 2] && left[i - 2] == right[j - 1] { best = best.min(two_ago[j - 2] + 1); // transposition } current[j] = best; } two_ago = std::mem::replace(&mut previous, current); } previous[right.len()] } /// Rule (a): every token of the shorter name is a token of the longer one. fn token_subset_score(a: &[String], b: &[String]) -> f64 { let set_a: HashSet<&str> = a.iter().map(String::as_str).collect(); let set_b: HashSet<&str> = b.iter().map(String::as_str).collect(); let (shorter, longer) = if set_a.len() <= set_b.len() { (&set_a, &set_b) } else { (&set_b, &set_a) }; for token in shorter { if !longer.contains(token) { return 0.0; } } let raw = (TOKEN_SUBSET_WEIGHT * shorter.len() as f64) / longer.len() as f64; if shorter.len() == 1 && longer.len() == 2 { return raw.max(TOKEN_SUBSET_HALF_NAME_FLOOR); } raw } /// True when `initial` is one letter and it opens `word`. /// /// "One letter" is one UTF-16 code unit, so an astral character is never an /// initial — which is the TypeScript's behaviour and, for a name key, the /// right one anyway. fn is_initial_of(initial: &str, word: &str) -> bool { utf16_len(initial) == 1 && utf16_len(word) > 1 && word.starts_with(initial) } /// Rule (b): first token equal, and one last token is the other's initial. fn initial_score(a: &[String], b: &[String]) -> f64 { if a.len() < 2 || b.len() < 2 { return 0.0; } if a[0] != b[0] { return 0.0; } let last_a = &a[a.len() - 1]; let last_b = &b[b.len() - 1]; if is_initial_of(last_a, last_b) || is_initial_of(last_b, last_a) { return INITIAL_WEIGHT; } 0.0 } /// Rule (c): same token count, every aligned pair equal or one edit apart. fn near_token_score(a: &[String], b: &[String]) -> f64 { if a.len() != b.len() || a.is_empty() { return 0.0; } let mut differing = 0u32; for (left, right) in a.iter().zip(b.iter()) { if left == right { continue; } if utf16_len(left).min(utf16_len(right)) < NEAR_TOKEN_MIN_LENGTH { return 0.0; } if edit_distance(left, right) > 1 { return 0.0; } differing += 1; } if differing == 0 { return 0.0; // Identical tokens are an equal key, scored 1. } let score = NEAR_TOKEN_WEIGHT - NEAR_TOKEN_PENALTY * f64::from(differing); if score > 0.0 { score } else { 0.0 } } /// Scores are written to a REAL column and compared against a threshold, so /// they are rounded to four places: `0.7 - 0.05` is 0.6499999999999999 in /// binary floating point, and a score is a weight, not a measurement. /// /// `math_round` and not `f64::round`: `Math.round` breaks a half toward +∞ and /// `f64::round` breaks it away from zero, and a score is never negative here /// only by luck. fn round(score: f64) -> f64 { math_round(score * 10_000.0) / 10_000.0 } /// True for a whole name that is a single token of two characters or fewer. fn is_bare_initial(tokens: &[String]) -> bool { tokens.len() == 1 && utf16_len(&tokens[0]) <= INITIAL_ONLY_MAX_LENGTH } /// How alike two names are, 0 … 1. 0 when either name has no key; 1 when the /// keys are equal; otherwise the best of the three rules above. pub fn name_match_score(a: &str, b: &str) -> f64 { let key_a = name_key(a); let key_b = name_key(b); if key_a.is_empty() || key_b.is_empty() { return 0.0; } if key_a == key_b { return 1.0; } let tokens_a: Vec = key_a.split(' ').map(str::to_string).collect(); let tokens_b: Vec = key_b.split(' ').map(str::to_string).collect(); if is_bare_initial(&tokens_a) || is_bare_initial(&tokens_b) { return 0.0; } round( token_subset_score(&tokens_a, &tokens_b) .max(initial_score(&tokens_a, &tokens_b)) .max(near_token_score(&tokens_a, &tokens_b)), ) } /// JavaScript's `<` on two strings: a lexicographic comparison of UTF-16 code /// units. /// /// Rust's own `str` ordering is over UTF-8 bytes, and the two disagree for any /// pair where one id holds an astral character and the other a code point in /// U+E000…U+FFFF. Person ids are minted ASCII, so on real data the orders /// coincide — but the tie-break is the whole determinism claim of this file /// ("the same answer on the Mac, the server and the phone"), and a claim that /// holds only for the ids we happen to mint today is not one worth making. fn js_str_cmp(a: &str, b: &str) -> std::cmp::Ordering { a.encode_utf16().cmp(b.encode_utf16()) } /// The candidates worth asking about for one imported person: everyone whose /// name scores at or above `min_score`, best first, at most `max` of them. /// The candidate never matches itself. Ties break on `person_id` ascending so /// the answer is the same everywhere and on every pass. pub fn suggest_person_matches( candidate: &PersonNamed, people: &[PersonNamed], options: SuggestPersonMatchesOptions, ) -> Vec { let min_score = options.min_score.unwrap_or(SUGGEST_MIN_SCORE); let max = options.max.unwrap_or(SUGGEST_MAX_CANDIDATES); if max == 0 { return Vec::new(); } let mut matches: Vec = Vec::new(); for person in people { if person.id == candidate.id { continue; } let score = name_match_score(&candidate.name, &person.name); if score < min_score { continue; } matches.push(PersonMatch { person_id: person.id.clone(), score, reason: if score == 1.0 { PersonMatchReason::NameExact } else { PersonMatchReason::NameFuzzy }, }); } // The TypeScript comparator answers 1 for two equal ids, which is not a // total order; Rust's sort requires one, so equal ids compare Equal here. // No score this produces is NaN — every one is `round`ed from a finite // maximum — so `partial_cmp` cannot be `None`. matches.sort_by(|left, right| { right .score .partial_cmp(&left.score) .expect("a score is never NaN") .then_with(|| js_str_cmp(&left.person_id, &right.person_id)) }); matches.truncate(max); matches } #[cfg(test)] #[path = "name_match_tests.rs"] mod tests;