use rusqlite::types::Value;usesuper::{fold_phones, PhoneFoldReport};usecrate::driver::Driver;usecrate::file_identity::read_file_identity;usecrate::protocol::derived_id::{contact_handle_id, person_handle_id};usecrate::test_support::{seeded_file, WORKSPACE};fn text(value: &str) -> Value {Value::Text(value.to_string())}fn person(db: &Driver, id: &str) { db.run("INSERT INTO cotton_people (id, workspace_id, full_name, created_at, updated_at) VALUES (?, ?, ?, '2026-01-01T00:00:00Z', '2026-01-01T00:00:00Z')", &[text(id), text(WORKSPACE), text(id)], ) .unwrap();}/// A handle as the earlier normaliser stored it: `normalised` given, under/// the id derived from it.fn handle(db: &Driver, person: &str, value: &str, normalised: &str, created: &str) {let namespace = read_file_identity(db).unwrap().unwrap(); db.run("INSERT INTO cotton_person_handles (id, workspace_id, person_id, kind, value, normalised, source, created_at, updated_at, _hlc) \ VALUES (?, ?, ?, 'phone', ?, ?, 'contacts', ?, ?, ?)", &[ text(&person_handle_id(namespace.namespace(), "phone", normalised)), text(WORKSPACE), text(person), text(value), text(normalised), text(created), text(created), text(&format!("stamp-{created}")), ], ) .unwrap();}fn contact(db: &Driver, id: &str, phone: &str, created: &str) {let namespace = read_file_identity(db).unwrap().unwrap(); db.run("INSERT INTO cotton_msg_contacts (id, workspace_id, phone_e164, created_at, updated_at) VALUES (?, ?, ?, ?, ?)", &[text(id), text(WORKSPACE), text(phone), text(created), text(created)], ) .unwrap(); db.run("INSERT INTO cotton_msg_contact_handles (id, workspace_id, contact_id, kind, value, created_at) VALUES (?, ?, ?, 'phone', ?, ?)", &[text(&contact_handle_id(namespace.namespace(), "phone", phone)), text(WORKSPACE), text(id), text(phone), text(created)], ) .unwrap();}fn handles_of(db: &Driver, person: &str) -> Vec<(String, String)> { db.all("SELECT id, normalised FROM cotton_person_handles WHERE person_id = ? ORDER BY normalised", &[text(person)], ) .unwrap() .iter() .map(|row| (row.text("id").unwrap().to_string(), row.text("normalised").unwrap().to_string())) .collect()}fn scalar(db: &Driver, sql: &str) -> String {let row = db.get(sql, &[]).unwrap().expect("a row");match row.get("v") {Some(Value::Text(text)) => text.clone(),Some(Value::Integer(n)) => n.to_string(), other => format!("{other:?}"), }}/// A Mac-shaped copy: the three trunk-0 shapes T8 found, one person holding/// one number twice, two people holding one number, and message contacts/// stored the old way, one of them colliding.fn synthetic_copy() -> Driver {let db = seeded_file("mac");for id in ["asha", "ben", "chitra", "dev", "esha", "farid"] { person(&db, id); } handle(&db, "asha", "+91 098765 43210", "9109876543210", "2026-01-01T00:00:01Z"); handle(&db, "ben", "+44 (0)20 7946 0958", "4402079460958", "2026-01-01T00:00:02Z"); handle(&db, "chitra", "0044 020 7946 0959", "004402079460959", "2026-01-01T00:00:03Z");// One person, one number, two spellings. handle(&db, "dev", "+91 98765 43299", "919876543299", "2026-01-01T00:00:04Z"); handle(&db, "dev", "+91 098765 43299", "9109876543299", "2026-01-01T00:00:05Z");// Two people, one number: esha's row is older. handle(&db, "esha", "+91 098765 43277", "9109876543277", "2026-01-01T00:00:06Z"); handle(&db, "farid", "0091 98765 43277", "00919876543277", "2026-01-01T00:00:07Z");// A number without a code stays as typed. handle(&db, "farid", "020 7946 0960", "02079460960", "2026-01-01T00:00:08Z"); contact(&db, "c-asha", "9109876543210", "2026-01-02T00:00:01Z"); contact(&db, "c-new", "919876543288", "2026-01-02T00:00:02Z"); contact(&db, "c-old", "9109876543288", "2026-01-02T00:00:03Z"); db}#[test]fn the_fold_writes_every_trunk_zero_shape_e164_and_settles() {let db = synthetic_copy();let namespace = read_file_identity(&db).unwrap().unwrap();let id = |normalised: &str| person_handle_id(namespace.namespace(), "phone", normalised);let report = fold_phones(&db).unwrap(); eprintln!("{report}"); assert_eq!( report,PhoneFoldReport { handles_moved: 4, handles_collapsed: 1, handles_kept: 1, contacts_moved: 1, contacts_kept: 1, contact_handles_moved: 1, contact_handles_collapsed: 0, contact_handles_kept: 1, region_pass: false, } ); assert_eq!(handles_of(&db, "asha"), vec![(id("919876543210"), "919876543210".to_string())]); assert_eq!(handles_of(&db, "ben"), vec![(id("442079460958"), "442079460958".to_string())]); assert_eq!(handles_of(&db, "chitra"), vec![(id("442079460959"), "442079460959".to_string())]);// Collapsed to the row already holding the number. assert_eq!(handles_of(&db, "dev"), vec![(id("919876543299"), "919876543299".to_string())]);// The older row keeps the number; the other person keeps theirs as stored.// Nobody is merged. assert_eq!(handles_of(&db, "esha"), vec![(id("919876543277"), "919876543277".to_string())]); assert_eq!( handles_of(&db, "farid"), vec![ (id("00919876543277"), "00919876543277".to_string()), (id("02079460960"), "02079460960".to_string()), ] ); assert_eq!(scalar(&db, "SELECT COUNT(*) AS v FROM cotton_people"), "6"); assert_eq!(scalar(&db, "SELECT phone_e164 AS v FROM cotton_msg_contacts WHERE id = 'c-asha'"), "919876543210"); assert_eq!(scalar(&db, "SELECT phone_e164 AS v FROM cotton_msg_contacts WHERE id = 'c-old'"), "9109876543288"); assert_eq!( scalar(&db, "SELECT id || '=' || value AS v FROM cotton_msg_contact_handles WHERE contact_id = 'c-asha'"), format!("{}=919876543210", contact_handle_id(namespace.namespace(), "phone", "919876543210")) ); assert_eq!( scalar(&db, "SELECT value AS v FROM cotton_msg_contact_handles WHERE contact_id = 'c-old'"),"9109876543288" ); assert!(super::folded(&db).unwrap());}/// RULE: the fold is ONE pass per file — a later open reads the done-marker/// and nothing else, so opening a folded file costs nothing (architect, 22/// Oct 2026: "later opens cost nothing").#[test]fn a_second_open_does_not_rescan() {let db = synthetic_copy(); owner_is(&db, "asha");let first = fold_phones(&db).unwrap(); assert!(first.region_pass, "{first}"); db.watch_statements(); assert_eq!(fold_phones(&db).unwrap(), PhoneFoldReport::default());let seen = db.statements_seen(); assert!( !seen.is_empty() && seen.iter().all(|sql| sql.contains("application_id")),"a folded file was read again: {seen:?}" );}/// The pass itself is idempotent: a copy that lost its header word folds/// again and changes nothing.#[test]fn a_copy_without_its_marker_folds_again_to_nothing() {// (No owner number here: the region pass neither runs nor marks.)let db = synthetic_copy(); fold_phones(&db).unwrap(); db.exec("PRAGMA application_id = 0").unwrap();let again = fold_phones(&db).unwrap(); assert!(again.wrote_nothing(), "{again}"); assert_eq!((again.handles_kept, again.contacts_kept, again.contact_handles_kept), (1, 1, 1));}#[test]fn a_file_with_no_identity_has_nothing_to_fold() {let db = crate::test_support::empty_file(); assert_eq!(fold_phones(&db).unwrap(), PhoneFoldReport::default());}fn owner_is(db: &Driver, person: &str) { db.run("UPDATE cotton_workspaces SET owner_person_id = ? WHERE id = ?", &[text(person), text(WORKSPACE)]).unwrap();}/// RULE: a number stored without its code is read in the country of the/// owner's own number, and only then (architect, 22 Oct 2026: "no default/// country" forbids a compiled default, not a country the owner's data/// states). A collision is a question, never a merge.#[test]fn the_region_pass_reads_code_less_numbers_in_the_owners_country() {let db = seeded_file("mac");for id in ["owner", "ben", "chitra", "dev", "esha"] { person(&db, id); } owner_is(&db, "owner"); handle(&db, "owner", "+91 98765 43200", "919876543200", "2026-01-01T00:00:01Z"); handle(&db, "ben", "098765 43211", "09876543211", "2026-01-01T00:00:02Z"); handle(&db, "chitra", "98765 43212", "9876543212", "2026-01-01T00:00:03Z"); handle(&db, "dev", "+91 98765 43213", "919876543213", "2026-01-01T00:00:04Z"); handle(&db, "esha", "09876543213", "09876543213", "2026-01-01T00:00:05Z");// A number with its code is never read in the owner's country. handle(&db, "esha", "+44 20 7946 0958", "442079460958", "2026-01-01T00:00:06Z"); contact(&db, "c-ben", "09876543211", "2026-01-02T00:00:01Z"); contact(&db, "c-uk", "442079460958", "2026-01-02T00:00:02Z");let report = fold_phones(&db).unwrap(); assert!(report.region_pass, "{report}");let normalised = |person: &str| handles_of(&db, person).into_iter().map(|(_, n)| n).collect::<Vec<_>>(); assert_eq!(normalised("ben"), ["919876543211"]); assert_eq!(normalised("chitra"), ["919876543212"]); assert_eq!(normalised("esha"), ["09876543213", "442079460958"]); assert_eq!(scalar(&db, "SELECT phone_e164 AS v FROM cotton_msg_contacts WHERE id = 'c-ben'"), "919876543211"); assert_eq!(scalar(&db, "SELECT phone_e164 AS v FROM cotton_msg_contacts WHERE id = 'c-uk'"), "442079460958"); assert_eq!(scalar(&db, "SELECT value AS v FROM cotton_msg_contact_handles WHERE contact_id = 'c-ben'"), "919876543211"); assert!(fold_phones(&db).unwrap().wrote_nothing());}#[test]fn with_no_owner_number_there_is_no_region_and_nothing_is_read_in_one() {let db = seeded_file("mac"); person(&db, "ben"); handle(&db, "ben", "098765 43211", "09876543211", "2026-01-01T00:00:02Z");let report = fold_phones(&db).unwrap(); assert!(!report.region_pass, "{report}"); assert_eq!(handles_of(&db, "ben").into_iter().map(|(_, n)| n).collect::<Vec<_>>(), ["09876543211"]);let id = scalar(&db, "SELECT application_id AS v FROM pragma_application_id"); assert_eq!(id, super::FOLDED.to_string(), "the region marker stays clear until there is a region");}