Cotton code
271 lines · 16.6 KB · TypeScriptRaw
/** * Bring the owner's personal Cotton database (life.db, Rust schema 141) into * the personal Durable Object, through its front door. * *   pnpm -s import-personal --from <life.db> --base <url> --token <file> [--media-root <dir>] [--slug <slug>] *   pnpm -s import-personal --from <life.db> --dry-run [--media-root <dir>] * * --from            the life.db, opened READ-ONLY (a copy is fine; nothing is written to it). * --base            where the Worker answers; a workers.dev / localhost / 127.0.0.1 host gets *                   the /b/<slug> prefix (slug from --slug, default the owner's own slug), a named host *                   (<slug>.cottondb.com) does not. * --token           a file holding the admin token, with --slug p-<database id>: on live /v1/admin takes it alone *                   (src/admin_door.ts). An invented account's owner `ctn_…` token still works on the dev Worker. * --media-root      the Mac's media store (media/ in the real data folder): every file a brought row names *                   goes to the object's R2 under the row's own key (PUT /v1/media/<key>), *                   those it holds already skipped by key (POST /v1/media/missing). Without *                   it the rows come and the summary says how many media they name. * * What moves: memories, projects, project links of every kind, notes, todos and their todo * lists, secrets (never a value: a secret life.db holds a value for stays on the Mac and is * named in the summary, for Cotton Keys to bring sealed by a vault device), sessions with their prompts, tasks and messages, devices, agent accounts; * every table a Mac tool draws (messages, chats, people, photos, videos, meetings, email, * calendar, money, documents… — the package tables `pnpm personal-tables` makes from schema * 141, each with its real columns); the owner's made tables (definitions and live * rows); and the owner's tool and board definitions, merged by id beside the package's * own tool (a tool's picture is a photo record, which comes with the photos). Every row keeps its * own id and times. A row whose link target is not coming is dropped (or, for an optional * link, the link is cleared), and the summary says so. A second run changes nothing and * moves no version. * * Every refusal (wrong schema, a link in a circle) comes before the * first write. The import itself goes in batches of at most 5000 rows; if the object refuses * a batch, the earlier ones have landed and a re-run brings only what differs. * * Tests: `pnpm -s test:scripts` (reader and mapper, on a synthetic life.db), and the * end-to-end run against `wrangler dev`: `pnpm -s exec tsx scripts/__tests__/e2e-import.ts`. */import { existsSync, readFileSync } from "node:fs";import { dirname, join, resolve } from "node:path";import { fileURLToPath } from "node:url";import { batches, planImport, UNBELIEVABLE_MAIL_DATE, type Plan } from "./import-personal/plan.ts";import { Refusal } from "./import-personal/refusal.ts";import { kitTables, MAPPINGS, readLifeDb, RUST_TABLES } from "./import-personal/source.ts";import { contentType, keyPath, namedKeys, planMedia, UPLOAD_MAX_BYTES } from "./import-personal/media.ts";import { personalSlug } from "./dev-server";const here = dirname(fileURLToPath(import.meta.url));const KITS = join(resolve(here, "../../.."), "crates/cotton-core/kits");const argv = process.argv.slice(2);const flag = (name: string): string | undefined => {  const i = argv.indexOf(`--${name}`);  return i >= 0 ? argv[i + 1] : undefined;};function need(name: string): string {  const v = flag(name);  if (!v || v.startsWith("--")) throw new Refusal(`usage: pnpm -s import-personal --from <life.db> --base <url> --token <file> [--media-root <dir>] [--slug <slug>] (missing --${name})`);  return v;}interface Answer {  status: number;  body: Record<string, unknown>;}async function call(base: string, token: string, method: string, path: string, body?: unknown): Promise<Answer> {  let r: Response;  try {    r = await fetch(`${base}${path}`, {      method,      headers: { authorization: `Bearer ${token}`, ...(body !== undefined ? { "content-type": "application/json" } : {}) },      body: body !== undefined ? JSON.stringify(body) : undefined,    });  } catch (error) {    throw new Refusal(`${method} ${base}${path}: ${(error as Error).message}`);  }  const text = await r.text();  let parsed: Record<string, unknown> = {};  try {    parsed = text ? (JSON.parse(text) as Record<string, unknown>) : {};  } catch {    throw new Refusal(`${method} ${path} → ${r.status}, not JSON: ${text.slice(0, 200)}`);  }  return { status: r.status, body: parsed };}async function ok(base: string, token: string, method: string, path: string, body?: unknown): Promise<Record<string, unknown>> {  const a = await call(base, token, method, path, body);  if (a.status !== 200) throw new Refusal(`${method} ${path} → ${a.status} ${String(a.body.code ?? "")}: ${String(a.body.message ?? JSON.stringify(a.body).slice(0, 300))}`);  return a.body;}function printPlan(plan: Plan): void {  for (const line of plan.left) console.log(`  ${line}`);  for (const r of plan.report) {    for (const [reason, n] of r.dropped) console.log(`  ${r.table}: dropped ${n} — ${reason}`);    for (const [column, n] of r.cleared) console.log(`  ${r.table}: cleared ${n} ${column} link${n === 1 ? "" : "s"} — the row it named is not coming`);    for (const [column, n] of r.undated) console.log(`  ${r.table}: cleared ${n} ${column}${n === 1 ? "" : "s"} — ${UNBELIEVABLE_MAIL_DATE}`);  }}/** `--dry-run`: what would go, by table, and the media the rows name; nothing is sent. */function dryRun(plan: Plan, mediaRoot: string | null): void {  console.log(`life.db ${plan.workspaceId} (a dry run: nothing is sent)`);  printPlan(plan);  const pad = (v: string | number, n: number): string => String(v).padStart(n);  console.log(`\n  ${"table".padEnd(24)}${pad("seen", 9)}${pad("to send", 9)}`);  for (const r of plan.report) if (r.seen) console.log(`  ${r.table.padEnd(24)}${pad(r.seen, 9)}${pad(r.sent, 9)}`);  console.log(`  ${"rows".padEnd(24)}${pad(plan.report.reduce((a, r) => a + r.seen, 0), 9)}${pad(plan.rows.length, 9)} in ${batches(plan.rows).length} batches`);  console.log(`  tools: ${plan.tools.map((t) => t.id).join(", ") || "none"}; boards: ${plan.boards.map((b) => b.id).join(", ") || "none"}`);  const named = namedKeys(plan.rows, plan.workspaceId, mediaRoot);  if (!mediaRoot) {    console.log(`  media: the rows name ${named.size}; pass --media-root to see which the store holds`);    return;  }  const media = planMedia(named, plan.workspaceId, mediaRoot, UPLOAD_MAX_BYTES);  const mb = media.found.reduce((a, m) => a + m.bytes, 0) / 1048576;  console.log(`  media: the rows name ${named.size}; the store holds ${media.found.length} (${mb.toFixed(1)} MB), lacks ${media.lost.length}, ${media.tooBig.length} past the upload limit, ${media.foreign.length} of another database`);}async function main(): Promise<void> {  const from = need("from");  if (argv.includes("--dry-run")) {    const mediaRoot = flag("media-root") ? resolve(flag("media-root")!) : null;    const tables = kitTables(KITS);    dryRun(planImport(readLifeDb(from, tables), tables), mediaRoot);    return;  }  const baseUrl = need("base").replace(/\/$/, "");  const tokenFile = need("token");  const mediaRoot = flag("media-root") ? resolve(flag("media-root")!) : null;  if (mediaRoot && !existsSync(mediaRoot)) throw new Refusal(`no media store at ${mediaRoot}`);  const slug = flag("slug") ?? personalSlug();  const token = readFileSync(tokenFile, "utf8").trim();  // The admin token (token scopes, 24 Nov 2026: with the switch on, /v1/admin takes the admin token alone) speaks  // to the object by its /b/<slug> address, on any host; an owner ctn_ token names its database itself.  const admin = !token.startsWith("ctn_");  if (admin && !flag("slug")) throw new Refusal("with the admin token, name the object: --slug p-<database id>");  const prefix = admin || /workers\.dev$|localhost|127\.0\.0\.1/.test(new URL(baseUrl).hostname) ? `/b/${slug}` : "";  const base = `${baseUrl}${prefix}`;  const tokenDb = admin ? (/^p-([0-9a-f-]{36})$/.exec(slug)?.[1] ?? null) : /^ctn_([0-9a-f-]{36})_/.exec(token)?.[1];  if (!tokenDb) throw new Refusal(admin ? `--slug ${slug} names no personal database: p-<database id>` : `${tokenFile} does not hold a ctn_ token`);  // Everything that can refuse does so here, before the first write.  const tables = kitTables(KITS);  const plan = planImport(readLifeDb(from, tables), tables);  if (tokenDb !== plan.workspaceId) throw new Refusal(`the token is for database ${tokenDb}; ${from} is database ${plan.workspaceId}`);  // AVATAR SEAL 3 (27 Nov 2026): an assistant's ctn_ token neither asks after nor writes a person's sealed-kind files  // (photos, books, music, films …): the media go with the admin token.  if (mediaRoot && !admin) throw new Refusal("--media-root sends a person's files, which an assistant's ctn_ token may not write: run it with the admin token (--slug p-<database id>)");  console.log(`life.db ${plan.workspaceId} → ${base}`);  printPlan(plan);  const defs = await call(base, token, "GET", "/v1/definitions");  if (defs.status === 503) throw new Refusal(`the object at ${base} has no definitions; onboard it first (pnpm -s onboard ${slug} --base ${baseUrl} --owner +91… --database-id ${plan.workspaceId})`);  if (defs.status !== 200) throw new Refusal(`GET /v1/definitions → ${defs.status} ${JSON.stringify(defs.body).slice(0, 300)}`);  const business = defs.body.business as { kind?: string; database_id?: string | null };  if (business.kind !== "personal") throw new Refusal(`the object at ${base} is not a personal database (kind ${String(business.kind)})`);  if (business.database_id && business.database_id !== plan.workspaceId) throw new Refusal(`the object at ${base} is database ${business.database_id}; ${from} is ${plan.workspaceId}`);  const held = new Set((defs.body.tables as { id: string }[]).map((t) => t.id));  const lacking = [...MAPPINGS, ...RUST_TABLES].map((m) => m.table).filter((t) => !held.has(t));  if (lacking.length) throw new Refusal(`the object lacks the personal tables ${lacking.join(", ")}; onboard it again`);  let metaMoved = false;  if (!business.database_id) {    metaMoved = true;    await ok(base, token, "PUT", "/v1/admin/business", { database_id: plan.workspaceId });    console.log(`  database_id set to ${plan.workspaceId}`);  }  if (plan.definitions.length) {    const d = await ok(base, token, "POST", "/v1/admin/definitions/tables", { tables: plan.definitions });    if (Number(d.changed) > 0) metaMoved = true;    console.log(`  made tables: ${plan.definitions.map((t) => t.id).join(", ")} (${String(d.changed)} definition${d.changed === 1 ? "" : "s"} changed)`);  }  // The owner's tools and boards, merged by id beside the package's own tool.  for (const [kind, docs] of [["tools", plan.tools], ["boards", plan.boards]] as const) {    if (!docs.length) continue;    const d = await ok(base, token, "POST", `/v1/admin/definitions/${kind}`, { [kind]: docs });    if (Number(d.changed) > 0) metaMoved = true;    console.log(`  ${kind}: ${docs.length} (${String(d.changed)} changed; the object holds ${String(d[kind])})`);  }  const calls = batches(plan.rows);  // What each brought row did, by table, as the object counts it: written (made or patched), unchanged, or deleted there since it came.  const counts = new Map<string, { written: number; unchanged: number; deleted: number }>();  let changed = 0;  let sent = 0;  const started = Date.now();  for (const [i, rows] of calls.entries()) {    const a = await call(base, token, "POST", "/v1/admin/import", { rows });    if (a.status !== 200) {      throw new Refusal(`import batch ${i + 1} of ${calls.length} refused → ${a.status} ${String(a.body.code ?? "")}: ${String(a.body.message ?? "")}${i ? `; batches 1–${i} landed, and a re-run brings only what differs` : "; nothing landed"}`);    }    changed += Number(a.body.changed);    sent += rows.length;    for (const [table, n] of Object.entries(a.body.puts as Record<string, { written: number; unchanged: number; deleted: number }>)) {      const c = counts.get(table) ?? { written: 0, unchanged: 0, deleted: 0 };      counts.set(table, { written: c.written + n.written, unchanged: c.unchanged + n.unchanged, deleted: c.deleted + n.deleted });    }    if ((i + 1) % 10 === 0 || i + 1 === calls.length) console.log(`  batch ${i + 1} of ${calls.length}: ${sent} rows, ${Math.round(sent / Math.max(0.001, (Date.now() - started) / 1000))} rows/s`);  }  const after = await ok(base, token, "GET", "/v1/admin/export?limit=1");  const pad = (v: string | number, n: number): string => String(v).padStart(n);  console.log(`\n  ${"table".padEnd(18)}${pad("seen", 7)}${pad("written", 9)}${pad("unchanged", 11)}${pad("dropped", 9)}`);  let written = 0;  for (const r of plan.report) {    const c = counts.get(r.table) ?? { written: 0, unchanged: 0, deleted: 0 };    written += c.written;    const dropped = [...r.dropped.values()].reduce((a, b) => a + b, 0);    console.log(`  ${r.table.padEnd(18)}${pad(r.seen, 7)}${pad(c.written, 9)}${pad(c.unchanged, 11)}${pad(dropped, 9)}${c.deleted ? `   (${c.deleted} deleted in the object; an import does not bring them back)` : ""}`);  }  if (changed > written) console.log(`  the object's rules changed ${changed - written} more row${changed - written === 1 ? "" : "s"}`);  console.log(`  version ${String(after.version)}${changed || metaMoved ? "" : " (unchanged: nothing differed)"}`);  const named = namedKeys(plan.rows, plan.workspaceId, mediaRoot);  if (!mediaRoot) {    if (named.size) console.log(`\n  media: the rows name ${named.size} file${named.size === 1 ? "" : "s"}; pass --media-root <the Mac's media store> to bring them`);    return;  }  await bringMedia(base, token, mediaRoot, planMedia(named, plan.workspaceId, mediaRoot, UPLOAD_MAX_BYTES), named.size);}/** Ask which keys the object lacks, 500 at a time, and send those, four at once. */async function bringMedia(base: string, token: string, root: string, media: ReturnType<typeof planMedia>, named: number): Promise<void> {  const missing: { key: string; bytes: number }[] = [];  for (let i = 0; i < media.found.length; i += 500) {    const chunk = media.found.slice(i, i + 500);    const answer = await ok(base, token, "POST", "/v1/media/missing", { keys: chunk.map((m) => m.key) });    const lacking = new Set(answer.missing as string[]);    missing.push(...chunk.filter((m) => lacking.has(m.key)));  }  const started = Date.now();  let sent = 0;  let bytes = 0;  const queue = [...missing];  const worker = async (): Promise<void> => {    for (let m = queue.shift(); m; m = queue.shift()) {      const body = readFileSync(join(root, m.key));      let r: Response;      try {        r = await fetch(`${base}/v1/media/${keyPath(m.key)}`, { method: "PUT", headers: { authorization: `Bearer ${token}`, "content-type": contentType(root, m.key) }, body });      } catch (error) {        throw new Refusal(`PUT /v1/media/${m.key}: ${(error as Error).message}; ${sent} uploaded before it, and a re-run sends only what is still missing`);      }      if (r.status !== 200 && r.status !== 201) throw new Refusal(`PUT /v1/media/${m.key} → ${r.status} ${(await r.text()).slice(0, 200)}; ${sent} uploaded before it, and a re-run sends only what is still missing`);      await r.arrayBuffer();      sent += 1;      bytes += m.bytes;      if (sent % 500 === 0) console.log(`  media: ${sent} of ${missing.length} sent, ${(bytes / 1048576).toFixed(1)} MB, ${(bytes / 1048576 / Math.max(0.001, (Date.now() - started) / 1000)).toFixed(1)} MB/s`);    }  };  await Promise.all([worker(), worker(), worker(), worker()]);  const mb = (n: number): string => `${(n / 1048576).toFixed(1)} MB`;  console.log(`\n  media: the rows name ${named}; ${media.found.length - missing.length} held already, ${sent} sent (${mb(bytes)})`);  if (media.lost.length) console.log(`  media: ${media.lost.length} named but not in ${root}, e.g. ${media.lost.slice(0, 3).map((l) => `${l.key} (${l.row})`).join(", ")}`);  if (media.foreign.length) console.log(`  media: ${media.foreign.length} named under another database's key, left: e.g. ${media.foreign.slice(0, 3).map((l) => `${l.key} (${l.row})`).join(", ")}`);  if (media.tooBig.length) console.log(`  media: ${media.tooBig.length} over ${mb(UPLOAD_MAX_BYTES)}, the most one upload through the Worker takes, left on the Mac: ${media.tooBig.map((t) => `${t.key} (${mb(t.bytes)})`).join(", ")}`);}try {  await main();} catch (error) {  if (error instanceof Refusal) {    console.error(`import-personal: ${error.message}`);    process.exit(1);  }  throw error;}