/** * Reading the owner's life.db (Rust schema 141), READ-ONLY, into the rows the * personal object's tables hold: one candidate per source row, keyed by the * package's own column keys, values in the object's shape (bool true/false, * JSON text parsed, NULL as null), each row's own id and times kept. * * Which life.db table fills which object table is `MAPPINGS` for the tables * the package shapes by hand: a target column `x` reads the source column * `x`, or `x_id` when only that exists (`project` ← `project_id`, * `to_session` ← `to_session_id`); a column with neither is a refusal, never a * silent gap. Every other table a Mac tool draws is `RUST_TABLES` * (rust-tables.json, made by `pnpm personal-tables` from schema 141): each * column under its own name, JSON and 0/1 as its Rust codec stores them. * workspace_id, _hlc and _born are never read. * * The tool and board definitions (cotton_tool_definitions, * cotton_board_definitions) come as the JSON the phone draws, every row: the * object keeps them beside the package's own tool. A tool's picture names a * photo record (`photo:<sha>`), which comes with the photo rows and its bytes * with the media, so the object serves it as it serves any photo; * cotton_tool_assets, the Mac's copy of a package's pictures, is not read. */import { existsSync, readdirSync, readFileSync } from"node:fs";import { dirname, join } from"node:path";import { DatabaseSync } from"node:sqlite";import { fileURLToPath } from"node:url";import { Refusal } from"./refusal.ts";exportconst SCHEMA_VERSION = 141;exportinterfaceColumnJson { key: string;type?: string; link_to?: string; required?: boolean; computed?: unknown;}exportinterfaceTableJson { id: string; columns: ColumnJson[]; [key: string]: unknown;}/** One row on its way to the object. */exportinterfaceCandidate { table: string; id: string; data: Record<string, unknown>; created_at?: string; updated_at?: string;}/** A tool's or a board's definition as life.db keeps it: the JSON the phone draws, with its id. */exporttypeDefinitionJson = { id: string } & Record<string, unknown>;exportinterfaceSource { workspaceId: string;/** Package tables, in write order. */ tables: { table: string; rows: Candidate[] }[];/** * The owner's made tables: the definition as it goes to the object, and its * live rows. A made table the personal package now ships (the kit's Work, * Quotas, Subscriptions…) is `packaged`: its rows come under the package's * definition, which the object already holds, and no definition is sent. */ made: { definition: TableJson; rows: Candidate[]; packaged: boolean }[];/** Every tool definition (cotton_tool_definitions) but the package's own, by id. */ tools: DefinitionJson[];/** Every board definition (cotton_board_definitions), by id. */ boards: DefinitionJson[];/** What stays on the Mac, said once each (unfiled notes, made tables without storage). */ left: string[];}interfaceMapping { table: string;from: string;/** Extra SQL condition; `:ws` is the workspace id. */ where?: string;/** Source columns holding JSON text (codec Json in cotton-store's table_specs.rs). */ json?: string[];/** Package columns life.db never had, filled on the object alone: an import leaves them unset. */ objectOnly?: string[];}/** One table a Mac tool draws, read with its real columns (rust-tables.json; scripts/personal-tables.ts makes it). */exportinterfaceRustTable { table: string;from: string; key: string; workspace: boolean; bin: boolean; columns: string[]; json: string[]; bool: string[];}exportconst RUST_TABLES = JSON.parse(readFileSync(join(dirname(fileURLToPath(import.meta.url)), "rust-tables.json"), "utf8")) asRustTable[];/** life.db table → personal package table, for the tables the package shapes by hand. */exportconst MAPPINGS: Mapping[] = [ { table: "project", from: "cotton_memory_projects", json: ["repos", "brand", "section_order"] }, { table: "memory", from: "cotton_memories" }, { table: "note", from: "cotton_notes" }, { table: "todo", from: "cotton_todos" }, { table: "secret", from: "cotton_secrets" },// A device's sync status is the object's (each sync page) and its phone's (sync_bytes, stalled_at), never the Mac's. { table: "device",from: "cotton_devices", json: ["agents", "account_ids", "repos", "ai_spend", "reported_state"], objectOnly: ["synced_at", "sync_version", "sync_rows_total", "sync_rows_done", "sync_bytes", "caught_up", "stalled_at"], }, { table: "agent_account", from: "cotton_agent_accounts" }, { table: "project_link", from: "cotton_project_links" }, { table: "record_group", from: "cotton_groups", where: "table_id = 'todo'", json: ["filter"] }, { table: "group_member", from: "cotton_group_members", where: "group_id IN (SELECT id FROM cotton_groups WHERE workspace_id = :ws AND table_id = 'todo')" }, { table: "session", from: "cotton_sessions", json: ["shipped"] }, { table: "prompt", from: "cotton_prompts" }, { table: "session_task", from: "cotton_session_tasks" }, { table: "session_message", from: "cotton_session_messages", json: ["media"] },];/** The personal kit's table definitions (crates/cotton-core/kits/personal/tables), read from the repository. */exportfunction kitTables(kitsDir: string): Map<string, TableJson> {const dir = join(kitsDir, "personal", "tables");if (!existsSync(dir)) thrownewRefusal(`no personal kit at ${dir}`);const out = newMap<string, TableJson>();for (const file of readdirSync(dir).filter((f) => f.endsWith(".json"))) {const t = JSON.parse(readFileSync(join(dir, file), "utf8")) asTableJson; out.set(t.id, t); }for (const m of [...MAPPINGS, ...RUST_TABLES]) if (!out.has(m.table)) thrownewRefusal(`the personal kit has no table ${m.table}; run pnpm -s personal-tables`);return out;}typeRaw = Record<string, unknown>;const quote = (name: string): string => `"${name.replace(/"/g, '""')}"`;function columnsOf(db: DatabaseSync, table: string): Set<string> | null {const exists = db.prepare("SELECT 1 AS x FROM sqlite_master WHERE type = 'table' AND name = ?").get(table);if (!exists) returnnull;returnnewSet((db.prepare(`PRAGMA table_info(${quote(table)})`).all() as { name: string }[]).map((c) => c.name));}function convert(where: string, column: ColumnJson, raw: unknown, json: boolean): unknown {if (raw === null || raw === undefined) returnnull;if (raw instanceofUint8Array) thrownewRefusal(`${where} holds bytes; the object keeps no bytes in a column`);if (typeof raw === "bigint") raw = Number(raw);if (json) {if (typeof raw !== "string") thrownewRefusal(`${where} should hold JSON text`);try {return JSON.parse(raw) as unknown; } catch {thrownewRefusal(`${where} is not valid JSON`); } }if (column.type === "bool") {if (typeof raw !== "number") thrownewRefusal(`${where} should be 0 or 1`);return raw !== 0; }return raw;}/** A value as its Rust codec stores it: JSON text parsed, 0/1 a bool, an integer a number. */function decode(where: string, raw: unknown, codec: "json" | "bool" | "plain"): unknown {if (raw === null || raw === undefined) returnnull;if (raw instanceofUint8Array) thrownewRefusal(`${where} holds bytes; the object keeps no bytes in a column`);if (typeof raw === "bigint") {if (raw > BigInt(Number.MAX_SAFE_INTEGER) || raw < BigInt(Number.MIN_SAFE_INTEGER)) thrownewRefusal(`${where} holds ${raw}, past what a JSON number keeps exactly`); raw = Number(raw); }if (codec === "json") {if (typeof raw !== "string") thrownewRefusal(`${where} should hold JSON text`);try {return JSON.parse(raw) as unknown; } catch {thrownewRefusal(`${where} is not valid JSON`); } }if (codec === "bool") {if (raw !== 0 && raw !== 1) thrownewRefusal(`${where} should be 0 or 1`);return raw === 1; }return raw;}/** Every row of a table a Mac tool draws, each column under its own name. */function readRust(db: DatabaseSync, ws: string, t: RustTable): Candidate[] {const have = columnsOf(db, t.from);if (!have) thrownewRefusal(`life.db has no table ${t.from}`);for (const c of [t.key, ...t.columns]) if (!have.has(c)) thrownewRefusal(`life.db's ${t.from} has no column ${c}`);const times = ["created_at", "updated_at"].filter((c) => have.has(c));const select = [...newSet([t.key, ...times, ...t.columns])];const order = have.has("created_at") ? `created_at, ${quote(t.key)}` : quote(t.key);const sql = `SELECT ${select.map(quote).join(", ")} FROM ${quote(t.from)}${t.workspace ? " WHERE workspace_id = :ws" : ""} ORDER BY ${order}`;const rows = (t.workspace ? db.prepare(sql).all({ ws }) : db.prepare(sql).all()) asRaw[];const json = newSet(t.json);const bool = newSet(t.bool);return rows.map((r) => {const id = String(r[t.key]);const data: Record<string, unknown> = {};for (const c of t.columns) data[c] = decode(`${t.from}.${c} of ${id}`, r[c], json.has(c) ? "json" : bool.has(c) ? "bool" : "plain");return { table: t.table, id, data, ...stamps(r) }; });}function stamps(row: Raw): { created_at?: string; updated_at?: string } {const out: { created_at?: string; updated_at?: string } = {};if (typeof row.created_at === "string") out.created_at = row.created_at;if (typeof row.updated_at === "string") out.updated_at = row.updated_at;return out;}/** The secrets life.db holds a value for: they stay on the Mac (sealing plan §7 step 6). */typeValued = Set<string>;function readMapped(db: DatabaseSync, ws: string, m: Mapping, def: TableJson, valued: Valued): Candidate[] {const have = columnsOf(db, m.from);if (!have) thrownewRefusal(`life.db has no table ${m.from}`);const picks: { column: ColumnJson; source: string }[] = [];for (const c of def.columns) {if (c.computed) continue;// A value never comes (see `valued`), nor life.db's own seal of it: the object's secrets are sealed by its own vault.if (m.table === "secret" && ["sealed", "value_enc", "vmk_version"].includes(c.key)) continue;if (m.objectOnly?.includes(c.key)) {if (have.has(c.key)) thrownewRefusal(`life.db's ${m.from} has a column ${c.key}, which only the object fills`);continue; }// A row's times travel beside it, never as its data.if (c.key === "created_at" || c.key === "updated_at") continue;const source = have.has(c.key) ? c.key : have.has(`${c.key}_id`) ? `${c.key}_id` : null;// A column the table's face works out (a note's `words`) is kept by no// table, and each life.db column fills one object column: the first that// names it (`project` before the face's `project_id`).if (!source || picks.some((p) => p.source === source)) continue; picks.push({ column: c, source }); }const extra = m.table === "secret" ? ["value_enc"] : [];const select = ["id", "created_at", "updated_at", ...extra, ...picks.map((p) => p.source)];const sql = `SELECT ${[...new Set(select)].map(quote).join(", ")} FROM ${quote(m.from)} WHERE workspace_id = :ws${m.where ? ` AND (${m.where})` : ""} ORDER BY created_at, id`;const rows = db.prepare(sql).all({ ws }) asRaw[];return rows.map((r) => {const id = String(r.id);const data: Record<string, unknown> = {};for (const p of picks) data[p.column.key] = convert(`${m.from}.${p.source} of ${id}`, p.column, r[p.source], m.json?.includes(p.source) ?? false);if (m.table === "secret") {// A secret with no value imports with none; one with a value is not brought (readLifeDb leaves it). data.sealed = null;if (typeof r.value_enc === "string") valued.add(id); }return { table: m.table, id, data, ...stamps(r) }; });}function readMade(db: DatabaseSync, ws: string, tables: Map<string, TableJson>, left: string[]): Source["made"] {const defs = db.prepare("SELECT id, definition FROM cotton_table_definitions WHERE workspace_id = :ws AND builtin = 0 ORDER BY id").all({ ws }) as { id: string; definition: string }[];// The package tables a life.db table of their own fills (MAPPINGS, RUST_TABLES).const taken = newSet([...MAPPINGS, ...RUST_TABLES].map((m) => m.table));const legacy = columnsOf(db, "cotton_records");const out: Source["made"] = [];for (const row of defs) {let definition: TableJson;try { definition = JSON.parse(row.definition) asTableJson; } catch {thrownewRefusal(`made table ${row.id}: its definition is not valid JSON`); }if (definition.id === undefined) definition = { ...definition, id: row.id };if (definition.id !== row.id) thrownewRefusal(`made table ${row.id}: its definition says id ${String(definition.id)}`);if (taken.has(row.id)) {// The Mac made this table before the personal package owned it (the// Sessions tool's `session`): the package's definition is the one the// object holds, and the rows come from their own Rust table, not here. left.push(`made table ${row.id}: the personal package defines it, so the Mac's definition is left behind`);continue; }if (!Array.isArray(definition.columns)) thrownewRefusal(`made table ${row.id}: its definition has no columns`);const packaged = tables.get(row.id);const real = `cotton_${row.id}`;const have = columnsOf(db, real);if (!have) {if (legacy && (db.prepare("SELECT COUNT(*) AS n FROM cotton_records WHERE table_id = ? AND deleted_at IS NULL").get(row.id) as { n: number }).n > 0) {thrownewRefusal(`made table ${row.id}: its rows are still in cotton_records; start the Mac's server once so it moves them to ${real}, then import`); } left.push(`made table ${row.id}: life.db has no ${real}, so it comes with no rows`); out.push({ definition: packaged ?? definition, rows: [], packaged: packaged !== undefined });continue; }const columns = definition.columns.filter((c) => !c.computed);for (const c of columns) if (!have.has(c.key)) thrownewRefusal(`life.db's ${real} has no column ${c.key}`);// A packaged table's rows come under the package's columns: a column only the Mac's definition has stays on the Mac, said.const keys = newSet((packaged?.columns ?? columns).map((c) => c.key));const lacking = columns.filter((c) => !keys.has(c.key)).map((c) => c.key);if (lacking.length) left.push(`made table ${row.id}: the personal package defines it without ${lacking.join(", ")}, so ${lacking.length === 1 ? "that column stays" : "those columns stay"} on the Mac`);const kept = columns.filter((c) => keys.has(c.key));const select = [...newSet(["id", "created_at", "updated_at", ...kept.map((c) => c.key)])];const rows = db.prepare(`SELECT ${select.map(quote).join(", ")} FROM ${quote(real)} WHERE deleted_at IS NULL ORDER BY created_at, id`).all() asRaw[]; out.push({ definition: packaged ?? definition, packaged: packaged !== undefined, rows: rows.map((r) => {const id = String(r.id);const data: Record<string, unknown> = {};for (const c of kept) data[c.key] = convert(`${real}.${c.key} of ${id}`, c, r[c.key], false);return { table: row.id, id, data, ...stamps(r) }; }), }); }return out;}/** The id of the personal kit's own tool (kits/personal/kit.json), which the object keeps as the kit ships it. */exportconst KIT_TOOL = "personal";/** * Every tool or board definition of the workspace, by id: its JSON as the * phone draws it, the row's id given to one that names none. A definition that * is not a JSON object, or names another id, or a tool with no name, stops the * run before the first write; a tool the package defines stays behind. */function readDefinitions(db: DatabaseSync, ws: string, kind: "tool" | "board", left: string[]): DefinitionJson[] {constfrom = kind === "tool" ? "cotton_tool_definitions" : "cotton_board_definitions";if (!columnsOf(db, from)) thrownewRefusal(`life.db has no table ${from}`);const rows = db.prepare(`SELECT id, definition FROM ${quote(from)} WHERE workspace_id = :ws ORDER BY id`).all({ ws }) as { id: string; definition: string }[];const out: DefinitionJson[] = [];for (const row of rows) {let parsed: unknown;try { parsed = JSON.parse(row.definition); } catch {thrownewRefusal(`${kind} ${row.id}: its definition is not valid JSON`); }if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) thrownewRefusal(`${kind} ${row.id}: its definition is not a JSON object`);const definition = ("id"in parsed ? parsed : { ...parsed, id: row.id }) asDefinitionJson;if (definition.id !== row.id) thrownewRefusal(`${kind} ${row.id}: its definition says id ${String(definition.id)}`);if (kind === "tool" && (typeof definition.name !== "string" || !definition.name)) thrownewRefusal(`tool ${row.id}: its definition has no name`);if (kind === "tool" && row.id === KIT_TOOL) { left.push(`tool ${row.id}: the personal package defines it, so the Mac's definition is left behind`);continue; } out.push(definition); }return out;}/** * Read life.db at `path`; refuses a file at any schema but 141. A secret * with a value is left on the Mac and said in `left`: the object no longer * seals a plaintext it is handed (k1 sealing is removed, sealing plan §7 * step 6), so a value reaches the object only sealed v2 by a vault device * (Cotton Keys). Never sent with no value either, which would empty the one * the object holds. */exportfunction readLifeDb(path: string, tables: Map<string, TableJson>): Source {if (!existsSync(path)) thrownewRefusal(`no file at ${path}`);let db: DatabaseSync;try { db = newDatabaseSync(path, { readOnly: true }); } catch (error) {thrownewRefusal(`cannot open ${path} as SQLite: ${(error as Error).message}`); }try {const version = Number((db.prepare("PRAGMA user_version").get() as { user_version: number }).user_version);if (version !== SCHEMA_VERSION) thrownewRefusal(`${path} is at schema ${version}; this import reads schema ${SCHEMA_VERSION} only`);const workspaces = db.prepare("SELECT id FROM cotton_workspaces").all() as { id: string }[];if (workspaces.length !== 1) thrownewRefusal(`${path} holds ${workspaces.length} workspaces; a personal database holds one`);const ws = workspaces[0]!.id;const left: string[] = [];const valued: Valued = newSet();const out: Source["tables"] = MAPPINGS.map((m) => ({ table: m.table, rows: readMapped(db, ws, m, tables.get(m.table)!, valued) }));const secrets = out.find((t) => t.table === "secret")!;for (const s of secrets.rows.filter((r) => valued.has(r.id))) left.push(`secret ${s.id} ("${String(s.data.name)}"): its value stays on the Mac; Cotton Keys brings it sealed by a vault device`); secrets.rows = secrets.rows.filter((r) => !valued.has(r.id));for (const t of RUST_TABLES) out.push({ table: t.table, rows: readRust(db, ws, t) });const made = readMade(db, ws, tables, left);return { workspaceId: ws, tables: out, made, tools: readDefinitions(db, ws, "tool", left), boards: readDefinitions(db, ws, "board", left), left }; } finally { db.close(); }}