/** * 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:`), 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"; export const SCHEMA_VERSION = 141; export interface ColumnJson { key: string; type?: string; link_to?: string; required?: boolean; computed?: unknown; } export interface TableJson { id: string; columns: ColumnJson[]; [key: string]: unknown; } /** One row on its way to the object. */ export interface Candidate { table: string; id: string; data: Record; 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. */ export type DefinitionJson = { id: string } & Record; export interface Source { 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[]; } interface Mapping { 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). */ export interface RustTable { table: string; from: string; key: string; workspace: boolean; bin: boolean; columns: string[]; json: string[]; bool: string[]; } export const RUST_TABLES = JSON.parse(readFileSync(join(dirname(fileURLToPath(import.meta.url)), "rust-tables.json"), "utf8")) as RustTable[]; /** life.db table → personal package table, for the tables the package shapes by hand. */ export const 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. */ export function kitTables(kitsDir: string): Map { const dir = join(kitsDir, "personal", "tables"); if (!existsSync(dir)) throw new Refusal(`no personal kit at ${dir}`); const out = new Map(); for (const file of readdirSync(dir).filter((f) => f.endsWith(".json"))) { const t = JSON.parse(readFileSync(join(dir, file), "utf8")) as TableJson; out.set(t.id, t); } for (const m of [...MAPPINGS, ...RUST_TABLES]) if (!out.has(m.table)) throw new Refusal(`the personal kit has no table ${m.table}; run pnpm -s personal-tables`); return out; } type Raw = Record; const quote = (name: string): string => `"${name.replace(/"/g, '""')}"`; function columnsOf(db: DatabaseSync, table: string): Set | null { const exists = db.prepare("SELECT 1 AS x FROM sqlite_master WHERE type = 'table' AND name = ?").get(table); if (!exists) return null; return new Set((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) return null; if (raw instanceof Uint8Array) throw new Refusal(`${where} holds bytes; the object keeps no bytes in a column`); if (typeof raw === "bigint") raw = Number(raw); if (json) { if (typeof raw !== "string") throw new Refusal(`${where} should hold JSON text`); try { return JSON.parse(raw) as unknown; } catch { throw new Refusal(`${where} is not valid JSON`); } } if (column.type === "bool") { if (typeof raw !== "number") throw new Refusal(`${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) return null; if (raw instanceof Uint8Array) throw new Refusal(`${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)) throw new Refusal(`${where} holds ${raw}, past what a JSON number keeps exactly`); raw = Number(raw); } if (codec === "json") { if (typeof raw !== "string") throw new Refusal(`${where} should hold JSON text`); try { return JSON.parse(raw) as unknown; } catch { throw new Refusal(`${where} is not valid JSON`); } } if (codec === "bool") { if (raw !== 0 && raw !== 1) throw new Refusal(`${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) throw new Refusal(`life.db has no table ${t.from}`); for (const c of [t.key, ...t.columns]) if (!have.has(c)) throw new Refusal(`life.db's ${t.from} has no column ${c}`); const times = ["created_at", "updated_at"].filter((c) => have.has(c)); const select = [...new Set([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()) as Raw[]; const json = new Set(t.json); const bool = new Set(t.bool); return rows.map((r) => { const id = String(r[t.key]); const data: Record = {}; 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). */ type Valued = Set; function readMapped(db: DatabaseSync, ws: string, m: Mapping, def: TableJson, valued: Valued): Candidate[] { const have = columnsOf(db, m.from); if (!have) throw new Refusal(`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)) throw new Refusal(`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 }) as Raw[]; return rows.map((r) => { const id = String(r.id); const data: Record = {}; 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, 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 = new Set([...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) as TableJson; } catch { throw new Refusal(`made table ${row.id}: its definition is not valid JSON`); } if (definition.id === undefined) definition = { ...definition, id: row.id }; if (definition.id !== row.id) throw new Refusal(`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)) throw new Refusal(`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) { throw new Refusal(`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)) throw new Refusal(`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 = new Set((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 = [...new Set(["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() as Raw[]; out.push({ definition: packaged ?? definition, packaged: packaged !== undefined, rows: rows.map((r) => { const id = String(r.id); const data: Record = {}; 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. */ export const 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[] { const from = kind === "tool" ? "cotton_tool_definitions" : "cotton_board_definitions"; if (!columnsOf(db, from)) throw new Refusal(`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 { throw new Refusal(`${kind} ${row.id}: its definition is not valid JSON`); } if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) throw new Refusal(`${kind} ${row.id}: its definition is not a JSON object`); const definition = ("id" in parsed ? parsed : { ...parsed, id: row.id }) as DefinitionJson; if (definition.id !== row.id) throw new Refusal(`${kind} ${row.id}: its definition says id ${String(definition.id)}`); if (kind === "tool" && (typeof definition.name !== "string" || !definition.name)) throw new Refusal(`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. */ export function readLifeDb(path: string, tables: Map): Source { if (!existsSync(path)) throw new Refusal(`no file at ${path}`); let db: DatabaseSync; try { db = new DatabaseSync(path, { readOnly: true }); } catch (error) { throw new Refusal(`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) throw new Refusal(`${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) throw new Refusal(`${path} holds ${workspaces.length} workspaces; a personal database holds one`); const ws = workspaces[0]!.id; const left: string[] = []; const valued: Valued = new Set(); 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(); } }