/** * `crates/cotton-core/src/messages/resolve_contact_tests.rs` and the calls the * object decides, over a real personal * object (test/import-file.ts) where the Rust used a fake file or a replica: * the reads are the object's own statements, so the archived-person and * kind filters the Rust checked as SQL text are checked here by what they * answer. A Rust patch's `workspace_id` has no column here (one database per * object), so the key-order case reads without it. */ import { describe, expect, it } from "vitest"; import { callChanges, type DeviceCall } from "../src/import/calls.ts"; import { contactHandleChanges, findContactByHandle, peopleByHandle, resolveContact } from "../src/import/contacts.ts"; import { handlesFrom, normalizeHandle, type Handle } from "../src/import/handles.ts"; import { callLogId, contactHandleId } from "../src/import/ids.ts"; import { CLEAR_IMPORT_OPEN, DATABASE_ID, http, personalObject } from "./personal.ts"; import { TestFile } from "./import-file.ts"; const WS = "ws-1"; const NOW = "2026-09-05T09:15:00.000Z"; const phone = (value: string): Handle => ({ kind: "phone", value }); const email = (value: string): Handle => ({ kind: "email", value }); /** As a caller passes it: through `normalizeHandle`, as the ingest does. */ const instagram = (value: string): Handle => normalizeHandle("instagram", value)!; /** The Rust `FakeFile` over an object: people with handles, contacts, and `resolve` = resolve, then apply. */ class ContactFile { readonly file: TestFile; private minted = 0; constructor(file: TestFile) { this.file = file; } static async open(): Promise { return new ContactFile(await TestFile.open("rc")); } async seedPerson(id: string, name: string, phones: string[], emails: string[], archived = false): Promise { await this.file.seedPerson(id, name, archived ? { archived_at: NOW } : {}); for (const [n, value] of phones.entries()) await this.file.seedPhone(`${id}-phone-${n}`, id, value); for (const [n, value] of emails.entries()) await this.file.seedPhone(`${id}-email-${n}`, id, value, "email"); } async resolve(handle: Handle, displayName: string | null, personId: string | null) { const result = await this.file.within((_o, reader) => resolveContact({ db: reader, namespace: WS, handle, displayName, personId, now: NOW, newId: () => `contact-${++this.minted}`, people: peopleByHandle(reader) }), ); await this.file.apply(result.changes); return result; } async contact(id: string): Promise> { const row = await this.file.one("message_contact", (r) => r.id === id); if (!row) throw new Error(`no contact ${id}`); return row.data; } } // ── normalizeContactHandle ────────────────────────────────────────────────── describe("normalizeContactHandle", () => { it("turns a number into the digits phone_e164 holds however it was written", () => { for (const raw of ["+91 90000 00001", "+919000000001", "919000000001", "91-900-000-0001"]) expect(normalizeHandle("phone", raw), raw).toEqual(phone("919000000001")); expect(normalizeHandle("phone", "4321")).toBeNull(); expect(normalizeHandle("phone", "9".repeat(16))).toBeNull(); expect(normalizeHandle("phone", "ravi")).toBeNull(); }); it("lower-cases an address and refuses what cannot be an identity", () => { expect(normalizeHandle("email", " Ravi@Example.COM ")).toEqual(email("ravi@example.com")); for (const bad of ["ravi-at-example.com", "@example.com", "ravi@", "a@b@c", "ravi @example.com"]) expect(normalizeHandle("email", bad), bad).toBeNull(); expect(normalizeHandle("email", "a@b")).toEqual(email("a@b")); }); }); // ── handleFrom / handlesFrom / requireHandle ──────────────────────────────── describe("handlesFrom", () => { it("prefers the phone and keeps the email as a second handle", () => { const source = { phone: "+91 90000 00001", email: "Ravi@Example.com" }; expect(handlesFrom(source, null)[0]).toEqual(phone("919000000001")); expect(handlesFrom(source, null)).toEqual([phone("919000000001"), email("ravi@example.com")]); }); it("falls through to the email when the number will not normalise", () => { expect(handlesFrom({ phone: "4321", email: "ravi@example.com" }, null)[0]).toEqual(email("ravi@example.com")); }); it("refuses loudly when a batch names no counterpart at all", () => { expect(handlesFrom({}, null)[0]).toBeUndefined(); }); }); // ── resolveContact ────────────────────────────────────────────────────────── describe("resolveContact", () => { it("creates a contact for a phone with the number as its primary", async () => { const file = await ContactFile.open(); const resolved = await file.resolve(phone("919000000001"), null, null); expect(resolved.created).toBe(true); const contact = await file.contact(resolved.contactId); expect(contact.phone_e164).toBe("919000000001"); expect(contact.display_name ?? null).toBeNull(); expect(contact.person_id ?? null).toBeNull(); expect(contact.auth_user_id ?? null).toBeNull(); const handles = await file.file.rows("message_contact_handle"); expect(handles).toHaveLength(1); expect(handles[0]!.id).toBe(contactHandleId(WS, "phone", "919000000001")); expect(handles[0]!.data).toMatchObject({ kind: "phone", value: "919000000001", contact_id: resolved.contactId }); }); it("creates a contact for an email with no number at all", async () => { const file = await ContactFile.open(); const resolved = await file.resolve(email("ravi@icloud.com"), null, null); expect((await file.contact(resolved.contactId)).phone_e164 ?? null).toBeNull(); const handles = await file.file.rows("message_contact_handle"); expect(handles).toHaveLength(1); expect(handles[0]!.data).toMatchObject({ kind: "email", value: "ravi@icloud.com" }); }); it("returns the same contact the second time and mints nothing", async () => { const file = await ContactFile.open(); const first = await file.resolve(phone("919000000001"), null, null); const second = await file.resolve(phone("919000000001"), null, null); expect(second.contactId).toBe(first.contactId); expect(second.created).toBe(false); expect(await file.file.count("message_contact")).toBe(1); }); it("finds a contact whose handle row has not landed yet and heals the file", async () => { const file = await ContactFile.open(); await file.file.seedContact("legacy", "919000000001", "Ravi"); const resolved = await file.resolve(phone("919000000001"), null, null); expect(resolved.contactId).toBe("legacy"); expect(resolved.created).toBe(false); const handles = await file.file.rows("message_contact_handle"); expect(handles).toHaveLength(1); expect(handles[0]!.data.contact_id).toBe("legacy"); }); it("fills a name and a person only where the file has none", async () => { const file = await ContactFile.open(); await file.file.seedContact("named", "919000000001", "Ravi (work)"); await file.seedPerson("person-ravi", "Ravi Kumar", ["919000000001"], []); await file.resolve(phone("919000000001"), "RAVI KUMAR \u{1f4f1}", null); const contact = await file.contact("named"); expect(contact.display_name).toBe("Ravi (work)"); expect(contact.person_id).toBe("person-ravi"); }); it("matches a person by phone and by email and takes the person's name", async () => { const file = await ContactFile.open(); await file.seedPerson("person-ravi", "Ravi Kumar", ["+91 90000 00001"], ["Ravi@Example.com"]); const byPhone = await file.resolve(phone("919000000001"), null, null); const byEmail = await file.resolve(email("ravi@example.com"), null, null); for (const id of [byPhone.contactId, byEmail.contactId]) expect(await file.contact(id)).toMatchObject({ person_id: "person-ravi", display_name: "Ravi Kumar" }); expect(byEmail.contactId).not.toBe(byPhone.contactId); }); it("takes a second number joining the same person later", async () => { const file = await ContactFile.open(); await file.seedPerson("person-ravi", "Ravi Kumar", ["919000000001"], []); const first = await file.resolve(phone("919000000001"), null, null); expect((await file.contact(first.contactId)).person_id).toBe("person-ravi"); await file.file.seedPhone("person-ravi-phone-1", "person-ravi", "919000000002"); const second = await file.resolve(phone("919000000002"), null, null); expect(second.created).toBe(true); expect(second.contactId).not.toBe(first.contactId); expect((await file.contact(second.contactId)).person_id).toBe("person-ravi"); }); it("lets the caller's people id beat the address book match", async () => { const file = await ContactFile.open(); await file.seedPerson("person-ravi", "Ravi Kumar", ["919000000001"], []); await file.seedPerson("person-asha", "Asha", [], []); const resolved = await file.resolve(phone("919000000001"), null, "person-asha"); expect((await file.contact(resolved.contactId)).person_id).toBe("person-asha"); }); }); // ── peopleByHandle ────────────────────────────────────────────────────────── describe("peopleByHandle", () => { it("skips an archived person and refuses a handle two people claim", async () => { const file = await ContactFile.open(); await file.seedPerson("person-ravi", "Ravi", ["919000000001", "919000000009"], []); await file.seedPerson("person-asha", "Asha", ["919000000009"], []); await file.seedPerson("person-old", "Someone Archived", ["919000000003"], [], true); const people = await file.file.within((_o, reader) => peopleByHandle(reader)); expect(people.get("phone:919000000001")?.id).toBe("person-ravi"); expect(people.has("phone:919000000009")).toBe(false); expect(people.has("phone:919000000003")).toBe(false); }); }); // ── contactHandleChanges ──────────────────────────────────────────────────── describe("contactHandleChanges", () => { it("writes a second handle onto a contact that already exists", async () => { const file = await ContactFile.open(); const resolved = await file.resolve(phone("919000000001"), null, null); const address = email("ravi@icloud.com"); const changes = contactHandleChanges(WS, resolved.contactId, address, NOW); expect(changes).toHaveLength(1); expect(changes[0]!.id).toBe(contactHandleId(WS, "email", "ravi@icloud.com")); await file.file.apply(changes); expect((await file.file.within((_o, reader) => findContactByHandle(reader, address)))?.id).toBe(resolved.contactId); expect((await file.contact(resolved.contactId)).phone_e164).toBe("919000000001"); }); }); // ── the patches, key for key ──────────────────────────────────────────────── describe("the patches", () => { it("carry the Rust's own keys in the Rust's own order (without workspace_id)", async () => { const file = await ContactFile.open(); const resolved = await file.resolve(email("ravi@icloud.com"), "Ravi", null); expect(resolved.changes).toHaveLength(2); const contact = resolved.changes[0]!.patch!; expect(Object.keys(contact)).toEqual(["id", "phone_e164", "display_name", "person_id", "auth_user_id", "vip", "muted", "blocked", "created_at", "updated_at"]); expect(contact.phone_e164).toBeNull(); expect(contact.vip).toBe(false); const handle = resolved.changes[1]!; expect(Object.keys(handle.patch!)).toEqual(["id", "contact_id", "kind", "value", "created_at"]); expect(handle.retract).toBeUndefined(); expect(handle.table).toBe("message_contact_handle"); }); it("an existing contact with nothing to fill owes only its handle row", async () => { const file = await ContactFile.open(); await file.resolve(phone("919000000001"), "Ravi", null); const again = await file.resolve(phone("919000000001"), "Ravi", null); expect(again.changes).toHaveLength(1); expect(again.changes[0]!.table).toBe("message_contact_handle"); }); }); // ── Node vectors ──────────────────────────────────────────────────────────── describe("Node vectors", () => { it("for the derived handle ids", () => { expect(contactHandleId(WS, "phone", "919000000001")).toBe("df194f37-68f1-2093-ac63-c37a25879b9d"); expect(contactHandleId(WS, "email", "ravi@icloud.com")).toBe("1c8bbc3c-cd3b-7550-f3b2-07119febeb1d"); }); it("for normalisation", () => { expect(normalizeHandle("email", "\u{feff}Ravi@Example.com\u{feff}")).toEqual(email("ravi@example.com")); expect(normalizeHandle("email", "\u{85}ravi@example.com")).toEqual(email("\u{85}ravi@example.com")); expect(normalizeHandle("email", "RAVI\u{130}@example.com")).toEqual(email("ravi\u{69}\u{307}@example.com")); expect(normalizeHandle("phone", "\u{feff}+91 (900) 000-0001.")).toEqual(phone("919000000001")); expect(normalizeHandle("phone", "\u{660}\u{661}919000000")).toBeNull(); }); }); // ── social handles ────────────────────────────────────────────────────────── describe("social handles", () => { it("an Instagram sender nobody carries stays unknown and makes no person", async () => { const file = await ContactFile.open(); await file.seedPerson("person-asha", "Asha Verma", ["+91 90000 00002"], []); const resolved = await file.resolve(instagram("@Night.Heron_77"), null, null); expect(resolved.created).toBe(true); const contact = await file.contact(resolved.contactId); expect(contact.person_id ?? null).toBeNull(); expect(contact.phone_e164 ?? null).toBeNull(); expect(resolved.changes.every((c) => c.table !== "person")).toBe(true); // Asha, and the object's own owner (src/owner.ts). expect(await file.file.count("person")).toBe(2); }); it("an Instagram sender links to the person carrying the handle", async () => { const file = await ContactFile.open(); await file.seedPerson("person-asha", "Asha Verma", [], []); await file.file.seedPhone("person-asha-ig", "person-asha", "night.heron_77", "instagram"); const resolved = await file.resolve(instagram("https://www.instagram.com/Night.Heron_77/"), null, null); const contact = await file.contact(resolved.contactId); expect(contact.person_id).toBe("person-asha"); expect(contact.phone_e164 ?? null).toBeNull(); }); }); // ── calls ─────────────────────────────────────────────────────────────────── const aCall = (externalId: string, handle: string | null, over: Partial = {}): DeviceCall => ({ source: "ios_call_history", externalId, provider: "cellular", direction: "out", outcome: "answered", startedAt: "2026-09-01T10:00:00.000Z", durationS: 60, handle, handleKind: "phone", name: null, device: "Mac (test)", meta: {}, ...over, }); const CALL_NOW = "2026-09-08T10:00:00.000Z"; async function changesFor(file: TestFile, calls: DeviceCall[]) { return file.within((_o, reader) => callChanges(reader, DATABASE_ID, calls, CALL_NOW)); } describe("calls", () => { it("a call becomes one row keyed by the source's own id", async () => { const file = await TestFile.open("calls"); await file.apply(await changesFor(file, [aCall("CALL-1", "919000000001")])); const rows = await file.rows("call"); expect(rows.map((r) => r.id)).toEqual([callLogId(DATABASE_ID, "ios_call_history", "CALL-1")]); }); it("the same call twice is still one row, which is what makes a re-read free", async () => { const file = await TestFile.open("calls"); const calls = [aCall("CALL-1", "919000000001")]; await file.apply(await changesFor(file, calls)); await file.apply(await changesFor(file, calls)); expect(await file.count("call")).toBe(1); }); it("a batch that names one call twice keeps the last and says so here", async () => { const file = await TestFile.open("calls"); const changes = await changesFor(file, [aCall("CALL-1", "919000000001"), aCall("CALL-1", "919000000002", { outcome: "missed" })]); expect(changes).toHaveLength(1); expect(changes[0]!.patch).toMatchObject({ outcome: "missed", handle: "919000000002" }); }); it("a handle is stored normalised when it can be and verbatim when it cannot", async () => { const file = await TestFile.open("calls"); const changes = await changesFor(file, [aCall("CALL-1", "+91 90000 00001"), aCall("CALL-2", "Unknown"), aCall("CALL-3", null)]); expect(changes.map((c) => c.patch!.handle)).toEqual(["919000000001", "Unknown", null]); }); it("a code-less call number is read in the owner's country", async () => { const file = await TestFile.open("calls"); file.ownerPhone = "919876543210"; await file.seedPerson("person-ravi", "person-ravi"); await file.seedPhone("handle-person-ravi", "person-ravi", "919812345678"); const [change] = await changesFor(file, [aCall("CALL-1", "098123 45678")]); expect(change!.patch).toMatchObject({ handle: "919812345678", person_id: "person-ravi" }); }); it("with no owner number a code-less call number stays as typed", async () => { const file = await TestFile.open("calls"); await file.seedPerson("person-ravi", "person-ravi"); await file.seedPhone("handle-person-ravi", "person-ravi", "919812345678"); const [change] = await changesFor(file, [aCall("CALL-1", "098123 45678")]); expect(change!.patch).toMatchObject({ handle: "09812345678", person_id: null }); }); it("meta is written as an object because the row's own check insists on one", async () => { const file = await TestFile.open("calls"); const [change] = await changesFor(file, [aCall("CALL-1", "919000000001", { meta: { source: { callType: 1, device: "Mac (test)" } } })]); const meta = change!.patch!.meta as Record>; expect(typeof meta).toBe("object"); expect(meta.source!.callType).toBe(1); const [bare] = await changesFor(file, [aCall("CALL-2", null)]); expect(bare!.patch!.meta).toEqual({}); await file.apply([change!, bare!]); expect((await file.one("call", (r) => r.data.external_id === "CALL-1"))!.data.meta).toEqual({ source: { callType: 1, device: "Mac (test)" } }); }); it("a call from somebody the file knows carries their person", async () => { const file = await TestFile.open("calls"); await file.seedPerson("person-1", "Ada"); await file.seedPhone("handle-person-1-phone", "person-1", "919000000001"); const [change] = await changesFor(file, [aCall("CALL-1", "919000000001")]); expect(change!.patch!.person_id).toBe("person-1"); }); it("a call from a number nobody in the file carries lands unattributed", async () => { const file = await TestFile.open("calls"); const [change] = await changesFor(file, [aCall("CALL-1", "919000009999")]); expect(change!.patch).toMatchObject({ person_id: null, contact_id: null, handle: "919000009999" }); }); it("a call from an unknown number snaps to the one person the phone named", async () => { const file = await TestFile.open("calls"); for (const [id, name] of [ ["person-1", "Invented Ada"], ["person-2", "Invented Twin"], ["person-3", "invented twin"], ] as const) await file.seedPerson(id, name); const changes = await changesFor(file, [aCall("CALL-1", "919000009999", { name: "invented ada" }), aCall("CALL-2", "919000009999", { name: "Invented Twin" }), aCall("CALL-3", "919000009999")]); expect(changes.map((c) => c.patch!.person_id)).toEqual(["person-1", null, null]); }); it("an empty batch writes nothing and says so", async () => { const slug = "calls-empty"; const { owner } = await personalObject(slug, CLEAR_IMPORT_OPEN); const res = await http<{ applied: Record; version: number }>(slug, "POST", "/v1/import/calls", { calls: [] }, { authorization: `Bearer ${owner}` }); expect(res.status, JSON.stringify(res.body)).toBe(200); expect(res.body.applied).toEqual({ calls: 0, people: 0 }); }); });