Cotton code
576 lines · 31.8 KB · TypeScriptRaw
/** * The Photos page, decided by the personal object: one asset, the four rules * of who each cluster is, one page, and the pure readings of apple_tests.rs * and name_match_tests.rs that the pass leans on. Every * picture is a handful of invented bytes and every name is invented. */import { SELF } from "cloudflare:test";import { describe, expect, it } from "vitest";import { mediaFaceId, mediaSightingId, photoRecordId } from "../src/import/ids.ts";import {  appleDateToIso,  captionOf,  enrichmentOf,  faceBoxOf,  faceChanges,  faceQualityOf,  formatFor,  onePerRow,  originalPathOf,  photosProblem,  subtypesOf,  type AppleAssetRow,} from "../src/import/photos.ts";import { DATABASE_ID, http, personalObject, put, PEOPLE_OPEN, PHOTOS_OPEN } from "./personal.ts";const fixtures = import.meta.glob("../../../crates/cotton-client/fixtures/import/photos.json", { eager: true, import: "default" }) as Record<string, Record<string, unknown>>;const FIXTURE = Object.values(fixtures)[0]!;const uuidOf = (n: number): string => `00000000-0000-4000-8000-${n.toString(16).toUpperCase().padStart(12, "0")}`;const appleSeconds = (iso: string): number => (Date.parse(iso) - 978_307_200_000) / 1000;function row(n: number, over: Partial<AppleAssetRow> = {}): AppleAssetRow {  return {    pk: n,    uuid: uuidOf(n),    kind: 0,    kindSubtype: 0,    uti: "public.jpeg",    directory: "0",    filename: `${uuidOf(n)}.jpeg`,    savedAssetType: 6,    dateCreated: appleSeconds("2026-08-14T09:00:00.000Z"),    timezoneOffset: 19_800,    latitude: -180,    longitude: -180,    width: 4000,    height: 3000,    orientation: 1,    favorite: 0,    hdrType: 0,    depthType: 0,    adjustmentsState: 0,    avalancheUuid: null,    isDetectedScreenshot: 0,    cameraCaptureDevice: 0,    cameraMake: null,    cameraModel: null,    originalFilename: null,    overallAestheticScore: 0.5,    curationScore: 0.5,    sceneAnalysisVersion: 0,    title: null,    longDescription: null,    ...over,  };}async function sha256(text: string): Promise<string> {  const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(text));  return [...new Uint8Array(digest)].map((b) => b.toString(16).padStart(2, "0")).join("");}async function putOriginal(slug: string, token: string, key: string, text: string, type = "image/jpeg"): Promise<void> {  const bytes = new TextEncoder().encode(text);  const res = await SELF.fetch(`https://example.test/b/${slug}/v1/media/${key}`, { method: "PUT", headers: { authorization: `Bearer ${token}`, "content-type": type, "content-length": String(bytes.length) }, body: bytes });  expect(res.status, await res.clone().text()).toBeLessThan(300);}interface Answer {  applied: { photos: number; videos: number; faces: number; people: number };  skipped: number;  notes: Record<string, number>;  version: number;}/** One personal object, its owner's two credentials, and the reads a test makes of it. */async function object(slug: string) {  const { credential, owner } = await personalObject(slug, { open: [...PEOPLE_OPEN.open, ...PHOTOS_OPEN.open] });  // The object's own owner is a person from its first sign-in (src/owner.ts); these reads are of the people the photos made.  const me = await http<{ business: { owner_person_id: string } }>(slug, "GET", "/v1/me", undefined, { authorization: `Bearer ${credential}` });  const ownerPerson = me.body.business.owner_person_id;  const rows = async (table: string): Promise<{ id: string; data: Record<string, unknown> }[]> => {    const all: { id: string; table: string; data: Record<string, unknown>; deleted?: boolean }[] = [];    let next: string | undefined;    do {      const page = await http<{ rows: typeof all; next?: string }>(slug, "GET", next ? `/v1/sync?cursor=${next}` : "/v1/sync?since=0", undefined, { authorization: `Bearer ${credential}` });      all.push(...page.body.rows);      next = page.body.next;    } while (next);    return all.filter((r) => r.table === table && !r.deleted && !(table === "person" && r.id === ownerPerson));  };  const post = async (work: unknown): Promise<Answer> => {    const res = await http<Answer>(slug, "POST", "/v1/import/photos", work, { authorization: `Bearer ${owner}` });    expect(res.status, JSON.stringify(res.body)).toBe(200);    return res.body;  };  /** One downloaded JPEG: its bytes PUT under the key the object will name. */  const original = async (text: string): Promise<string> => {    const sha = await sha256(text);    // The Mac sends the original with its device credential (an assistant's token may not write a person's photos: AVATAR SEAL 3).    await putOriginal(slug, credential, `${DATABASE_ID}/photos/${sha}.jpg`, text);    return sha;  };  const version = async (): Promise<number> => (await http<{ version: number }>(slug, "GET", "/v1/me", undefined, { authorization: `Bearer ${credential}` })).body.version;  return { credential, owner, rows, post, original, version };}const page = (assets: unknown[], clusters: Record<string, unknown> = {}) => ({ library: "/Users/example/Pictures/Photos Library.photoslibrary", assets, clusters });const cluster = (uuid: string, fullName: string | null, contactIdentifier: string | null = null) => ({ person: { pk: 1, uuid, fullName, displayName: null, faceCount: 1, mergeTargetPk: null }, contactIdentifier });const face = (uuid: string, personUuid: string | null, over: Record<string, unknown> = {}) => ({ uuid, assetPk: 1, centerX: 0.5, centerY: 0.6, size: 0.1, quality: 0.51, personPk: personUuid ? 10 : null, personUuid, isInTrash: 0, hidden: 0, ...over });// ── the pure readings ────────────────────────────────────────────────────describe("what Apple's rows mean (apple_tests.rs)", () => {  it("converts Core Data seconds from the 2001 epoch", () => {    expect(appleDateToIso(0)).toBe("2001-01-01T00:00:00.000Z");    expect(appleDateToIso(appleSeconds("2026-08-14T09:00:00.000Z"))).toBe("2026-08-14T09:00:00.000Z");    expect(appleDateToIso(null)).toBeNull();    expect(appleDateToIso(Number.NaN)).toBeNull();  });  it("reads -180 as no location and only writes a pair", () => {    expect(enrichmentOf(row(1, { latitude: 12.97, longitude: -180 }), { labels: [] })).toMatchObject({ latitude: null, longitude: null });    expect(enrichmentOf(row(1, { latitude: 12.97, longitude: 77.59 }), { labels: [] })).toMatchObject({ latitude: 12.97, longitude: 77.59 });  });  it("maps the measured type identifiers and refuses the rest", () => {    expect(formatFor("public.heic")).toEqual({ contentType: "image/heic", ext: "heic", kind: "photo" });    expect(formatFor("com.apple.quicktime-movie")).toEqual({ contentType: "video/quicktime", ext: "mov", kind: "video" });    expect(formatFor("public.tiff")).toBeNull();    expect(formatFor("public.jpeg-2000")).toBeNull();    expect(formatFor(null)).toBeNull();  });  it("reads every subtype flag in a fixed order, once, and counts an unknown code rather than guessing", () => {    expect(subtypesOf(row(1, { kindSubtype: 10 })).subtypes).toEqual(["screenshot"]);    expect(subtypesOf(row(1, { isDetectedScreenshot: 1 })).subtypes).toEqual(["screenshot"]);    expect(subtypesOf(row(1, { kindSubtype: 10, isDetectedScreenshot: 1 })).subtypes).toEqual(["screenshot"]);    expect(subtypesOf(row(1, { kindSubtype: 2, cameraCaptureDevice: 1, avalancheUuid: "burst", hdrType: 3, depthType: 1, adjustmentsState: 1 })).subtypes).toEqual(["live", "selfie", "burst", "hdr", "portrait", "edited"]);    expect(subtypesOf(row(1, { kind: 1, kindSubtype: 100 }))).toEqual({ subtypes: [], unknownSubtype: 100 });    expect(subtypesOf(row(1, { kindSubtype: 103 })).subtypes).toEqual(["screen_recording"]);  });  it("carries offset, camera, orientation, favourite and the filename; scores only when analysis ran, clamped", () => {    const read = enrichmentOf(row(1, { cameraMake: "Maker", cameraModel: "Model 1", favorite: 1, originalFilename: "IMG_0001.HEIC", orientation: 6 }), { labels: [] });    expect(read).toMatchObject({ taken_offset: 19_800, camera_make: "Maker", camera_model: "Model 1", favourite: true, original_filename: "IMG_0001.HEIC", orientation: 6, labels: [] });    expect(enrichmentOf(row(1, { orientation: 9 }), { labels: [] }).orientation).toBeNull();    expect(enrichmentOf(row(1), { labels: [] })).toMatchObject({ aesthetic_score: null, curation_score: null });    expect(enrichmentOf(row(1, { overallAestheticScore: 0.71, curationScore: 0.2, sceneAnalysisVersion: 3 }), { labels: [] })).toMatchObject({ aesthetic_score: 0.71, curation_score: 0.2 });    expect(enrichmentOf(row(1, { overallAestheticScore: 1.4, curationScore: -3, sceneAnalysisVersion: 3 }), { labels: [] })).toMatchObject({ aesthetic_score: 1, curation_score: -1 });    expect(enrichmentOf(row(1), { name: "Somewhere", city: "Townsville", labels: ["beach"] })).toMatchObject({ place_name: "Somewhere", place_city: "Townsville", labels: ["beach"] });  });  it("makes a caption of the title and description the person typed", () => {    expect(captionOf(row(1))).toBeNull();    expect(captionOf(row(1, { title: " Trip " }))).toBe("Trip");    expect(captionOf(row(1, { title: " Trip ", longDescription: "Day one" }))).toBe("Trip — Day one");    expect(captionOf(row(1, { title: "   " }))).toBeNull();  });  it("finds the original by the measured shapes and names any other", () => {    expect(originalPathOf("A", "x.heic", 6)).toEqual({ library: "originals/A/x.heic" });    expect(originalPathOf("scope/uuid", "x.heic", 4)).toEqual({ shared: "scopes/cloudsharing/data/scope/uuid/x.heic" });    expect(originalPathOf("/Volumes/Pictures", "x.heic", 10)).toEqual({ referenced: "/Volumes/Pictures/x.heic" });    expect(originalPathOf("??", "x.heic", 6)).toEqual({ unknown: 'an unrecognised directory shape "??"' });    expect(originalPathOf("A", null, 6)).toEqual({ unknown: "the asset names no file" });  });  it("flips Apple's bottom-left centre into a top-left box with the side doubled, and reads -1 as unmeasured", () => {    const box = faceBoxOf(0.5, 0.6, 0.1)!;    expect(box.x).toBeCloseTo(0.4, 9);    expect(box.y).toBeCloseTo(0.3, 9);    expect(box.w).toBeCloseTo(0.2, 9);    expect(box.h).toBeCloseTo(0.2, 9);    expect(faceBoxOf(0.5, 0.6, 0)).toBeNull();    expect(faceBoxOf(0.5, 0.6, Number.NaN)).toBeNull();    expect(faceQualityOf(-1)).toBeNull();    expect(faceQualityOf(1.5)).toBe(1);  });});describe("the ids the Rust pins", () => {  it("derives the ids the Rust pins", () => {    expect(mediaFaceId("photo", "photo:abc", "photos", "face-1")).toBe("99c1ec2f-36e9-8b84-a0ec-44d2c08cdd42");    expect(mediaSightingId("photo", "photo:abc", "photos", "asset-1")).toBe("01498773-468c-f700-b661-2a96d59cb37b");  });});describe("one face", () => {  const record = `photo:${"a".repeat(64)}`;  const NOW = "2026-09-08T09:00:00.000Z";  it("lands with its box, its cluster and its person", () => {    const [change, ...rest] = faceChanges("photo", record, face("F1", "P-A"), "P-A", "p-a", NOW);    expect(rest).toEqual([]);    expect(change!.id).toBe(mediaFaceId("photo", record, "apple", "F1"));    expect(change!.patch).toMatchObject({ record_kind: "photo", record_id: record, source: "apple", source_id: "F1", quality: 0.51, cluster_id: "P-A", person_id: "p-a" });  });  it("nobody has named still lands, pointing at no one, and -1 is not a quality", () => {    const changes = faceChanges("photo", record, face("F1", null, { quality: -1 }), null, null, NOW);    expect(changes).toHaveLength(1);    expect(changes[0]!.patch).toMatchObject({ person_id: null, cluster_id: null, quality: null });  });  it("in the bin or hidden is not written at all, and one with no area is dropped", () => {    expect(faceChanges("photo", record, face("F1", null, { isInTrash: 1 }), null, null, NOW)).toEqual([]);    expect(faceChanges("photo", record, face("F1", null, { hidden: 1 }), null, null, NOW)).toEqual([]);    expect(faceChanges("photo", record, face("F1", null, { size: 0 }), null, null, NOW)).toEqual([]);  });  it("keeps the first change for a row reached twice", () => {    const kept = onePerRow([      { table: "photo", id: "x", patch: { n: 1 } },      { table: "sighting", id: "x", patch: { n: 2 } },      { table: "photo", id: "x", patch: { n: 3 } },    ]);    expect(kept.map((c) => c.patch!.n)).toEqual([1, 2]);  });});describe("a page serde would refuse", () => {  it("is named by its first bad field", () => {    expect(photosProblem(FIXTURE)).toBeNull();    expect(photosProblem({ assets: [], clusters: {} })).toBe("library: expected a string");    expect(photosProblem(page([{ row: { ...row(1), uuid: 7 }, place: { labels: [] }, faces: [] }]))).toBe("assets[0].row.uuid: expected a string");    expect(photosProblem(page([{ row: { ...row(1), width: 1.5 }, place: { labels: [] }, faces: [] }]))).toBe("assets[0].row.width: expected a whole number or null");    expect(photosProblem(page([{ row: row(1), place: {}, faces: [] }]))).toBe("assets[0].place.labels: expected an array of strings");    expect(photosProblem(page([{ row: row(1), place: { labels: [] }, faces: [{ uuid: "F" }] }]))).toBe("assets[0].faces[0].assetPk: expected a whole number");    expect(photosProblem(page([{ row: row(1), place: { labels: [] }, faces: [], sha256: "../x" }]))).toBe("assets[0].sha256: expected a lowercase hex sha256 or null");    expect(photosProblem(page([], { C: { person: { pk: 1 } } }))).toBe("clusters.C.person.uuid: expected a string");    // An absent sha256 and absent optional columns are what serde's defaults read.    expect(photosProblem(page([{ row: { pk: 1, uuid: "u", kind: 0 }, place: { labels: [] }, faces: [] }]))).toBeNull();  });});// ── the route ────────────────────────────────────────────────────────────describe("POST /v1/import/photos", () => {  const SLUG = "import-photos";  let o: Awaited<ReturnType<typeof object>>;  it("refuses anyone but the owner, and a page serde would refuse", async () => {    o = await object(SLUG);    expect((await http(SLUG, "POST", "/v1/import/photos", page([]))).status).toBe(403);    const bad = await http<{ code: string; message: string }>(SLUG, "POST", "/v1/import/photos", { assets: [] }, { authorization: `Bearer ${o.owner}` });    expect(bad.status).toBe(400);    expect(bad.body).toMatchObject({ code: "bad_batch", message: "library: expected a string" });  });  it("writes nothing for an empty page and moves no version", async () => {    const before = await o.version();    const res = await o.post(page([]));    expect(res).toEqual({ applied: { photos: 0, videos: 0, faces: 0, people: 0 }, skipped: 0, notes: {}, version: before });  });  it("imports the fixture page the Mac serialises: the photo, its sighting, its face and the person its cluster names", async () => {    const asset = (FIXTURE.assets as Record<string, unknown>[])[0]!;    const sha = asset.sha256 as string;    await putOriginal(SLUG, o.credential, `${DATABASE_ID}/photos/${sha}.heic`, "foo", "image/heic");    const res = await o.post(FIXTURE);    expect(res.applied).toEqual({ photos: 1, videos: 0, faces: 1, people: 1 });    expect(res.notes).toEqual({ "read:photosImported": 1, "read:photosLabelled": 1, "read:photosPerson:created": 1 });    const id = photoRecordId(sha);    const [photo] = await o.rows("photo");    expect(photo!.id).toBe(id);    expect(photo!.data).toMatchObject({      key: `${DATABASE_ID}/photos/${sha}.heic`,      sha256: sha,      content_type: "image/heic",      size_bytes: 3,      width: 4032,      height: 3024,      taken_at: appleDateToIso(782000000.5),      favourite: true,      latitude: 30.4532,      longitude: 78.0712,      place_name: "Trailhead",      place_city: "Mussoorie",      camera_model: "iPhone 17 Pro",      original_filename: "IMG_0101.HEIC",      aesthetic_score: 0.81,      curation_score: 0.6,      subtypes: [],      labels: ["Mountain", "Sky"],      caption: null,    });    const uuid = "B0B0B0B0-0000-4000-8000-000000000101";    const [sighting] = await o.rows("sighting");    expect(sighting!.id).toBe(mediaSightingId("photo", id, "apple_library", uuid));    expect(sighting!.data).toMatchObject({ record_kind: "photo", record_id: id, source: "apple_library", source_id: uuid, key: `${DATABASE_ID}/photos/${sha}.heic` });    const [person] = await o.rows("person");    expect(person!.data).toMatchObject({ full_name: "Asha Example", contact_source: "apple_library", device_contact_id: "C0C0C0C0-0000-4000-8000-0000000000C7:ABPerson" });    const [f] = await o.rows("face");    expect(f!.id).toBe(mediaFaceId("photo", id, "apple", "F0F0F0F0-0000-4000-8000-000000000F01"));    expect(f!.data).toMatchObject({ cluster_id: "A7C1D2E3-0000-4000-8000-0000000000A7", person_id: person!.id, quality: 0.73 });  });  it("writes no second row when the same page comes again, and moves no version", async () => {    const before = await o.version();    const res = await o.post(FIXTURE);    expect(res).toEqual({ applied: { photos: 0, videos: 0, faces: 0, people: 0 }, skipped: 1, notes: { "read:photosAlready": 1, "read:photosLabelled": 1, "read:photosPerson:existing": 1 }, version: before });    expect(await o.rows("photo")).toHaveLength(1);    expect(await o.rows("sighting")).toHaveLength(1);    expect(await o.rows("person")).toHaveLength(1);  });  it("re-writes what Apple learned between runs on an asset it already holds, but never its star", async () => {    const asset = (FIXTURE.assets as Record<string, unknown>[])[0]!;    const moved = { ...FIXTURE, assets: [{ ...asset, row: { ...(asset.row as object), favorite: 0, overallAestheticScore: 0.9 } }] };    const res = await o.post(moved);    expect(res.notes["read:photosAlready"]).toBe(1);    const [photo] = await o.rows("photo");    // The star is the person's once the picture is here: Apple unstarring it on the Mac does not take it.    expect(photo!.data).toMatchObject({ favourite: true, aesthetic_score: 0.9 });  });  it("keeps a star the phone took off when the Mac's library still holds it", async () => {    const [held] = await o.rows("photo");    const off = await http(SLUG, "POST", "/v1/act", { act: "update", args: { table: "photo", id: held!.id, data: { favourite: false } } }, { authorization: `Bearer ${o.credential}` });    expect(off.status, JSON.stringify(off.body)).toBe(200);    // The fixture's row says favourite 1: the Mac's next run must not star it again.    expect((await o.post(FIXTURE)).notes["read:photosAlready"]).toBe(1);    const [photo] = await o.rows("photo");    expect(photo!.data).toMatchObject({ favourite: false });  });  it("counts an asset whose original is not here rather than failing", async () => {    const unhashed = await o.post(page([{ row: row(2), place: { labels: [] }, faces: [] }]));    const unput = await o.post(page([{ row: row(3), place: { labels: [] }, faces: [], sha256: await sha256("never put") }]));    for (const res of [unhashed, unput]) {      expect(res.notes).toEqual({ notDownloaded: 1 });      expect(res.applied.photos).toBe(0);    }    expect(await o.rows("photo")).toHaveLength(1);  });  it("counts a type the limits do not admit by its own name, and a kind that disagrees with its type", async () => {    const sha = await o.original("a synthetic picture");    const res = await o.post(      page([        { row: row(4, { uti: "public.tiff" }), place: { labels: [] }, faces: [], sha256: sha },        { row: row(5, { uti: null }), place: { labels: [] }, faces: [], sha256: sha },        { row: row(6, { kind: 1 }), place: { labels: [] }, faces: [], sha256: sha },      ]),    );    expect(res.notes).toEqual({ "unsupported:public.tiff": 1, "unsupported:(no type)": 1, "unsupported:public.jpeg": 1 });    expect(res.applied.photos).toBe(0);  });  it("names an unrecognised directory shape rather than guessing at it", async () => {    const sha = await o.original("a synthetic picture");    const res = await o.post(page([{ row: row(7, { directory: "??" }), place: { labels: [] }, faces: [], sha256: sha }]));    expect(res.notes).toEqual({ 'unlocatable:an unrecognised directory shape "??"': 1 });  });  it("counts an unknown subtype and still imports the asset", async () => {    const sha = await o.original("a synthetic picture");    const res = await o.post(page([{ row: row(8, { kindSubtype: 100 }), place: { labels: [] }, faces: [], sha256: sha }]));    expect(res.notes).toEqual({ "read:photosUnknownSubtype": 1, "read:photosImported": 1 });    const photo = (await o.rows("photo")).find((p) => p.id === photoRecordId(sha))!;    expect(photo.data).toMatchObject({ key: `${DATABASE_ID}/photos/${sha}.jpg`, content_type: "image/jpeg", size_bytes: 19, taken_at: "2026-08-14T09:00:00.000Z", subtypes: [] });  });  it("adds a sighting to a picture it already holds under another, and makes no second row", async () => {    const sha = await o.original("a synthetic picture");    const res = await o.post(page([{ row: row(9), place: { labels: [] }, faces: [], sha256: sha }]));    expect(res.notes).toEqual({ "read:photosMerged": 1 });    expect(res.applied.photos).toBe(1);    expect((await o.rows("photo")).filter((p) => p.id === photoRecordId(sha))).toHaveLength(1);    expect((await o.rows("sighting")).filter((s) => s.data.record_id === photoRecordId(sha))).toHaveLength(2);  });  it("keeps a picture the owner removed removed, by its sighting and by its bytes", async () => {    const sha = await o.original("a picture to remove");    await o.post(page([{ row: row(10), place: { labels: [] }, faces: [], sha256: sha }]));    const removed = await http(SLUG, "POST", "/v1/act", { act: "delete", args: { table: "photo", id: photoRecordId(sha) } }, { authorization: `Bearer ${o.credential}` });    expect(removed.status, JSON.stringify(removed.body)).toBe(200);    const again = await o.post(page([{ row: row(10), place: { labels: [] }, faces: [face("F9", null)], sha256: sha }]));    expect(again.notes).toEqual({ "read:photosRemoved": 1 });    expect(again.skipped).toBe(1);    const elsewhere = await o.post(page([{ row: row(11), place: { labels: [] }, faces: [], sha256: sha }]));    expect(elsewhere.notes).toEqual({ "read:photosRemoved": 1 });    expect((await o.rows("photo")).some((p) => p.id === photoRecordId(sha))).toBe(false);    expect((await o.rows("face")).some((f) => f.data.source_id === "F9")).toBe(false);  });  it("files a video under videos/ as a video", async () => {    const text = "a synthetic film";    const sha = await sha256(text);    await putOriginal(SLUG, o.credential, `${DATABASE_ID}/videos/${sha}.mov`, text, "video/quicktime");    const res = await o.post(page([{ row: row(12, { kind: 1, uti: "com.apple.quicktime-movie", filename: "film.mov" }), place: { labels: [] }, faces: [], sha256: sha }]));    expect(res.applied).toMatchObject({ photos: 0, videos: 1 });    const [video] = await o.rows("video");    expect(video!.id).toBe(`video:${sha}`);    expect(video!.data).toMatchObject({ key: `${DATABASE_ID}/videos/${sha}.mov`, content_type: "video/quicktime" });  });});describe("faces and people on one page", () => {  it("two faces of one person in one picture write two faces and one person", async () => {    const o = await object("import-photos-two-faces");    const sha = await o.original("a synthetic picture");    const res = await o.post(page([{ row: row(1), place: { labels: [] }, faces: [face("face-1", "cluster-a"), face("face-2", "cluster-a", { centerX: 0.2 })], sha256: sha }], { "cluster-a": cluster("cluster-a", "Nila Rao") }));    expect(res.applied).toEqual({ photos: 1, videos: 0, faces: 2, people: 1 });    const faces = await o.rows("face");    const [person] = await o.rows("person");    expect(faces.map((f) => f.data.person_id)).toEqual([person!.id, person!.id]);    // Counted per face, decided once per cluster.    expect(res.notes["read:photosPerson:created"]).toBe(2);  });  it("a cluster nobody named lands its faces pointing at no one", async () => {    const o = await object("import-photos-unnamed");    const sha = await o.original("a synthetic picture");    const res = await o.post(page([{ row: row(1), place: { labels: [] }, faces: [face("face-1", "cluster-a")], sha256: sha }], { "cluster-a": cluster("cluster-a", null) }));    expect(res.applied).toEqual({ photos: 1, videos: 0, faces: 1, people: 0 });    expect(res.notes["read:photosPerson:unnamed"]).toBe(1);    const [f] = await o.rows("face");    expect(f!.data).toMatchObject({ person_id: null, cluster_id: "cluster-a" });  });  it("a face whose cluster the page does not carry lands with no cluster and no person", async () => {    const o = await object("import-photos-ungrouped");    const sha = await o.original("a synthetic picture");    await o.post(page([{ row: row(1), place: { labels: [] }, faces: [face("face-1", "elsewhere")], sha256: sha }]));    const [f] = await o.rows("face");    expect(f!.data).toMatchObject({ person_id: null, cluster_id: null });  });});describe("who each cluster is", () => {  let n = 0;  /** A fresh object holding `people`, and a resolve that posts one picture whose face carries `clusterUuid`. */  async function world(people: { id: string; full_name: string; device_contact_id?: string; archived_at?: string }[] = [], faces: { cluster: string; person: string | null }[] = []) {    const slug = `import-photos-people-${++n}`;    const o = await object(slug);    const rows: Record<string, unknown>[] = people.map(({ id, ...data }) => ({ verb: "put", table: "person", id, data: { contact_source: "manual", ...data } }));    faces.forEach((f, i) => rows.push({ verb: "put", table: "face", id: `face-${i}`, data: { record_kind: "photo", record_id: `photo:${"a".repeat(64)}`, source: "apple", source_id: `F${i}`, x: 0.1, y: 0.1, w: 0.2, h: 0.2, cluster_id: f.cluster, person_id: f.person } }));    if (rows.length) await put(slug, rows);    let asset = 100;    const resolve = async (uuid: string, name: string | null, contact: string | null = null): Promise<{ answer: Answer; personId: unknown }> => {      const sha = await o.original(`picture ${++asset}`);      const answer = await o.post(page([{ row: row(asset), place: { labels: [] }, faces: [face(`face-${asset}`, uuid)], sha256: sha }], { [uuid]: cluster(uuid, name, contact) }));      const f = (await o.rows("face")).find((x) => x.data.source_id === `face-${asset}`)!;      return { answer, personId: f.data.person_id };    };    const suggestions = async () => (await o.rows("person_suggestion")).map((s): Record<string, unknown> => ({ id: s.id, ...s.data })).sort((a, b) => String(a.candidate_id).localeCompare(String(b.candidate_id)));    return { ...o, slug, resolve, suggestions };  }  it("rule 1 reuses the person its faces already point at, the majority when the owner split it", async () => {    const w = await world(      [        { id: "p-a", full_name: "Someone" },        { id: "p-b", full_name: "Somebody Else" },      ],      [        { cluster: "C", person: "p-a" },        { cluster: "C", person: "p-b" },        { cluster: "C", person: "p-a" },      ],    );    const { answer, personId } = await w.resolve("C", "Whatever Apple Says");    expect(personId).toBe("p-a");    expect(answer.notes["read:photosPerson:existing"]).toBe(1);  });  it("rule 2 the Contacts card Photos matched", async () => {    const w = await world([{ id: "p-a", full_name: "A Different Spelling", device_contact_id: "CARD-1" }]);    const { answer, personId } = await w.resolve("C", "Some Name", "CARD-1");    expect(personId).toBe("p-a");    expect(answer.notes["read:photosPerson:byContact"]).toBe(1);    expect(await w.rows("person")).toHaveLength(1);  });  it("rule 3 exactly one active person with that name, spelled anyhow", async () => {    const w = await world([      { id: "p-a", full_name: "test   person" },      { id: "p-old", full_name: "Test Person", archived_at: "2026-08-02T00:00:00.000Z" },    ]);    const { answer, personId } = await w.resolve("C", "Test Person");    expect(personId).toBe("p-a");    expect(answer.notes["read:photosPerson:byName"]).toBe(1);    expect(await w.rows("person")).toHaveLength(2);    expect(await w.suggestions()).toEqual([]);  });  it("rule 4 creates the person from the library, with the card when there is one", async () => {    const w = await world();    const { answer, personId } = await w.resolve("C", "New Person", "CARD-9");    expect(answer.notes["read:photosPerson:created"]).toBe(1);    const [person] = await w.rows("person");    expect(person!.id).toBe(personId);    expect(person!.data).toMatchObject({ full_name: "New Person", contact_source: "apple_library", device_contact_id: "CARD-9" });    expect(await w.suggestions()).toEqual([]);  });  // People suggestions are retired (TABLE DROP 1): a tie creates the person and asks nothing.  it("an exact name tie creates the person and asks nothing: suggestions are retired", async () => {    const w = await world([      { id: "p-a", full_name: "Test Person" },      { id: "p-b", full_name: "test  person" },      { id: "p-old", full_name: "Test Person", archived_at: "2026-08-02T00:00:00.000Z" },    ]);    const { answer } = await w.resolve("C", "Test Person");    expect(answer.notes["read:photosPerson:ambiguous"]).toBe(1);    expect(await w.suggestions()).toEqual([]);    expect(await w.rows("person")).toHaveLength(4);  });  it("the person it created for a tie answers the next cluster with that name", async () => {    const w = await world([      { id: "p-a", full_name: "Test Person" },      { id: "p-b", full_name: "Test Person" },    ]);    const sha = await w.original("one picture, two clusters");    const res = await w.post(      page([{ row: row(1), place: { labels: [] }, faces: [face("f-c", "C"), face("f-d", "D", { centerX: 0.2 })], sha256: sha }], {        C: cluster("C", "Test Person"),        D: cluster("D", "test person"),      }),    );    expect(res.notes).toMatchObject({ "read:photosPerson:ambiguous": 1, "read:photosPerson:byName": 1 });    const faces = await w.rows("face");    expect(faces[0]!.data.person_id).toBe(faces[1]!.data.person_id);    expect(await w.rows("person")).toHaveLength(3);    expect(await w.suggestions()).toEqual([]);  });  it("never proposes the person it just created against themselves, and a name nobody is near asks nothing", async () => {    const w = await world([{ id: "p-a", full_name: "Ravi Kumar" }]);    await w.resolve("C", "Zeenat Quraishi");    expect(await w.suggestions()).toEqual([]);    expect(await w.rows("person")).toHaveLength(2);  });  it("decides once per cluster however many faces carry it, and a second cluster of the name is answered by the first", async () => {    const w = await world();    const sha = await w.original("a family picture");    const res = await w.post(      page([{ row: row(1), place: { labels: [] }, faces: [face("f-1", "C"), face("f-2", "C", { centerX: 0.2 }), face("f-3", "D", { centerX: 0.8 })], sha256: sha }], {        C: cluster("C", "New Person"),        D: cluster("D", "new  person"),      }),    );    expect(res.notes).toMatchObject({ "read:photosPerson:created": 2, "read:photosPerson:byName": 1 });    expect(res.applied.people).toBe(1);    expect(new Set((await w.rows("face")).map((f) => f.data.person_id)).size).toBe(1);  });});// RULE (e2e rulings R2, 16 Nov 2026): with People or Photos sealed the object never decides the library (it would read// and write their words in the clear); the Mac decides it over its own opened copy and lands it through import_rows.describe("the photo library with People and Photos sealed", () => {  it("is refused at the object's route, decided on the Mac", async () => {    const slug = "photos-sealed-route";    const { credential } = await personalObject(slug);    const page = await http<{ code: string }>(slug, "POST", "/v1/import/photos", { workspaceId: DATABASE_ID, assets: [], clusters: [] }, { authorization: `Bearer ${credential}` });    expect(page.status).toBe(410);    expect(page.body.code).toBe("decided_on_the_mac");  });});