Cotton code
495 lines · 28.1 KB · TypeScriptRaw
/** * THE INVENTED LIFE: every row, chat and file the seed brings, worked out * from a seed, a scale, a day and the database's id alone, so two runs with * the same four make the same database byte for byte. * * A row carries only what a person or an importer writes: a column a person * edits, or a column the importer's source holds (a storage column of the * Rust store, `tables[].columns` in the kit's JSON — the Mail import's * subject, the Photos import's size). Nothing an engine works out is written: * an event's people come from its attendees by the calendar engine, a * thread's name and preview from the WhatsApp import. * * Chats are not rows here: they are WhatsApp import batches * (`POST /v1/import/messages`), which make the thread, its contacts, members, * messages and reactions as the Mac's importer does, matching each number to * the person who holds it. * * Times are the owner's (India, UTC+05:30) written as UTC instants, as the * store keeps them; an all-day event runs from local midnight (18:30Z the * day before) to the last millisecond of its last day. */import type { EnvelopeMessage, ImportBatch } from "../../src/import/envelope.ts";import { cover, portrait, scene, SCENES, type Picture } from "./pictures.ts";import { idOf, Rng, sha256 } from "./rng.ts";import * as W from "./words.ts";export type Scale = "small" | "medium";export const SCALES: readonly Scale[] = ["small", "medium"];export interface LifeOptions {  /** The fixed seed: the same seed, scale, day and database make the same life. */  seed: string;  scale: Scale;  /** The day the life is lived up to, YYYY-MM-DD: past rows fall before it, coming ones after. */  today: string;  /** The database the media keys and the chats' batches name. */  databaseId: string;}/** One row of `POST /v1/admin/import`, brought with its own id (verb `put`). */export interface SeedRow {  table: string;  id: string;  data: Record<string, unknown>;  created_at?: string;  updated_at?: string;}export interface SeedMedia {  key: string;  contentType: string;  bytes: Uint8Array;}/** * A film file made at seed time (dev-seed/cinemas.ts, by ffmpeg): its key and * type, and how to make it. Never bytes here: the invented life stays pure, * and no video is ever checked in. */export interface SeedVideo {  key: string;  contentType: string;  /**   * whole.mp4 plays on the phone as it is; source.mkv waits for the Mac; hls   * is a folder as the Mac lays one (its key the master, master.m3u8): the   * picture and tone in fMP4 segments, and an English WebVTT track.   */  container: "mp4" | "mkv" | "hls";  seconds: number;  /** The test tone's pitch in Hz: each file its own, so no two hash alike. */  tone: number;}export interface Life {  rows: SeedRow[];  chats: ImportBatch[];  media: SeedMedia[];  /** The films' own files, made by ffmpeg when the seed runs. */  videos: SeedVideo[];  /** Rows per table the life brings, the chats' messages under `message` and their threads under `thread`. */  counts: Record<string, number>;}/** The medium life; small is a quarter of each (at least one). */const MEDIUM = {  person: 25,  note: 40,  event: 60,  todo: 40,  thread: 12,  messagesLo: 30,  messagesHi: 80,  email_thread: 10,  photo: 60,  album: 4,  film: 10,  book: 10,  memory: 20,} as const;type Counts = { -readonly [K in keyof typeof MEDIUM]: number };export function sizes(scale: Scale): Counts {  const out = { ...MEDIUM } as Counts;  if (scale === "small") for (const key of Object.keys(out) as (keyof Counts)[]) out[key] = Math.max(1, Math.round(MEDIUM[key] / 4));  return out;}const IST_MS = 5.5 * 3600 * 1000;const DAY_MS = 86400 * 1000;/** The UTC instant of a local (UTC+05:30) time `days` from `today`. */function at(today: string, days: number, hour = 0, minute = 0): string {  const base = Date.parse(`${today}T00:00:00Z`) + days * DAY_MS + (hour * 60 + minute) * 60000 - IST_MS;  return new Date(base).toISOString();}/** The local date `days` from `today`. */function dayOf(today: string, days: number): string {  return new Date(Date.parse(`${today}T00:00:00Z`) + days * DAY_MS).toISOString().slice(0, 10);}const pad = (n: number, width: number): string => String(n).padStart(width, "0");/** * A person's number: `+91 90000 1NNNN`, the stand-in shape (four zeros in a * row) the no-real-identities guard admits and no carrier issues. */export function standInPhone(n: number): string {  return `+9190000${pad(10000 + n, 5)}`;}export function generateLife(options: LifeOptions): Life {  const { seed, today, databaseId } = options;  const size = sizes(options.scale);  const root = new Rng(`${seed}:${options.scale}:${today}`);  const rows: SeedRow[] = [];  const media = new Map<string, SeedMedia>();  const id = (table: string, n: number | string): string => idOf(seed, table, n);  const put = (row: SeedRow): SeedRow => {    rows.push(row);    return row;  };  const store = (folder: string, picture: Picture | { bytes: Uint8Array }, ext: "png" | "wav"): string => {    const key = `${databaseId}/${folder}/${sha256(picture.bytes)}.${ext}`;    media.set(key, { key, contentType: ext === "png" ? "image/png" : "audio/wav", bytes: picture.bytes });    return key;  };  // ── people ──────────────────────────────────────────────────────────  const rp = root.fork("people");  const firsts = rp.some(W.FIRST_NAMES, size.person);  const lasts = rp.shuffle(W.LAST_NAMES);  const people = firsts.map((first, i) => {    const last = lasts[i % lasts.length]!;    return { id: id("person", i), first, name: `${first} ${last}`, phone: standInPhone(i + 1), email: `${first}.${last}@mail.example`.toLowerCase().replace(/[^a-z.@-]/g, "") };  });  const cast = (rng: Rng): W.Cast => ({ person: () => rng.pick(people).first });  people.forEach((p, i) => {    const r = rp.fork(`person-${i}`);    const avatar = store("photos", portrait(r, p.name.split(" ").map((w) => w[0]).join("").slice(0, 2)), "png");    const data: Record<string, unknown> = { full_name: p.name, city: r.pick(W.TOWNS), language: "en", avatar_key: avatar };    if (r.chance(0.6)) {      data.org = r.pick(W.ORGS);      data.role_title = r.pick(W.ROLES);    }    if (r.chance(0.8)) data.birthday = `${r.int(1958, 2004)}-${pad(r.int(1, 12), 2)}-${pad(r.int(1, 28), 2)}`;    if (r.chance(0.4)) data.summary = W.paragraphs(r, cast(r), 1);    const made = at(today, -r.int(200, 900), 10);    put({ table: "person", id: p.id, data, created_at: made, updated_at: made });    // A handle as the app writes one a person adds (src/owner.ts): the value and its normalised form, which the chats' import and the calendar engine match on.    put({ table: "person_handle", id: id("person_handle", `${i}-phone`), data: { person_id: p.id, kind: "phone", value: p.phone, normalised: digits(p.phone), source: "manual", position: 0 }, created_at: made, updated_at: made });    if (r.chance(0.7)) put({ table: "person_handle", id: id("person_handle", `${i}-email`), data: { person_id: p.id, kind: "email", value: p.email, normalised: p.email, source: "manual", position: 1 }, created_at: made, updated_at: made });  });  // ── photos and albums ───────────────────────────────────────────────  const rf = root.fork("photos");  const photos = Array.from({ length: size.photo }, (_, i) => {    const r = rf.fork(`photo-${i}`);    const kind = r.pick(SCENES);    const tall = r.chance(0.25);    const picture = scene(r, kind, tall ? 360 : 480, tall ? 480 : 360);    const sha = sha256(picture.bytes);    const key = store("photos", picture, "png");    const days = -r.int(1, 365);    const taken = at(today, days, r.int(7, 20), r.int(0, 59));    const data: Record<string, unknown> = {      key, sha256: sha, content_type: "image/png", size_bytes: picture.bytes.length, width: picture.width, height: picture.height,      taken_at: taken, original_filename: `IMG_${pad(4100 + i, 4)}.PNG`,    };    if (r.chance(0.3)) data.caption = W.sentence(r, cast(r));    if (r.chance(0.5)) {      data.place_name = r.pick(W.VENUES);      data.place_city = r.pick(W.TOWNS);    }    if (r.chance(0.1)) data.favourite = true;    const row = put({ table: "photo", id: `photo:${sha}`, data, created_at: taken, updated_at: taken });    return { id: row.id, taken, days };  });  const byTime = [...photos].sort((a, b) => a.taken.localeCompare(b.taken));  const perAlbum = Math.max(1, Math.floor((photos.length * 0.4) / size.album));  for (let a = 0; a < size.album; a += 1) {    const r = rf.fork(`album-${a}`);    const members = byTime.slice(a * perAlbum * 2, a * perAlbum * 2 + perAlbum);    if (!members.length) break;    const albumId = id("album", a);    const first = members[0]!;    const last = members[members.length - 1]!;    const kind = a % 2 === 0 ? "trip" : "event";    put({      table: "album", id: albumId,      // Kept, so decided when: the phone's own album holds a decision exactly when it is not open.      data: { kind, state: "kept", decided_at: last.taken, title: kind === "trip" ? W.tripTitle(r, cast(r)) : r.pick(["Pottery evening", "Garden party", "Book swap afternoon", "Market morning"]), title_by: "user", starts_at: dayOf(today, first.days), ends_at: dayOf(today, last.days), cover_id: first.id },      created_at: last.taken, updated_at: last.taken,    });    members.forEach((m, k) => put({ table: "album_item", id: id("album_item", `${a}-${k}`), data: { album_id: albumId, record_kind: "photo", record_id: m.id, added_by: "user", sort_at: m.taken }, created_at: m.taken, updated_at: m.taken }));  }  // ── notes ───────────────────────────────────────────────────────────  const rn = root.fork("notes");  for (let i = 0; i < size.note; i += 1) {    const r = rn.fork(`note-${i}`);    const edited = at(today, -r.int(0, 364), r.int(7, 22), r.int(0, 59));    const made = new Date(Date.parse(edited) - r.int(0, 20) * DAY_MS).toISOString();    const data: Record<string, unknown> = { body: W.paragraphs(r, cast(r), r.int(2, 5)), updated_at: edited };    // A few untitled, as people leave them: the first line stands in.    if (i % 9 !== 4) data.title = W.noteTitle(r);    if (r.chance(0.05)) data.archived_at = dayOf(today, -r.int(0, 30));    put({ table: "note", id: id("note", i), data, created_at: made, updated_at: edited });  }  // ── calendar ────────────────────────────────────────────────────────  const re = root.fork("events");  const trips = Math.max(1, Math.round(size.event / 20));  for (let i = 0; i < size.event; i += 1) {    const r = re.fork(`event-${i}`);    const eventId = id("event", i);    const days = r.int(-90, 60);    const data: Record<string, unknown> = {};    if (i < trips) {      // A trip of several days, all day.      const length = r.int(2, 5);      Object.assign(data, { title: W.tripTitle(r, cast(r)), all_day: true, starts_at: at(today, days), ends_at: new Date(Date.parse(at(today, days + length)) - 1).toISOString(), kind: "travel" });    } else {      const shape = W.eventShape(r);      data.title = W.fill(r, shape.title, cast(r));      if (shape.allDay) Object.assign(data, { all_day: true, starts_at: at(today, days), ends_at: new Date(Date.parse(at(today, days + 1)) - 1).toISOString() });      else {        const hour = r.int(7, 20);        const minute = r.pick([0, 0, 15, 30, 45]);        const start = at(today, days, hour, minute);        Object.assign(data, { all_day: false, starts_at: start, ends_at: new Date(Date.parse(start) + shape.hours * 3600000).toISOString() });      }      // Most carry the kind a person picked; the rest are left for the object's classifier.      if (r.chance(0.8)) data.kind = shape.kind;      if (r.chance(0.6)) data.location = r.pick(W.VENUES);      if (i === trips || i === trips + 1) data.rrule = "FREQ=WEEKLY;COUNT=8";    }    if (r.chance(0.3)) data.notes = W.sentence(r, cast(r));    if (r.chance(0.5)) data.my_response = "accepted";    const made = at(today, Math.min(days, 0) - r.int(1, 20), 9);    data.created_at = made;    put({ table: "event", id: eventId, data, created_at: made, updated_at: made });    if (r.chance(0.4)) {      for (const [k, guest] of r.some(people, r.int(1, 3)).entries()) {        put({ table: "event_attendee", id: id("event_attendee", `${i}-${k}`), data: { event_id: eventId, phone: guest.phone, display_name: guest.name, response: r.pick(["accepted", "tentative", "needs_action"]) }, created_at: made, updated_at: made });      }    }  }  // ── todos ───────────────────────────────────────────────────────────  const rt = root.fork("todos");  for (let i = 0; i < size.todo; i += 1) {    const r = rt.fork(`todo-${i}`);    const made = at(today, -r.int(1, 120), r.int(8, 21));    const status = r.chance(0.3) ? "done" : r.chance(0.08) ? "dropped" : "open";    const data: Record<string, unknown> = { title: W.todoTitle(r, cast(r)), status, priority: r.pick([0, 0, 0, 1, 2]) };    if (r.chance(0.6)) data.due_at = at(today, r.int(-20, 30), r.pick([9, 9, 18]), r.pick([0, 30]));    if (r.chance(0.35)) data.notes = W.sentence(r, cast(r));    let edited = made;    if (status === "done") {      edited = new Date(Math.min(Date.parse(at(today, 0, 0)), Date.parse(made) + r.int(1, 10) * DAY_MS)).toISOString();      data.completed_at = edited;    }    put({ table: "todo", id: id("todo", i), data, created_at: made, updated_at: edited });  }  // ── chats (WhatsApp import batches) ─────────────────────────────────  const rc = root.fork("chats");  const chats: ImportBatch[] = [];  let messageCount = 0;  const groups = Math.max(size.thread >= 4 ? 3 : 1, Math.round(size.thread / 4));  const dmPeople = rc.some(people, size.thread - groups);  for (let t = 0; t < size.thread; t += 1) {    const r = rc.fork(`thread-${t}`);    const group = t >= size.thread - groups;    const members = group ? r.some(people, r.int(3, Math.min(6, people.length))) : [dmPeople[t % dmPeople.length]!];    const count = r.int(size.messagesLo, size.messagesHi);    let clock = Date.parse(at(today, -r.int(20, 60), r.int(8, 11)));    const messages: EnvelopeMessage[] = [];    const ext = (m: number): string => `dev-seed-${seed}-${t}-${m}`;    const pictures = r.chance(0.6) ? r.int(1, 3) : 0;    const pictureAt = new Set(r.some(Array.from({ length: count }, (_, k) => k), pictures));    for (let m = 0; m < count; m += 1) {      clock += r.chance(0.2) ? r.int(6, 30) * 3600000 : r.int(1, 90) * 60000;      // People write while awake: a message that would fall in the small hours waits for the morning.      const hour = new Date(clock + IST_MS).getUTCHours();      if (hour < 7) clock += (7 - hour) * 3600000 + r.int(0, 120) * 60000;      clock = Math.min(clock, Date.parse(at(today, 0, 0)) - (count - m) * 60000);      const out = r.chance(0.45);      const sender = r.pick(members);      const message: EnvelopeMessage = { direction: out ? "out" : "in", body: W.messageLine(r, cast(r)), sentAt: new Date(clock).toISOString(), externalId: ext(m) };      if (group && !out) message.senderLabel = sender.name;      if (pictureAt.has(m)) {        const picture = scene(r, r.pick(SCENES), 320, 240);        message.media = [{ key: store(`messages/chat-${t}`, picture, "png"), contentType: "image/png", width: picture.width, height: picture.height, sizeBytes: picture.bytes.length }];        if (r.chance(0.5)) message.body = "";      }      if (m > 3 && r.chance(0.08)) message.replyToExternalId = ext(m - r.int(1, 3));      if (r.chance(0.07)) message.reactions = [{ emoji: r.pick(["❤️", "😂", "👍", "🙏"]), actor: out ? digits(sender.phone) : "owner" }];      messages.push(message);    }    messageCount += messages.length;    const participant = (p: (typeof people)[number]): { label: string; phone: string } => ({ label: p.name, phone: digits(p.phone) });    chats.push(      group        ? { workspaceId: databaseId, channel: "whatsapp", thread: { kind: "group", title: W.GROUPS[(t - (size.thread - groups)) % W.GROUPS.length]!, externalKey: `dev-seed-${seed}-group-${t}`, participants: members.map(participant) }, messages }        : { workspaceId: databaseId, channel: "whatsapp", dm: participant(members[0]!), messages },    );  }  // ── email ───────────────────────────────────────────────────────────  const rm = root.fork("email");  const me = "me@mail.example";  for (let i = 0; i < size.email_thread; i += 1) {    const r = rm.fork(`mail-${i}`);    const threadId = id("email_thread", i);    const fromPerson = i % 5 >= 3;    const person = r.pick(people);    const service = W.SERVICE_MAIL[i % W.SERVICE_MAIL.length]!;    const from = fromPerson ? { name: person.name, address: person.email } : { name: service.from, address: service.address };    const subject = fromPerson ? r.pick([`Photos from ${W.TOWNS[i % W.TOWNS.length]}`, "Recipe you asked for", "Plans for the weekend", "The book I mentioned"]) : W.fill(r, r.pick(service.subjects), cast(r));    const n = fromPerson ? r.int(2, 4) : 1;    // The first two threads are the morning's mail, so Email's Today view    // holds what a real inbox's does; the rest are the months before.    const ago = r.int(2, 120);    const hour = r.int(8, 20);    let clock = Date.parse(i < 2 ? at(today, 0, 7, i * 20) : at(today, -ago, hour));    const first = new Date(clock).toISOString();    let last = first;    // Who wrote, as the mail reader settles it on every thread it files    // (cotton-tools emails/kinds.rs): a person the owner writes back to, a    // service otherwise. Email's People and Records views read nothing else.    const thread = put({ table: "email_thread", id: threadId, data: { external_key: `dev-seed-${seed}-mail-${i}`, subject, first_at: first, email_count: n, sender_address: from.address, sender_kind: fromPerson ? "person" : "service" } });    for (let k = 0; k < n; k += 1) {      const outgoing = fromPerson && k % 2 === 1;      const body = W.paragraphs(r, cast(r), r.int(1, 3));      const sent = new Date(clock).toISOString();      last = sent;      put({        table: "email", id: id("email", `${i}-${k}`),        data: {          thread_id: threadId, external_id: `<dev-seed-${seed}-${i}-${k}@mail.example>`, subject: k ? `Re: ${subject}` : subject,          from_email: outgoing ? me : from.address, from_name: outgoing ? "Me" : from.name, recipients: [outgoing ? from.address : me],          sent_at: sent, body, snippet: body.slice(0, 120), unread: !outgoing && k === n - 1 && r.chance(0.5), starred: r.chance(0.1), in_inbox: true, account: me,        },        created_at: sent, updated_at: sent,      });      clock += r.int(2, 48) * 3600000;    }    Object.assign(thread, { data: { ...thread.data, last_at: last }, created_at: first, updated_at: last });    put({ table: "email_participant", id: id("email_participant", `${i}-from`), data: { thread_id: threadId, email: from.address, display_name: from.name, role: "from" }, created_at: first, updated_at: first });    put({ table: "email_participant", id: id("email_participant", `${i}-to`), data: { thread_id: threadId, email: me, display_name: "Me", role: "to" }, created_at: first, updated_at: first });  }  // ── films and books ─────────────────────────────────────────────────  const rl = root.fork("library");  rl.some(W.FILM_TITLES, size.film).forEach((title, i) => {    const r = rl.fork(`film-${i}`);    const watched = r.chance(0.6);    const data: Record<string, unknown> = {      title, year: String(r.int(1978, 2025)), poster: store("photos", cover(r, title, 240, 360), "png"), kind: r.chance(0.2) ? "series" : "film",      status: watched ? "watched" : "want_to_watch", minutes: r.int(84, 160), director: `${r.pick(W.FIRST_NAMES)} ${r.pick(W.LAST_NAMES)}`,    };    if (watched) Object.assign(data, { watched_on: dayOf(today, -r.int(3, 300)), rating: r.int(2, 5), watched_with: r.pick(people).first });    if (r.chance(0.3)) data.recommended_by = r.pick(people).id;    if (r.chance(0.3)) data.review = W.sentence(r, cast(r));    const days = -r.int(30, 400);    const made = at(today, days, 20);    data.added_on = dayOf(today, days);    put({ table: "film", id: id("film", i), data, created_at: made, updated_at: made });  });  rl.some(W.BOOK_TITLES, size.book).forEach((title, i) => {    const r = rl.fork(`book-${i}`);    const status = r.pick(["want_to_read", "reading", "finished", "finished", "stopped"] as const);    const pages = r.int(140, 520);    const added = -r.int(40, 400);    const data: Record<string, unknown> = { title, author: `${r.pick(W.FIRST_NAMES)} ${r.pick(W.LAST_NAMES)}`, cover: store("photos", cover(r, title, 240, 360), "png"), status, pages, added_on: dayOf(today, added), source: "typed" };    if (status !== "want_to_read") data.started_on = dayOf(today, added + r.int(1, 30));    if (status === "reading") Object.assign(data, { progress: r.int(3, 95), position_at: at(today, -r.int(0, 6), 21) });    if (status === "finished") Object.assign(data, { finished_on: dayOf(today, -r.int(1, 39)), rating: r.int(4, 10) / 2, read_count: 1 });    if (r.chance(0.3)) data.review = W.sentence(r, cast(r));    const made = at(today, -r.int(30, 400), 21);    put({ table: "book", id: id("book", i), data, created_at: made, updated_at: made });  });  // ── cinemas ─────────────────────────────────────────────────────────  // The same at every scale, as the phone and the Mac leave them: a film  // that plays as it came (whole.mp4, half watched), one sent up as an MKV  // still waiting for the Mac (needs_mac, its source.mkv), one the Mac  // converted (an HLS master with an English track), and a series of  // one season and three episodes, each a whole.mp4, the first watched. Every  // file is a few seconds of test picture and tone that ffmpeg makes when  // the seed runs (dev-seed/cinemas.ts); the player's resume points and its  // watch rows are what it would have written.  const videos: SeedVideo[] = [];  const FILE = { mp4: ["whole.mp4", "video/mp4"], mkv: ["source.mkv", "video/x-matroska"], hls: ["master.m3u8", "application/vnd.apple.mpegurl"] } as const;  const video = (owner: string, container: SeedVideo["container"], tone: number, seconds = 4): string => {    const [name, contentType] = FILE[container];    const key = `${databaseId}/films/${owner}/${name}`;    videos.push({ key, contentType, container, seconds, tone });    return key;  };  const cinemaDay = -12;  const cinemaMade = at(today, cinemaDay, 19);  const wholeId = id("film", "cinemas-whole");  const wholePlayed = at(today, -1, 21, 15);  put({    table: "film", id: wholeId,    data: { title: "Harbour of Small Lights", year: "2021", kind: "film", status: "watching", file: video(wholeId, "mp4", 330), minutes: 1, director: "Ilse Marrow", added_on: dayOf(today, cinemaDay), position: 2, position_at: wholePlayed, last_watched_at: wholePlayed },    created_at: cinemaMade, updated_at: wholePlayed,  });  const waitingId = id("film", "cinemas-waiting");  put({    table: "film", id: waitingId,    data: { title: "The Salt Flats Overnight", year: "2017", kind: "film", status: "want_to_watch", needs_mac: true, source_file: video(waitingId, "mkv", 392), added_on: dayOf(today, cinemaDay) },    created_at: cinemaMade, updated_at: cinemaMade,  });  // A film the Mac has converted, streamed from its HLS master with an  // English track: the one Give subtitles takes (a film kept whole is refused  // until the Mac converts it), a minute long so its resume point can be walked.  const streamedId = id("film", "cinemas-streamed");  put({    table: "film", id: streamedId,    data: {      title: "The Lantern Ferry", year: "2019", kind: "film", status: "want_to_watch", file: video(streamedId, "hls", 523, 60), minutes: 1, director: "Oda Brennvik", added_on: dayOf(today, cinemaDay),      subtitles: JSON.stringify([{ language: "en", name: "English", source: "embedded", made_at: cinemaMade, file: "sub-en.vtt" }]),    },    created_at: cinemaMade, updated_at: cinemaMade,  });  const seriesId = id("film", "cinemas-series");  const episodePlayed = at(today, -3, 22, 5);  put({ table: "film", id: seriesId, data: { title: "Lowmarsh", year: "2024", kind: "series", status: "watching", added_on: dayOf(today, cinemaDay), position_at: episodePlayed, last_watched_at: episodePlayed }, created_at: cinemaMade, updated_at: episodePlayed });  const seasonId = id("film_season", "cinemas-series-1");  put({ table: "film_season", id: seasonId, data: { film: seriesId, number: 1, title: "Season 1", year: "2024" }, created_at: cinemaMade, updated_at: cinemaMade });  const episodeIds = ["Pilot", "Cicadas", "The Long Night"].map((title, k) => {    const episodeId = id("film_episode", `cinemas-series-1-${k + 1}`);    const data: Record<string, unknown> = { season: seasonId, series: seriesId, number: k + 1, title, file: video(episodeId, "mp4", 440 + k * 110), minutes: 1, aired: dayOf(today, -400 + k * 7) };    if (k === 0) Object.assign(data, { status: "watched", watched_on: dayOf(today, -3) });    put({ table: "film_episode", id: episodeId, data, created_at: cinemaMade, updated_at: k === 0 ? episodePlayed : cinemaMade });    return episodeId;  });  put({ table: "watch", id: id("watch", "cinemas-whole"), data: { film: wholeId, started_at: at(today, -1, 21, 13), seconds: 2, finished: false, device: "iPhone" }, created_at: wholePlayed, updated_at: wholePlayed });  put({ table: "watch", id: id("watch", "cinemas-episode-1"), data: { film: seriesId, episode: episodeIds[0]!, started_at: at(today, -3, 22, 1), seconds: 4, finished: true, device: "iPhone" }, created_at: episodePlayed, updated_at: episodePlayed });  // Synthetic film list: a list of films as an assistant makes one over  // Cotton MCP (record_group and group_member rows), holding a film that  // plays, the series and the film waiting for the Mac, in that order.  const filmListId = id("record_group", "cinemas-list");  put({ table: "record_group", id: filmListId, data: { table_id: "film", name: "Synthetic film list", position: 0 }, created_at: cinemaMade, updated_at: cinemaMade });  [wholeId, seriesId, waitingId].forEach((film, k) =>    put({ table: "group_member", id: id("group_member", `cinemas-list-${k}`), data: { group: filmListId, record_id: film, place: k + 1 }, created_at: cinemaMade, updated_at: cinemaMade }),  );  // ── memories ────────────────────────────────────────────────────  const rq = root.fork("memories");  // The memory table the assistants write (remember): the owner's own sentences, every fifth one archived.  for (let i = 0; i < size.memory; i += 1) {    const r = rq.fork(`memory-${i}`);    const made = at(today, -r.int(1, 300), 22);    const archived = i % 5 === 4;    const data = { slug: `memory-${i + 1}`, title: W.memoryLine(r, cast(r), i), body: W.sentence(r, cast(r)), status: archived ? "archived" : "active", archived_at: archived ? made : null, visibility: "private", origin_kind: "user", origin_label: null, machine: null };    put({ table: "memory", id: id("memory", i), data, created_at: made, updated_at: made });  }  const counts: Record<string, number> = {};  for (const row of rows) counts[row.table] = (counts[row.table] ?? 0) + 1;  counts.thread = chats.length;  counts.message = messageCount;  return { rows, chats, media: [...media.values()], videos, counts };}/** A number as the WhatsApp batch spells it: digits, no `+`. */function digits(phone: string): string {  return phone.replace(/\D/g, "");}