/** * A synthetic life.db: the real CREATE TABLEs of schema 141 (from the * committed snapshot crates/cotton-store/tests/fixtures/schema-snapshot.json), * invented rows, and a vault minted here — two master-key versions, the old * one retired under the new, wrapped for a Mac vault key and a phone key made * here. The seal, wrap and retire are written again with node:crypto (JWK for * the X25519 halves), apart from the script's own code, so a test that passes * is two implementations agreeing. Nothing here is real. */ import { createCipheriv, createHash, createPrivateKey, createPublicKey, diffieHellman, generateKeyPairSync, hkdfSync, randomBytes } from "node:crypto"; import { chmodSync, mkdirSync, readFileSync, writeFileSync } from "node:fs"; import { dirname, join, resolve } from "node:path"; import { DatabaseSync } from "node:sqlite"; import { fileURLToPath } from "node:url"; import { deflateSync } from "node:zlib"; import { RUST_TABLES } from "../import-personal/source.ts"; const here = dirname(fileURLToPath(import.meta.url)); export const REPO = resolve(here, "../../../.."); export const KITS = join(REPO, "crates/cotton-core/kits"); const SNAPSHOT = join(REPO, "crates/cotton-store/tests/fixtures/schema-snapshot.json"); export const WS = "5a1e0000-0000-4000-8000-000000000001"; const TABLES = [ "cotton_workspaces", "cotton_memories", "cotton_memory_projects", "cotton_project_links", "cotton_notes", "cotton_todos", "cotton_groups", "cotton_group_members", "cotton_secrets", "cotton_vault_keys", "cotton_vault_state", "cotton_vault_retired_keys", "cotton_sessions", "cotton_prompts", "cotton_session_tasks", "cotton_session_messages", "cotton_devices", "cotton_agent_accounts", "cotton_table_definitions", "cotton_tool_definitions", "cotton_board_definitions", // Every table a Mac tool draws. ...RUST_TABLES.map((t) => t.from), ]; // ── the vault, written independently of scripts/import-personal/vault.ts ───── const b64u = (b: Uint8Array): string => Buffer.from(b).toString("base64url"); export function x25519Pair(): { secret: Buffer; pub: Buffer } { const { privateKey } = generateKeyPairSync("x25519"); const jwk = privateKey.export({ format: "jwk" }) as { d: string; x: string }; return { secret: Buffer.from(jwk.d, "base64url"), pub: Buffer.from(jwk.x, "base64url") }; } function keyFromJwk(secret?: Buffer, pub?: Buffer) { if (secret) { const x = pub ?? Buffer.alloc(0); return createPrivateKey({ key: { kty: "OKP", crv: "X25519", d: secret.toString("base64url"), x: x.toString("base64url") }, format: "jwk" }); } return createPublicKey({ key: { kty: "OKP", crv: "X25519", x: pub!.toString("base64url") }, format: "jwk" }); } function gcm(key: Uint8Array, nonce: Uint8Array, plaintext: Uint8Array, aad: Uint8Array): Buffer { const c = createCipheriv("aes-256-gcm", key, nonce); c.setAAD(aad); const ct = Buffer.concat([c.update(plaintext), c.final()]); return Buffer.concat([ct, c.getAuthTag()]); } /** seal.rs: "v2:" + b64u(nonce || AES-256-GCM(key, nonce, payload, aad = label:version)). */ export function seal(key: Uint8Array, label: string, version: number, payload: Uint8Array | string): string { const nonce = randomBytes(12); return `v2:${b64u(Buffer.concat([nonce, gcm(key, nonce, Buffer.from(payload), Buffer.from(`${label}:${version}`))]))}`; } /** wrap.rs: "w1:" + b64u(eph_pub || nonce || ct), aad = recipient_pub. */ export function wrap(recipientPub: Buffer, plaintext: Uint8Array): string { const eph = x25519Pair(); const shared = diffieHellman({ privateKey: keyFromJwk(eph.secret, eph.pub), publicKey: keyFromJwk(undefined, recipientPub) }); const key = Buffer.from(hkdfSync("sha256", shared, Buffer.concat([eph.pub, recipientPub]), "cotton-vault-wrap-v1", 32)); const nonce = randomBytes(12); return `w1:${b64u(Buffer.concat([eph.pub, nonce, gcm(key, nonce, plaintext, recipientPub)]))}`; } function kcv(key: Uint8Array, ws: string, version: number): string { const v = Buffer.alloc(4); v.writeUInt32BE(version); return b64u(Buffer.from(hkdfSync("sha256", key, "cotton vault kcv", Buffer.concat([Buffer.from(ws), Buffer.from([0]), v]), 16))); } /** chain.rs `retire`: the old key sealed under the new one. */ export function retire(old: Buffer, oldVersion: number, next: Buffer, nextVersion: number, ws: string): { version: number; under_version: number; under_kcv: string; wrapped: string } { const underKcv = kcv(next, ws, nextVersion); return { version: oldVersion, under_version: nextVersion, under_kcv: underKcv, wrapped: seal(next, `retired-key:${ws}:${oldVersion}:${underKcv}`, nextVersion, old) }; } // ── the file ───────────────────────────────────────────────────────────────── export interface Fixture { path: string; vaultKeyPath: string; /** Opened payloads by secret id: what the object must be handed to seal. */ payloads: Record; /** The Mac's media store: `/`, content types in `/.meta/.json`. */ mediaRoot: string; /** Every media key the rows name and the store holds, with its bytes. */ media: Record; /** A key a row names that the store does not hold. */ lostKey: string; } /** A real PNG of `w`×`h` pixels in one colour: the resizer must be able to read it. */ export function png(w: number, h: number, rgb: [number, number, number] = [200, 80, 40]): Buffer { const crcTable = Array.from({ length: 256 }, (_, n) => { let c = n; for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1; return c >>> 0; }); const crc = (b: Buffer): number => { let c = 0xffffffff; for (const x of b) c = crcTable[(c ^ x) & 0xff]! ^ (c >>> 8); return (c ^ 0xffffffff) >>> 0; }; const chunk = (type: string, data: Buffer): Buffer => { const len = Buffer.alloc(4); len.writeUInt32BE(data.length); const body = Buffer.concat([Buffer.from(type), data]); const sum = Buffer.alloc(4); sum.writeUInt32BE(crc(body)); return Buffer.concat([len, body, sum]); }; const ihdr = Buffer.alloc(13); ihdr.writeUInt32BE(w, 0); ihdr.writeUInt32BE(h, 4); ihdr.set([8, 2, 0, 0, 0], 8); const raw = Buffer.concat(Array.from({ length: h }, () => Buffer.from([0, ...Array.from({ length: w }, () => rgb).flat()]))); return Buffer.concat([Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]), chunk("IHDR", ihdr), chunk("IDAT", deflateSync(raw)), chunk("IEND", Buffer.alloc(0))]); } const sha = (b: Buffer): string => createHash("sha256").update(b).digest("hex"); const T0 = "2026-09-01T08:00:00.000Z"; const T1 = "2026-10-20T10:30:00.000Z"; export function createTables(db: DatabaseSync, names = TABLES): void { const snapshot = JSON.parse(readFileSync(SNAPSHOT, "utf8")) as { kind: string; name: string; sql: string }[]; for (const name of names) { const t = snapshot.find((o) => o.kind === "table" && o.name === name); if (!t) throw new Error(`the snapshot has no table ${name}`); db.exec(t.sql); } } const shapes = new WeakMap>>(); /** One row; the frame `common` spreads (workspace, times, _hlc) is left out where the table does not carry it. */ function insert(db: DatabaseSync, table: string, row: Record): void { const byTable = shapes.get(db) ?? new Map>(); shapes.set(db, byTable); const have = byTable.get(table) ?? new Set((db.prepare(`PRAGMA table_info("${table}")`).all() as { name: string }[]).map((c) => c.name)); byTable.set(table, have); const keys = Object.keys(row).filter((k) => have.has(k) || !["workspace_id", "created_at", "updated_at", "_hlc"].includes(k)); db.prepare(`INSERT INTO "${table}" (${keys.map((k) => `"${k}"`).join(", ")}) VALUES (${keys.map(() => "?").join(", ")})`).run(...keys.map((k) => row[k]!)); } /** The made table `quota`, stored as package_tables.rs derives it: metadata columns, then one per definition column; drawn by its title, slip and tile as the phone draws a table no app ships. */ export const QUOTA_DEFINITION = { format_version: 1, id: "quota", name: "Quota", plural: "Quotas", picture: null, builtin: false, engine: null, title: "name", date: null, project: null, order: null, slip: { title: "name", subtitle: null, trailing: null, photo: null, toggle: null }, tile: { face: "slip-list" }, page: [{ heading: null, columns: ["name", "provider", "email"] }], columns: [ { key: "name", label: "Name", type: "text", required: true }, { key: "provider", label: "Provider", type: "choice", choices: ["claude", "codex"] }, { key: "email", label: "Email", type: "text" }, { key: "session_pct", label: "Session %", type: "number" }, { key: "session_resets_at", label: "Session resets", type: "text" }, { key: "week_pct", label: "Week %", type: "number" }, { key: "week_resets_at", label: "Week resets", type: "text" }, { key: "checked_at", label: "Checked", type: "text" }, { key: "macs", label: "Macs", type: "text" }, { key: "live", label: "Live", type: "bool" }, ], }; /** An invented tool in the definition shape the phone draws, its picture the photo record named. */ export function gardenTool(photo: string): Record { return { views: [{ id: "all", label: "All", visibility: "owner", is_default: true, read: { table: "todo" } }], id: "garden", name: "Garden", purpose: "What grows where.", picture: { photo }, card_stock: "sage", tables: ["todo"], instructions: "", automations: [], author: { device: "cotton", name: "Cotton" }, signature: null, }; } /** An invented Home board. */ export const HOME_BOARD = { format_version: 1, id: "home", parts: [{ kind: "tools", face: "fan" }] }; /** Build the synthetic life.db in `dir`; `version` stamps PRAGMA user_version. */ export function buildLifeDb(dir: string, opts: { version?: number; workspaceId?: string; tamper?: boolean; messages?: number } = {}): Fixture { const ws = opts.workspaceId ?? WS; const path = join(dir, "life.db"); // Foreign keys off while building, as an old file may carry an orphan the import must drop. const db = new DatabaseSync(path, { enableForeignKeyConstraints: false }); createTables(db); const common = { workspace_id: ws, created_at: T0, updated_at: T1, _hlc: "1760000000000:0000:test-author" }; insert(db, "cotton_workspaces", { id: ws, name: "Personal", owner_user_id: "user-invented", created_at: T0, kind: "personal" }); insert(db, "cotton_memory_projects", { id: "p-cotton", slug: "cotton", name: "Cotton", repos: '["https://git.example.test/acme/cotton.git"]', brand: '{"color":"#123456"}', description: "An invented project", ...common }); insert(db, "cotton_memory_projects", { id: "p-garden", slug: "garden", name: "Garden", repos: "[]", status: "archived", ...common }); insert(db, "cotton_memories", { id: "m-1", slug: "tea-before-code", title: "Tea comes before code.", origin_kind: "user", ...common }); insert(db, "cotton_memories", { id: "m-2", slug: "old-rule", title: "An older rule.", origin_kind: "agent", origin_label: "claude", status: "archived", archived_at: T1, superseded_by: "m-1", ...common }); insert(db, "cotton_notes", { id: "n-proc", kind: "note", title: "Release", body: "Trigger: when shipping\nRun the checks.", pinned: 1, ...common }); insert(db, "cotton_notes", { id: "n-binned", kind: "note", title: "Old", body: "gone", trashed_at: T1, ...common }); insert(db, "cotton_notes", { id: "n-loose", kind: "note", title: "Loose", body: "nobody files this", ...common }); insert(db, "cotton_todos", { id: "t-1", title: "Water the plants", status: "open", priority: 0, ...common }); insert(db, "cotton_todos", { id: "t-2", title: "Buy seeds", status: "done", priority: 2, completed_at: T1, ...common }); insert(db, "cotton_groups", { id: "g-agents", table_id: "todo", name: "Agents", position: 1, ...common }); insert(db, "cotton_groups", { id: "g-home", table_id: "tool_order", name: "Home", ...common }); insert(db, "cotton_group_members", { id: "gm-1", group_id: "g-agents", record_id: "t-1", place: 1.5, ...common }); insert(db, "cotton_group_members", { id: "gm-ghost", group_id: "g-agents", record_id: "t-nowhere", place: 2, ...common }); insert(db, "cotton_group_members", { id: "gm-home", group_id: "g-home", record_id: "tool-x", place: 1, ...common }); insert(db, "cotton_project_links", { id: "l-mem", project_id: "p-cotton", record_kind: "memory", record_id: "m-1", applied_by: "user", pinned: 1, position: 1000, ...common }); insert(db, "cotton_project_links", { id: "l-note", project_id: "p-cotton", record_kind: "note", record_id: "n-proc", applied_by: "agent", ...common }); insert(db, "cotton_project_links", { id: "l-binned", project_id: "p-cotton", record_kind: "note", record_id: "n-binned", applied_by: "agent", ...common }); insert(db, "cotton_project_links", { id: "l-todo", project_id: "p-garden", record_kind: "todo", record_id: "t-2", applied_by: "user", ...common }); insert(db, "cotton_project_links", { id: "l-thread", project_id: "p-cotton", record_kind: "thread", record_id: "th-1", applied_by: "router", ...common }); insert(db, "cotton_project_links", { id: "l-secret", project_id: "p-cotton", record_kind: "secret", record_id: "s-key", applied_by: "user", ...common }); // The vault: key v1 retired under v2; v2 wrapped for this Mac and for a phone. const mac = x25519Pair(); const phone = x25519Pair(); const vmk1 = randomBytes(32); const vmk2 = randomBytes(32); insert(db, "cotton_vault_state", { workspace_id: ws, vmk_version: 2, rotated_at: T1, created_at: T0, updated_at: T1 }); insert(db, "cotton_vault_keys", { id: "vk-phone", device_id: "phone-device", public_key: b64u(phone.pub), wrapped_vmk: wrap(phone.pub, vmk2), vmk_version: 2, ...common }); insert(db, "cotton_vault_keys", { id: "vk-mac", device_id: `server:${b64u(mac.pub)}`, public_key: b64u(mac.pub), wrapped_vmk: wrap(mac.pub, vmk2), vmk_version: 2, ...common }); const link = retire(vmk1, 1, vmk2, 2, ws); insert(db, "cotton_vault_retired_keys", { id: "rk-1", workspace_id: ws, ...link, retired_at: T1, actor: "test", _hlc: "" }); const payloads: Record = { "s-key": JSON.stringify({ kind: "api_key", key: "sk-invented-0000" }), "s-login": JSON.stringify({ kind: "login", password: "invented-password" }), }; insert(db, "cotton_secrets", { id: "s-key", kind: "api_key", name: "Anthropic", service: "anthropic", hint: "0000", value_enc: seal(vmk2, "s-key", 2, payloads["s-key"]!), vmk_version: 2, ...common }); // Sealed before the rotation: opens only through the retired-key chain. insert(db, "cotton_secrets", { id: "s-login", kind: "login", name: "Garden shop", site: "shop.example.test", username: "me", value_enc: opts.tamper ? `v2:${b64u(randomBytes(40))}` : seal(vmk1, "s-login", 1, payloads["s-login"]!), vmk_version: 1, ...common }); insert(db, "cotton_secrets", { id: "s-empty", kind: "note", name: "Named, no value", vmk_version: 0, ...common }); insert(db, "cotton_sessions", { id: "se-1", project_id: "p-cotton", tool: "claude-code", external_id: "ext-1", machine: "mac-c", last_active_at: T1, title: "Invented session", shipped: '["https://git.example.test/acme/cotton/pull/1"]', turn_count: 3, prompt_count: 2, host_owned: 1, ...common }); insert(db, "cotton_sessions", { id: "se-2", project_id: "p-gone", tool: "codex", external_id: "ext-2", last_active_at: T1, ...common }); insert(db, "cotton_prompts", { id: "pr-1", session_id: "se-1", project_id: "p-cotton", seq: 0, ts: T0, text: "Make it so.", ...common }); insert(db, "cotton_prompts", { id: "pr-orphan", session_id: "se-ghost", seq: 0, ts: T0, text: "Nobody hears this.", ...common }); insert(db, "cotton_session_tasks", { id: "st-1", session_id: "se-1", seq: 0, text: "Write the test", state: "done", ...common }); insert(db, "cotton_session_messages", { id: "sm-1", project_id: "p-cotton", to_kind: "session", to_session_id: "se-1", from_kind: "owner", kind: "instruction", body: "Carry on.", media: "[]", ...common }); insert(db, "cotton_devices", { id: "d-mac", device_id: "mac-1", name: "mac-c", platform: "macos", approved_at: T0, approved_by_device: "mac-1", agents: '{"claude-code":"1.0.0"}', account_ids: "{}", cpu_count: 12, mem_total_gb: 48.5, ...common }); insert(db, "cotton_agent_accounts", { id: "a-1", provider: "anthropic", email: "owner@example.test", label: "Personal", ...common }); // Made tables: quota with storage; a definition without an id and with no storage yet. insert(db, "cotton_table_definitions", { id: "todo", definition: '{"id":"todo","columns":[]}', builtin: 1, ...common }); insert(db, "cotton_table_definitions", { id: "quota", definition: JSON.stringify(QUOTA_DEFINITION), builtin: 0, ...common }); insert(db, "cotton_table_definitions", { id: "reading", definition: JSON.stringify({ format_version: 1, name: "Reading", columns: [{ key: "name", type: "text" }] }), builtin: 0, ...common }); db.exec( `CREATE TABLE "cotton_quota" ("id" TEXT PRIMARY KEY, "workspace_id" TEXT, "created_at" TEXT, "updated_at" TEXT, "deleted_at" TEXT, "record_byline" TEXT, "_hlc" TEXT NOT NULL DEFAULT '', "_born" TEXT, ` + `"name" TEXT, "provider" TEXT, "email" TEXT, "session_pct" NUMERIC, "session_resets_at" TEXT, "week_pct" NUMERIC, "week_resets_at" TEXT, "checked_at" TEXT, "macs" TEXT, "live" INTEGER)`, ); insert(db, "cotton_quota", { id: "q-1", workspace_id: ws, created_at: T0, updated_at: T1, name: "Claude personal", provider: "claude", email: "owner@example.test", session_pct: 42, week_pct: 17.5, checked_at: T1, live: 1 }); insert(db, "cotton_quota", { id: "q-2", workspace_id: ws, created_at: T0, updated_at: T1, name: "Codex", provider: "codex", live: 0 }); insert(db, "cotton_quota", { id: "q-gone", workspace_id: ws, created_at: T0, updated_at: T1, deleted_at: T1, name: "Deleted", live: 1 }); // ── the Mac tools' own tables, and the media their rows name ────────────── const mediaRoot = join(dir, "media"); const media: Record = {}; const store = (key: string, bytes: Buffer, contentType?: string): string => { mkdirSync(dirname(join(mediaRoot, key)), { recursive: true }); writeFileSync(join(mediaRoot, key), bytes); if (contentType) { mkdirSync(dirname(join(mediaRoot, ".meta", key)), { recursive: true }); writeFileSync(join(mediaRoot, ".meta", `${key}.json`), JSON.stringify({ contentType })); } media[key] = bytes; return key; }; const picture = png(64, 48); const pictureSha = sha(picture); const photoKey = store(`${ws}/photos/${pictureSha}.png`, picture, "image/png"); // A thumbnail tier the Mac made: derived from the original, never a row's, never brought. mkdirSync(join(mediaRoot, ws, "photos"), { recursive: true }); writeFileSync(join(mediaRoot, ws, "photos", `${pictureSha}.t256.jpg`), Buffer.from("tier")); const binnedPicture = png(8, 8, [10, 10, 10]); const film = Buffer.from("not really an mp4, but bytes all the same"); const filmSha = sha(film); const videoKey = store(`${ws}/videos/${filmSha}.mp4`, film, "video/mp4"); const posterKey = store(`${ws}/videos/${filmSha}.poster.jpg`, png(16, 9), "image/jpeg"); const attachment = png(20, 20, [0, 120, 255]); const attachmentKey = store(`${ws}/messages/th-1/${sha(attachment)}.png`, attachment); const avatar = png(12, 12, [255, 200, 0]); const avatarKey = store(`${ws}/people/p-asha/${sha(avatar)}.png`, avatar); const statusKey = store(`${ws}/messages/statuses/${sha(Buffer.from("status"))}.jpg`, Buffer.from("status"), "image/jpeg"); const fullAudio = store(`${ws}/meetings/mt-1/full.m4a`, Buffer.from("the whole meeting"), "audio/mp4"); const segment = store(`${ws}/meetings/mt-1/segments/000.m4a`, Buffer.from("segment 0"), "audio/mp4"); void fullAudio; const lostKey = `${ws}/messages/th-1/${"0".repeat(64)}.jpg`; insert(db, "cotton_people", { id: "p-asha", full_name: "Asha Invented", avatar_key: avatarKey, ...common }); insert(db, "cotton_person_handles", { id: "ph-1", person_id: "p-asha", kind: "phone", value: "+15550001111", normalised: "+15550001111", source: "manual", ...common }); insert(db, "cotton_msg_contacts", { id: "c-asha", person_id: "p-asha", display_name: "Asha", phone_e164: "15550001111", avatar_key: avatarKey, vip: 1, ...common }); insert(db, "cotton_msg_threads", { id: "th-1", kind: "dm", contact_id: "c-asha", title: "Asha", archived: 0, ...common }); insert(db, "cotton_msg_thread_participants", { id: "tp-1", thread_id: "th-1", contact_id: "c-asha", role: "member", ...common }); insert(db, "cotton_msg_owner_settings", { workspace_id: ws, handle: "invented-owner", display_name: "Owner", created_at: T0, updated_at: T1 }); const message = (id: string, extra: Record) => insert(db, "cotton_msg_messages", { id, thread_id: "th-1", workspace_id: ws, direction: "in", channel: "whatsapp", origin: "imported", sent_at: T1, created_at: T0, ...extra }); message("mm-1", { body: "Hello from Asha", sent_at: "2026-10-20T09:00:00.000Z" }); message("mm-2", { body: "", reply_to_id: "mm-1", media: JSON.stringify([{ key: attachmentKey, contentType: "image/png", width: 20, height: 20 }, { key: lostKey, contentType: "image/jpeg" }]), sent_at: "2026-10-20T09:01:00.000Z" }); message("mm-3", { body: "Replying to a message the export lost", reply_to_id: "mm-gone", sent_at: "2026-01-02T09:00:00.000Z" }); db.exec("BEGIN"); for (let i = 0; i < (opts.messages ?? 0); i++) { message(`mm-bulk-${String(i).padStart(7, "0")}`, { body: `Invented message ${i} ${"lorem ipsum ".repeat(8)}`, direction: i % 2 ? "out" : "in", sent_at: new Date(Date.parse(T0) + i * 60_000).toISOString(), meta: JSON.stringify({ n: i }) }); } db.exec("COMMIT"); insert(db, "cotton_msg_reactions", { id: "r-1", workspace_id: ws, thread_id: "th-1", message_id: "mm-1", actor: "c-asha", emoji: "👍", created_at: T0 }); insert(db, "cotton_photos", { id: `photo:${pictureSha}`, key: photoKey, sha256: pictureSha, content_type: "image/png", size_bytes: picture.length, taken_at: T0, width: 64, height: 48, favourite: 1, labels: '["garden"]', ...common }); // A binned photo comes as it is, its bytes too: the bin is the owner's to empty. const binnedSha = sha(binnedPicture); const binnedKey = store(`${ws}/photos/${binnedSha}.png`, binnedPicture, "image/png"); insert(db, "cotton_photos", { id: `photo:${binnedSha}`, key: binnedKey, sha256: binnedSha, content_type: "image/png", size_bytes: binnedPicture.length, taken_at: T0, trashed_at: T1, ...common }); insert(db, "cotton_videos", { id: `video:${filmSha}`, key: videoKey, poster_key: posterKey, sha256: filmSha, content_type: "video/mp4", size_bytes: film.length, taken_at: T0, ...common }); insert(db, "cotton_meetings", { id: "mt-1", source: "recorded", started_at: T0, status_changed_at: T1, status: "ready", title: "Invented standup", segments: JSON.stringify([{ seq: 0, path: segment, durationMs: 1000, uploadedAt: null }]), ...common }); insert(db, "cotton_meeting_utterances", { id: "mu-1", meeting_id: "mt-1", seq: 0, speaker_label: "A", t0_ms: 0, t1_ms: 900, text: "Good morning.", created_at: T0 }); insert(db, "cotton_events", { id: "ev-1", collection_id: "col-invented", title: "Dentist", starts_at: "2026-11-01T10:00:00.000Z", all_day: 0, created_at: T0, updated_at: T1 }); insert(db, "cotton_notes", { id: "n-walk", kind: "note", title: "Walkthrough", body: "Two screens", ...common }); insert(db, "cotton_note_attachments", { id: "na-1", note_id: "n-walk", record_kind: "photo", record_id: `photo:${pictureSha}`, position: 0, ...common }); insert(db, "cotton_stories", { id: "sty-1", source: "whatsapp", account: "invented", external_id: "status-1", kind: "image", posted_at: T0, expires_at: T1, media_key: statusKey, created_at: T0, workspace_id: ws }); insert(db, "cotton_email_threads", { id: "et-1", external_key: "thread-invented", subject: "Your receipt", ...common }); insert(db, "cotton_emails", { id: "em-1", thread_id: "et-1", external_id: "msg-invented", from_email: "shop@example.test", sent_at: T1, subject: "Your receipt", recipients: '["owner@example.test"]', attachments: JSON.stringify([{ name: "receipt.png", mime: "image/png", key: attachmentKey }]), unread: 1, created_at: T0, workspace_id: ws }); // The owner's tools and boards: one whose picture is the photo above, one naming a photo the file lacks, one with none; a board. insert(db, "cotton_tool_definitions", { id: "garden", definition: JSON.stringify(gardenTool(`photo:${pictureSha}`)), builtin: 0, ...common }); insert(db, "cotton_tool_definitions", { id: "seeds", definition: JSON.stringify({ ...gardenTool(`photo:${"f".repeat(64)}`), id: "seeds", name: "Seeds" }), builtin: 0, ...common }); insert(db, "cotton_tool_definitions", { id: "chores", definition: JSON.stringify({ name: "Chores", tables: ["todo"], instructions: "", automations: [], author: { device: "cotton", name: "Cotton" }, signature: null }), builtin: 1, ...common }); insert(db, "cotton_board_definitions", { id: "home", definition: JSON.stringify(HOME_BOARD), builtin: 0, ...common }); insert(db, "cotton_project_links", { id: "l-journal", project_id: "p-garden", record_kind: "journal", record_id: "n-loose", applied_by: "user", ...common }); insert(db, "cotton_project_links", { id: "l-person", project_id: "p-garden", record_kind: "person", record_id: "p-asha", applied_by: "router", ...common }); insert(db, "cotton_project_links", { id: "l-call", project_id: "p-garden", record_kind: "call", record_id: "call-nowhere", applied_by: "router", ...common }); db.exec(`PRAGMA user_version = ${opts.version ?? 141}`); db.close(); const vaultKeyPath = join(dir, "vault.key"); writeFileSync(vaultKeyPath, mac.secret); chmodSync(vaultKeyPath, 0o600); return { path, vaultKeyPath, payloads, mediaRoot, media, lostKey }; }