Cotton code
355 lines · 16.1 KB · TypeScriptRaw
/** * The personal package's tables for the Mac's Rust tool tables, made from * schema 141 — what the owner's life.db holds: * *   pnpm -s personal-tables          write them *   pnpm -s personal-tables --check  fail when the checked-in files differ * * For every table a shipped tool draws (the 0.29.66 bases' `tables`), less * the ones the package already shapes by hand (memory, note, todo, session…), * it writes `crates/cotton-core/kits/personal/tables/<id>.json` * and lists the id in the kit's kit.json; and it writes the import's map * (`scripts/import-personal/rust-tables.json`): which life.db table fills * which object table, its key column, and which columns hold JSON or 0/1. * * A table's id is its tool's (`cotton_msg_messages` → `message`), or for a * tool's other tables the name in SECONDARY. Every stored column comes, keyed * by its own name (`thread_id`), so a row arrives with its real columns. A * column takes the base's type, name and choices where the base draws it, else * one from its Rust codec; a foreign key, or a base link to a table that comes, * is a link — required when the key is NOT NULL. Every column is read only: * the Mac's engines wrote these rows, and an import or the Mac's importers * write them again; nothing composes them on the object. * * Sources, all in the repository: crates/cotton-store/tests/fixtures/ * schema-snapshot.json (schema 141's CREATE TABLEs), crates/cotton-tools/ * tests/fixtures/shipped-bases/0.29.66-141/*.json, and the codecs in * crates/cotton-store/src/schema/table_specs.rs. */import { existsSync, readdirSync, readFileSync, writeFileSync } from "node:fs";import { isGoneTable } from "../src/retired.ts";import { dirname, join, resolve } from "node:path";import { DatabaseSync } from "node:sqlite";import { fileURLToPath } from "node:url";const here = dirname(fileURLToPath(import.meta.url));const REPO = resolve(here, "../../..");const KIT = join(REPO, "crates/cotton-core/kits/personal");const SNAPSHOT = join(REPO, "crates/cotton-store/tests/fixtures/schema-snapshot.json");const BASES = join(REPO, "crates/cotton-tools/tests/fixtures/shipped-bases/0.29.66-141");const SPECS = join(REPO, "crates/cotton-store/src/schema/table_specs.rs");export const RUST_TABLES = join(here, "import-personal/rust-tables.json");/** The phone's map of the same tables (`cotton_core::toolkits::PERSONAL_STORAGE`): which object table fills which of its own. */export const STORAGE = join(KIT, "storage.json");/** * Hand-shaped tables the phone keeps none of: a device is a Mac's or a phone's registration with the relay, which the * phone no longer dials (its own row is its copy's). * * A secret is the phone's since Cotton Keys took Passwords (owner, 11 Nov 2026): a device seals its value v2 under * the vault master key into value_enc, the rule a passkey's private key is sealed by, and the object only carries * it. A row the Worker sealed keeps its k1 text in `sealed`, which no phone opens. */const OBJECT_ONLY = new Set(["device"]);/** * Columns of a hand-shaped table the phone keeps to itself and never hands the object: a secret's `hint` is the last * four characters of its value, which the Worker must never read. */const PHONE_ONLY: Record<string, Set<string>> = { secret: new Set(["hint"]) };/** Rust tables the package already shapes by hand, and the table each fills (import-personal/source.ts MAPPINGS). */export const HAND_SHAPED: Record<string, string> = {  cotton_memory_projects: "project",  cotton_memories: "memory",  cotton_notes: "note",  cotton_todos: "todo",  cotton_secrets: "secret",  cotton_devices: "device",  cotton_agent_accounts: "agent_account",  cotton_project_links: "project_link",  cotton_groups: "record_group",  cotton_group_members: "group_member",  cotton_sessions: "session",  cotton_prompts: "prompt",  cotton_session_tasks: "session_task",  cotton_session_messages: "session_message",  cotton_vault_keys: "vault_key",};/** A tool's tables beyond the one named for it. */const SECONDARY: Record<string, string> = {  cotton_account_usage_samples: "account_usage_sample",  cotton_dev_jobs: "dev_job",  cotton_document_pages: "document_page",  cotton_email_participants: "email_participant",  cotton_blocked_senders: "blocked_sender",  cotton_event_attendees: "event_attendee",  cotton_meeting_utterances: "meeting_utterance",  cotton_msg_contact_handles: "message_contact_handle",  cotton_msg_contacts: "message_contact",  cotton_msg_owner_settings: "message_settings",  cotton_msg_reactions: "message_reaction",  cotton_msg_receipts: "message_receipt",  cotton_msg_thread_filings: "thread_filing",  cotton_msg_thread_marks: "thread_mark",  cotton_news_seen: "news_seen",  cotton_note_attachments: "note_attachment",  cotton_repo_bundles: "repo_bundle",  cotton_repo_clones: "repo_clone",  cotton_repo_commits: "repo_commit",  cotton_repo_jobs: "repo_job",  cotton_repo_merge_queue: "repo_merge_queue",  cotton_repo_runners: "repo_runner",  cotton_screenplay_draft_scenes: "screenplay_draft_scene",  cotton_thought_attachments: "thought_attachment",};/** Columns that are the row's own frame, never its data: its key and times travel beside it, the rest stays on the Mac. */const FRAME = new Set(["workspace_id", "created_at", "updated_at", "_hlc", "_born"]);type Codec = "Text" | "Int" | "Real" | "Bool" | "Json" | "MoneyMinor" | "DecimalText" | "Timestamp";/** One life.db table the import reads into an object table. */export interface RustTable {  table: string;  from: string;  /** The key column: `id`, or `workspace_id` for a one-row settings table. */  key: string;  /** Whether rows carry `workspace_id` (a few child tables do not). */  workspace: boolean;  /** Whether a row may sit in the bin (`trashed_at`); a binned row stays on the Mac. */  bin: boolean;  columns: string[];  json: string[];  bool: string[];}interface BaseColumn {  key: string;  name?: string;  type?: string;  link_to?: string;  choices?: unknown;  labels?: unknown;  format?: string;  multiple?: boolean;}interface Base {  id: string;  name?: string;  plural?: string;  date?: string | null;  title?: string | null;  columns: BaseColumn[];  tables?: { name: string }[];}function codecs(): Map<string, Map<string, Codec>> {  const src = readFileSync(SPECS, "utf8");  const out = new Map<string, Map<string, Codec>>();  for (const chunk of src.split("TableSpec {").slice(1)) {    const name = /name:\s*"(\w+)"/.exec(chunk)?.[1];    if (!name) continue;    const body = chunk.split("natural_key")[0]!;    out.set(name, new Map([...body.matchAll(/\(\s*"(\w+)",\s*Codec::(\w+)\s*\)/g)].map((m) => [m[1]!, m[2] as Codec])));  }  return out;}const words = (id: string): string => id.replace(/_/g, " ");const capital = (s: string): string => s.charAt(0).toUpperCase() + s.slice(1);/** One object table as the phone stores it: the Rust table it fills, its key, and each object column's own column there. */export interface Stored {  table: string;  from: string;  key: string;  workspace: boolean;  columns: Record<string, string>;}export interface Generated {  tables: Map<string, Record<string, unknown>>;  map: RustTable[];  storage: Stored[];  /** Tables a tool names that schema 141 does not hold. */  absent: string[];}export function generate(): Generated {  const snapshot = JSON.parse(readFileSync(SNAPSHOT, "utf8")) as { kind: string; name: string; sql: string }[];  const db = new DatabaseSync(":memory:");  for (const o of snapshot) if (o.kind === "table" && o.name.startsWith("cotton_")) db.exec(o.sql);  const specs = codecs();  const bases = readdirSync(BASES)    .filter((f) => f.endsWith(".json"))    .sort()    .map((f) => JSON.parse(readFileSync(join(BASES, f), "utf8")) as Base);  // Which object table each Rust table becomes, and the base that draws it.  const idOf = new Map<string, string>(Object.entries(HAND_SHAPED));  const baseOf = new Map<string, Base>();  const absent: string[] = [];  const wanted: string[] = [];  for (const b of bases) {    for (const t of b.tables ?? []) {      if (!snapshot.some((o) => o.kind === "table" && o.name === t.name)) {        absent.push(t.name);        continue;      }      if (HAND_SHAPED[t.name]) continue;      const id = SECONDARY[t.name] ?? b.id;      // A table an object holds as retired (src/retired.ts) is never made again.      if (isGoneTable(id)) continue;      if ([...idOf.values()].includes(id)) throw new Error(`${t.name} and another table would both be ${id}`);      idOf.set(t.name, id);      baseOf.set(t.name, b);      wanted.push(t.name);    }  }  const toolTable = new Map(bases.map((b) => [b.id, [...idOf].find(([rust]) => baseOf.get(rust)?.id === b.id && !SECONDARY[rust])?.[1] ?? b.id]));  const held = new Set(idOf.values());  const tables = new Map<string, Record<string, unknown>>();  const map: RustTable[] = [];  for (const rust of wanted.sort()) {    const id = idOf.get(rust)!;    const base = baseOf.get(rust)!;    const primary = !SECONDARY[rust];    const info = db.prepare(`PRAGMA table_info("${rust}")`).all() as { name: string; type: string; notnull: number; dflt_value: unknown; pk: number }[];    const fks = new Map((db.prepare(`PRAGMA foreign_key_list("${rust}")`).all() as { table: string; from: string }[]).map((f) => [f.from, f.table]));    const spec = specs.get(rust);    if (!spec) throw new Error(`table_specs.rs has no codecs for ${rust}`);    const pk = info.find((c) => c.pk === 1)?.name;    if (!pk) throw new Error(`${rust} has no single-column key`);    const names = new Set(info.map((c) => c.name));    const drawn = new Map((primary ? base.columns : []).map((c) => [c.key, c]));    const columns: Record<string, unknown>[] = [];    const entry: RustTable = { table: id, from: rust, key: pk, workspace: names.has("workspace_id"), bin: names.has("trashed_at"), columns: [], json: [], bool: [] };    for (const c of info) {      if (FRAME.has(c.name) || c.name === pk) continue;      const codec = spec.get(c.name);      if (!codec) throw new Error(`table_specs.rs has no codec for ${rust}.${c.name}`);      entry.columns.push(c.name);      if (codec === "Json") entry.json.push(c.name);      if (codec === "Bool") entry.bool.push(c.name);      const b = drawn.get(c.name);      const fk = fks.get(c.name);      const linkTo = fk && idOf.has(fk) ? idOf.get(fk)! : b?.type === "link" && b.link_to && held.has(toolTable.get(b.link_to) ?? "") ? toolTable.get(b.link_to)! : null;      const out: Record<string, unknown> = { key: c.name };      if (b?.name) out.name = b.name;      if (linkTo) {        out.type = "link";        out.link_to = linkTo;        if (fk && c.notnull === 1) out.required = true;      } else if (codec === "Bool") out.type = "bool";      else if (b?.type && b.type !== "link" && b.type !== "bool" && !(codec === "Json" && b.type !== "file" && b.type !== "photo" && b.multiple !== true)) {        out.type = b.type;        for (const k of ["choices", "labels", "format", "multiple"] as const) if (b[k] !== undefined) out[k] = b[k];      } else if (codec === "Int" || codec === "Real") out.type = "number";      else if (codec === "MoneyMinor") out.type = "amount";      else if (codec === "Timestamp") Object.assign(out, { type: "date", format: "calendar-datetime" });      else out.type = codec === "Json" ? "longtext" : "text";      out.readonly = true;      columns.push(out);    }    const keys = new Set(columns.map((c) => c.key));    const def: Record<string, unknown> = {      format_version: 1,      id,      name: primary && base.name ? base.name : capital(words(id)),      plural: primary && base.plural ? base.plural : `${capital(words(id))}s`,      builtin: true,      visibility: "owner",    };    const date = primary ? base.date : null;    if (date && (keys.has(date) || date === "created_at" || date === "updated_at")) def.date = date;    if (primary && base.title && keys.has(base.title)) def.title = base.title;    def.columns = columns;    def.instructions = `The Mac's ${rust}, brought with its own ids, times and columns.`;    tables.set(id, def);    map.push(entry);  }  // The phone's map: the hand-shaped tables, each column read as the import reads it  // (`x`, or `x_id` when only that exists), and every Rust table under its own names.  const storage: Stored[] = [];  for (const [rust, id] of Object.entries(HAND_SHAPED)) {    if (OBJECT_ONLY.has(id)) continue;    const def = JSON.parse(readFileSync(join(KIT, "tables", `${id}.json`), "utf8")) as { columns: { key: string; computed?: unknown }[] };    const info = db.prepare(`PRAGMA table_info("${rust}")`).all() as { name: string; pk: number }[];    const names = new Set(info.map((c) => c.name));    const columns: Record<string, string> = {};    const filled = new Set<string>();    for (const c of def.columns) {      if (c.computed || FRAME.has(c.key) || PHONE_ONLY[id]?.has(c.key)) continue;      const source = names.has(c.key) ? c.key : names.has(`${c.key}_id`) ? `${c.key}_id` : null;      // A column the face works out (a note's `words`) has no home in the      // Mac's table, and each of its columns is filled by one object column:      // the first that names it (`project` before the face's `project_id`).      if (!source || filled.has(source)) continue;      filled.add(source);      columns[c.key] = source;    }    storage.push({ table: id, from: rust, key: "id", workspace: names.has("workspace_id"), columns });  }  for (const t of map) storage.push({ table: t.table, from: t.from, key: t.key, workspace: t.workspace, columns: Object.fromEntries(t.columns.map((c) => [c, c])) });  storage.sort((a, b) => a.table.localeCompare(b.table));  db.close();  return { tables, map, storage, absent };}const text = (v: unknown): string => `${JSON.stringify(v, null, 2)}\n`;type Def = Record<string, unknown> & { columns?: { key: string }[] };/** * A table as the package keeps it: the checked-in file, and what schema 141 * makes that the file lacks. A table's face — its card, slip, tile, page, * engine, commands and every column or column word the face adds — is the * file's own (laid from the owner's life.db definitions, 26 Oct 2026), so a * run never takes it away; its id, format and visibility are schema 141's. */export function kept(made: Def, held: Def | null): Def {  if (!held) return made;  const out: Def = { ...held };  for (const [k, v] of Object.entries(made)) if (!(k in out) || k === "format_version" || k === "id" || k === "visibility") out[k] = v;  const columns = held.columns ?? [];  const keys = new Set(columns.map((c) => c.key));  out.columns = [...columns, ...(made.columns ?? []).filter((c) => !keys.has(c.key))];  return out;}function heldTable(id: string): Def | null {  const path = join(KIT, "tables", `${id}.json`);  return existsSync(path) ? (JSON.parse(readFileSync(path, "utf8")) as Def) : null;}/** What the files would hold, by path. */export function files(g: Generated = generate()): Map<string, string> {  const out = new Map<string, string>();  for (const [id, def] of g.tables) out.set(join(KIT, "tables", `${id}.json`), text(kept(def as Def, heldTable(id))));  const kit = JSON.parse(readFileSync(join(KIT, "kit.json"), "utf8")) as { tables: string[] };  const listed = kit.tables.filter((t) => !g.tables.has(t));  out.set(join(KIT, "kit.json"), text({ ...kit, tables: [...listed, ...[...g.tables.keys()].sort()] }));  out.set(RUST_TABLES, text(g.map));  out.set(STORAGE, text(g.storage));  return out;}if (process.argv[1] === fileURLToPath(import.meta.url)) {  const g = generate();  const want = files(g);  if (process.argv.includes("--check")) {    const stale = [...want].filter(([path, body]) => !existsSync(path) || readFileSync(path, "utf8") !== body).map(([path]) => path);    if (stale.length) {      console.error(`personal-tables: ${stale.length} file${stale.length === 1 ? "" : "s"} differ from what schema 141 makes; run pnpm -s personal-tables\n  ${stale.join("\n  ")}`);      process.exit(1);    }    console.log(`personal-tables: ${g.tables.size} tables match`);  } else {    for (const [path, body] of want) writeFileSync(path, body);    console.log(`personal-tables: ${g.tables.size} tables written; not in schema 141: ${g.absent.join(", ") || "none"}`);  }}