Cotton code
377 lines · 22.8 KB · TypeScriptRaw
/** * The import's reader, mapper and vault, on a synthetic life.db built from the * real schema-141 DDL (fixture.ts). No network, no real data. */import { mkdtempSync, readFileSync, rmSync } from "node:fs";import { tmpdir } from "node:os";import { join } from "node:path";import { DatabaseSync } from "node:sqlite";import { afterEach, beforeEach, describe, expect, it } from "vitest";import { batches, believableMailDate, planImport, type ImportRow, type Plan } from "../import-personal/plan.ts";import { KIT_TOOL, kitTables, readLifeDb, type TableJson } from "../import-personal/source.ts";import { files } from "../personal-tables.ts";import { contentType, HOLDERS, namedKeys, planMedia } from "../import-personal/media.ts";import { buildLifeDb, createTables, gardenTool, HOME_BOARD, KITS, QUOTA_DEFINITION, WS } from "./fixture.ts";let dir: string;let tables: Map<string, TableJson>;beforeEach(() => {  dir = mkdtempSync(join(tmpdir(), "import-personal-"));  tables = kitTables(KITS);});afterEach(() => rmSync(dir, { recursive: true, force: true }));function planOf(opts: Parameters<typeof buildLifeDb>[1] = {}): { plan: Plan; payloads: Record<string, string> } {  const f = buildLifeDb(dir, opts);  return { plan: planImport(readLifeDb(f.path, tables), tables), payloads: f.payloads };}const row = (plan: Plan, table: string, id: string): ImportRow | undefined => plan.rows.find((r) => r.table === table && r.id === id);const report = (plan: Plan, table: string) => plan.report.find((r) => r.table === table)!;describe("reading life.db", () => {  it("refuses a file at any schema but 141", () => {    const f = buildLifeDb(dir, { version: 140 });    expect(() => readLifeDb(f.path, tables)).toThrow(/schema 140; this import reads schema 141 only/);  });  it("opens the file read-only and leaves it as it was", () => {    const f = buildLifeDb(dir);    readLifeDb(f.path, tables);    const db = new DatabaseSync(f.path, { readOnly: true });    expect((db.prepare("PRAGMA user_version").get() as { user_version: number }).user_version).toBe(141);    db.close();  });  it("refuses a file with two workspaces", () => {    const path = join(dir, "two.db");    const db = new DatabaseSync(path);    createTables(db, ["cotton_workspaces"]);    for (const id of ["a", "b"]) db.prepare("INSERT INTO cotton_workspaces (id, name, owner_user_id, created_at) VALUES (?, 'x', ?, 'now')").run(id, id);    db.exec("PRAGMA user_version = 141");    db.close();    expect(() => readLifeDb(path, tables)).toThrow(/holds 2 workspaces/);  });});describe("the plan", () => {  it("keeps each row's id and times, copies only the package's columns, and shapes values for the object", () => {    const { plan } = planOf();    expect(plan.workspaceId).toBe(WS);    const project = row(plan, "project", "p-cotton")!;    expect(project.created_at).toBe("2026-09-01T08:00:00.000Z");    expect(project.updated_at).toBe("2026-10-20T10:30:00.000Z");    expect(project.data.repos).toEqual(["https://git.example.test/acme/cotton.git"]);    expect(project.data.brand).toEqual({ color: "#123456" });    for (const r of plan.rows) {      const known = new Set((tables.get(r.table) ?? (QUOTA_DEFINITION as TableJson)).columns.map((c) => c.key));      for (const key of Object.keys(r.data)) expect(known.has(key), `${r.table}.${key}`).toBe(true);      for (const gone of ["workspace_id", "_hlc", "_born", "value_enc", "vmk_version"]) expect(r.data).not.toHaveProperty(gone);    }    expect(row(plan, "note", "n-proc")!.data.pinned).toBe(true);    expect(row(plan, "project_link", "l-mem")!.data).toMatchObject({ project: "p-cotton", record_kind: "memory", record_id: "m-1", pinned: true, position: 1000 });    const session = row(plan, "session", "se-1")!.data;    expect(session).toMatchObject({ project: "p-cotton", host_owned: true, shipped: ["https://git.example.test/acme/cotton/pull/1"], turn_count: 3 });    expect(row(plan, "prompt", "pr-1")!.data).toMatchObject({ session: "se-1", project: "p-cotton", seq: 0 });    expect(row(plan, "session_message", "sm-1")!.data).toMatchObject({ to_session: "se-1", from_session: null, media: [] });    expect(row(plan, "group_member", "gm-1")!.data).toMatchObject({ group: "g-agents", record_id: "t-1", place: 1.5 });    expect(row(plan, "device", "d-mac")!.data).toMatchObject({ device_id: "mac-1", agents: { "claude-code": "1.0.0" }, account_ids: {}, repos: null, mem_total_gb: 48.5 });    expect(row(plan, "memory", "m-2")!.data).toMatchObject({ status: "archived", superseded_by: "m-1", origin_label: "claude" });  });  it("leaves each secret with a value on the Mac, naming it, never sends it emptied, and brings one with none", () => {    const { plan, payloads } = planOf();    // k1 sealing is removed (sealing plan §7 step 6): a value reaches the object only sealed by a vault device.    expect(row(plan, "secret", "s-key")).toBeUndefined();    expect(row(plan, "secret", "s-login")).toBeUndefined();    expect(row(plan, "secret", "s-empty")!.data.sealed).toBeNull();    for (const id of ["s-key", "s-login"]) expect(plan.left.some((l) => l.startsWith(`secret ${id} `) && l.includes("stays on the Mac")), id).toBe(true);    const all = JSON.stringify(plan);    for (const payload of Object.values(payloads)) expect(all).not.toContain(payload);  });  it("brings every note but the binned ones, and only todo lists", () => {    const { plan } = planOf();    for (const id of ["n-proc", "n-loose", "n-walk"]) expect(row(plan, "note", id), id).toBeDefined();    expect(row(plan, "note", "n-binned")).toBeUndefined();    expect(report(plan, "note").seen).toBe(4);    expect(report(plan, "note").dropped.get("in the bin")).toBe(1);    expect(plan.left.some((l) => l.startsWith("note:"))).toBe(false);    expect(row(plan, "record_group", "g-agents")).toBeDefined();    expect(row(plan, "record_group", "g-home")).toBeUndefined();    expect(row(plan, "group_member", "gm-home")).toBeUndefined();  });  it("drops a row whose required link is not coming, clears an optional one, and counts both", () => {    const { plan } = planOf();    expect(row(plan, "prompt", "pr-orphan")).toBeUndefined();    expect(report(plan, "prompt").dropped.get("its session is not there")).toBe(1);    expect(row(plan, "session", "se-2")!.data.project).toBeNull();    expect(report(plan, "session").cleared.get("project")).toBe(1);    expect(row(plan, "group_member", "gm-ghost")).toBeUndefined();    expect(report(plan, "group_member").dropped.get("its todo is not there")).toBe(1);    const links = report(plan, "project_link");    expect(links.dropped.get("its note is not there")).toBe(1);    expect(links.dropped.get("its call is not there")).toBe(1);    // Its secret holds a value, which stays on the Mac, so the link to it does not come either.    expect(links.dropped.get("its secret is not there")).toBe(1);    expect(links.sent).toBe(6);  });  it("files a project link of any kind the object holds: a chat, a person, a journal entry as its note", () => {    const { plan } = planOf();    expect(row(plan, "project_link", "l-thread")!.data).toMatchObject({ record_kind: "thread", record_id: "th-1" });    expect(row(plan, "project_link", "l-person")!.data).toMatchObject({ record_kind: "person", record_id: "p-asha" });    expect(row(plan, "project_link", "l-journal")!.data).toMatchObject({ record_kind: "journal", record_id: "n-loose" });  });  it("brings every table a Mac tool draws with its real columns: JSON parsed, 0/1 a bool, its own key", () => {    const { plan } = planOf();    const mm2 = row(plan, "message", "mm-2")!;    expect(mm2.data).toMatchObject({ thread_id: "th-1", reply_to_id: "mm-1", direction: "in", channel: "whatsapp", origin: "imported", sent_at: "2026-10-20T09:01:00.000Z", reactions: [], meta: {} });    expect((mm2.data.media as { key: string }[])[0]!.key).toMatch(/\/messages\/th-1\/[0-9a-f]{64}\.png$/);    expect(mm2.created_at).toBe("2026-09-01T08:00:00.000Z");    expect(Object.keys(mm2.data)).not.toContain("workspace_id");    expect(Object.keys(mm2.data)).not.toContain("_hlc");    expect(row(plan, "message_contact", "c-asha")!.data).toMatchObject({ person_id: "p-asha", vip: true, muted: false });    expect(row(plan, "thread", "th-1")!.data).toMatchObject({ kind: "dm", contact_id: "c-asha", archived: false });    expect(row(plan, "thread_member", "tp-1")!.data).toMatchObject({ thread_id: "th-1", contact_id: "c-asha" });    expect(row(plan, "message_reaction", "r-1")!.data).toMatchObject({ message_id: "mm-1", emoji: "👍" });    expect(row(plan, "person_handle", "ph-1")!.data).toMatchObject({ person_id: "p-asha", value: "+15550001111" });    expect(row(plan, "meeting", "mt-1")!.data.segments).toEqual([expect.objectContaining({ seq: 0, durationMs: 1000 })]);    expect(row(plan, "meeting_utterance", "mu-1")!.data).toMatchObject({ meeting_id: "mt-1", text: "Good morning." });    expect(row(plan, "event", "ev-1")!.data).toMatchObject({ title: "Dentist", all_day: false });    expect(row(plan, "note_attachment", "na-1")!.data).toMatchObject({ note_id: "n-walk", record_kind: "photo" });    expect(row(plan, "email", "em-1")!.data).toMatchObject({ thread_id: "et-1", unread: true, recipients: ["owner@example.test"] });    // A one-row settings table is keyed by its workspace.    expect(row(plan, "message_settings", WS)!.data).toMatchObject({ handle: "invented-owner", display_name: "Owner" });    const photos = plan.rows.filter((r) => r.table === "photo");    expect(photos).toHaveLength(2);    expect(photos.find((p) => p.data.trashed_at)?.data.trashed_at, "a binned photo comes as it is").toBe("2026-10-20T10:30:00.000Z");    expect(photos.find((p) => !p.data.trashed_at)!.data).toMatchObject({ favourite: true, labels: ["garden"], width: 64 });  });  it("clears a reply to a message the file does not hold, and says so", () => {    const { plan } = planOf();    expect(row(plan, "message", "mm-3")!.data.reply_to_id).toBeNull();    expect(report(plan, "message").cleared.get("reply_to_id")).toBe(1);  });  it("orders a long chain of replies, each after the one it answers, without running out of stack", () => {    const f = buildLifeDb(dir, { messages: 0 });    const db = new DatabaseSync(f.path, { enableForeignKeyConstraints: false });    const add = db.prepare("INSERT INTO cotton_msg_messages (id, thread_id, workspace_id, direction, channel, origin, sent_at, created_at, body, reply_to_id) VALUES (?, 'th-1', ?, 'in', 'sms', 'imported', '2026-10-01T00:00:00.000Z', '2026-10-01T00:00:00.000Z', 'x', ?)");    // Newest first in the file, so every row names one the walk has not reached yet.    db.exec("BEGIN");    for (let i = 20_000; i > 0; i--) add.run(`chain-${i}`, WS, i === 1 ? null : `chain-${i - 1}`);    db.exec("COMMIT");    db.close();    const plan = planImport(readLifeDb(f.path, tables), tables);    const at = new Map(plan.rows.map((r, i) => [r.id, i]));    expect(at.get("chain-1")!).toBeLessThan(at.get("chain-2")!);    expect(at.get("chain-19999")!).toBeLessThan(at.get("chain-20000")!);  });  it("every package table the Mac's tools fill is what pnpm personal-tables makes from schema 141", () => {    const stale = [...files()].filter(([path, body]) => readFileSync(path, "utf8") !== body).map(([path]) => path);    expect(stale, "run pnpm -s personal-tables").toEqual([]);  });  it("drops a row that is missing a required value", () => {    const f = buildLifeDb(dir);    const db = new DatabaseSync(f.path);    db.prepare("UPDATE cotton_quota SET name = NULL WHERE id = 'q-2'").run();    db.close();    const plan = planImport(readLifeDb(f.path, tables), tables);    expect(row(plan, "quota", "q-2")).toBeUndefined();    expect(report(plan, "quota").dropped.get("no name")).toBe(1);  });  /** RULE: A mail date outside 1900–2100 that life.db holds is not brought as a date — the email is dropped and its thread's first_at / last_at cleared, each counted — because the old app stored a Google notice's "Mon, 16 Sep 2611" header before it bounded mail dates, and the push kept the object's newest email in the year 2611 (26 Oct 2026). */  it("drops an email dated outside 1900–2100 and clears its thread's dates, and counts both", () => {    const f = buildLifeDb(dir);    const db = new DatabaseSync(f.path);    // What the old app stored for a synthetic "Date: Mon, 16 Sep 2611 18:03:30 +0000".    db.prepare("UPDATE cotton_emails SET sent_at = '2611-09-16T18:03:30.000Z' WHERE id = 'em-1'").run();    db.prepare("UPDATE cotton_email_threads SET first_at = '2611-09-16T18:03:30.000Z', last_at = 'not a date' WHERE id = 'et-1'").run();    db.close();    const plan = planImport(readLifeDb(f.path, tables), tables);    expect(row(plan, "email", "em-1")).toBeUndefined();    expect(report(plan, "email").dropped.get("dated outside 1900–2100")).toBe(1);    expect(row(plan, "email_thread", "et-1")!.data).toMatchObject({ first_at: null, last_at: null });    expect(report(plan, "email_thread").undated).toEqual(new Map([["first_at", 1], ["last_at", 1]]));    expect(believableMailDate("2100-12-31T23:59:59.000Z")).toBe(true);    expect(believableMailDate("1900-01-01T00:00:00.000Z")).toBe(true);    expect(believableMailDate("1899-12-31T23:59:59.000Z")).toBe(false);  });  it("brings a believable mail date as it is", () => {    const { plan } = planOf();    expect(believableMailDate(row(plan, "email", "em-1")!.data.sent_at)).toBe(true);    expect(report(plan, "email").dropped.size).toBe(0);    expect(report(plan, "email_thread").undated.size).toBe(0);  });  it("orders every link's target before the row that names it", () => {    const { plan } = planOf();    const at = new Map(plan.rows.map((r, i) => [`${r.table}/${r.id}`, i]));    const linkTo = (table: string) => (tables.get(table)?.columns ?? []).filter((c) => c.type === "link" && c.link_to);    let checked = 0;    for (const [i, r] of plan.rows.entries()) {      for (const c of linkTo(r.table)) {        const v = r.data[c.key];        if (typeof v !== "string") continue;        expect(at.get(`${c.link_to}/${v}`), `${r.table}/${r.id}.${c.key}`).toBeLessThan(i);        checked += 1;      }    }    expect(checked).toBeGreaterThan(6);  });  it("brings the made tables: the definition with an id, live rows only", () => {    const { plan } = planOf();    expect(plan.definitions.map((d) => d.id)).toEqual(["reading"]);    expect(plan.definitions[0]).toMatchObject({ id: "reading", name: "Reading" });    expect(plan.left).toContain("made table reading: life.db has no cotton_reading, so it comes with no rows");    expect(row(plan, "todo", "todo")).toBeUndefined();  });  /** RULE (owner, 26 Oct 2026): the kit ships the owner's made tables (Quotas' quota among them), so their rows come under the package's columns and the Mac's definition stays behind; a column only the Mac's definition has is said, never sent. */  it("brings a made table the package now ships under the package's columns, and sends no definition for it", () => {    const { plan } = planOf();    expect(plan.definitions.some((d) => d.id === "quota")).toBe(false);    const packaged = new Set(tables.get("quota")!.columns.map((c) => c.key));    expect(QUOTA_DEFINITION.columns.map((c) => c.key).filter((k) => !packaged.has(k))).toEqual(["session_resets_at", "live"]);    expect(plan.left).toContain("made table quota: the personal package defines it without session_resets_at, live, so those columns stay on the Mac");    expect(row(plan, "quota", "q-1")!.data).toEqual({      name: "Claude personal", provider: "claude", email: "owner@example.test", session_pct: 42, week_pct: 17.5, week_resets_at: null, checked_at: "2026-10-20T10:30:00.000Z", macs: null,    });    expect(row(plan, "quota", "q-2")!.data).toMatchObject({ name: "Codex", provider: "codex" });    expect(row(plan, "quota", "q-gone")).toBeUndefined();  });  it("leaves a made table the personal package already defines, rather than refusing the file", () => {    const f = buildLifeDb(dir, {});    const db = new DatabaseSync(f.path);    db.prepare("INSERT INTO cotton_table_definitions (id, definition, builtin, workspace_id, created_at, updated_at) VALUES ('session', '{\"id\":\"session\",\"columns\":[]}', 0, ?, '2026-10-01T00:00:00Z', '2026-10-01T00:00:00Z')").run(WS);    db.close();    const plan = planImport(readLifeDb(f.path, tables), tables);    expect(plan.definitions.map((d) => d.id)).toEqual(["reading"]);    expect(plan.left).toContain("made table session: the personal package defines it, so the Mac's definition is left behind");  });  it("brings every tool and board definition as the phone draws it, the row's id given to one that names none", () => {    const { plan } = planOf();    expect(plan.tools.map((t) => t.id)).toEqual(["chores", "garden", "seeds"]);    const garden = plan.tools.find((t) => t.id === "garden")!;    const photo = (garden.picture as { photo: string }).photo;    expect(garden).toEqual(gardenTool(photo));    expect(row(plan, "photo", photo), "the garden's picture is a photo record that comes with the photos").toBeDefined();    expect(plan.tools.find((t) => t.id === "chores")).toMatchObject({ id: "chores", name: "Chores", tables: ["todo"] });    expect(plan.boards).toEqual([HOME_BOARD]);  });  it("says a tool whose picture names a photo that is not coming", () => {    const { plan } = planOf();    expect(plan.left).toContain(`tool seeds: its picture names photo:${"f".repeat(64)}, which is not coming, so the object has no picture for it`);    expect(plan.left.some((l) => l.startsWith("tool garden"))).toBe(false);  });  it("leaves the package's own tool to the package, never sending the Mac's over it", () => {    const kit = JSON.parse(readFileSync(join(KITS, "personal", "kit.json"), "utf8")) as { id: string };    expect(KIT_TOOL).toBe(kit.id);    const f = buildLifeDb(dir, {});    const db = new DatabaseSync(f.path);    db.prepare("INSERT INTO cotton_tool_definitions (id, definition, builtin, workspace_id, created_at, updated_at) VALUES ('personal', '{\"id\":\"personal\",\"name\":\"Old personal\"}', 0, ?, '2026-10-01T00:00:00Z', '2026-10-01T00:00:00Z')").run(WS);    db.close();    const plan = planImport(readLifeDb(f.path, tables), tables);    expect(plan.tools.map((t) => t.id)).toEqual(["chores", "garden", "seeds"]);    expect(plan.left).toContain("tool personal: the personal package defines it, so the Mac's definition is left behind");  });  it("refuses a tool or board definition it cannot send, before anything is planned", () => {    for (const [table, definition, message] of [      ["cotton_tool_definitions", "not json", /tool odd: its definition is not valid JSON/],      ["cotton_tool_definitions", "[1]", /tool odd: its definition is not a JSON object/],      ["cotton_tool_definitions", '{"id":"other","name":"Other"}', /tool odd: its definition says id other/],      ["cotton_tool_definitions", '{"tables":[]}', /tool odd: its definition has no name/],      ["cotton_board_definitions", '"home"', /board odd: its definition is not a JSON object/],    ] as const) {      rmSync(dir, { recursive: true, force: true });      dir = mkdtempSync(join(tmpdir(), "import-personal-"));      const f = buildLifeDb(dir, {});      const db = new DatabaseSync(f.path);      db.prepare(`INSERT INTO ${table} (id, definition, builtin, workspace_id, created_at, updated_at) VALUES ('odd', ?, 0, ?, '2026-10-01T00:00:00Z', '2026-10-01T00:00:00Z')`).run(definition, WS);      db.close();      expect(() => readLifeDb(f.path, tables)).toThrow(message);    }  });  it("is the same plan twice", () => {    const f = buildLifeDb(dir);    const a = planImport(readLifeDb(f.path, tables), tables);    const b = planImport(readLifeDb(f.path, tables), tables);    expect(JSON.stringify(b.rows)).toBe(JSON.stringify(a.rows));    expect(JSON.stringify([b.tools, b.boards])).toBe(JSON.stringify([a.tools, a.boards]));  });});describe("batches", () => {  it("cuts at 5000 rows and keeps the order", () => {    const rows: ImportRow[] = Array.from({ length: 12001 }, (_, i) => ({ verb: "put", table: "todo", id: `t-${i}`, data: { title: "x" } }));    const out = batches(rows);    expect(out.map((b) => b.length)).toEqual([5000, 5000, 2001]);    expect(out.flat()).toEqual(rows);  });  it("cuts by size too", () => {    const rows: ImportRow[] = Array.from({ length: 10 }, (_, i) => ({ verb: "put", table: "prompt", id: `p-${i}`, data: { text: "y".repeat(1000) } }));    expect(batches(rows, 5000, 3000).every((b) => b.length <= 2)).toBe(true);  });});describe("the media the rows name", () => {  it("finds every key a row names in the Mac's store — a photo, a video and its poster, an attachment, an avatar, a status, a meeting's folder — and none of the thumbnail tiers", () => {    const f = buildLifeDb(dir);    const plan = planImport(readLifeDb(f.path, tables), tables);    const named = namedKeys(plan.rows, WS, f.mediaRoot);    expect([...named.keys()].sort()).toEqual([...Object.keys(f.media), f.lostKey].sort());    expect([...named.keys()].some((k) => k.includes(".t256."))).toBe(false);    expect(named.get(f.lostKey)).toBe("message/mm-2");    const media = planMedia(named, WS, f.mediaRoot, 100 * 1024 * 1024);    expect(media.found.map((m) => m.key).sort()).toEqual(Object.keys(f.media).sort());    expect(media.lost).toEqual([{ key: f.lostKey, row: "message/mm-2" }]);    expect(planMedia(named, WS, f.mediaRoot, 20).tooBig.length, "a file past the upload limit is said, not sent").toBeGreaterThan(0);  });  it("leaves what a row has let go of, and a key of another database", () => {    const rows: ImportRow[] = [      { verb: "put", table: "story", id: "s1", data: { media_key: `${WS}/messages/statuses/a.jpg`, media_dropped_at: "2026-10-01T00:00:00Z" } },      { verb: "put", table: "photo", id: "p1", data: { key: "00000000-0000-4000-8000-000000000000/photos/b.jpg" } },      { verb: "put", table: "feedback", id: "f1", data: { image_sha256: "c".repeat(64), image_ext: "PNG" } },    ];    const named = namedKeys(rows, WS, null);    expect([...named.keys()]).toEqual(["00000000-0000-4000-8000-000000000000/photos/b.jpg", `${WS}/walkthroughs/${"c".repeat(64)}.png`]);    expect(planMedia(named, WS, dir, 1).foreign.map((m) => m.key)).toEqual(["00000000-0000-4000-8000-000000000000/photos/b.jpg"]);  });  it("reads a key's content type from the store's sidecar, else from its extension", () => {    const f = buildLifeDb(dir);    const video = Object.keys(f.media).find((k) => k.endsWith(".mp4"))!;    expect(contentType(f.mediaRoot, video)).toBe("video/mp4");    const attachment = Object.keys(f.media).find((k) => k.includes("/messages/th-1/"))!;    expect(contentType(f.mediaRoot, attachment), "no sidecar: the extension").toBe("image/png");    expect(contentType(f.mediaRoot, `${WS}/x/blob.unknown`)).toBe("application/octet-stream");  });  it("names only columns the package tables hold", () => {    for (const [table, columns] of Object.entries(HOLDERS)) {      const keys = (tables.get(table)?.columns ?? []).map((c) => c.key);      for (const c of columns) expect(keys, `${table}.${c}`).toContain(c);    }  });});