/** * The personal kit merges add-only into every object (owner, 26 Oct 2026): * an object brought to an older kit, or to none, takes every kit tool, board * and package table it lacks on its next request, and nothing it holds is * replaced except the build's card on every table and matched tool view — a person's edits stand, and a tool or board they removed is not * brought back. */import { env, runInDurableObject, SELF } from"cloudflare:test";import { describe, expect, it } from"vitest";import { brought, givenBy, grown, KEEP_RULE, KIT_GIVEN, KIT_LAID, KIT_LAID_TABLES, KIT_LAID_TOOLS, KIT_VERSION, kitVersion, laidLooksBy, lookOf, lookStamp, readGiven, retiredBy, shellBoard, stampOf, typeKit } from"../src/kit_keep.ts";import { KITS, PERSONAL } from"../src/kits.ts";import { marksProblem } from"../src/definition_writes.ts";import { ruled } from"../src/seal.ts";import { served } from"../src/retired.ts";import { ADMIN, DATABASE_ID, http, KIT_MANIFESTS, OWNER_PHONE, personalObject } from"./personal.ts";import { Store } from"../src/store.ts";import OLD_ALBUM from"./fixtures/music-old/music_album.json";import OLD_ARTIST from"./fixtures/music-old/artist.json";import OLD_CINEMAS from"./fixtures/cinemas-old/cinemas.json";typeDoc = Record<string, unknown>;typeDefs = { tools: Doc[]; boards: Doc[]; tables: Doc[] };/** Every table holds rows: a pass stays add-only. */const HELD = (): number => 1;/** The kit last laid these tables' looks, so a held look that differs is the person's edit. */const lookLaidAs = (...tables: Doc[]): Record<string, string> => Object.fromEntries(tables.map((t) => [String(t.id), lookStamp(t)]));const ids = (docs: Doc[]): string[] => docs.map((d) => String(d.id)).sort();/** The kit as an object is made from and kept to: without the tables and tools held as retired (src/retired.ts `served`). */const SERVED = served(PERSONAL);const { own: PERSONAL_TOOLS, boards: KIT_BOARDS } = PERSONAL;const KIT_TOOLS = SERVED.tools;/** The kit's tables as an object keeps them: through the seal rule (src/business.ts `KIT`). */const PERSONAL_TABLES = SERVED.tables.map(ruled);/** Every table the kit still lists, retired ones included: the shipped definitions the pure keep is tried on. */const LISTED_TABLES = PERSONAL.tables.map(ruled);const SHELL_BOARDS = KITS["shell"]!.boards.map((b) => String(b.id));const KIT: Kit = { own: PERSONAL_TOOLS, tools: KIT_TOOLS, boards: KIT_BOARDS, tables: PERSONAL_TABLES, shell: SHELL_BOARDS };/** The object's meta value under `key`, read in place. */asyncfunction meta(slug: string, key: string): Promise<string | null> {const stub = env.BUSINESS.get(env.BUSINESS.idFromName(slug));return runInDurableObject(stub, (_instance, state) => {const row = state.storage.sql.exec<{ value: string }>("SELECT value FROM meta WHERE key = ?", key).toArray()[0];return row ? row.value : null; });}/** As if a later Worker shipped another kit: the object's kit version is not this one. */asyncfunction olderKit(slug: string): Promise<void> {const stub = env.BUSINESS.get(env.BUSINESS.idFromName(slug));await runInDurableObject(stub, (_instance, state) => { state.storage.sql.exec("UPDATE meta SET value = 'an-older-kit' WHERE key = ?", KIT_VERSION); });}/** * An object made before the kit (the owner's): its own Home edited, the * package's own tool and an edited Todos, most tables (Books' book edited, * short of a column and holding one row, so it stays add-only), and no * record of a kit — only the package's old stamp. * The Home goes first: an object takes no kit until it holds tables. */asyncfunction oldObject(slug: string): Promise<void> { expect((await http(slug, "PUT", "/v1/admin/business", { name: "Personal", kind: "personal", owner_phone: OWNER_PHONE, database_id: DATABASE_ID, timezone: "Asia/Kolkata" }, ADMIN)).status).toBe(200);const kitHome = KIT_BOARDS.find((b) => b.id === "home")!;const home = { ...kitHome, picture: "object-edited", parts: [{ kind: "device" }, ...(kitHome.parts asDoc[])] }; expect((await http(slug, "POST", "/v1/admin/definitions/boards", { boards: [home, OLD_SETTINGS] }, ADMIN)).status).toBe(200);const todos = { ...KIT_TOOLS.find((t) => t.id === "todos")!, name: "My todos" };const tables = PERSONAL_TABLES.filter((t) => !["film", "watch", "highlight"].includes(String(t.id))).map((t) => t.id === "book" ? { ...t, name: "My book", columns: (t.columns asDoc[]).filter((c) => c.key !== "pages") } : t, ); expect((await http(slug, "PUT", "/v1/admin/definitions", { tools: [...PERSONAL_TOOLS, todos], tables, flavour: { flavour: "personal" } }, ADMIN)).status).toBe(200);const stub = env.BUSINESS.get(env.BUSINESS.idFromName(slug));await runInDurableObject(stub, (_instance, state) => { state.storage.sql.exec("INSERT INTO meta (key, value) VALUES ('package_stamp', 'an-old-package') ON CONFLICT (key) DO UPDATE SET value = excluded.value");const at = "2026-11-04T06:00:00.000Z"; state.storage.sql.exec("INSERT INTO rows (table_id, id, data, owner, version, deleted, created_at, updated_at) VALUES ('book', 'b1', ?, NULL, 1, 0, ?, ?)", JSON.stringify({ title: "The Lantern Orchard" }), at, at); });}/** * The settings board as an older kit laid it: no Backup or Cotton server, * and a row a person added at its end. */const OLD_SETTINGS: Doc = (() => {const kitSettings = KIT_BOARDS.find((b) => b.id === "settings")!;return { ...kitSettings, parts: (kitSettings.parts asDoc[]).map((part) =>Array.isArray(part.rows) ? { ...part, heading: "An older heading", rows: [...(part.rows asDoc[]).filter((r) => r.id !== "backup" && r.id !== "server"), { id: "invented-row", data: { name: "An invented row", route: "/about" } }] } : part, ), };})();describe("offered faces and their owned choice rows", () => { it("brings offers as the build's whole card and adds the settings table whole", () => {const person = PERSONAL_TABLES.find(t => t.id === "book")!;const settings = PERSONAL_TABLES.find(t => t.id === "face_settings")!;const result = grown([{ ...person, card: { face: "person" }, name: "Edited" }], [person, settings], HELD, lookLaidAs(person)); expect(result.tables.find(t => t.id === "book")?.card).toEqual(person.card); expect(result.tables.find(t => t.id === "book")?.name).toBe("Edited"); expect(result.tables.find(t => t.id === "face_settings")).toEqual(settings); });});describe("an object brought to an older kit, or to none", () => {const SLUG = "kit-keep-old"; it("takes every kit tool, board and table it lacks, and keeps its edited ones", async () => {await oldObject(SLUG);const defs = (await http<Defs>(SLUG, "GET", "/v1/definitions", undefined, ADMIN)).body; expect(ids(defs.tools)).toEqual(ids([...PERSONAL_TOOLS, ...KIT_TOOLS])); expect(defs.tools.find((t) => t.id === "todos")!.name, "a person's edit to a tool stands").toBe("My todos");for (const manifest of KIT_MANIFESTS.filter((m) => m.id !== "todos")) expect(defs.tools.find((t) => t.id === manifest.id)).toEqual(manifest); expect(ids(defs.boards)).toEqual(ids(KIT_BOARDS));const home = defs.boards.find((b) => b.id === "home")!;const kitHome = KIT_BOARDS.find((b) => b.id === "home")!; expect((home.parts asDoc[]).map((part) => part.kind), "Home is a shell screen: the kit's parts, no device part").toEqual((kitHome.parts asDoc[]).map((part) => part.kind)); expect(home.picture, "the kit's, over an older edit").toEqual(kitHome.picture);const settings = defs.boards.find((b) => b.id === "settings")!;const rows = ((settings.parts asDoc[]).find((part) => Array.isArray(part.rows))!.rows asDoc[]).map((r) => String(r.id)); expect(rows.slice(0, 2), "an existing object's Settings leads with Backup and Cotton server").toEqual(["backup", "server"]); expect(rows.at(-1), "a row a person added is kept, after the kit's").toBe("invented-row");for (const id of ["film", "watch", "highlight"]) expect(defs.tables.find((t) => t.id === id), id).toEqual(PERSONAL_TABLES.find((t) => t.id === id));const book = defs.tables.find((t) => t.id === "book")!;const kitBook = PERSONAL_TABLES.find((t) => t.id === "book")!; expect(lookOf(book), "no record of a look the kit laid: the kit's look, over the held one").toEqual(lookOf(kitBook)); expect((book.columns asDoc[]).at(-1)?.key, "a column it lacks is added after its own").toBe("pages"); expect(await meta(SLUG, KIT_VERSION)).toBe(kitVersion(KIT)); expect(await meta(SLUG, "package_stamp"), "the package's stamp is the kit's now").toBeNull(); }); it("changes nothing and moves no version on a second pass", async () => {const before = (await http<{ version: number }>(SLUG, "GET", "/v1/admin/export?limit=1", undefined, ADMIN)).body.version;const defs = (await http<Defs>(SLUG, "GET", "/v1/definitions", undefined, ADMIN)).body;await olderKit(SLUG);const again = (await http<{ version: number }>(SLUG, "GET", "/v1/admin/export?limit=1", undefined, ADMIN)).body; expect(again.version).toBe(before); expect((await http<Defs>(SLUG, "GET", "/v1/definitions", undefined, ADMIN)).body).toEqual(defs); expect(await meta(SLUG, KIT_VERSION)).toBe(kitVersion(KIT)); }); it("does not bring back a tool the person removed, and lays a removed shell board again", async () => {const defs = (await http<Defs>(SLUG, "GET", "/v1/definitions", undefined, ADMIN)).body; expect((await http(SLUG, "PUT", "/v1/admin/definitions", { tools: defs.tools.filter((t) => t.id !== "books"), tables: defs.tables }, ADMIN)).status).toBe(200);const stub = env.BUSINESS.get(env.BUSINESS.idFromName(SLUG));await runInDurableObject(stub, (_instance, state) => { state.storage.sql.exec("DELETE FROM definitions WHERE id = 'board:tools'"); });await olderKit(SLUG);const after = (await http<Defs>(SLUG, "GET", "/v1/definitions", undefined, ADMIN)).body; expect(after.tools.some((t) => t.id === "books")).toBe(false); expect(after.boards.find((b) => b.id === "tools"), "a shell board is the app's screen").toEqual(KIT_BOARDS.find((b) => b.id === "tools")); }); it("says the kit version in the admin export", async () => {const exported = (await http<{ kit_version: string }>(SLUG, "GET", "/v1/admin/export?limit=1", undefined, ADMIN)).body; expect(exported.kit_version).toBe(kitVersion(KIT)); });/** RULE (5 Nov 2026): the owner's object held the Books tool as the kit laid it weeks before; the next keep brings the kit's Books whole, and an edited Todos stands. */ it("brings the kit's tool whole over one held as the kit last laid it, and records what it laid", async () => {const kitBooks = KIT_TOOLS.find((t) => t.id === "books")!;const oldBooks = { id: "books", name: "Books", tables: ["book"], views: ["reading", "to_read", "read", "all"].map((id) => ({ id, read: { table: "book" } })) };const stub = env.BUSINESS.get(env.BUSINESS.idFromName(SLUG));await runInDurableObject(stub, (_instance, state) => {const laid = JSON.parse(state.storage.sql.exec<{ value: string }>("SELECT value FROM meta WHERE key = ?", KIT_LAID_TOOLS).one().value) asRecord<string, Doc>; state.storage.sql.exec("UPDATE meta SET value = ? WHERE key = ?", JSON.stringify({ ...laid, books: oldBooks }), KIT_LAID_TOOLS); state.storage.sql.exec("INSERT INTO definitions (id, kind, json) VALUES ('tool:books', 'tool', ?)", JSON.stringify(oldBooks)); });await olderKit(SLUG);const defs = (await http<Defs>(SLUG, "GET", "/v1/definitions", undefined, ADMIN)).body; expect(defs.tools.find((t) => t.id === "books"), "unedited since the kit laid it: the kit's").toEqual(kitBooks); expect(defs.tools.find((t) => t.id === "todos")!.name, "edited since the kit laid it: the person's").toBe("My todos");const laid = JSON.parse((await meta(SLUG, KIT_LAID_TOOLS))!) asRecord<string, Doc>; expect(laid["books"], "what the kit laid now is its current tool").toEqual(kitBooks); });});describe("a Home the phone edited, on the next kit", () => {const SLUG = "kit-keep-home-edit"; it("keeps the person's Home through a keep pass, and records the Home the kit laid", async () => {const { credential } = await personalObject(SLUG);const auth = { authorization: `Bearer ${credential}` };const served = (await http<Defs>(SLUG, "GET", "/v1/definitions", undefined, auth)).body.boards.find((b) => b.id === "home")!; expect(JSON.parse((await meta(SLUG, KIT_LAID))!).home, "the kit's Home is recorded as laid").toEqual(KIT_BOARDS.find((b) => b.id === "home"));const edited = { ...served, picture: "object-synthetic" }; expect((await http(SLUG, "POST", "/v1/act", { act: "definition", args: { kind: "board", definition: edited, base: served } }, auth)).status).toBe(200);await olderKit(SLUG);const home = (await http<Defs>(SLUG, "GET", "/v1/definitions", undefined, auth)).body.boards.find((b) => b.id === "home")!; expect(home.picture, "the person's Home stands over the kit's").toBe("object-synthetic"); expect(await meta(SLUG, KIT_VERSION)).toBe(kitVersion(KIT)); });});/** * RULE (coordinator, 5 Nov 2026, KEEP_RULE 11): 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 held. A held table's look the person never edited is now * the kit's whole; storage stays the table's; an edited look stays, said once * in the keep's notices. */describe("a stale table look on an object, on the next kit", () => {const SLUG = "kit-keep-look";const kitBook = PERSONAL_TABLES.find((t) => t.id === "book")!;/** The book as the kit laid it before Books' doors (c2682a0ed6): one "Find a book" field, "No books yet". */const staleBook: Doc = { ...kitBook, create: { label: "Find a book", act: { name: "find_book", argument: "query" } }, empty: { title: "No books yet", message: "Share a book in, or find one by name." }, };const doorsOf = (book: Doc): string[] => (((book.create asDoc | undefined)?.doors asDoc[] | undefined) ?? []).map((d) => String(d.id)); it("lays the kit's look over the book the kit last laid, keeps its storage, and moves the definitions' etag", async () => {await personalObject(SLUG); expect(JSON.parse((await meta(SLUG, KIT_LAID_TABLES))!), "each kit table's look is recorded as laid").toEqual(laidLooksBy(KIT));const stub = env.BUSINESS.get(env.BUSINESS.idFromName(SLUG));await runInDurableObject(stub, (_instance, state) => { state.storage.sql.exec("UPDATE definitions SET json = ? WHERE id = 'table:book'", JSON.stringify(staleBook));const laid = JSON.parse(state.storage.sql.exec<{ value: string }>("SELECT value FROM meta WHERE key = ?", KIT_LAID_TABLES).one().value) asRecord<string, string>; state.storage.sql.exec("UPDATE meta SET value = ? WHERE key = ?", JSON.stringify({ ...laid, book: lookStamp(staleBook) }), KIT_LAID_TABLES);const at = "2026-11-05T06:00:00.000Z"; state.storage.sql.exec("INSERT INTO rows (table_id, id, data, owner, version, deleted, created_at, updated_at) VALUES ('book', 'b1', ?, NULL, 1, 0, ?, ?)", JSON.stringify({ title: "The Lantern Orchard" }), at, at); });const before = await http<Defs & { etag: string }>(SLUG, "GET", "/v1/definitions", undefined, ADMIN); expect(doorsOf(before.body.tables.find((t) => t.id === "book")!), "the stale look is what the object holds").toEqual([]);await olderKit(SLUG);const after = await http<Defs & { etag: string }>(SLUG, "GET", "/v1/definitions", undefined, ADMIN);const book = after.body.tables.find((t) => t.id === "book")!; expect(doorsOf(book), "Plus opens the kit's doors").toEqual(["find", "file", "folder", "goodreads"]); expect((book.empty asDoc).title).toBe("A place for your next book."); expect(book, "the kit's book whole: its storage was the kit's too").toEqual(kitBook); expect(after.body.etag, "a phone pulls the new look on its next pass").not.toBe(before.body.etag); expect(JSON.parse((await meta(SLUG, KIT_LAID_TABLES))!).book, "what the kit laid now is its current look").toBe(lookStamp(kitBook)); expect(JSON.parse((await meta(SLUG, "kit_notices"))!)).toEqual([]); }); it("keeps a look the person edited through the definition act, says so, and a second keep changes nothing", async () => {const { credential } = await personalObject(SLUG);const auth = { authorization: `Bearer ${credential}` };const served = (await http<Defs>(SLUG, "GET", "/v1/definitions", undefined, auth)).body.tables.find((t) => t.id === "book")!;const edited = { ...served, name: "Volume", empty: { title: "Nothing on the shelf." } };const wrote = await http(SLUG, "POST", "/v1/act", { act: "definition", args: { kind: "table", definition: edited, base: served } }, auth); expect(wrote.status, JSON.stringify(wrote.body)).toBe(200);await olderKit(SLUG);const book = (await http<Defs>(SLUG, "GET", "/v1/definitions", undefined, auth)).body.tables.find((t) => t.id === "book")!; expect(book.name, "the person's look stands over the kit's").toBe("Volume"); expect(book.empty).toEqual({ title: "Nothing on the shelf." }); expect({ columns: book.columns, commands: book.commands, card: book.card }, "storage untouched").toEqual({ columns: kitBook.columns, commands: kitBook.commands, card: kitBook.card });const exported = (await http<{ kit_notices: string[]; version: number }>(SLUG, "GET", "/v1/admin/export?limit=1", undefined, ADMIN)).body; expect(exported.kit_notices, "the keep says it kept the person's look").toEqual([expect.stringContaining('table "book": the person\'s look is kept over the kit\'s (empty, name)')]); expect(JSON.parse((await meta(SLUG, KIT_LAID_TABLES))!).book, "told from the look the kit last laid").toBe(lookStamp(kitBook));const defs = (await http<Defs>(SLUG, "GET", "/v1/definitions", undefined, auth)).body;await olderKit(SLUG); expect((await http<Defs>(SLUG, "GET", "/v1/definitions", undefined, auth)).body, "a second keep changes nothing").toEqual(defs); expect((await http<{ version: number }>(SLUG, "GET", "/v1/admin/export?limit=1", undefined, ADMIN)).body.version).toBe(exported.version); });});describe("the links index on a definitions change", () => {const SLUG = "kit-keep-links";/** The links index of the event and person_note tables (the owner's own person and handle are indexed beside them), each entry "table id column → target". */asyncfunction links(): Promise<string[]> {const stub = env.BUSINESS.get(env.BUSINESS.idFromName(SLUG));return runInDurableObject(stub, (_instance, state) => state.storage.sql .exec<{ table_id: string; id: string; column: string; target: string }>("SELECT table_id, id, column, target FROM links WHERE table_id IN ('event', 'person_note') ORDER BY table_id, id, column") .toArray() .map((l) => `${l.table_id} ${l.id} ${l.column} → ${l.target}`), ); }/** The kit's event table with its picture's photo `as` the given type. */const eventWith = (as: "text" | "link" | null): Doc => {const event = PERSONAL_TABLES.find((t) => t.id === "event")!;const columns = (event.columns asDoc[]).flatMap((c) => (c.key !== "picture_photo_id" ? [c] : as === null ? [] : as === "link" ? [c] : [{ key: c.key, label: c.label, type: "text" }]));// The seal names only columns the table has.const seal = event.seal as { clear: string[] } | undefined;return { ...event, columns, ...(seal && as === null ? { seal: { ...seal, clear: seal.clear.filter((k) => k !== "picture_photo_id") } } : {}) }; }; it("indexes the link a kit brings, from the rows that hold it, and leaves every other table's links as they stand", async () => {// An object held at a kit whose event had no picture yet; a copy wrote one in. expect((await http(SLUG, "PUT", "/v1/admin/business", { name: "Personal", kind: "personal", owner_phone: OWNER_PHONE, database_id: DATABASE_ID, timezone: "Asia/Kolkata" }, ADMIN)).status).toBe(200);const tables = PERSONAL_TABLES.map((t) => (t.id === "event" ? eventWith(null) : t)); expect((await http(SLUG, "PUT", "/v1/admin/definitions", { tools: PERSONAL_TOOLS, tables, flavour: { flavour: "personal" } }, ADMIN)).status).toBe(200);const stub = env.BUSINESS.get(env.BUSINESS.idFromName(SLUG));await runInDurableObject(stub, (_instance, state) => {const at = "2026-10-29T06:00:00.000Z"; state.storage.sql.exec("INSERT INTO rows (table_id, id, data, owner, version, deleted, created_at, updated_at) VALUES ('event', 'e1', ?, NULL, 1, 0, ?, ?)", JSON.stringify({ title: "Evening run", starts_at: "2026-11-02", picture_photo_id: "photo-1" }), at, at);// An entry no rebuild of the index would make: it stands only while the index is never rebuilt whole. state.storage.sql.exec("INSERT INTO links (table_id, id, column, target) VALUES ('person_note', 'n1', 'person_id', 'p1')"); });await olderKit(SLUG);// The next request brings the kit: its event's picture is a link, and only that column is indexed. expect((await http<Defs>(SLUG, "GET", "/v1/definitions", undefined, ADMIN)).body.tables.find((t) => t.id === "event")!.columns).toEqual(eventWith("link").columns); expect(await meta(SLUG, KIT_VERSION)).toBe(kitVersion(KIT)); expect(await links()).toEqual(["event e1 picture_photo_id → photo-1", "person_note n1 person_id → p1"]); }); it("drops the links of a column that is no longer a link, and leaves the rest", async () => { expect((await http(SLUG, "POST", "/v1/admin/definitions/tables", { tables: [eventWith("text")] }, ADMIN)).status).toBe(200); expect(await links()).toEqual(["person_note n1 person_id → p1"]); expect((await http(SLUG, "POST", "/v1/admin/definitions/tables", { tables: [eventWith("link")] }, ADMIN)).status).toBe(200); expect(await links()).toEqual(["event e1 picture_photo_id → photo-1", "person_note n1 person_id → p1"]); });});describe("what a kit brings", () => {const kit: Kit = { own: [{ id: "personal", tables: ["a", "b"] }], tools: [{ id: "t1", name: "One" }, { id: "t2", name: "Two" }], boards: [{ id: "home", parts: [] }], tables: [ { id: "a", columns: [{ key: "x" }, { key: "y" }] }, { id: "b", columns: [] }, ], shell: [], };/** The kit last laid these tools as they now ship, so a held one that differs is the person's edit. */const laidAs = (...tools: Doc[]): Record<string, Doc> => Object.fromEntries(tools.map((t) => [String(t.id), t])); it("lays a shell board's kit version over the held one, keeping a row only the held list names at the end", () => {const shipped = { id: "settings", parts: [{ kind: "list", table: "settings", heading: null, rows: [{ id: "backup" }, { id: "server" }, { id: "about", data: { name: "About" } }] }] };const held = { id: "settings", picture: "mine", parts: [{ kind: "device" }, { kind: "list", table: "settings", heading: "Old", rows: [{ id: "about", data: { name: "Old about" } }, { id: "mine" }] }] };const shellKit: Kit = { ...kit, boards: [shipped], shell: ["settings"] };const { docs } = brought({ tool: kit.own, board: [held], table: kit.tables }, shellKit, HELD, givenBy(shellKit)); expect(docs.board).toEqual([{ id: "settings", parts: [{ kind: "list", table: "settings", heading: null, rows: [{ id: "backup" }, { id: "server" }, { id: "about", data: { name: "About" } }, { id: "mine" }] }] }]); expect(shellBoard(undefined, shipped), "a shell board not held comes whole").toEqual(shipped); expect(brought({ tool: kit.own, board: [shellBoard(held, shipped)], table: kit.tables }, shellKit, HELD, givenBy(shellKit)).docs.board, "and a second pass changes nothing").toEqual([]); }); it("keeps a shell board the person edited since the kit last laid it, and lays the kit over one they did not", () => {const lastKit = { id: "home", picture: "object-person", parts: [{ kind: "head" }, { kind: "tools", size: "large" }] };const newKit = { id: "home", picture: "object-person", parts: [{ kind: "head" }, { kind: "today" }, { kind: "tools", size: "large" }] };const shellKit: Kit = { ...kit, boards: [newKit], shell: ["home"] };const pass = (home: Doc) => brought({ tool: kit.own, board: [home], table: kit.tables }, shellKit, HELD, givenBy(shellKit), { home: lastKit });const edited = { ...lastKit, parts: [{ kind: "head" }, { kind: "tools", size: "small" }] };const kept = pass(edited); expect(kept.docs.board, "an edited Home stays as the person left it").toEqual([]); expect(kept.laid.home, "the kit's Home of this pass is recorded").toEqual(newKit); expect(brought({ tool: kit.own, board: [edited], table: kit.tables }, shellKit, HELD, givenBy(shellKit), kept.laid).docs.board, "and stays edited on the next pass").toEqual([]); expect(pass({ ...lastKit, parts: [{ kind: "head" }, { kind: "tools", size: "large", empty: ["books"] }] }).docs.board, "Home as served, with the tools the object works out as empty, is not an edit").toEqual([newKit]); expect(pass(lastKit).docs.board, "an unedited Home follows the kit").toEqual([newKit]); expect(pass(lastKit).laid.home).toEqual(newKit); }); it("leaves a board the shell kit does not own as the add-only merge leaves it", () => {const held = { id: "home", picture: "mine", parts: [{ kind: "device" }] };const { docs } = brought({ tool: kit.own, board: [held], table: kit.tables }, kit, HELD, givenBy(kit)); expect(docs.board).toEqual([]); }); it("adds what was never given, the package's tables as the package grows them, and keeps what is held as it is", () => {const held = { tool: [{ id: "personal", tables: ["a"] }, { id: "t1", name: "Mine" }], board: [], table: [{ id: "a", name: "Edited", columns: [{ key: "x", name: "X!" }] }] };const { docs, given } = brought(held, kit, HELD, null, {}, {}, lookLaidAs(...kit.tables)); expect(docs.tool).toEqual([{ id: "personal", tables: ["a", "b"] }, { id: "t2", name: "Two" }]); expect(docs.board).toEqual([{ id: "home", parts: [] }]); expect(docs.table).toEqual([{ id: "a", name: "Edited", columns: [{ key: "x", name: "X!" }, { key: "y" }] }, { id: "b", columns: [] }]); expect(given).toEqual({ tool: ["personal", "t1", "t2"], board: ["home"] }); }); it("brings back no tool or board it gave that is no longer held", () => {const { docs } = brought({ tool: [{ id: "personal", tables: ["a", "b"] }], board: [], table: kit.tables }, kit, HELD, givenBy(kit)); expect(docs).toEqual({ tool: [], board: [], table: [] }); }); it("removes cards dropped by the kit while keeping the owner's tool and view edits", () => {const views = ["past", "future", "banks", "cards"].map((id) => ({ id, name: `My ${id}`, read: { table: "mine" }, card: { face: "transaction" } }));const held = { id: "money", name: "My money", instructions: "Mine", views };const shipped = { id: "money", name: "Money", views: views.map(({ id }) => ({ id, name: id, read: { table: "transaction" } })) };const nextKit = { ...kit, tools: [shipped] };const result = brought({ tool: [held], board: kit.boards, table: kit.tables }, nextKit, HELD, givenBy(nextKit), {}, laidAs(shipped));const expected = { ...held, views: views.map(({ card: _card, ...view }) => view) }; expect(result.docs.tool).toEqual([kit.own[0], expected]); expect(held.views[0]!.card).toEqual({ face: "transaction" }); expect(brought({ tool: [kit.own[0]!, expected], board: kit.boards, table: kit.tables }, nextKit, HELD, result.given, {}, result.laidTools).docs.tool).toEqual([]); }); it("takes the kit's whole new view card by id, keeping absent and owner-only views", () => {const privateView = { id: "private", name: "Mine", card: { face: "note" } };const heldView = { id: "all", name: "My books", card: { face: "book", fields: [{ slot: "title", column: "old" }] } };const held = { id: "books", name: "My library", views: [privateView, heldView] };const card = { face: "book.hardback" };const nextKit = { ...kit, tools: [{ id: "books", views: [{ id: "all", name: "All", card }, { id: "new", card }] }] };const result = brought({ tool: [held], board: kit.boards, table: kit.tables }, nextKit, HELD, givenBy(nextKit), {}, laidAs(...nextKit.tools)); expect(result.docs.tool).toEqual([kit.own[0], { ...held, views: [privateView, { ...heldView, card }] }]); });/** RULE (3 Nov 2026): a view reading an engine's table the kit retired is the kit's old view, never the person's: Memories moved off memory_entry onto memory reaches every object. */ it("moves a held tool off a table the kit retired onto the kit's views and tables, keeping the person's own views and keys", () => {const retiredTable = { id: "old_entry", engine: "memory", builtin: true, columns: [{ key: "title" }] };const mine = { id: "mine", label: "Mine", read: { table: "a" } };const held = { id: "memories", name: "My memories", tables: ["old_entry", "a"], views: [{ id: "all", label: "All", read: { table: "old_entry" }, card: { face: "memory" } }, { id: "by_project", read: { table: "old_entry" } }, mine] };const shipped = { id: "memories", name: "Memories", tables: ["memory"], views: [{ id: "all", label: "All", read: { table: "memory", where: { status: "active" } } }, { id: "archived", label: "Archived", read: { table: "memory", where: { status: "archived" } } }] };const nextKit: Kit = { ...kit, tools: [shipped], tables: [...kit.tables, { id: "memory", engine: "memory", columns: [] }] };const heldTables = [...nextKit.tables, retiredTable];const retired = retiredBy(heldTables, nextKit.tables); expect(["old_entry", "a", "memory", "never_held"].map(retired), "an engine's table the kit dropped, alone").toEqual([true, false, false, false]);const result = brought({ tool: [kit.own[0]!, held], board: kit.boards, table: heldTables }, nextKit, HELD, givenBy(nextKit), {}, laidAs(shipped));const moved = { ...held, tables: ["memory", "a"], views: [...shipped.views, mine] }; expect(result.docs.tool).toEqual([moved]); expect(result.docs.table, "the retired table stays held: rows may name it").toEqual([]); expect(brought({ tool: [kit.own[0]!, moved], board: kit.boards, table: heldTables }, nextKit, HELD, result.given, {}, result.laidTools).docs.tool, "and a second pass changes nothing").toEqual([]);const made = { id: "made", columns: [] }; expect(retiredBy([made], nextKit.tables)("made"), "a table the person made is never retired").toBe(false);const onMade = { ...held, tables: ["made"], views: [{ id: "all", read: { table: "made" } }] }; expect(brought({ tool: [kit.own[0]!, onMade], board: kit.boards, table: [...nextKit.tables, made] }, nextKit, HELD, givenBy(nextKit), {}, laidAs(shipped)).docs.tool, "a view the person pointed at their own table stays").toEqual([]); });/** RULE (5 Nov 2026): an unedited held tool is the kit's whole — the owner's object kept the Books tool laid weeks before, which the new Books could not draw. */ it("replaces a held tool the person never edited with the kit's whole, and keeps one they edited", () => {const old = { id: "books", name: "Books", views: [{ id: "reading" }, { id: "to_read" }, { id: "read" }, { id: "all" }] };const shipped = { id: "books", name: "Books", acts: [{ id: "find" }], views: [{ id: "reading" }, { id: "want_to_read" }, { id: "stopped" }, { id: "finished" }, { id: "all" }] };const nextKit: Kit = { ...kit, tools: [shipped] };const held = (tool: Doc) => ({ tool: [kit.own[0]!, tool], board: kit.boards, table: kit.tables });const unedited = brought(held(old), nextKit, HELD, givenBy(nextKit), {}, laidAs(old)); expect(unedited.docs.tool, "held as the kit last laid it: the kit's current tool").toEqual([shipped]); expect(unedited.laidTools, "and the kit's current tool is what it laid").toEqual({ books: shipped });const mine = { ...old, views: [...old.views, { id: "mine", read: { table: "a" } }] }; expect(brought(held(mine), nextKit, HELD, givenBy(nextKit), {}, laidAs(old)).docs.tool, "edited since: held").toEqual([]); expect(brought(held(old), nextKit, HELD, givenBy(nextKit)).docs.tool, "no record, and the kit gave it: the kit's to lay").toEqual([shipped]); expect(brought(held(old), nextKit, HELD, null).docs.tool, "no record, and no kit ever gave it: held").toEqual([]); expect(brought({ ...held(old), tool: [kit.own[0]!] }, nextKit, HELD, givenBy(nextKit), {}, laidAs(old)).docs.tool, "removed: stays removed").toEqual([]); expect(brought(held(shipped), nextKit, HELD, unedited.given, {}, unedited.laidTools).docs.tool, "a second pass changes nothing").toEqual([]);const picked = { ...old, picture: { photo: "photo:mine", object: "tool-mine" } };const kept = brought(held(picked), nextKit, HELD, givenBy(nextKit)).docs.tool; expect(kept, "the kit's tool, with the picture the person picked").toEqual([{ ...shipped, picture: picked.picture }]);const later = { ...shipped, name: "Library" };const again = brought(held(kept[0]!), { ...nextKit, tools: [later] }, HELD, unedited.given, {}, { books: kept[0]! }).docs.tool; expect(again, "and the next kit is laid over it again: what was laid is what the person did not edit").toEqual([{ ...later, picture: picked.picture }]); }); it("takes a table the package keeps under an engine as the package defines it, and adds keys to any other", () => {const held = [ { id: "kit", name: "Mine", columns: [{ key: "x", name: "Edited" }] }, { id: "kept", name: "Old", columns: [{ key: "x", type: "text", readonly: true }, { key: "own", type: "text" }] }, ];const shipped = [ { id: "kit", name: "Shipped", slip: { title: "x" }, columns: [{ key: "x", name: "X" }] }, { id: "kept", name: "Kept", engine: "todos", slip: { title: "x" }, columns: [{ key: "x", type: "date" }, { key: "y", type: "text" }] }, ];const { tables, changed, laidLooks } = grown(held, shipped, HELD, lookLaidAs({ id: "kit", name: "Old" })); expect(changed).toBe(2); expect(tables[0], "a face arrives, what it holds stays").toEqual({ id: "kit", name: "Mine", slip: { title: "x" }, columns: [{ key: "x", name: "Edited" }] }); expect(tables[1], "the engine's table is the package's, and keeps its own column").toEqual({ id: "kept", name: "Kept", engine: "todos", slip: { title: "x" }, columns: [{ key: "x", type: "date" }, { key: "y", type: "text" }, { key: "own", type: "text" }], }); expect(grown(tables, shipped, HELD, laidLooks).changed, "a second look takes nothing").toBe(0); });/** RULE (owner, 4 Nov 2026): named lists on every table a person opens — a table held from before the kit declared its groups takes them, and a stack the owner set on an engineless table stays his. */ it("brings the kit's groups to every held table that lacks them, and keeps an owner's stack", () => {const grouped = PERSONAL_TABLES.filter((t) => t.groups !== undefined);for (const id of ["event", "film", "book", "memory"]) { expect(grouped.map((t) => String(t.id)), id).toContain(id); }const held = grouped.map(({ groups: _groups, ...rest }) => rest);const { tables, changed } = grown(held, grouped, HELD); expect(changed).toBe(grouped.length);for (const t of grouped) expect(tables.find((h) => h.id === t.id)?.groups, String(t.id)).toEqual(t.groups);const film = grouped.find((t) => t.id === "film")!; expect(film.engine ?? null, "film is engineless").toBeNull();const owned = { ...film, groups: { stack: "slips" } }; expect(grown([owned], [film], HELD, lookLaidAs(film)).tables[0]?.groups, "the owner's stack stays").toEqual({ stack: "slips" }); }); it("takes the kit's new card face on an engineless held table", () => {const held = { id: "book", card: { face: "book" }, columns: [{ key: "title", name: "My title" }, { key: "own" }] };const shipped = { id: "book", card: { face: "book.hardback" }, columns: [{ key: "title" }, { key: "pages" }] };const { tables, changed } = grown([held], [shipped], HELD); expect(changed).toBe(1); expect(tables).toEqual([{ ...held, card: shipped.card, columns: [...held.columns, { key: "pages" }] }]); expect(grown(tables, [shipped], HELD).changed).toBe(0); }); it("keeps an owner-edited slip and takes the kit's whole card", () => {const held = { id: "film", slip: { player: "My player" }, card: { face: "film", fields: [{ slot: "title", column: "old" }] }, columns: [] };const shipped = { id: "film", slip: { player: "Shipped player" }, card: { face: "film.vhs" }, columns: [] }; expect(grown([held], [shipped], HELD, lookLaidAs(shipped))).toMatchObject({ tables: [{ ...held, card: shipped.card }], changed: 1 }); });/** RULE (KEEP_RULE 14, e2e rulings R1, 15 Nov 2026): a held table with rows takes the kit's seal block exactly, so a column the kit moves out of `clear` is sealed on an object that already holds the table. */ it("lays the kit's seal block over a held table's", () => {const columns = [{ key: "day", type: "date" }, { key: "title", type: "text" }];const held = { id: "journal_entry", seal: { clear: ["day", "title"] }, columns };const shipped = { id: "journal_entry", seal: { clear: ["day"], blind: ["title"] }, columns };const { tables, changed } = grown([held], [shipped], HELD, lookLaidAs(shipped)); expect({ seal: tables[0]!.seal, changed }).toEqual({ seal: shipped.seal, changed: 1 }); expect(grown(tables, [shipped], HELD, lookLaidAs(shipped)).changed, "a second look takes nothing").toBe(0); }); it("leaves a held card alone when the kit names no card", () => {const held = { id: "book", card: { face: "book" }, columns: [] }; expect(grown([held], [{ id: "book", columns: [] }], HELD)).toMatchObject({ tables: [held], changed: 0 }); });/** RULE (owner, 26 Oct 2026): a text column the kit now keeps as a person link (message_contact's and face's person_id) reaches an object that holds it as text, add-only: only its type moves, its words and rows stay. */ it("links a held text column the kit now keeps as a link, and leaves every other held column as it is", () => {const held = [{ id: "contact", columns: [{ key: "person_id", type: "text", readonly: true, name: "Who" }, { key: "note", type: "text" }] }];const shipped = [{ id: "contact", columns: [{ key: "person_id", type: "link", link_to: "person", readonly: true }, { key: "note", type: "longtext" }] }];const { tables, changed } = grown(held, shipped, HELD); expect(changed).toBe(1); expect(tables[0]).toEqual({ id: "contact", columns: [{ key: "person_id", type: "link", readonly: true, name: "Who", link_to: "person" }, { key: "note", type: "text" }] }); expect(grown(tables, shipped, HELD).changed, "a second look takes nothing").toBe(0); });/** RULE (KEEP_RULE 13, 13 Nov 2026): a held column takes the kit's `until` (a range's first day) and `default` where it says nothing of them, and keeps its own. */ it("gives a held column the kit's until and default where it says nothing of them, and keeps its own", () => {const held = [{ id: "trip", columns: [{ key: "starts", type: "date", name: "From" }, { key: "ends", type: "date" }, { key: "kind", type: "choice", choices: ["ticket", "note"], default: "note" }] }];const shipped = [{ id: "trip", columns: [{ key: "starts", type: "date", until: "ends" }, { key: "ends", type: "date" }, { key: "kind", type: "choice", choices: ["ticket", "note"], default: "ticket" }] }];const { tables, changed } = grown(held, shipped, HELD); expect(changed).toBe(1); expect(tables[0]).toEqual({ id: "trip", columns: [{ key: "starts", type: "date", name: "From", until: "ends" }, { key: "ends", type: "date" }, { key: "kind", type: "choice", choices: ["ticket", "note"], default: "note" }] }); expect(grown(tables, shipped, HELD).changed, "a second look takes nothing").toBe(0); });/** RULE (4 Nov 2026): a column the kit keeps readonly, no person's to edit (a highlight's passage and place), reaches an object that holds it with nothing said of readonly, add-only: it takes readonly and nothing else; one the owner set either way stays. *//** RULE (17 Nov 2026): a column the kit says outright is not readonly, because an act of the table writes it (a film's subtitle_work), stops being readonly on an object that held it readonly; a held readonly column the kit says nothing of stays. */ it("frees a held readonly column the kit says outright is not readonly", () => {const held = [{ id: "film", columns: [{ key: "subtitle_work", type: "choice", readonly: true, hidden: true }, { key: "subtitle_note", type: "text", readonly: true }] }];const shipped = [{ id: "film", columns: [{ key: "subtitle_work", type: "choice", readonly: false, hidden: true }, { key: "subtitle_note", type: "text" }] }];const { tables, changed } = grown(held, shipped, HELD); expect(changed).toBe(1); expect(tables[0]).toEqual({ id: "film", columns: [{ key: "subtitle_work", type: "choice", readonly: false, hidden: true }, { key: "subtitle_note", type: "text", readonly: true }] }); }); it("gives a held column the kit's readonly where it says nothing of it, and keeps one the owner set", () => {const held = [{ id: "highlight", columns: [{ key: "text", type: "longtext", name: "Words" }, { key: "chapter", type: "text", readonly: false }, { key: "note", type: "longtext" }] }];const shipped = [{ id: "highlight", columns: [{ key: "text", type: "longtext", readonly: true, required: true }, { key: "chapter", type: "text", readonly: true }, { key: "note", type: "longtext" }] }];const { tables, changed } = grown(held, shipped, HELD); expect(changed).toBe(1); expect(tables[0]).toEqual({ id: "highlight", columns: [{ key: "text", type: "longtext", name: "Words", readonly: true }, { key: "chapter", type: "text", readonly: false }, { key: "note", type: "longtext" }] }); expect(grown(tables, shipped, HELD).changed, "a second look takes nothing").toBe(0); });/** RULE (5 Nov 2026): a kit table's retired column reaches a held table only once it no longer holds it: a keep is add-only, so a table still holding `notes` keeps it a column, never one both kept and retired. */ it("lays a kit table's retired column only on a held table that no longer holds it", () => {const shipped = [{ id: "film", retired: [{ key: "notes", type: "longtext" }], columns: [{ key: "title", type: "text" }, { key: "review", type: "longtext" }] }];const holding = [{ id: "film", columns: [{ key: "title", type: "text" }, { key: "notes", type: "longtext" }] }];const { tables, changed } = grown(holding, shipped, HELD); expect(changed).toBe(1); expect(tables[0], "notes stays a column, nothing retired yet; review is added").toEqual({ id: "film", columns: [{ key: "title", type: "text" }, { key: "notes", type: "longtext" }, { key: "review", type: "longtext" }] }); expect(grown(tables, shipped, HELD).changed, "a second look takes nothing").toBe(0);const without = [{ id: "film", columns: [{ key: "title", type: "text" }] }]; expect(grown(without, shipped, HELD).tables[0]!.retired, "a held table without the column takes the entry").toEqual([{ key: "notes", type: "longtext" }]);const owned = [{ id: "film", retired: [{ key: "old", type: "text" }], columns: [{ key: "title", type: "text" }] }]; expect(grown(owned, shipped, HELD).tables[0]!.retired, "after the held table's own entries").toEqual([{ key: "old", type: "text" }, { key: "notes", type: "longtext" }]);const engine = [{ ...shipped[0]!, engine: "films" }]; expect(grown(holding, engine, HELD).tables[0], "a table under an engine keeps the held column after the kit's, and so does not retire it").toEqual({ ...engine[0], retired: undefined, columns: [...engine[0]!.columns, { key: "notes", type: "longtext" }] }); });/** RULE (5 Nov 2026): a held choice column takes each choice the kit adds, after its own and with the kit's label, so a card naming the new ones stays a card of the table; no choice it holds is taken. */ it("adds the kit's new choices to a held choice column, keeping every one it holds", () => {const held = [{ id: "film", columns: [{ key: "status", type: "choice", choices: ["watchlist", "watched"], labels: { watchlist: "To watch" } }] }];const shipped = [{ id: "film", columns: [{ key: "status", type: "choice", choices: ["want_to_watch", "watching", "watched"], labels: { want_to_watch: "Want to watch", watching: "Watching", watched: "Watched" } }] }];const { tables, changed } = grown(held, shipped, HELD); expect(changed).toBe(1); expect(tables[0]).toEqual({ id: "film", columns: [{ key: "status", type: "choice", choices: ["watchlist", "watched", "want_to_watch", "watching"], labels: { watchlist: "To watch", want_to_watch: "Want to watch", watching: "Watching" } }] }); expect(grown(tables, shipped, HELD).changed, "a second look takes nothing").toBe(0); }); it("ships the highlight's passage and place readonly and its note the person's", () => {const highlight = PERSONAL_TABLES.find((t) => t.id === "highlight")!;constreadonly = (highlight.columns asDoc[]).filter((c) => c.readonly === true).map((c) => String(c.key));// What a send stamps (sent_by, sent_by_number, sent_at, send_id) is the receiver's record of it, never edited. expect(readonly).toEqual(["text", "locator", "progress", "page_label", "chapter", "made_at", "sent_by", "sent_by_number", "sent_at", "send_id"]); });/** RULE (owner, 27 Oct 2026): every money row carries its account's balance before and after it and whether it overdraws; an account says the day its balance is for and the balance it is known to have held. A held money table takes them on its next request. */ it("ships the money tables' running balance columns, and a held money table takes them", () => {const shipped = (id: string): Doc => LISTED_TABLES.find((t) => t.id === id)!;const keys = (t: Doc): string[] => (t.columns asDoc[]).map((c) => String(c.key)); expect(keys(shipped("transaction"))).toEqual(expect.arrayContaining(["balance_before_minor", "balance_after_minor", "balance_state"])); expect((shipped("transaction").columns asDoc[]).find((c) => c.key === "balance_state")).toMatchObject({ type: "choice", choices: ["ok", "overdrawn", "recovers"], readonly: true }); expect(keys(shipped("money_account"))).toEqual(expect.arrayContaining(["balance_minor", "balance_as_of", "known_balance_minor", "known_balance_on"]));const added = ["balance_before_minor", "balance_after_minor", "balance_state", "balance_as_of", "known_balance_minor", "known_balance_on"];const held = ["transaction", "money_account"].map((id) => ({ ...shipped(id), card: undefined, columns: (shipped(id).columns asDoc[]).filter((c) => !added.includes(String(c.key))) }));const { tables, changed } = grown(held, [shipped("transaction"), shipped("money_account")], HELD); expect(changed).toBe(2); expect(tables).toEqual([shipped("transaction"), shipped("money_account")]); expect(tables[0]?.card).toMatchObject({ face: "transaction.receipt", faces: [{ face: "transaction.cheque" }] }); expect(tables[1]?.card).toMatchObject({ face: "account.statement" }); });/** RULE (owner, 27 Oct 2026): the owner states the balance an account held, from the phone's edit fan or over Cotton MCP; the balance the engine works out stays its own. An account table held with the known balance read only takes it editable. */ it("ships the known balance editable and the worked-out balance read only, and a held account table takes them", () => {const shipped = LISTED_TABLES.find((t) => t.id === "money_account")!;const column = (t: Doc, key: string): Doc => (t.columns asDoc[]).find((c) => c.key === key)!; expect(["known_balance_minor", "known_balance_on"].map((k) => column(shipped, k).readonly ?? false)).toEqual([false, false]); expect(["balance_minor", "balance_as_of"].map((k) => column(shipped, k).readonly)).toEqual([true, true]);const held = { ...shipped, columns: (shipped.columns asDoc[]).map((c) => (String(c.key).startsWith("known_balance_") ? { ...c, readonly: true } : c)) };const { tables, changed } = grown([held], [shipped], HELD); expect(changed).toBe(1); expect(tables).toEqual([shipped]); }); it("reads back what it gave, and stamps a kit by its content", () => { expect(readGiven(null)).toBeNull(); expect(readGiven(JSON.stringify(givenBy(kit)))).toEqual(givenBy(kit)); expect(kitVersion(kit)).toBe(kitVersion(kit)); expect(kitVersion(kit)).not.toBe(kitVersion({ ...kit, tools: [] })); expect(stampOf("a")).not.toBe(stampOf("b")); expect(KIT_GIVEN).toBe("kit_given"); });});describe("the kit's version", () => { it("stamps the merge rule with the kit, so a new rule runs the pass again over the same files", () => { expect(kitVersion(KIT)).toBe(stampOf(`${KEEP_RULE}:${JSON.stringify(KIT)}`)); expect(KEEP_RULE).toBe(16); expect(kitVersion(KIT)).not.toBe(stampOf(`2:${JSON.stringify(KIT)}`)); expect(kitVersion(KIT)).not.toBe(stampOf(JSON.stringify(KIT))); });});// Photos reads the union; its stored photos keep their own detail definition.describe("the Photos union definition", () => { it("adds media whole to an older object and refreshes an imported media card", () => {const photo = PERSONAL_TABLES.find((t) => t.id === "photo")!;const media = PERSONAL_TABLES.find((t) => t.id === "media")!; expect(media.card).toEqual(photo.card); expect(media.tables).toEqual([]); expect(grown([photo], [photo, media], HELD)).toMatchObject({ tables: [photo, media], changed: 1 });const stale = { ...media, card: { face: "photo" }, columns: [] }; expect(grown([photo, stale], [photo, media], HELD)).toMatchObject({ tables: [photo, media], changed: 1 }); expect(KIT_TOOLS.filter((t) => t.id === "photos")).toHaveLength(1); });});/** * RULE (coordinator, 5 Nov 2026, KEEP_RULE 11): a held table whose look the * person never edited takes the kit's look whole. The owner's artist and * music_album (test/fixtures/music-old, copies of the live definitions) held * their old create, empty, page, sort and instructions under an add-only keep. */describe("a held table's look is the kit's unless the person edited it", () => {const old = [OLD_ARTIST, OLD_ALBUM] asDoc[];const shipped = ["artist", "music_album"].map((id) => LISTED_TABLES.find((t) => t.id === id)!);/** What the look rule never touches: the add-only keep's storage, its columns and card. */const storage = (t: Doc): Doc => Object.fromEntries(Object.entries(t).filter(([k]) => !(k in lookOf(t))));/** The keep as it was before the rule: every look held, told as the person's edit. */const addOnly = grown(old, shipped, HELD, lookLaidAs(...old.map((t) => ({ ...t, name: "a look no kit laid" })))).tables; it("lays the kit's look over the look the kit last laid (or over any, with no record), keeps storage, and a second keep changes nothing", () => { expect(old.map((t, i) => lookStamp(t) === lookStamp(shipped[i]!)), "the fixtures' looks are stale").toEqual([false, false]);for (const record of [{}, lookLaidAs(...old)]) {const first = grown(old, shipped, HELD, record); expect(first.changed).toBe(2); expect(first.notices).toEqual([]);for (const [i, t] of first.tables.entries()) { expect(lookOf(t), String(t.id)).toEqual(lookOf(shipped[i]!)); expect(storage(t), `${String(t.id)}: columns, commands, card and identity as the add-only keep leaves them`).toEqual(storage(addOnly[i]!)); } expect(first.laidLooks).toEqual(lookLaidAs(...shipped));const second = grown(first.tables, shipped, HELD, first.laidLooks); expect(second.changed, "a second keep changes nothing").toBe(0); expect(second.notices).toEqual([]); } }); it("keeps a look the person edited since the kit laid it, and says so", () => {const mine = { ...OLD_ARTIST, name: "Musician" } asDoc;const first = grown([mine, OLD_ALBUM asDoc], shipped, HELD, lookLaidAs(...old)); expect(lookOf(first.tables[0]!), "the person's look, with what the kit adds").toEqual(lookOf({ ...addOnly[0]!, name: "Musician" })); expect(first.tables[0]!.create).toEqual(OLD_ARTIST.create); expect(storage(first.tables[0]!)).toEqual(storage(addOnly[0]!)); expect(lookOf(first.tables[1]!), "an unedited table beside it takes the kit's").toEqual(lookOf(shipped[1]!)); expect(first.notices).toEqual([expect.stringMatching(/^table "artist": the person's look is kept over the kit's \(.*\bname\b.*\)/)]); expect(first.laidLooks.artist, "told from the look the kit last laid").toBe(lookStamp(OLD_ARTIST asDoc));const second = grown(first.tables, shipped, HELD, first.laidLooks); expect(second.changed, "a second keep changes nothing").toBe(0); expect(second.notices, "and says it again").toEqual(first.notices);const back = { ...first.tables[0]!, ...lookOf(shipped[0]!) }; expect(grown([back], [shipped[0]!], HELD, first.laidLooks).notices, "a look set back to the kit's is the kit's again").toEqual([]); }); it("removes a look key the kit no longer carries, keeping the held order", () => {const held = { id: "a", name: "A", banner: "old", columns: [{ key: "x" }], commands: [{ id: "c" }], sort: { by: "x" } };const kitA = { id: "a", name: "A2", columns: [{ key: "x" }, { key: "y" }], commands: [{ id: "d" }], empty: { title: "Nothing" } };const { tables } = grown([held], [kitA], HELD); expect(tables).toEqual([{ id: "a", name: "A2", columns: [{ key: "x" }, { key: "y" }], commands: [{ id: "d" }], empty: { title: "Nothing" } }]); expect(Object.keys(tables[0]!)).toEqual(["id", "name", "columns", "commands", "empty"]); });});/** * RULE (coordinator, 5 Nov 2026, KEEP_RULE 12): a held table's commands and * acts are the build's, never a person's (FIXED keys no act or MCP path * writes). The owner's book held 8 commands while the kit's had 12 (rate, * review, find_details, add_file missing): every keep lays them as the kit has them. */describe("a held table's commands and acts are the kit's", () => {const kitBook = PERSONAL_TABLES.find((t) => t.id === "book")!;const ids = (t: Doc, key: "commands" | "acts"): string[] => ((t[key] asDoc[] | undefined) ?? []).map((c) => String(c.id));/** The owner's book: the kit's look, eight of its twelve commands, and an act an older kit had. */const held: Doc = { ...kitBook, commands: (kitBook.commands asDoc[]).filter((c) => !["rate", "review", "find_details", "add_file"].includes(String(c.id))), acts: [{ id: "old_act" }] }; it("lays the kit's commands and acts over fewer, and a second keep changes nothing", () => { expect(ids(held, "commands")).toHaveLength(8);const first = grown([held], [kitBook], HELD, lookLaidAs(kitBook)); expect(ids(first.tables[0]!, "commands"), "the kit's twelve, in its order").toEqual(ids(kitBook, "commands")); expect(first.tables[0]!.acts, "acts as the kit has them").toEqual(kitBook.acts); expect(first.tables[0]!, "the kit's book whole: its look and columns were the kit's already").toEqual(kitBook); expect(first.notices).toEqual([]); expect(grown(first.tables, [kitBook], HELD, first.laidLooks).changed, "a second keep changes nothing").toBe(0);const noActs = { ...kitBook };delete noActs.acts; expect("acts"in grown([held], [noActs], HELD, lookLaidAs(kitBook)).tables[0]!, "an act the kit no longer has is removed").toBe(false); }); it("leaves the look rule as it is: an edited look stays beside the kit's commands", () => {const mine = { ...held, name: "Volume" };const first = grown([mine], [kitBook], HELD, lookLaidAs(kitBook)); expect(first.tables[0]!.name).toBe("Volume"); expect(first.tables[0]!.commands).toEqual(kitBook.commands); expect(first.notices).toEqual([expect.stringContaining('table "book": the person\'s look is kept')]); expect(grown(first.tables, [kitBook], HELD, first.laidLooks).changed, "a second keep changes nothing").toBe(0); }); it("keeps marks bound to a command the kit lays: a kept look's mark on a command gone takes the kit's marks", () => {const kitA = { id: "a", columns: [], commands: [{ id: "done", kind: "update" }], marks: { check: "done" } };const keptLook = { id: "a", name: "Mine", columns: [], commands: [{ id: "tick", kind: "update" }], marks: { check: "tick" } };const first = grown([keptLook], [kitA], HELD, lookLaidAs({ id: "a", columns: [], marks: { check: "tick" } })); expect(first.tables[0]).toEqual({ id: "a", name: "Mine", columns: [], commands: kitA.commands, marks: { check: "done" } }); expect(marksProblem(first.tables[0]!)).toBeNull(); expect(first.notices[1]).toContain("marks named a command the kit no longer lays");for (const t of grown(PERSONAL_TABLES.map((t) => ({ ...t, commands: [] })), PERSONAL_TABLES, HELD).tables) expect(marksProblem(t), String(t.id)).toBeNull(); });});/** RULE (coordinator, 4 Nov 2026): a kit may reshape a table the object holds no rows in; a table with a row stays add-only. */describe("an empty table is the kit's to reshape", () => {const held = { id: "book", name: "Book", columns: [ { key: "title", type: "text" }, { key: "status", type: "choice", choices: ["to_read", "reading", "read"] }, { key: "quote", type: "longtext" }, ], commands: [{ id: "old", label: "Old" }], };const shipped = { id: "book", name: "Book", columns: [ { key: "title", type: "text" }, { key: "status", type: "choice", choices: ["want_to_read", "reading", "finished", "stopped"] }, { key: "file", type: "file" }, ], commands: [{ id: "start", label: "Start reading" }], }; it("replaces a table with no rows whole: columns, choices and commands", () => {const { tables, changed } = grown([held], [shipped], () => 0); expect(changed).toBe(1); expect(tables, "the kit's definition, nothing of the held one").toEqual([shipped]); expect(grown(tables, [shipped], () => 0).changed, "a second look takes nothing").toBe(0); }); it("keeps a table with one row add-only: its choices and its columns stand, a new column and the kit's new choices are added, its commands are the kit's", () => {const { tables } = grown([held], [shipped], (id) => (id === "book" ? 1 : 0));const status = { key: "status", type: "choice", choices: ["to_read", "reading", "read", "want_to_read", "finished", "stopped"] }; expect(tables).toEqual([{ ...held, columns: [held.columns[0], status, held.columns[2], { key: "file", type: "file" }], commands: shipped.commands }]); expect((tables[0]!.columns asDoc[]).find((c) => c.key === "status")?.choices, "no held choice is taken; the kit's are added after").toEqual(status.choices); }); it("counts a binned row as a row: the object reshapes only a table it never wrote in", async () => {const slug = "kit-keep-empty";const old = { ...PERSONAL_TABLES.find((t) => t.id === "book")!, name: "Old book", columns: [{ key: "title", name: "Title", type: "text" }, { key: "quote", name: "Quote", type: "longtext" }], seal: null };const setUp = async (rows: "none" | "binned"): Promise<Doc> => { expect((await http(slug, "PUT", "/v1/admin/business", { name: "Personal", kind: "personal", owner_phone: OWNER_PHONE, database_id: DATABASE_ID, timezone: "Asia/Kolkata" }, ADMIN)).status).toBe(200);const tables = PERSONAL_TABLES.map((t) => (t.id === "book" ? old : t)); expect((await http(slug, "PUT", "/v1/admin/definitions", { tools: PERSONAL_TOOLS, tables, flavour: { flavour: "personal" } }, ADMIN)).status).toBe(200);const stub = env.BUSINESS.get(env.BUSINESS.idFromName(slug));await runInDurableObject(stub, (_instance, state) => { state.storage.sql.exec("DELETE FROM rows WHERE table_id = 'book'");if (rows === "binned") {const at = "2026-11-04T06:00:00.000Z"; state.storage.sql.exec("INSERT INTO rows (table_id, id, data, owner, version, deleted, created_at, updated_at) VALUES ('book', 'b1', ?, NULL, 1, 1, ?, ?)", JSON.stringify({ title: "Gone", quote: "kept" }), at, at); } });await olderKit(slug);return (await http<Defs>(slug, "GET", "/v1/definitions", undefined, ADMIN)).body.tables.find((t) => t.id === "book")!; }; expect(await setUp("none"), "no row: the kit's book whole").toEqual(PERSONAL_TABLES.find((t) => t.id === "book"));const kept = await setUp("binned"); expect(kept.name, "a binned row keeps the table add-only, and its look, apart from what the first keep laid, is the person's").toBe("Old book"); expect((kept.columns asDoc[]).map((c) => c.key)).toContain("quote"); });});/** * RULE (owner, 6 Nov 2026): Cinemas drops Continue watching, opens on Films, * and All (the latest added first) takes Recently added's place beside a new * A to Z. An object already brought to the kit Cotton Cinemas 1.0 (2) shipped * with (test/fixtures/cinemas-old, the manifest as it stood) takes the new * views on its next keep — the held tool is unedited since the kit laid it, so * it is the kit's whole (rule 9, no KEEP_RULE change) — and a list of films * stands; one the person edited stays as they left it. */describe("Cinemas held on the views of Cotton Cinemas 1.0 (2), on the next kit", () => {const OLD = OLD_CINEMAS asDoc;const KIT_CINEMAS = KIT_TOOLS.find((t) => t.id === "cinemas")!;const stub = (slug: string) => env.BUSINESS.get(env.BUSINESS.idFromName(slug));const rows = (slug: string, table: string) => runInDurableObject(stub(slug), (_i, state) => newStore(state.storage.sql, () => newDate()).select(table, [], "created_at, id", 10_000).map((r) => ({ id: r.id, data: r.data })));/** The object as the old kit left it: Cinemas held as `held`, the kit having laid the old tool, a film on a list. */asyncfunction onTheOldKit(slug: string, held: Doc): Promise<void> {await personalObject(slug);await runInDurableObject(stub(slug), (_instance, state) => {const row = state.storage.sql.exec<{ value: string }>("SELECT value FROM meta WHERE key = ?", KIT_LAID_TOOLS).toArray()[0];const laid = row ? (JSON.parse(row.value) asRecord<string, Doc>) : {}; state.storage.sql.exec("INSERT INTO meta (key, value) VALUES (?, ?) ON CONFLICT (key) DO UPDATE SET value = excluded.value", KIT_LAID_TOOLS, JSON.stringify({ ...laid, cinemas: OLD })); state.storage.sql.exec("INSERT INTO definitions (id, kind, json) VALUES ('tool:cinemas', 'tool', ?) ON CONFLICT (id) DO UPDATE SET json = excluded.json", JSON.stringify(held));const at = "2026-11-05T18:00:00.000Z";const put = (table: string, id: string, data: Doc) => state.storage.sql.exec("INSERT INTO rows (table_id, id, data, owner, version, deleted, created_at, updated_at) VALUES (?, ?, ?, NULL, 1, 0, ?, ?)", table, id, JSON.stringify(data), at, at); put("film", "f1", { title: "Harbour of Invented Lights", kind: "film", status: "watching", position: 600, position_at: at, added_on: "2026-11-05" }); put("record_group", "g1", { table_id: "film", name: "Invented weekend" }); put("group_member", "m1", { group: "g1", record_id: "f1", place: 1 }); });const before = (await http<Defs>(slug, "GET", "/v1/definitions", undefined, ADMIN)).body.tools.find((t) => t.id === "cinemas"); expect(before, "the object holds the old Cinemas before the keep").toEqual(held);await olderKit(slug); } it("lays the kit's views over the old ones the kit last laid: Films the default, All and A to Z, no Continue watching, Recently added or Watchlist", async () => {const SLUG = "kit-keep-cinemas-old";await onTheOldKit(SLUG, OLD);const defs = (await http<Defs>(SLUG, "GET", "/v1/definitions", undefined, ADMIN)).body;const cinemas = defs.tools.find((t) => t.id === "cinemas")!; expect(cinemas, "unedited since the kit laid it: the kit's whole").toEqual(KIT_CINEMAS);const views = cinemas.views asDoc[];// The view list is the kit's (KIT_CINEMAS, above); only what the keep decides is asserted here. expect(views.map((v) => v.id)).toEqual(expect.arrayContaining(["films", "all", "a_to_z"])); expect(views.filter((v) => v.is_default === true).map((v) => v.id), "it opens on Films").toEqual(["films"]); expect(views.find((v) => v.id === "all")!.sort).toEqual({ column: "added_on", descending: true }); expect(views.find((v) => v.id === "a_to_z")!.sort).toEqual({ column: "title", descending: false }); expect(JSON.stringify(cinemas)).not.toMatch(/"continue"|recently_added|"watchlist"|Continue watching|Recently added|Watchlist/); expect((JSON.parse((await meta(SLUG, KIT_LAID_TOOLS))!) asRecord<string, Doc>)["cinemas"], "what the kit laid now is the new tool").toEqual(KIT_CINEMAS);const lists = (await rows(SLUG, "record_group")).filter((g) => g.data.table_id === "film"); expect(lists.map((g) => [g.id, g.data.name]), "the list of films stands").toEqual([["g1", "Invented weekend"]]); expect((await rows(SLUG, "group_member")).filter((m) => m.data.group === "g1").map((m) => m.data.record_id)).toEqual(["f1"]); expect((await rows(SLUG, "film")).find((f) => f.id === "f1")!.data.position_at, "its resume point stands, for the poster's strip").toBe("2026-11-05T18:00:00.000Z"); }); it("leaves a Cinemas the person edited as they left it", async () => {const SLUG = "kit-keep-cinemas-edited";const edited = { ...OLD, name: "My cinema" };await onTheOldKit(SLUG, edited);const cinemas = (await http<Defs>(SLUG, "GET", "/v1/definitions", undefined, ADMIN)).body.tools.find((t) => t.id === "cinemas")!; expect(cinemas, "edited since the kit laid it: the person's").toEqual(edited); });});/** * RULE (owner, 6 Nov 2026): Cinemas' fan tiles are data — the black felt * letterboard, a pictogram on every tile (`fan_tile`). An object holding the * old Cinemas tool (test/fixtures/cinemas-old, no tile) takes the kit's tile * with the kit's tool on its next keep (rule 9: unedited since the kit laid * it, so the kit's whole; no KEEP_RULE change), and every picture the tile * names is the object's to serve by its reference, from the Worker's own * kit (src/kit_pictures.ts), so a signed-in phone draws a changed pictogram * with the deploy and no new build. A Cinemas the person edited stays as * they left it: no tile is laid on it. */describe("Cinemas takes the letterboard tile on the next kit", () => {const OLD = OLD_CINEMAS asDoc;const KIT_CINEMAS = KIT_TOOLS.find((t) => t.id === "cinemas")!;const TILE = KIT_CINEMAS.fan_tile asRecord<string, unknown>;const stub = (slug: string) => env.BUSINESS.get(env.BUSINESS.idFromName(slug));const photos = (): string[] => {const named = [TILE.stock, ...["pictures", "views", "acts", "doors"].flatMap((part) => Object.values((TILE[part] asRecord<string, unknown>) ?? {}))];return [...newSet(named.map((p) => (p as { photo: string }).photo))]; };const media = (slug: string, credential: string, key: string, method = "GET") => SELF.fetch(`https://example.test/b/${slug}/v1/media/${encodeURIComponent(key)}`, { method, headers: { authorization: `Bearer ${credential}` } });asyncfunction heldAs(slug: string, held: Doc): Promise<string> {const { credential } = await personalObject(slug);await runInDurableObject(stub(slug), (_instance, state) => {const row = state.storage.sql.exec<{ value: string }>("SELECT value FROM meta WHERE key = ?", KIT_LAID_TOOLS).toArray()[0];const laid = row ? (JSON.parse(row.value) asRecord<string, Doc>) : {}; state.storage.sql.exec("INSERT INTO meta (key, value) VALUES (?, ?) ON CONFLICT (key) DO UPDATE SET value = excluded.value", KIT_LAID_TOOLS, JSON.stringify({ ...laid, cinemas: OLD })); state.storage.sql.exec("INSERT INTO definitions (id, kind, json) VALUES ('tool:cinemas', 'tool', ?) ON CONFLICT (id) DO UPDATE SET json = excluded.json", JSON.stringify(held)); });await olderKit(slug);return credential; } it("the kit names a letterboard tile with a stock and a pictogram for every view, door and role", () => { expect(OLD.fan_tile, "the old tool had none").toBeUndefined(); expect(TILE.type).toBe("letterboard"); expect(Object.keys(TILE.views asDoc).sort()).toEqual(((KIT_CINEMAS.views asDoc[]).map((v) => String(v.id))).sort()); expect(Object.keys(TILE.pictures asDoc).sort()).toEqual(["list", "more", "new_list"]); expect(Object.keys(TILE.doors asDoc).sort()).toEqual(["files", "find", "folder"]);for (const act of KIT_CINEMAS.acts asDoc[]) expect((TILE.acts asDoc)[String(act.id)], String(act.id)).toBeDefined(); }); it("lays the tile on a Cinemas the kit laid, and serves every picture it names", async () => {const SLUG = "kit-keep-cinemas-tile";const credential = await heldAs(SLUG, OLD);const cinemas = (await http<Defs>(SLUG, "GET", "/v1/definitions", undefined, ADMIN)).body.tools.find((t) => t.id === "cinemas")!; expect(cinemas.fan_tile, "the kit's tile, with the kit's tool").toEqual(TILE);for (const photo of photos()) {const res = await media(SLUG, credential, photo); expect(res.status, photo).toBe(200); expect(res.headers.get("content-type")).toBe("image/png");const bytes = newUint8Array(await res.arrayBuffer());const digest = [...newUint8Array(await crypto.subtle.digest("SHA-256", bytes))].map((b) => b.toString(16).padStart(2, "0")).join(""); expect(`photo:${digest}`, "the bytes are the picture the reference names").toBe(photo); } expect((await media(SLUG, credential, photos()[0]!, "HEAD")).status).toBe(200); expect((await media(SLUG, credential, `photo:${"0".repeat(64)}`)).status, "a picture no kit carries is no key of this database").toBe(404); expect((await SELF.fetch(`https://example.test/b/${SLUG}/v1/media/${encodeURIComponent(photos()[0]!)}`)).status, "the owner's alone").toBe(403); }); it("lays no tile on a Cinemas the person edited", async () => {const SLUG = "kit-keep-cinemas-tile-edited";const edited = { ...OLD, name: "My cinema" };await heldAs(SLUG, edited);const cinemas = (await http<Defs>(SLUG, "GET", "/v1/definitions", undefined, ADMIN)).body.tools.find((t) => t.id === "cinemas")!; expect(cinemas, "edited since the kit laid it: the person's, with no tile").toEqual(edited); });});