Cotton code
593 lines · 30.4 KB · TypeScriptRaw
/** * A personal object keeps the kit (owner, 26 Oct 2026): the personal kit ships * everything built for Personal, every object gets the whole kit, and kit * changes merge add-only, never over a person's edits; the card is the build's * on every table and every tool's view, and the kit names it. * * The kit is the personal kit this Worker bundles (src/kits.ts, from * crates/cotton-core/kits/personal): its own tool (its kit.json, the object's * map of its tables), its tools, the shell's boards it lists, and its tables. * An object made from it (src/business.ts `provision`) holds it whole * at the kit's version (`KIT_VERSION`). On the first request after a Worker * with another kit, it takes what the kit brings: * * - a tool or a board it does not hold and was never given (`KIT_GIVEN`), *   whole. One the person edited stays as edited; one they removed stays *   removed. The kit's own tool is the kit's to say (no face draws *   it, nothing edits it) and is the shipped one. * - a SHELL board (the shell kit's: settings, home, tools, database) is the *   app's shell screen (coordinator, 1 Nov 2026): a keep lays the kit's *   version of it over one the person has not edited, so an existing *   object's Settings leads with Backup and Cotton server and its Home loses *   the device part. Add-only still protects the person: a row a held list *   part names that the kit's part lacks (one a person or an older kit added) *   is kept after the kit's rows; everything else (parts, order, titles, *   lines, acts) is the kit's. One the person HAS edited (the phone saves *   Home through the definition act) stays as edited (coordinator, 2 Nov *   2026): edited means it differs from what the kit last laid, which the *   object keeps under `KIT_LAID`; with no record (no keep has laid one since *   the rule), the held board is the kit's to lay. * - a held tool the person has NOT edited is the kit's current tool whole *   (coordinator, 5 Nov 2026: the owner's object kept the Books tool the kit *   laid weeks before, and the new Books could not draw it). Edited is told *   as boards tell it: the tool differs from what the kit last laid, which *   the object keeps under `KIT_LAID_TOOLS`. With no record (no keep has laid *   one since the rule), a tool the kit gave (`KIT_GIVEN`) is the kit's to *   lay, and one it never gave (an object brought to no kit before) is held. *   A held tool's picture is the person's pick (the owner's Birthdays and *   Notebook carry pictures no kit shipped) and stays on the kit's tool. * - a held tool the person HAS edited keeps everything except its matched *   views' cards, which take the kit's, including a removal when the kit *   names none. Every other tool and view key stays held, and a held view *   the kit lacks stays whole. * - a held tool that reads a RETIRED table (one the kit no longer ships *   that the object holds under an engine: the build's, which no person *   makes or edits, so a view reading it is the kit's old view, never the *   person's) takes the kit's views and tables: *   the kit's views, then each held view the kit lacks that reads no retired *   table; the kit's tables, then each held table that is not retired *   (Memories off memory_entry onto memory, 3 Nov 2026). Its other keys *   stay held. * - the kit's tables as the kit always reached an object (the device's *   sync columns of 26 Oct 2026 never reached the owner's, and every write *   naming one was stripped and answered Ok): a table it does not hold, *   whole; a table the kit keeps under an engine, as the kit defines *   it (the build's, which no owner edits: the face the phone draws), keeping *   after its columns any the object holds that it lacks; and on any other *   table, each key and each column it lacks, added. No column is taken away *   and a table the kit dropped stays, since rows may name it. On every table *   the card is the build's: a card the kit names replaces the held one; if *   the kit names none, a held card on an engineless table stays. * - a held table that holds NO rows on the object is the kit's whole *   (coordinator, 4 Nov 2026): with nothing written in it, no row can name a *   column or a choice it would lose, so the kit may reshape it — columns, *   choices, commands and every other key replaced. Books' book was redone *   this way. A table with even one row (a binned one counts) stays add-only. * - a kit table's `retired` entry (a column the kit no longer keeps) is laid *   on a held table only once the held table no longer names that column *   (coordinator, 5 Nov 2026): an add-only keep never takes a column away, so *   on a table still holding it the entry waits, else the held definition *   says a column is both kept and retired, which the phone's store refuses *   ("a retired column is no longer a column"). Cinemas' film retires `notes` *   this way; the owner's one-time `reshape_films` lays the kit's film whole. * - a held table whose LOOK the person has not edited takes the kit's look *   whole (coordinator, 5 Nov 2026: the owner's Books showed Plus as one *   "Find a book" field and "No books yet" weeks after the kit's book named *   its doors and its empty line, since an add-only keep never replaced a *   look key the table already held). The look is every key but the ones *   that say what a table IS (`FIXED` in src/definition_writes.ts), its *   `columns` and its `card`, which keep their own rules above: each look key *   is set as the kit has it, and one the kit no longer carries is removed. *   Storage never moves: columns, engine, commands, acts, connections and *   identity stay the table's. Edited is told as tools tell it: the look *   differs from what the kit last laid, which the object keeps stamped under *   `KIT_LAID_TABLES`; with no record (no keep has laid one since the rule), *   the held look is the kit's to lay; a look that already reads as the *   kit's now is the kit's (a one-time reshape, or a hand fix, laid it). A *   look the person edited stays, and the keep says so in its notices *   (`KIT_NOTICES`). The owner's `definition` act and `update_definition` *   write nothing more: a table look they change differs from the stamp, *   which this rule reads as the person's edit, and one they set back to the *   kit's is the kit's again. * - a held table's `commands` and `acts` are the build's, never a person's *   (coordinator, 5 Nov 2026: FIXED keys no act or MCP path writes; the *   owner's book held 8 commands while the kit's had 12, so Books' stars, *   Find details and Add a file had nothing to run): every keep lays them *   exactly as the kit has them, one the kit lacks removed. A look the person *   kept whose `marks` name a command no longer laid takes the kit's marks, *   said in the notices, so the held table never binds a mark to nothing. * * An object brought to no kit before (the owner's, made by `pnpm onboard`) * was given nothing: its first pass takes everything it lacks. */import { FIXED, marksProblem } from "./definition_writes.ts";import { withoutEmpty } from "./fan.ts";/** The meta key holding the version of the kit the object was last brought to. */export const KIT_VERSION = "kit_version";/** The meta key holding the tools and boards the kit has given the object (`Given`, as JSON). */export const KIT_GIVEN = "kit_given";/** The meta key holding each shell board as the kit last laid it (`Laid`, as JSON): what an edit is told from. */export const KIT_LAID = "kit_laid";/** The meta key holding each kit tool as the kit last laid it (`Laid`, as JSON): what a tool's edit is told from. */export const KIT_LAID_TOOLS = "kit_laid_tools";/** The meta key holding each kit table's look as the kit last laid it, stamped (`LaidLooks`, as JSON): what a table look's edit is told from. */export const KIT_LAID_TABLES = "kit_laid_tables";/** The meta key holding what the last keep said (a list of lines, as JSON): each table look it kept as the person edited it. */export const KIT_NOTICES = "kit_notices";/** The meta key the personal tables' stamp was kept under before the kit kept them with the rest. */export const RETIRED_PACKAGE_STAMP = "package_stamp";type Doc = Record<string, unknown>;/** The definitions the kit is made of, by kind. */export interface Kit {  /** The kit's own tool: its kit.json, the object's map of its tables. */  own: Doc[];  tools: Doc[];  boards: Doc[];  tables: Doc[];  /** The ids of the shell kit's boards: the app's shell screens, laid whole on every keep. */  shell: string[];}export type Kind = "tool" | "board" | "table";/** The ids of the tools and boards the kit has given an object. */export type Given = Record<"tool" | "board", string[]>;/** Each shell board by id, as the kit last laid it on an object. */export type Laid = Record<string, Doc>;/** Each kit table's look by id, as the kit last laid it on an object, stamped (`lookStamp`). */export type LaidLooks = Record<string, string>;/** Two FNV-1a 32-bit passes of different seeds, as hex: a stamp, not a secret. */export function stampOf(text: string): string {  let a = 0x811c9dc5;  let b = 0x01000193 ^ text.length;  for (let i = 0; i < text.length; i++) {    const c = text.charCodeAt(i);    a = Math.imul(a ^ c, 0x01000193);    b = Math.imul(b ^ c, 0x01000193) ^ (b >>> 15);  }  return (a >>> 0).toString(16).padStart(8, "0") + (b >>> 0).toString(16).padStart(8, "0");}const versions = new WeakMap<Kit, string>();/** * The merge rule's own number, part of the kit's version: it moves when what * a pass takes from the kit changes (3: a tool view's card is the build's * too, including removals, 30 Oct 2026; 4: a shell board is the kit's on * every keep, 1 Nov 2026; 5: a shell board the person edited stays, told * from what the kit last laid, 2 Nov 2026; 6: a held tool reading a table * the kit retired takes the kit's views and tables, 3 Nov 2026; 7: a held * table with no rows is the kit's whole, 4 Nov 2026; 8: a held column takes * the kit's readonly where it says nothing of it, 4 Nov 2026; 9: a held * tool the person has not edited is the kit's whole, 5 Nov 2026; 10: a kit * table's retired column is laid only once the held table no longer holds * it, and a held choice column takes the choices the kit adds, 5 Nov 2026; * 11: a held table whose look the person has not edited takes the kit's * look whole, 5 Nov 2026; 12: a held table's commands and acts are the * kit's on every keep, 5 Nov 2026; 13: a held column takes the kit's * `until` and `default` where it says nothing of them, 13 Nov 2026; 14: a * held table's seal block is the kit's, 15 Nov 2026; 15: a table or tool * src/retired.ts names is held as retired under its meta key, never served, * its rows kept, 17 Nov 2026; 16: a held column the kit says outright is * not readonly, because an act of the table writes it, stops being readonly, * 17 Nov 2026), so every object runs * the pass again over the same kit files and takes what the new rule brings. */export const KEEP_RULE = 16;/** The version of `kit`: the stamp of the merge rule and the kit, worked out once per isolate. */export function kitVersion(kit: Kit): string {  let version = versions.get(kit);  if (!version) {    version = stampOf(`${KEEP_RULE}:${JSON.stringify(kit)}`);    versions.set(kit, version);  }  return version;}const idOf = (d: Doc): string => String(d.id);const same = (a: unknown, b: unknown): boolean => JSON.stringify(a) === JSON.stringify(b);function columnsOf(t: Doc): Doc[] {  return Array.isArray(t.columns) ? (t.columns as Doc[]) : [];}/** Every tool and board `kit` gives. */export function givenBy(kit: Kit): Given {  return { tool: [...kit.own, ...kit.tools].map(idOf), board: kit.boards.map(idOf) };}/** The shell boards `kit` lays on an object made from it: its own. */export function laidBy(kit: Kit): Laid {  return Object.fromEntries(kit.boards.filter((b) => kit.shell.includes(idOf(b))).map((b) => [idOf(b), b]));}/** The kit tools `kit` lays on an object made from it: every one, as it ships. */export function laidToolsBy(kit: Kit): Laid {  return Object.fromEntries(kit.tools.map((t) => [idOf(t), t]));}/** The keys of a table that are never its look: what it IS (`FIXED`), its columns and its card, which keep their own rules. */const NOT_LOOK = new Set([...FIXED, "columns", "card"]);/** A table's look: every key but what it is, its columns and its card. */export function lookOf(table: Doc): Doc {  return Object.fromEntries(Object.entries(table).filter(([k]) => !NOT_LOOK.has(k)));}/** JSON with each object's keys in order: a look stamps the same in whatever order a phone wrote it. */function canonical(value: unknown): string {  if (Array.isArray(value)) return `[${value.map(canonical).join(",")}]`;  if (value && typeof value === "object") {    const entries = Object.entries(value as Doc).filter(([, v]) => v !== undefined).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0));    return `{${entries.map(([k, v]) => `${JSON.stringify(k)}:${canonical(v)}`).join(",")}}`;  }  return JSON.stringify(value) ?? "null";}/** The stamp of a table's look: what a keep records it laid, and tells an edit from. */export function lookStamp(table: Doc): string {  return stampOf(canonical(lookOf(table)));}/** The kit table looks `kit` lays on an object made from it: every one, stamped. */export function laidLooksBy(kit: Kit): LaidLooks {  return Object.fromEntries(kit.tables.map((t) => [idOf(t), lookStamp(t)]));}/** Read back a `KIT_LAID_TABLES` meta value; empty when no keep recorded one. */export function readLaidLooks(text: string | null): LaidLooks {  return text ? (JSON.parse(text) as LaidLooks) : {};}/** Read back a `KIT_LAID` or `KIT_LAID_TOOLS` meta value; empty when no keep recorded one. */export function readLaid(text: string | null): Laid {  return text ? (JSON.parse(text) as Laid) : {};}/** Read back a `KIT_GIVEN` meta value; null when the object was brought to no kit before. */export function readGiven(text: string | null): Given | null {  if (!text) return null;  const parsed = JSON.parse(text) as Partial<Given>;  return { tool: parsed.tool ?? [], board: parsed.board ?? [] };}/** How many rows (live or binned) the object holds in a table, by id. */export type RowsIn = (table: string) => number;/** * The held tables with what `shipped` grew since. A table it adds comes * whole, and so does one the object holds no row in (`rows`): the kit * reshapes an empty table whole. A table the kit keeps under an engine is the build's — the * owner's definition tools never write one (`update_definition` refuses an * engine's table) — so the object takes the kit's definition of it, its * face and its columns' words, and keeps after them any column it holds that * the kit lacks. On any other table, each key and each column the held * one lacks is added, a text column the kit now keeps as a link takes * that link (a link holds the id a text held, so no row moves), and a column * the kit keeps readonly takes it where the held one says nothing; nothing else * it holds changes, except its card: the card is the build's on every table, * so a card the kit names replaces the held one; absent from the kit, the * held card on an engineless table stays. Its look (`lookOf`) is the kit's * whole unless the person edited it since the kit last laid it (`laidLooks`, * KEEP_RULE 11): no record, a look as the kit last laid it, or one that * already reads as the kit's now, and every look key is set as the kit has * it, one the kit no longer carries removed; an edited look stays, said in * `notices`. `changed` counts the tables that moved; `laidLooks` is each kit * table's look as this pass leaves it laid (the kit's, or, kept as edited, * the record it was told from). */export function grown(held: Doc[], shipped: Doc[], rows: RowsIn, laidLooks: LaidLooks = {}): { tables: Doc[]; changed: number; laidLooks: LaidLooks; notices: string[] } {  const byId = new Map(held.map((t) => [idOf(t), t]));  const nowLaid: LaidLooks = {};  const notices: string[] = [];  let changed = 0;  for (const p of shipped) {    const id = idOf(p);    const h = byId.get(id);    const kitLook = lookStamp(p);    nowLaid[id] = kitLook;    if (!h) {      byId.set(id, p);      changed++;      continue;    }    let next: Doc;    if (rows(id) === 0) next = p;    else if (typeof p.engine === "string" && p.engine) next = engineTable(h, p);    else {      const record = laidLooks[id];      const heldLook = lookStamp(h);      if (record === undefined || heldLook === record || heldLook === kitLook) next = lookLaid(addedTo(h, p), p);      else {        next = addedTo(h, p);        nowLaid[id] = record;        notices.push(lookKept(h, p));        if (marksProblem(next)) {          next = withKitMarks(next, p);          notices.push(`table ${JSON.stringify(id)}: its marks named a command the kit no longer lays, so they are the kit's`);        }      }    }    if (same(next, h)) continue;    byId.set(id, next);    changed++;  }  return { tables: [...byId.values()], changed, laidLooks: nowLaid, notices };}/** `out` with the kit's `marks`, or none where the kit names none. */function withKitMarks(out: Doc, p: Doc): Doc {  const next: Doc = { ...out };  if ("marks" in p) next.marks = p.marks;  else delete next.marks;  return next;}/** `out` with the kit's look: each look key as `p` has it, in `out`'s order, one `p` lacks removed, then `p`'s others. */function lookLaid(out: Doc, p: Doc): Doc {  const next: Doc = {};  for (const [k, v] of Object.entries(out)) {    if (NOT_LOOK.has(k)) next[k] = v;    else if (k in p) next[k] = p[k];  }  for (const [k, v] of Object.entries(p)) if (!NOT_LOOK.has(k) && !(k in next)) next[k] = v;  return next;}/** The notice for a table look kept as the person edited it, naming the keys it holds apart from the kit's. */function lookKept(h: Doc, p: Doc): string {  const held = lookOf(h);  const kit = lookOf(p);  const apart = [...new Set([...Object.keys(held), ...Object.keys(kit)])].filter((k) => canonical(held[k]) !== canonical(kit[k])).sort();  return `table ${JSON.stringify(idOf(h))}: the person's look is kept over the kit's (${apart.join(", ")}), since it differs from what the kit last laid`;}/** The kit's definition, with each column the held one has and it lacks kept after its own. */function engineTable(h: Doc, p: Doc): Doc {  const keys = new Set(columnsOf(p).map((c) => String(c.key)));  return retiredKept(h, p, { ...p, columns: [...columnsOf(p), ...columnsOf(h).filter((c) => !keys.has(String(c.key)))] });}function retiredOf(t: Doc): Doc[] {  return Array.isArray(t.retired) ? (t.retired as Doc[]) : [];}/** * `out` (the held table as a keep makes it) with its `retired` list: the held * table's own entries, then each of the kit's whose column `out` no longer * names. A column still held is never retired by a keep: the entry waits * until the column is gone (5 Nov 2026). */function retiredKept(h: Doc, p: Doc, out: Doc): Doc {  const held = retiredOf(h);  const named = new Set([...held.map((r) => String(r.key)), ...columnsOf(out).map((c) => String(c.key))]);  const laid = [...held, ...retiredOf(p).filter((r) => !named.has(String(r.key)))];  const next: Doc = { ...out };  if (laid.length || "retired" in h) next.retired = laid;  else delete next.retired;  return next;}/** * The keys of a table that are the build's on every keep, laid exactly as the kit has them (KEEP_RULE 12). The * `seal` block too (KEEP_RULE 14, 15 Nov 2026, e2e rulings R1): which columns the object holds only sealed is * the kit's to say, so a kit that moves a column out of `clear` reaches an object whose table holds rows. */const BUILDS = ["commands", "acts", "seal"] as const;/** * The held definition with each key and column of the kit's it lacks, each * held column as the kit now keeps it (`columnKept`). The card is the build's on every table: * a card the kit names replaces the held one; absent from the kit, it stays. * Its commands and acts are the build's too: exactly the kit's, one the kit * lacks removed. */function addedTo(h: Doc, p: Doc): Doc {  const out: Doc = { ...h };  for (const [k, v] of Object.entries(p)) if (k === "card" || !(k in out)) out[k] = v;  for (const k of BUILDS) {    if (k in p) out[k] = p[k];    else delete out[k];  }  const shipped = new Map(columnsOf(p).map((c) => [String(c.key), c]));  const keys = new Set(columnsOf(h).map((c) => String(c.key)));  out.columns = [...columnsOf(h).map((c) => columnKept(c, shipped.get(String(c.key)))), ...columnsOf(p).filter((c) => !keys.has(String(c.key)))];  return retiredKept(h, p, out);}/** * A held column as the kit now keeps it, add-only: a text the kit keeps as a * link (26 Oct 2026: message_contact's and face's person_id, a person's id * all along) takes that link; a column the kit keeps readonly, no person's to * edit (4 Nov 2026: a highlight's passage and place), takes `readonly` where * the held one says nothing of it, while one the owner set either way stays, * save that a column the kit says outright is not readonly (17 Nov 2026: a * film's subtitle_work, which Find subtitles and Make subtitles write) stops * being readonly, since a readonly column refuses the table's own act; * a choice column takes each choice the kit adds that it lacks, after its * own, with the kit's label for it (5 Nov 2026: the film's status grows * want_to_watch, watching and stopped beside watchlist, which its rows still * hold, so the kit's card, whose state names the new ones, stays a card of * this table); a column the kit reads as a range's first day (`until`, 13 * Nov 2026: a trip's starts is until its ends, so a trip given only the day * it starts stands in Upcoming and Past) or gives a new record a value * (`default`: a trip's paper is a ticket unless it says otherwise) takes * that where the held one says nothing of it, since no row holds either. * Anything else a held column holds stays as it is. *//** A column's readings no row holds, taken from the kit where the held column says nothing of them (KEEP_RULE 13). */const SAID_WHERE_HELD_SAYS_NOTHING = ["until", "default"] as const;function columnKept(held: Doc, shipped: Doc | undefined): Doc {  let out = held;  if (held.type === "text" && shipped?.type === "link" && typeof shipped.link_to === "string") out = { ...out, type: "link", link_to: shipped.link_to };  if (shipped?.readonly === true && !("readonly" in held)) out = { ...out, readonly: true };  if (shipped?.readonly === false && held.readonly === true) out = { ...out, readonly: false };  for (const key of SAID_WHERE_HELD_SAYS_NOTHING) if (shipped?.[key] !== undefined && !(key in held)) out = { ...out, [key]: shipped[key] };  if (held.type === "choice" && shipped?.type === "choice" && Array.isArray(held.choices) && Array.isArray(shipped.choices)) {    const have = held.choices as unknown[];    const more = (shipped.choices as unknown[]).filter((c) => !have.includes(c));    if (more.length) {      out = { ...out, choices: [...have, ...more] };      const labels = shipped.labels && typeof shipped.labels === "object" ? (shipped.labels as Record<string, unknown>) : {};      const added = Object.fromEntries(more.filter((c) => typeof c === "string" && c in labels).map((c) => [c as string, labels[c as string]]));      if (Object.keys(added).length) out.labels = { ...((held.labels as Record<string, unknown> | undefined) ?? {}), ...added };    }  }  return out;}/** * What `kit` brings an object holding `held` (with `rows` in each of its * tables) that was given `before` and on which the kit last laid `laid` * (shell boards), `laidTools` (kit tools) and `laidLooks` (kit table looks): * the definitions to merge by id, each kind apart, what it has then been * given, each shell board, kit tool and kit table look as this pass lays it * (whether it laid it, or kept the person's edit in its place), and what the * pass says: each table look kept as the person edited it. */export function brought(  held: Record<Kind, Doc[]>,  kit: Kit,  rows: RowsIn,  before: Given | null,  laid: Laid = {},  laidTools: Laid = {},  laidLooks: LaidLooks = {},): { docs: Record<Kind, Doc[]>; given: Given; laid: Laid; laidTools: Laid; laidLooks: LaidLooks; notices: string[] } {  const was = { tool: new Set(before?.tool), board: new Set(before?.board) };  const holds = (kind: Kind): Map<string, Doc> => new Map(held[kind].map((d) => [idOf(d), d]));  const tools = holds("tool");  const boards = holds("board");  const tables = holds("table");  const retired = retiredBy(held.table, kit.tables);  const fresh = (shipped: Doc[], have: Map<string, Doc>, kind: "tool" | "board"): Doc[] => shipped.filter((d) => !have.has(idOf(d)) && !was[kind].has(idOf(d)));  const nowLaid: Laid = {};  const nowLaidTools: Laid = {};  const kept = grown(held.table, kit.tables, rows, laidLooks);  const docs: Record<Kind, Doc[]> = {    tool: [      ...kit.own.filter((d) => !same(tools.get(idOf(d)), d)),      ...fresh(kit.tools, tools, "tool").map((p) => (nowLaidTools[idOf(p)] = p)),      ...kit.tools.flatMap((p) => {        const id = idOf(p);        const h = tools.get(id);        if (!h) return [];        const record = laidTools[id];        const unedited = record !== undefined ? same(h, record) : was.tool.has(id);        let next: Doc;        if (unedited) {          next = "picture" in h ? { ...p, picture: h.picture } : p;          nowLaidTools[id] = next;        } else {          next = viewCards(readsRetired(h, retired) ? repointed(h, p, retired) : h, p);          // Kept as edited from what the kit laid; with no record, from the kit's tool now.          nowLaidTools[id] = record ?? p;        }        return same(next, h) ? [] : [next];      }),    ],    board: [      ...fresh(kit.boards.filter((d) => !kit.shell.includes(idOf(d))), boards, "board"),      ...kit.boards.flatMap((p) => {        const id = idOf(p);        if (!kit.shell.includes(id)) return [];        const h = boards.get(id);        const next = shellBoard(h, p);        nowLaid[id] = next;        // Told apart as kept: Home is served with the tools it works out as empty (src/fan.ts).        const before = laid[id];        const edited = h !== undefined && before !== undefined && !same(withoutEmpty(h), withoutEmpty(before));        return edited || same(next, h) ? [] : [next];      }),    ],    table: kept.tables.filter((t) => !same(tables.get(idOf(t)), t)),  };  const now = givenBy(kit);  const union = (k: keyof Given): string[] => [...new Set([...(before?.[k] ?? []), ...now[k]])].sort();  return { docs, given: { tool: union("tool"), board: union("board") }, laid: nowLaid, laidTools: nowLaidTools, laidLooks: kept.laidLooks, notices: kept.notices };}/** Whether a table is retired: the object holds it under an engine (the build's, which no person makes or edits) and the kit no longer ships it. A table the person made is held with no engine, and never retired. */export function retiredBy(held: Doc[], shipped: Doc[]): (id: string) => boolean {  const ships = new Set(shipped.map(idOf));  const retired = new Set(held.filter((t) => typeof t.engine === "string" && t.engine !== "" && !ships.has(idOf(t))).map(idOf));  return (id) => retired.has(id);}function viewReads(view: Doc): string | undefined {  const read = view.read as Doc | undefined;  return typeof read?.table === "string" ? read.table : undefined;}/** Whether a held tool names a retired table, in a view's read or its tables. */function readsRetired(tool: Doc, retired: (id: string) => boolean): boolean {  const views = Array.isArray(tool.views) ? (tool.views as Doc[]) : [];  const named = Array.isArray(tool.tables) ? (tool.tables as unknown[]) : [];  return views.some((v) => viewReads(v) !== undefined && retired(viewReads(v)!)) || named.some((t) => retired(String(t)));}/** A held tool off a retired table: the kit's views, then each held view the kit lacks that reads no retired table; the kit's tables, then each held one not retired. */function repointed(held: Doc, shipped: Doc, retired: (id: string) => boolean): Doc {  const kitViews = Array.isArray(shipped.views) ? (shipped.views as Doc[]) : [];  const kitIds = new Set(kitViews.map(idOf));  const heldViews = Array.isArray(held.views) ? (held.views as Doc[]) : [];  const kitTables = Array.isArray(shipped.tables) ? (shipped.tables as unknown[]).map(String) : [];  const heldTables = Array.isArray(held.tables) ? (held.tables as unknown[]).map(String) : [];  // The kit's acts too, which its views name (Music's On this phone), then each held one the kit lacks.  const kitActs = Array.isArray(shipped.acts) ? (shipped.acts as Doc[]) : [];  const kitActIds = new Set(kitActs.map(idOf));  const acts = [...kitActs, ...(Array.isArray(held.acts) ? (held.acts as Doc[]) : []).filter((a) => !kitActIds.has(idOf(a)))];  return {    ...held,    views: [...kitViews, ...heldViews.filter((v) => !kitIds.has(idOf(v)) && !(viewReads(v) !== undefined && retired(viewReads(v)!)))],    tables: [...kitTables, ...heldTables.filter((t) => !kitTables.includes(t) && !retired(t))],    ...(acts.length ? { acts } : {}),  };}/** A held tool keeps everything except matched views' cards, which the kit names or removes. */function viewCards(held: Doc, shipped: Doc): Doc {  if (!Array.isArray(held.views) || !Array.isArray(shipped.views)) return held;  const views = new Map((shipped.views as Doc[]).map((v) => [idOf(v), v]));  return {    ...held,    views: (held.views as Doc[]).map((v) => {      const kitView = views.get(idOf(v));      if (!kitView) return v;      const next = { ...v };      if ("card" in kitView) next.card = kitView.card;      else delete next.card;      return next;    }),  };}/** * A shell board as every keep lays it: the kit's, with each row a held list * part names that the kit's same part (by kind and table) lacks kept after * the kit's rows — a row a person or an older kit added is never dropped. */export function shellBoard(held: Doc | undefined, shipped: Doc): Doc {  if (!held || !Array.isArray(held.parts) || !Array.isArray(shipped.parts)) return shipped;  const partKey = (part: Doc): string => `${String(part.kind)}:${String(part.table ?? "")}`;  const heldParts = new Map((held.parts as Doc[]).filter((part) => Array.isArray(part.rows)).map((part) => [partKey(part), part]));  return {    ...shipped,    parts: (shipped.parts as Doc[]).map((part) => {      const h = heldParts.get(partKey(part));      if (!h || !Array.isArray(part.rows)) return part;      const kitRows = new Set((part.rows as Doc[]).map(idOf));      const added = (h.rows as Doc[]).filter((row) => !kitRows.has(idOf(row)));      return added.length ? { ...part, rows: [...(part.rows as Doc[]), ...added] } : part;    }),  };}