Cotton code
543 lines · 35.5 KB · TypeScriptRaw
/** * Books in the object (src/books.ts): Start reading and Finished stamp the * database's own day, find_book asks Open Library (a fetch stubbed here) and * fills only empty columns, and a Goodreads export comes in by header name, * found again by its Goodreads id. Every title, author and ISBN is invented; * the export is test/fixtures/books/goodreads_library_export.csv. */import { env, runInDurableObject } from "cloudflare:test";import { describe, expect, it } from "vitest";import type { Fetcher } from "../src/artwork.ts";import { BOOK_SOURCES, csvRows, isbnOf, LOOKUP_WAIT_MS, NOT_ANSWERING, readExport, USER_AGENT } from "../src/books.ts";import { grown } from "../src/kit_keep.ts";import { PERSONAL } from "../src/kits.ts";import type { Business } from "../src/business.ts";import { localDate } from "../src/protocol.ts";import { Store } from "../src/store.ts";import { derivedId } from "../src/import/ids.ts";import { bodyAad } from "../src/seal.ts";import { openArrivalRow } from "./arrival_keys.ts";import { sealRow } from "./seal-device.ts";import { DATABASE_ID, answer, http, personalObject, refusal, BOOKS_OPEN } from "./personal.ts";import EXPORT from "./fixtures/books/goodreads_library_export.csv?raw";import FILLED_FROM_LIST from "../../../crates/cotton-core/tests/fixtures/book_filled_from.json";const stub = (slug: string) => env.BUSINESS.get(env.BUSINESS.idFromName(slug));const JPEG = Uint8Array.from(atob("/9j/4AAQSkZJRgABAQEASABIAAD/2wBDAP//////////////////////////////////////////////////////////////////////////////////////wgALCAABAAEBAREA/8QAFBABAAAAAAAAAAAAAAAAAAAAAP/aAAgBAQABPxA="), (c) => c.charCodeAt(0));const today = (): string => localDate(new Date(), "Asia/Kolkata");type Row = { id: string; data: Record<string, unknown> };async function act(slug: string, credential: string, name: string, args: Record<string, unknown>) {  return http<Record<string, unknown>>(slug, "POST", "/v1/act", { act: name, args }, { authorization: `Bearer ${credential}` });}async function rows(slug: string, table: string): Promise<Row[]> {  return runInDurableObject(stub(slug), (_i, state) => new Store(state.storage.sql, () => new Date()).select(table, [], "created_at, id", 10_000).map((r) => ({ id: r.id, data: r.data })));}async function book(slug: string, id: string): Promise<Record<string, unknown>> {  const found = (await rows(slug, "book")).find((r) => r.id === id);  expect(found, id).toBeDefined();  return found!.data;}type Answer = { json: unknown } | { status: number } | { bytes: Uint8Array } | { text: string } | { throws: true };/** Open Library, stubbed: each URL prefix answered — by the next of its answers while it has more than one, its last after — every request kept. */function openLibrary(answers: [string, Answer | Answer[]][]): { fetch: Fetcher; asked: { url: string; agent: string | null }[] } {  const asked: { url: string; agent: string | null }[] = [];  const queues = answers.map(([prefix, given]) => [prefix, Array.isArray(given) ? [...given] : [given]] as const);  return {    asked,    fetch: async (url, init) => {      asked.push({ url, agent: new Headers(init?.headers).get("user-agent") });      const queue = queues.find(([prefix]) => url.startsWith(prefix))?.[1];      if (!queue) return new Response("not stubbed", { status: 599 });      const hit = queue.length > 1 ? queue.shift()! : queue[0]!;      if ("throws" in hit) throw new TypeError("network connection lost");      if ("json" in hit) return Response.json(hit.json);      if ("bytes" in hit) return new Response(hit.bytes, { headers: { "content-type": "image/jpeg" } });      if ("text" in hit) return new Response(hit.text, { headers: { "content-type": "text/html" } });      return new Response(`error code: ${hit.status}`, { status: hit.status });    },  };}/** The waits find_book took before asking again, in milliseconds. */let waited: number[] = [];async function given(slug: string, fetch: Fetcher): Promise<void> {  waited = [];  await runInDurableObject(stub(slug), (instance: Business) => {    instance.bookFetcher = fetch;    instance.bookWait = async (ms) => {      waited.push(ms);    };  });}const DOC = { key: "/works/OL1W", title: "The Lantern Orchard", author_name: ["Irena Valcourt"], first_publish_year: 2017, number_of_pages_median: 312, cover_i: 4242, language: ["eng"] };/** RULE (owner, 4 Nov 2026): Start reading and Finished stamp the day in the database's own zone and count the reading; starting a finished book is a re-read. */describe("start_book and finish_book", () => {  const SLUG = "books-reading";  let credential = "";  let id = "";  it("starts a book today and finishes it today, one more reading counted", async () => {    ({ credential } = await personalObject(SLUG, { arrival: true, ...BOOKS_OPEN }));    const made = await http<{ made: { id: string } }>(SLUG, "POST", "/v1/act", { act: "create", args: { table: "book", data: { title: "Glass Hours", status: "want_to_read" } } }, { authorization: `Bearer ${credential}` });    id = made.body.made.id;    const started = await act(SLUG, credential, "start_book", { book: id });    expect(started.status, JSON.stringify(started.body)).toBe(200);    expect(started.body.book).toBe(id);    expect(await book(SLUG, id)).toMatchObject({ status: "reading", started_on: today() });    expect((await act(SLUG, credential, "start_book", { book: id })).body).toMatchObject({ code: "already_reading" });    expect((await act(SLUG, credential, "finish_book", { book: id })).status).toBe(200);    expect(await book(SLUG, id)).toMatchObject({ status: "finished", finished_on: today(), read_count: 1 });    expect((await act(SLUG, credential, "finish_book", { book: id })).body).toMatchObject({ code: "already_finished" });  });  it("starts a finished book again as a re-read, and counts the second finish", async () => {    await act(SLUG, credential, "start_book", { book: id });    const reread = await book(SLUG, id);    expect(reread.status).toBe("reading");    expect(reread.finished_on ?? null, "a re-read clears the finished day").toBeNull();    await act(SLUG, credential, "finish_book", { book: id });    expect((await book(SLUG, id)).read_count).toBe(2);  });  it("refuses a book that is not there, and a book named by nothing", async () => {    expect((await act(SLUG, credential, "start_book", { book: "no-such-book" })).body).toMatchObject({ code: "no_such_book" });    expect((await act(SLUG, credential, "finish_book", {})).body).toMatchObject({ code: "bad_args" });  });});/** RULE (5 Nov 2026): a book's kind follows its file. Any write that leaves a book's `file` set and its `format` empty sets `format` from the file's extension; a file of another kind is refused; a format named, or no file, is left as it is. */describe("a book's format follows its file", () => {  const SLUG = "books-format";  const EPUB = `${DATABASE_ID}/books/${"ab".repeat(32)}.epub`;  const PDF = `${DATABASE_ID}/books/${"cd".repeat(32)}.pdf`;  const MOBI = `${DATABASE_ID}/books/${"ef".repeat(32)}.mobi`;  let credential = "";  let owner = "";  const write = (verb: string, args: Record<string, unknown>) => http<{ made?: { id: string }; code?: string }>(SLUG, "POST", "/v1/act", { act: verb, args }, { authorization: `Bearer ${credential}` });  it("sets epub or pdf on a create that names a file and no format", async () => {    ({ credential, owner } = await personalObject(SLUG, { arrival: true, ...BOOKS_OPEN }));    const epub = await write("create", { table: "book", data: { title: "Salt Ledger", file: EPUB } });    expect(epub.status, JSON.stringify(epub.body)).toBe(200);    expect(await book(SLUG, epub.body.made!.id)).toMatchObject({ file: EPUB, format: "epub" });    const pdf = await write("create", { table: "book", data: { title: "Paper Weather", file: PDF, format: null } });    expect(pdf.status, JSON.stringify(pdf.body)).toBe(200);    expect(await book(SLUG, pdf.body.made!.id)).toMatchObject({ file: PDF, format: "pdf" });  });  it("sets it on an update that adds the file, and leaves a book with no file without one", async () => {    const made = await write("create", { table: "book", data: { title: "Quiet Harbour" } });    const id = made.body.made!.id;    expect((await book(SLUG, id)).format ?? null, "no file, no format").toBeNull();    expect((await write("update", { table: "book", id, data: { rating: 4 } })).status).toBe(200);    expect((await book(SLUG, id)).format ?? null).toBeNull();    expect((await write("update", { table: "book", id, data: { file: PDF } })).status).toBe(200);    expect(await book(SLUG, id)).toMatchObject({ file: PDF, format: "pdf" });  });  it("leaves a format the write names", async () => {    const made = await write("create", { table: "book", data: { title: "Named Kind", file: EPUB, format: "pdf" } });    expect(await book(SLUG, made.body.made!.id)).toMatchObject({ file: EPUB, format: "pdf" });  });  it("refuses a file of any other kind, on a create and on an update, and writes nothing", async () => {    const before = (await rows(SLUG, "book")).length;    const created = await write("create", { table: "book", data: { title: "Wrong Kind", file: MOBI } });    expect(created.status).toBe(400);    expect(created.body.code).toBe("bad_book_file");    expect((await rows(SLUG, "book")).length).toBe(before);    const made = await write("create", { table: "book", data: { title: "Still No File" } });    const updated = await write("update", { table: "book", id: made.body.made!.id, data: { file: MOBI } });    expect(updated.status).toBe(400);    expect(updated.body.code).toBe("bad_book_file");    expect((await book(SLUG, made.body.made!.id)).file ?? null).toBeNull();  });  it("holds over MCP: create_record refuses the readonly file before the rule, and an update fills a held book's missing format", async () => {    expect(await refusal(SLUG, owner, "create_record", { table: "book", data: { title: "By MCP", file: EPUB } })).toContain('"file" is read only');    // A book kept before the rule, its file set and its format empty, written past the engine.    const id = "book-before-the-rule";    await runInDurableObject(stub(SLUG), (_i, state) => {      new Store(state.storage.sql, () => new Date()).insert("book", id, { title: "Kept Before", file: EPUB, status: "reading" }, null, 1);    });    expect((await book(SLUG, id)).format ?? null).toBeNull();    await answer(SLUG, owner, "update_record", { table: "book", id, patch: { rating: 5 } });    expect(await book(SLUG, id)).toMatchObject({ rating: 5, format: "epub" });  });});/** RULE (owner, 4 Nov 2026): find_book asks Open Library from the object, identified, and fills only empty columns; the cover comes by cover id; 403 and 429 are refusals to try later. *//** RULE: a book's filled_from names one closed list of sources, the core's (cotton_core::books::SOURCES), by the shared fixture. */describe("where a book's facts came from", () => {  it("names the sources cotton-core names, and no other", () => {    expect([...BOOK_SOURCES]).toEqual(FILLED_FROM_LIST.sources);  });});const filledFrom = (data: Record<string, unknown>): Record<string, string> => JSON.parse(String(data.filled_from)) as Record<string, string>;const from = (source: string, columns: string[]): Record<string, string> => Object.fromEntries(columns.map((k) => [k, source]));describe("find_book", () => {  const SLUG = "books-find";  let credential = "";  it("makes a Want to read book from a query's first match, its cover kept as the object's media", async () => {    ({ credential } = await personalObject(SLUG, { arrival: true, ...BOOKS_OPEN }));    const ol = openLibrary([      ["https://openlibrary.org/search.json?", { json: { docs: [DOC, { ...DOC, key: "/works/OL2W", title: "Another" }] } }],      ["https://covers.openlibrary.org/b/id/4242-L.jpg", { bytes: JPEG }],    ]);    await given(SLUG, ol.fetch);    const found = await act(SLUG, credential, "find_book", { query: "lantern orchard" });    expect(found.status, JSON.stringify(found.body)).toBe(200);    expect(found.body).toMatchObject({ made: true });    expect(ol.asked[0]!.url).toContain("q=lantern+orchard");    expect(ol.asked.every((a) => a.agent === USER_AGENT), "Open Library is told who asks").toBe(true);    const data = await book(SLUG, String(found.body.book));    expect(data).toMatchObject({ title: "The Lantern Orchard", author: "Irena Valcourt", year: "2017", pages: 312, ol_work: "OL1W", language: "en", status: "want_to_read", source: "lookup", added_on: today() });    expect(String(data.cover)).toMatch(/^11111111-1111-4111-8111-111111111111\/photos\/[0-9a-f]{64}\.jpg$/);    expect(data.isbn ?? null, "a query names no edition, so no ISBN is guessed").toBeNull();    expect(filledFrom(data), "each column the lookup gave says open_library").toEqual(from("open_library", ["title", "author", "year", "pages", "ol_work", "language", "cover"]));    const again = await act(SLUG, credential, "find_book", { query: "the lantern orchard" });    expect(again.body, "the same work is the same book").toMatchObject({ book: found.body.book, made: false, filled: [] });  });  it("fills only the empty columns of a named book by its ISBN", async () => {    const made = await http<{ made: { id: string } }>(SLUG, "POST", "/v1/act", { act: "create", args: { table: "book", data: { title: "My own title", author: "Irena Valcourt" } } }, { authorization: `Bearer ${credential}` });    const id = made.body.made.id;    const ol = openLibrary([["https://openlibrary.org/search.json?", { json: { docs: [{ ...DOC, key: "/works/OL9W", cover_i: undefined }] } }]]);    await given(SLUG, ol.fetch);    const filled = await act(SLUG, credential, "find_book", { isbn: "978-0-00-000001-9", book: id });    expect(filled.status, JSON.stringify(filled.body)).toBe(200);    expect(ol.asked[0]!.url).toContain("isbn=9780000000019");    expect([...(filled.body.filled as string[])].sort()).toEqual(["isbn", "language", "ol_work", "pages", "year"]);    expect(await book(SLUG, id)).toMatchObject({ title: "My own title", isbn: "9780000000019", ol_work: "OL9W" });    expect(filledFrom(await book(SLUG, id)), "only what it filled is said").toEqual(from("open_library", ["isbn", "language", "ol_work", "pages", "year"]));  });  it("fills only the empty columns of a named book by its title and author (Find details)", async () => {    const made = await http<{ made: { id: string } }>(SLUG, "POST", "/v1/act", { act: "create", args: { table: "book", data: { title: "Lantern Orchard (my copy)", author: "Irena Valcourt" } } }, { authorization: `Bearer ${credential}` });    const id = made.body.made.id;    const ol = openLibrary([["https://openlibrary.org/search.json?", { json: { docs: [{ ...DOC, key: "/works/OL7W", cover_i: undefined }] } }]]);    await given(SLUG, ol.fetch);    const filled = await act(SLUG, credential, "find_book", { query: "Lantern Orchard Irena Valcourt", book: id });    expect(filled.status, JSON.stringify(filled.body)).toBe(200);    expect(filled.body).toMatchObject({ book: id, made: false });    expect(ol.asked[0]!.url).toContain("q=Lantern+Orchard+Irena+Valcourt");    expect(await book(SLUG, id)).toMatchObject({ title: "Lantern Orchard (my copy)", author: "Irena Valcourt", ol_work: "OL7W", year: "2017" });  });  it("refuses nothing found, a bad request, and Open Library asked too often", async () => {    await given(SLUG, openLibrary([["https://openlibrary.org/search.json?", { json: { docs: [] } }]]).fetch);    expect((await act(SLUG, credential, "find_book", { query: "zz" })).body).toMatchObject({ code: "no_book_found" });    for (const status of [403, 429]) {      await given(SLUG, openLibrary([["https://openlibrary.org/search.json?", { status }]]).fetch);      const refused = await act(SLUG, credential, "find_book", { query: "zz" });      expect(refused.status).toBe(503);      expect(refused.body).toMatchObject({ code: "lookup_failed" });      expect(String(refused.body.message)).toContain("try again later");    }    expect((await act(SLUG, credential, "find_book", { query: "a", isbn: "9780000000019" })).body).toMatchObject({ code: "bad_args" });    expect((await act(SLUG, credential, "find_book", { isbn: "12" })).body).toMatchObject({ code: "bad_args" });    expect((await act(SLUG, credential, "find_book", { query: "a", book: "b" })).body).toMatchObject({ code: "no_such_book" });    const before = (await rows(SLUG, "book")).length;    expect(before, "a refused lookup writes nothing").toBe(3);  });});/** RULE (7 Nov 2026: Open Library's Cloudflare answered the Worker 521 for minutes): a lookup Open Library does not answer is asked once more after a short wait; still unanswered, the act answers the honest line and the book keeps what it has — never a silent empty, never "nothing found". */describe("find_book when Open Library is not answering", () => {  const SLUG = "books-find-521";  let credential = "";  const SEARCH = "https://openlibrary.org/search.json?";  const COVER = "https://covers.openlibrary.org/b/id/4242-L.jpg";  it("asks once more after a short wait and finds the book when the second ask is answered", async () => {    ({ credential } = await personalObject(SLUG, { arrival: true, ...BOOKS_OPEN }));    const ol = openLibrary([      [SEARCH, [{ status: 521 }, { json: { docs: [DOC] } }]],      [COVER, { bytes: JPEG }],    ]);    await given(SLUG, ol.fetch);    const found = await act(SLUG, credential, "find_book", { query: "lantern orchard" });    expect(found.status, JSON.stringify(found.body)).toBe(200);    expect(found.body).toMatchObject({ made: true });    expect(found.body.cover_unanswered, "the cover was answered").toBeUndefined();    expect(ol.asked.filter((a) => a.url.startsWith(SEARCH))).toHaveLength(2);    expect(waited).toEqual([LOOKUP_WAIT_MS]);    expect(await book(SLUG, String(found.body.book))).toMatchObject({ title: "The Lantern Orchard", ol_work: "OL1W" });  });  it("refuses in the honest line after one retry, for a 521, any 5xx, no answer, or a 200 that is no search answer, and the named book keeps what it has", async () => {    const made = await http<{ made: { id: string } }>(SLUG, "POST", "/v1/act", { act: "create", args: { table: "book", data: { title: "My own title", author: "Irena Valcourt", year: "1999" } } }, { authorization: `Bearer ${credential}` });    const id = made.body.made.id;    const before = await book(SLUG, id);    const count = (await rows(SLUG, "book")).length;    for (const answer of [{ status: 521 }, { status: 503 }, { status: 500 }, { throws: true }, { text: "<html>Web server is down</html>" }, { json: { error: "busy" } }] as Answer[]) {      const ol = openLibrary([[SEARCH, answer]]);      await given(SLUG, ol.fetch);      const refused = await act(SLUG, credential, "find_book", { query: "Lantern Orchard Irena Valcourt", book: id });      expect(refused.status, JSON.stringify(answer)).toBe(503);      expect(refused.body, JSON.stringify(answer)).toMatchObject({ code: "lookup_failed", message: NOT_ANSWERING });      expect(ol.asked, "asked once more, never a third time").toHaveLength(2);      expect(waited).toEqual([LOOKUP_WAIT_MS]);      expect(await book(SLUG, id), "the book keeps what it has").toEqual(before);    }    expect((await rows(SLUG, "book")).length, "nothing made").toBe(count);  });  it("Open Library turning the lookup away for being asked too often is not asked again: 403 and 429 are refused at once", async () => {    for (const status of [403, 429]) {      const ol = openLibrary([[SEARCH, { status }]]);      await given(SLUG, ol.fetch);      const refused = await act(SLUG, credential, "find_book", { query: "zz" });      expect(refused.body).toMatchObject({ code: "lookup_failed" });      expect(ol.asked).toHaveLength(1);      expect(waited).toEqual([]);    }  });  it("writes the details when only the cover goes unanswered, asked twice, and says so in the answer", async () => {    const ol = openLibrary([      [SEARCH, { json: { docs: [{ ...DOC, key: "/works/OL5W" }] } }],      [COVER, { status: 521 }],    ]);    await given(SLUG, ol.fetch);    const found = await act(SLUG, credential, "find_book", { query: "lantern orchard again" });    expect(found.status, JSON.stringify(found.body)).toBe(200);    expect(found.body).toMatchObject({ made: true, cover_unanswered: NOT_ANSWERING });    expect(ol.asked.filter((a) => a.url.startsWith(COVER))).toHaveLength(2);    expect(waited).toEqual([LOOKUP_WAIT_MS]);    const data = await book(SLUG, String(found.body.book));    expect(data).toMatchObject({ title: "The Lantern Orchard", ol_work: "OL5W" });    expect(data.cover ?? null, "no cover kept; the artwork engine asks again").toBeNull();  });});/** RULE (owner, 4 Nov 2026): a Goodreads export is read by header name: Exclusive Shelf is the status (a dnf shelf stopped), other shelves are lists, Book Id finds a book again, 0 is none. */describe("import_goodreads", () => {  const SLUG = "books-goodreads";  let credential = "";  it("reads the export by header name, ISBNs unwrapped, a quoted comma and a doubled quote kept", () => {    const books = readExport(EXPORT);    expect(books).toHaveLength(10);    expect(isbnOf('="9780000000019"')).toBe("9780000000019");    expect(isbnOf('=""')).toBe("");    expect(csvRows('a,"b, c","d ""e"""\n1,2,3\n')).toEqual([["a", "b, c", 'd "e"'], ["1", "2", "3"]]);    const first = books[0]!;    expect(first.data).toMatchObject({ title: "The Lantern Orchard", isbn: "9780000000019", rating: 5, finished_on: "2026-09-21", added_on: "2026-01-04", read_count: 2, pages: 312, year: "2017", status: "finished", review: "Slow first third,\nthen it would not let go." });    expect(books[2]!.data, "0 is no rating and no reading").toMatchObject({ status: "reading", rating: null, read_count: null, isbn: "0000000036" });    expect(books[3]!.data.pages, "0 pages is none").toBeNull();    expect(books[4]!.data.rating, "a half star stays").toBe(3.5);    expect(books[5]!.data.status, "a dnf shelf is stopped").toBe("stopped");    expect(books[5]!.lists, "and no list").toEqual([]);    expect(books[1]!.data.year, "the published year when no original").toBe("2021");    // Columns moved and an older export's extra ones are read by name.    const shuffled = `Exclusive Shelf,Recommended By,Title,Author,Book Id\nto-read,Someone,An Invented Book,A. Writer,7\n`;    expect(readExport(shuffled)[0]!.data).toMatchObject({ title: "An Invented Book", goodreads_id: "7", status: "want_to_read" });  });  it("brings ten books onto their views and one list made from the custom shelf", async () => {    ({ credential } = await personalObject(SLUG, { arrival: true, ...BOOKS_OPEN }));    const imported = await act(SLUG, credential, "import_goodreads", { file: EXPORT });    expect(imported.status, JSON.stringify(imported.body)).toBe(200);    expect(imported.body).toMatchObject({ books: 10, made: 10, updated: 0, lists: 1 });    const books = await rows(SLUG, "book");    const by = (status: string) => books.filter((b) => b.data.status === status).length;    expect([by("finished"), by("reading"), by("want_to_read"), by("stopped")]).toEqual([4, 2, 3, 1]);    expect(books.every((b) => b.data.source === "goodreads")).toBe(true);    const orchard = books.find((b) => b.data.goodreads_id === "900001")!;    expect(filledFrom(orchard.data), "each column the export gave says goodreads; source is the door, not a fact").toEqual(from("goodreads", Object.keys(orchard.data).filter((k) => !["source", "filled_from"].includes(k))));    // The phone lands on the deck at the first book the import made (the coordinator, 4 Nov 2026).    const first = books.find((b) => b.id === (imported.body as { first?: string }).first);    expect(first?.data.title, "first names the export's first book made").toBe("The Lantern Orchard");    const groups = (await rows(SLUG, "record_group")).filter((g) => g.data.table_id === "book");    // Lists are sealed: the shelf lands sealed at arrival under the id its name derives, its name inside.    expect(groups.map((g) => g.id)).toEqual([derivedId("record_group", ["book", "favourites"])]);    expect(String(groups[0]!.data.dek_enc)).toMatch(/^a1:/);    expect(await openArrivalRow(groups[0]!.data, bodyAad(DATABASE_ID, "record_group", groups[0]!.id), "record_group", groups[0]!.id)).toMatchObject({ name: "favourites" });    const members = (await rows(SLUG, "group_member")).filter((m) => m.data.group === groups[0]!.id);    const titles = members.map((m) => books.find((b) => b.id === m.data.record_id)?.data.title).sort();    expect(titles).toEqual(["An Index of Small Birds", "Notes from a Tidal Kitchen", "The Lantern Orchard"]);  });  it("updates on a second import, found by Goodreads id: no second book and no second list", async () => {    const changed = EXPORT.replace("900004,The Cartographer's Second Wife,Dov Hallerin", "900004,The Cartographer's Second Wife,Dov Hallerin-Ash");    const again = await act(SLUG, credential, "import_goodreads", { file: changed });    expect(again.body).toMatchObject({ books: 10, made: 0, updated: 1, lists: 0 });    const found = (await rows(SLUG, "book")).find((b) => b.id === (again.body as { first?: string }).first);    expect(found?.data.title, "with none made, first names the first book found again").toBe("The Lantern Orchard");    expect((await rows(SLUG, "book")).length).toBe(10);    expect((await rows(SLUG, "group_member")).length, "a book is on a list once").toBe(3);    const cartographer = (await rows(SLUG, "book")).find((b) => b.data.goodreads_id === "900004")!;    expect(filledFrom(cartographer.data).author, "the re-import's fill says goodreads").toBe("goodreads");  });  it("refuses a file that is no Goodreads export, and writes nothing", async () => {    const refused = await act(SLUG, credential, "import_goodreads", { file: "Name,Phone\nA,1\n" });    expect(refused.status).toBe(400);    expect(refused.body).toMatchObject({ code: "not_goodreads" });    expect((await act(SLUG, credential, "import_goodreads", {})).body).toMatchObject({ code: "bad_args" });  });});/** RULE (owner, 4 Nov 2026): a re-import never moves a book backwards: status only forward (want to read, reading, stopped, finished), and what the owner set in Cotton is filled only when empty. */describe("import_goodreads over a book changed in Cotton", () => {  const SLUG = "books-goodreads-again";  let credential = "";  const ids = new Map<string, string>();  const byGoodreads = async (gid: string) => book(SLUG, ids.get(gid)!);  const update = async (gid: string, data: Record<string, unknown>) => {    const done = await act(SLUG, credential, "update", { table: "book", id: ids.get(gid)!, data });    expect(done.status, JSON.stringify(done.body)).toBe(200);  };  const POSITION = '{"href":"chapter-3.xhtml","locations":{"progression":0.4}}';  it("keeps the owner's reading, rating and review and moves only forward", async () => {    ({ credential } = await personalObject(SLUG, { arrival: true, ...BOOKS_OPEN }));    expect((await act(SLUG, credential, "import_goodreads", { file: EXPORT })).status).toBe(200);    for (const r of await rows(SLUG, "book")) ids.set(String(r.data.goodreads_id), r.id);    // In Cotton: a to-read book started and read into, a rating and review rewritten, a finished book started again.    await update("900004", { status: "reading", started_on: "2026-10-30", position: POSITION, progress: 40, position_at: "2026-11-01T08:00:00Z" });    await update("900001", { rating: 2, review: "Mine now." });    expect((await act(SLUG, credential, "start_book", { book: ids.get("900008")! })).status).toBe(200);    const file = [      ["900001,The Lantern Orchard,", (l: string) => l.replace(",312,", ",320,").replace(",5,4.12,", ",3,4.12,").replace('"Slow first third,<br/>then it would not let go."', "Changed my mind.")],      ["900007,", (l: string) => l.replace(",0,4.01,", ",4,4.01,")],      ["900010,", (l: string) => l.replace(",2017,,,2026/10/20,,,to-read,,,,0,0", ",2017,,2026/11/01,2026/10/20,,,read,,,,1,0")],      ["900002,", (l: string) => l.replace("2026/07/19,2025/12/30,,,read", "2026/07/19,2025/12/30,dnf,dnf (#2),read")],      ["900009,", (l: string) => l.replace("2026/10/01,,,currently-reading", "2026/10/01,dnf,dnf (#3),currently-reading")],      ["900006,", (l: string) => l.replace("2026/04/15,dnf,dnf (#1),read", "2026/04/15,,,to-read")],    ] as const;    const changed = EXPORT.split("\n")      .map((line) => {        const edit = file.find(([prefix]) => line.startsWith(prefix));        if (!edit) return line;        const after = edit[1](line);        expect(after, `the fixture line ${edit[0]} changed`).not.toBe(line);        return after;      })      .join("\n");    const again = await act(SLUG, credential, "import_goodreads", { file: changed });    expect(again.status, JSON.stringify(again.body)).toBe(200);    expect(again.body).toMatchObject({ books: 10, made: 0, updated: 4, lists: 0 });    expect(await byGoodreads("900004"), "a book started in Cotton stays reading, its place kept").toMatchObject({ status: "reading", started_on: "2026-10-30", position: POSITION, progress: 40, position_at: "2026-11-01T08:00:00Z" });    expect(await byGoodreads("900001"), "the owner's rating and review stand; Goodreads' pages still update").toMatchObject({ rating: 2, review: "Mine now.", pages: 320 });    expect((await byGoodreads("900007")).rating, "an empty rating is filled").toBe(4);    expect(await byGoodreads("900010"), "want to read the file says finished is finished").toMatchObject({ status: "finished", finished_on: "2026-11-01", read_count: 1 });    expect((await byGoodreads("900002")).status, "a dnf shelf never stops a finished book").toBe("finished");    expect((await byGoodreads("900009")).status, "a dnf shelf stops a book being read").toBe("stopped");    expect((await byGoodreads("900006")).status, "a stopped book is not put back to want to read").toBe("stopped");    const reread = await byGoodreads("900008");    expect(reread, "a re-read under way is not finished by the file's earlier reading").toMatchObject({ status: "reading", started_on: today() });    expect(reread.finished_on ?? null).toBeNull();  });});/** RULE (5 Nov 2026): a list carries the person's own picture, a photo column the kit adds to `record_group` add-only — an object holding lists made before it takes the column on its next keep, and nothing else of the table moves. */describe("a list's picture column", () => {  it("ships record_group's picture as a photo column, and a held record_group takes it add-only", () => {    const shipped = PERSONAL.tables.find((t) => t.id === "record_group")!;    const columns = shipped.columns as { key: string; type: string }[];    expect(columns.find((c) => c.key === "picture")).toEqual({ key: "picture", name: "Picture", type: "photo" });    const held = { ...shipped, columns: columns.filter((c) => c.key !== "picture") };    const { tables, changed } = grown([held], [shipped], () => 2);    expect(changed).toBe(1);    expect((tables[0]!.columns as { key: string }[]).map((c) => c.key)).toEqual([...held.columns.map((c) => c.key), "picture"]);    expect(grown(tables, [shipped], () => 2).changed, "a second keep takes nothing").toBe(0);  });});/** * RULE (e2e rulings R1, R2; 16 Nov 2026): books are sealed. * A book find_book makes lands sealed at arrival under the id its Open * Library work derives, so the same work finds it again; a lookup's details * for a sealed book go as a fill patch, which the phone lays only where the * book is empty, never over the person's own title; Start and Finished move * a sealed book by its clear status and count; a Goodreads import finds a * sealed book again by the id its Goodreads id derives. */describe("books under the seal", () => {  const SLUG = "books-sealed";  let credential = "";  const DK = Uint8Array.from({ length: 32 }, (_, i) => (i * 13 + 7) & 0xff);  const opened = async (id: string): Promise<Record<string, unknown>> => {    const data = await book(SLUG, id);    const aad = bodyAad(DATABASE_ID, "book", id);    const out = String(data.dek_enc).startsWith("a1:") ? await openArrivalRow(data, aad, "book", id) : {};    for (const p of (data.arrival_patches as Record<string, unknown>[] | undefined) ?? []) {      const part = await openArrivalRow(p, aad, "book", id);      for (const [k, v] of Object.entries(part)) if (!p.fill || out[k] === undefined || out[k] === null || out[k] === "") out[k] = v;    }    return out;  };  it("lands a found book sealed at arrival under its work's id, and finds it again by that id", async () => {    ({ credential } = await personalObject(SLUG, { arrival: true }));    const ol = openLibrary([["https://openlibrary.org/search.json?", { json: { docs: [{ ...DOC, cover_i: undefined }] } }]]);    await given(SLUG, ol.fetch);    const found = await act(SLUG, credential, "find_book", { query: "lantern orchard" });    expect(found.status, JSON.stringify(found.body)).toBe(200);    expect(found.body).toMatchObject({ made: true, book: derivedId("book", ["open_library", "OL1W"]) });    const data = await book(SLUG, String(found.body.book));    expect(String(data.dek_enc)).toMatch(/^a1:/);    expect(data).toMatchObject({ status: "want_to_read", source: "lookup" });    for (const k of ["title", "author", "ol_work", "isbn"]) expect(data, k).not.toHaveProperty(k);    expect(await opened(String(found.body.book))).toMatchObject({ title: "The Lantern Orchard", author: "Irena Valcourt", ol_work: "OL1W" });    const again = await act(SLUG, credential, "find_book", { query: "the lantern orchard" });    expect(again.body).toMatchObject({ book: found.body.book, made: false });    expect((await rows(SLUG, "book")).length).toBe(1);  });  it("fills a sealed book's empty columns as a fill patch, never over the person's own title", async () => {    const id = "book-mine";    const made = await act(SLUG, credential, "create", { table: "book", id, data: { status: "reading", ...(await sealRow(DK, "book", id, 1, { title: "My own title" })) } });    expect(made.status, JSON.stringify(made.body)).toBe(200);    const ol = openLibrary([["https://openlibrary.org/search.json?", { json: { docs: [{ ...DOC, key: "/works/OL9W", cover_i: undefined }] } }]]);    await given(SLUG, ol.fetch);    const filled = await act(SLUG, credential, "find_book", { isbn: "978-0-00-000001-9", book: id });    expect(filled.status, JSON.stringify(filled.body)).toBe(200);    const data = await book(SLUG, id);    const patches = data.arrival_patches as Record<string, unknown>[];    expect(patches).toHaveLength(1);    expect(patches[0]!.fill).toBe(true);    const part = await openArrivalRow(patches[0]!, bodyAad(DATABASE_ID, "book", id), "book", id);    expect(part).toMatchObject({ isbn: "9780000000019", ol_work: "OL9W", author: "Irena Valcourt" });    expect(JSON.stringify(data)).not.toContain("Irena");  });  it("starts and finishes a sealed book by its clear status and count", async () => {    expect((await act(SLUG, credential, "finish_book", { book: "book-mine" })).status).toBe(200);    expect(await book(SLUG, "book-mine")).toMatchObject({ status: "finished", finished_on: today(), read_count: 1 });  });  it("imports a Goodreads library sealed at arrival, and finds each book again by its Goodreads id", async () => {    const first = await act(SLUG, credential, "import_goodreads", { file: EXPORT });    expect(first.status, JSON.stringify(first.body)).toBe(200);    expect(first.body).toMatchObject({ books: 10, made: 10 });    const imported = (await rows(SLUG, "book")).filter((r) => r.data.source !== "lookup" && r.id !== "book-mine");    expect(imported).toHaveLength(10);    expect(imported.every((r) => String(r.data.dek_enc).startsWith("a1:") && !("title" in r.data))).toBe(true);    const again = await act(SLUG, credential, "import_goodreads", { file: EXPORT });    expect(again.body).toMatchObject({ books: 10, made: 0 });    expect((await rows(SLUG, "book")).length).toBe(12);  });});