Cotton code
584 lines · 26.6 KB · RustRaw
//! `cotton_store::open_bundle`: a kit's library laid as a folder tree other//! apps open, from a synthetic copy holding the kit's own table definitions.use std::path::Path;use cotton_store::fixtures::open_bundle::*;use cotton_store::fixtures::{file_at_version, NOW, OWNER};use cotton_store::meta::{seed_meta, Meta};use cotton_store::open_bundle::{write_open_bundle, Kit, Written};use cotton_store::schema::ddl::SCHEMA_VERSION;use cotton_store::Driver;use rusqlite::types::Value as SqlValue;use serde_json::{json, Value};const DB: &str = "11111111-1111-4111-8111-111111111111";const EXPORTED_AT: &str = "2026-11-07T10:00:00.000Z";/// The personal kit's table definitions, as the build ships them.const KIT: &[(&str, &str)] = &[    ("book", include_str!("../../cotton-core/kits/personal/tables/book.json")),    ("highlight", include_str!("../../cotton-core/kits/personal/tables/highlight.json")),    ("song", include_str!("../../cotton-core/kits/personal/tables/song.json")),    ("music_album", include_str!("../../cotton-core/kits/personal/tables/music_album.json")),    ("artist", include_str!("../../cotton-core/kits/personal/tables/artist.json")),    ("listen", include_str!("../../cotton-core/kits/personal/tables/listen.json")),    ("film", include_str!("../../cotton-core/kits/personal/tables/film.json")),    ("film_season", include_str!("../../cotton-core/kits/personal/tables/film_season.json")),    ("film_episode", include_str!("../../cotton-core/kits/personal/tables/film_episode.json")),    ("watch", include_str!("../../cotton-core/kits/personal/tables/watch.json")),];fn text(value: &str) -> SqlValue {    SqlValue::Text(value.to_string())}/// A copy whose own id is `DB`, holding the kit's tables.fn copy() -> Driver {    let db = file_at_version(SCHEMA_VERSION);    let meta = Meta { workspace_id: DB.into(), owner_id: OWNER.into(), device_id: "phone".into(), last_server_seq: 0, last_hlc: None };    seed_meta(&db, &meta, SCHEMA_VERSION).expect("seeds the identity");    db.run(        "INSERT INTO cotton_workspaces (id, name, owner_user_id, created_at) VALUES (?,?,?,?)",        &[text(DB), text("A copy"), text(OWNER), text(NOW)],    )    .expect("the workspace row");    for (id, definition) in KIT {        db.run(            "INSERT INTO cotton_table_definitions (id, workspace_id, definition, created_at, updated_at) VALUES (?,?,?,?,?)",            &[text(id), text(DB), text(definition), text(NOW), text(NOW)],        )        .expect("the definition");    }    let (_, refused) = cotton_store::schema::package_shape::step_file(&db).expect("lays the kit's tables");    assert!(refused.is_empty(), "{refused:?}");    db}fn read(dir: &Path, relative: &str) -> String {    std::fs::read_to_string(dir.join(relative)).unwrap_or_else(|error| panic!("{relative}: {error}"))}fn lay(db: &Driver, kit: Kit, shelf: &mut Shelf) -> (tempfile::TempDir, Written) {    let dir = tempfile::tempdir().expect("a folder");    let written = write_open_bundle(db, kit, dir.path(), shelf, EXPORTED_AT).expect("lays the bundle");    (dir, written)}// ── Books ────────────────────────────────────────────────────────────────/// RULE (open bundle, 7 Nov 2026): books lay as `Books/<Author>/<Title>/` holding the file and cover as stored and a `metadata.opf`, with the OPDS catalogues and goodreads.csv at the root; an author's folder is spelled once, a title taken twice gets `(2)`, a binned book stays out and bytes the holder lacks are said, never invented.#[test]fn open_bundle_books_lay_a_calibre_shaped_tree() {    let db = copy();    let mut shelf = Shelf::default();    shelf_of_books(&db, DB, &mut shelf);    let (dir, written) = lay(&db, Kit::Books, &mut shelf);    assert_eq!(        written.files,        BOOKS_TREE    );    assert_eq!(written.missing_media, books_missing(DB));    assert_eq!(std::fs::read(dir.path().join("Books/Ana Vell/Harbour Lights/Harbour Lights.epub")).unwrap(), EPUB, "copied as stored");    assert_eq!(std::fs::read(dir.path().join("Books/Ana Vell/Harbour Lights/cover.jpg")).unwrap(), JPEG);    assert_eq!(std::fs::read(dir.path().join("Books/Ana Vell/Two Rooms_ A Novel/Two Rooms_ A Novel.pdf")).unwrap(), PDF);}/// RULE (open bundle, 7 Nov 2026): metadata.opf is an EPUB 3 package document: Dublin Core title, creator, language, date and identifiers (the book, its ISBN, its Open Library work), series as belongs-to-collection with its position, and the file and cover beside it.#[test]fn open_bundle_books_write_the_opf_byte_for_byte() {    let db = copy();    let mut shelf = Shelf::default();    shelf_of_books(&db, DB, &mut shelf);    let (dir, _) = lay(&db, Kit::Books, &mut shelf);    assert_eq!(        read(dir.path(), "Books/Ana Vell/Harbour Lights/metadata.opf"),        r##"<?xml version="1.0" encoding="UTF-8"?><package xmlns="http://www.idpf.org/2007/opf" version="3.0" unique-identifier="uid">  <metadata xmlns:dc="http://purl.org/dc/elements/1.1/">    <dc:identifier id="uid">urn:cotton:book:book-1</dc:identifier>    <dc:identifier id="isbn">urn:isbn:0141439513</dc:identifier>    <dc:identifier id="olid">https://openlibrary.org/works/OL1W</dc:identifier>    <dc:title>Harbour Lights</dc:title>    <dc:creator id="creator">Ana Vell</dc:creator>    <meta refines="#creator" property="role" scheme="marc:relators">aut</meta>    <dc:language>en</dc:language>    <dc:date>2019</dc:date>    <meta property="belongs-to-collection" id="series">Lantern Cycle</meta>    <meta refines="#series" property="collection-type">series</meta>    <meta refines="#series" property="group-position">2</meta>  </metadata>  <manifest>    <item id="book" href="Harbour%20Lights.epub" media-type="application/epub+zip"/>    <item id="cover" href="cover.jpg" media-type="image/jpeg" properties="cover-image"/>  </manifest></package>"##    );    assert_eq!(        read(dir.path(), "Books/Ana Vell/Harbour Lights (2)/metadata.opf"),        r##"<?xml version="1.0" encoding="UTF-8"?><package xmlns="http://www.idpf.org/2007/opf" version="3.0" unique-identifier="uid">  <metadata xmlns:dc="http://purl.org/dc/elements/1.1/">    <dc:identifier id="uid">urn:cotton:book:book-3</dc:identifier>    <dc:title>Harbour Lights</dc:title>    <dc:creator id="creator">Ana Vell</dc:creator>    <meta refines="#creator" property="role" scheme="marc:relators">aut</meta>  </metadata>  <manifest/></package>"##    );}/// RULE (open bundle, 7 Nov 2026): the Books root carries an OPDS 2.0 catalog.json and an OPDS 1.2 catalog.xml of every book whose file is in the bundle, with URL-encoded relative links to the file and cover.#[test]fn open_bundle_books_write_both_opds_catalogues_byte_for_byte() {    let db = copy();    let mut shelf = Shelf::default();    shelf_of_books(&db, DB, &mut shelf);    let (dir, _) = lay(&db, Kit::Books, &mut shelf);    assert_eq!(        read(dir.path(), "Books/catalog.json"),        r#"{  "metadata": {    "title": "Cotton Books",    "modified": "2026-11-07T10:00:00.000Z",    "numberOfItems": 2  },  "links": [    {      "rel": "self",      "href": "catalog.json",      "type": "application/opds+json"    }  ],  "publications": [    {      "metadata": {        "@type": "http://schema.org/Book",        "identifier": "urn:isbn:0141439513",        "title": "Harbour Lights",        "author": "Ana Vell",        "language": "en",        "published": "2019",        "numberOfPages": 312,        "belongsTo": {          "series": {            "name": "Lantern Cycle",            "position": 2          }        }      },      "links": [        {          "rel": "http://opds-spec.org/acquisition",          "href": "Ana%20Vell/Harbour%20Lights/Harbour%20Lights.epub",          "type": "application/epub+zip"        }      ],      "images": [        {          "href": "Ana%20Vell/Harbour%20Lights/cover.jpg",          "type": "image/jpeg"        }      ]    },    {      "metadata": {        "@type": "http://schema.org/Book",        "identifier": "urn:isbn:9780000000002",        "title": "Two Rooms: A Novel",        "author": "ana vell"      },      "links": [        {          "rel": "http://opds-spec.org/acquisition",          "href": "Ana%20Vell/Two%20Rooms_%20A%20Novel/Two%20Rooms_%20A%20Novel.pdf",          "type": "application/pdf"        }      ]    }  ]}"#    );    assert_eq!(        read(dir.path(), "Books/catalog.xml"),        r##"<?xml version="1.0" encoding="UTF-8"?><feed xmlns="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/terms/" xmlns:opds="http://opds-spec.org/2010/catalog">  <id>urn:cotton:books:11111111-1111-4111-8111-111111111111</id>  <title>Cotton Books</title>  <updated>2026-11-07T10:00:00.000Z</updated>  <author><name>Cotton</name></author>  <link rel="self" href="catalog.xml" type="application/atom+xml;profile=opds-catalog;kind=acquisition"/>  <link rel="start" href="catalog.xml" type="application/atom+xml;profile=opds-catalog;kind=acquisition"/>  <entry>    <title>Harbour Lights</title>    <id>urn:cotton:book:book-1</id>    <updated>2026-10-01T09:00:00.000Z</updated>    <author><name>Ana Vell</name></author>    <dc:identifier>urn:isbn:0141439513</dc:identifier>    <dc:language>en</dc:language>    <dc:issued>2019</dc:issued>    <link rel="http://opds-spec.org/image" href="Ana%20Vell/Harbour%20Lights/cover.jpg" type="image/jpeg"/>    <link rel="http://opds-spec.org/acquisition" href="Ana%20Vell/Harbour%20Lights/Harbour%20Lights.epub" type="application/epub+zip"/>  </entry>  <entry>    <title>Two Rooms: A Novel</title>    <id>urn:cotton:book:book-2</id>    <updated>2026-10-01T09:00:00.000Z</updated>    <author><name>ana vell</name></author>    <dc:identifier>urn:isbn:9780000000002</dc:identifier>    <link rel="http://opds-spec.org/acquisition" href="Ana%20Vell/Two%20Rooms_%20A%20Novel/Two%20Rooms_%20A%20Novel.pdf" type="application/pdf"/>  </entry></feed>"##    );}/// RULE (open bundle, 7 Nov 2026): goodreads.csv carries Goodreads' import columns, one row per book: the status as its exclusive shelf (a stopped book on dnf, which Cotton's own import reads back as stopped), an ISBN-10 also as its ISBN-13, dates as Goodreads writes them, 0 for no rating.#[test]fn open_bundle_books_write_the_goodreads_csv_byte_for_byte() {    let db = copy();    let mut shelf = Shelf::default();    shelf_of_books(&db, DB, &mut shelf);    let (dir, _) = lay(&db, Kit::Books, &mut shelf);    assert_eq!(        read(dir.path(), "Books/goodreads.csv"),        "Book Id,Title,Author,ISBN,ISBN13,My Rating,Date Read,Date Added,Exclusive Shelf,My Review,Read Count\n\         ,Lost Pages,,,,0,,,dnf,,0\n\         77,Harbour Lights,Ana Vell,0141439513,9780141439518,4,2026/09/12,2026/08/01,read,\"Quiet, \"\"salty\"\", good.\",1\n\         ,Harbour Lights,Ana Vell,,,0,,,to-read,,0\n\         ,Two Rooms: A Novel,ana vell,,9780000000002,0,,,currently-reading,,0\n"    );}/// RULE (open bundle, 7 Nov 2026): a book's highlights lay beside it in reading order, as Markdown and as a W3C Web Annotation collection whose TextQuoteSelector carries the Locator's text around the passage and, for a PDF, its page.#[test]fn open_bundle_books_write_highlights_as_markdown_and_web_annotations() {    let db = copy();    let mut shelf = Shelf::default();    shelf_of_books(&db, DB, &mut shelf);    let (dir, _) = lay(&db, Kit::Books, &mut shelf);    assert_eq!(        read(dir.path(), "Books/Ana Vell/Harbour Lights/Harbour Lights.highlights.md"),        "# Harbour Lights\n\nAna Vell\n\n> Lamps came on.\n\n— 2026-09-01\n\n> The tide\n> went out.\n\nTwice!\n\n— Low Water · p. 41 · 2026-09-02\n\n"    );    let first: Value = serde_json::from_str(&read(dir.path(), "Books/Ana Vell/Harbour Lights/Harbour Lights.highlights.jsonld")).unwrap();    assert_eq!(        first,        json!({            "@context": "http://www.w3.org/ns/anno.jsonld",            "id": "urn:cotton:book:book-1:highlights",            "type": "AnnotationCollection",            "label": "Harbour Lights",            "total": 2,            "first": {"type": "AnnotationPage", "items": [                {"id": "urn:cotton:highlight:hl-1", "type": "Annotation", "motivation": "highlighting", "created": "2026-09-01",                 "target": {"source": "Harbour Lights.epub", "selector": [{"type": "TextQuoteSelector", "exact": "Lamps came on."}]}},                {"id": "urn:cotton:highlight:hl-2", "type": "Annotation", "motivation": "commenting", "created": "2026-09-02",                 "body": {"type": "TextualBody", "value": "Twice!", "format": "text/plain"},                 "target": {"source": "Harbour Lights.epub", "selector": [                     {"type": "TextQuoteSelector", "exact": "The tide\nwent out.", "prefix": "At dusk ", "suffix": " Then"}]}},            ]},        })    );    let pdf: Value = serde_json::from_str(&read(dir.path(), "Books/Ana Vell/Two Rooms_ A Novel/Two Rooms_ A Novel.highlights.jsonld")).unwrap();    assert_eq!(        pdf["first"]["items"][0]["target"]["selector"][1],        json!({"type": "FragmentSelector", "conformsTo": "http://tools.ietf.org/rfc/rfc3778", "value": "page=7"})    );}/// RULE (open bundle, 7 Nov 2026): a bundle is laid into an empty folder; a kit root already holding files is refused, never written into.#[test]fn open_bundle_refuses_a_kit_root_that_already_holds_files() {    let db = copy();    let dir = tempfile::tempdir().expect("a folder");    std::fs::create_dir_all(dir.path().join("Books")).unwrap();    std::fs::write(dir.path().join("Books/mine.txt"), b"keep me").unwrap();    let refused = write_open_bundle(&db, Kit::Books, dir.path(), &mut Shelf::default(), EXPORTED_AT).expect_err("refused");    assert!(refused.to_string().contains("empty folder"), "{refused}");    assert_eq!(read(dir.path(), "Books/mine.txt"), "keep me");}// ── Music ────────────────────────────────────────────────────────────────/// RULE (open bundle, 7 Nov 2026): songs lay as `Music/<Album artist>/<Album>/NN Title.<ext>` as stored, `D-NN` on a many-disc album, with the album's cover (else a song's) beside them; a song whose bytes the holder lacks is said, one with no file lays nothing.#[test]fn open_bundle_music_lays_artist_album_track_folders() {    let db = copy();    let mut shelf = Shelf::default();    a_record_collection(&db, DB, &mut shelf);    let (dir, written) = lay(&db, Kit::Music, &mut shelf);    assert_eq!(        written.files,        MUSIC_TREE    );    assert_eq!(written.missing_media, music_missing(DB));    assert_eq!(std::fs::read(dir.path().join("Music/The Paper Lanterns/Harbour Lights/03 Low Tide.flac")).unwrap(), FLAC, "copied, never transcoded");    assert_eq!(std::fs::read(dir.path().join("Music/Ana Vell/Two Rooms/cover.png")).unwrap(), PNG);}/// RULE (open bundle, 7 Nov 2026): each list of songs is an M3U8 in its own order, #EXTINF with whole seconds and `Artist - Title`, paths relative to the playlist; a song whose file is not in the bundle is left out.#[test]fn open_bundle_music_writes_m3u8_playlists_byte_for_byte() {    let db = copy();    let mut shelf = Shelf::default();    a_record_collection(&db, DB, &mut shelf);    let (dir, _) = lay(&db, Kit::Music, &mut shelf);    assert_eq!(        read(dir.path(), "Music/playlists/Road Trip.m3u8"),        "#EXTM3U\n\         #PLAYLIST:Road Trip\n\         #EXTINF:150,Ana Vell - The Stair\n\         ../Ana Vell/Two Rooms/1-04 The Stair.mp3\n\         #EXTINF:203,The Paper Lanterns - Low Tide\n\         ../The Paper Lanterns/Harbour Lights/03 Low Tide.flac\n"    );}/// RULE (open bundle, 7 Nov 2026): listens.jsonl holds the listens that count (finished, or half the song or four minutes, whichever is less), oldest first, in ListenBrainz' import shape with the MusicBrainz ids the copy holds.#[test]fn open_bundle_music_writes_listens_in_listenbrainz_shape() {    let db = copy();    let mut shelf = Shelf::default();    a_record_collection(&db, DB, &mut shelf);    let (dir, _) = lay(&db, Kit::Music, &mut shelf);    assert_eq!(        read(dir.path(), "Music/listens.jsonl"),        concat!(            r#"{"listened_at":1788166800,"track_metadata":{"artist_name":"The Paper Lanterns","track_name":"Lamps","release_name":"Harbour Lights","additional_info":{"release_mbid":"mb-rel-1","artist_mbids":["mb-art-1"],"duration_ms":180000,"media_player":"Cotton","submission_client":"Cotton"}}}"#, "\n",            r#"{"listened_at":1788256800,"track_metadata":{"artist_name":"The Paper Lanterns","track_name":"Low Tide","release_name":"Harbour Lights","additional_info":{"recording_mbid":"mb-rec-1","release_mbid":"mb-rel-1","artist_mbids":["mb-art-1"],"duration_ms":203400,"media_player":"Cotton","submission_client":"Cotton"}}}"#, "\n",            r#"{"listened_at":1788307200,"track_metadata":{"artist_name":"Someone","track_name":"Radio Song","additional_info":{"media_player":"Cotton","submission_client":"Cotton"}}}"#, "\n",        )    );}// ── Films ────────────────────────────────────────────────────────────────/// RULE (open bundle, 7 Nov 2026): films lay as `Films/<Title (Year)>/<Title (Year)>.<ext>` as stored (an HLS stream as its master and renditions under `.hls/`, each subtitle rendition beside it as `<Title (Year)>.<lang>.vtt`), with a Kodi NFO, poster and fanart; a series as `Films/<Series>/Season NN/<Series> - SNNENN - <Title>.<ext>` with episode NFOs, thumbs, tvshow.nfo and season posters; an episode waiting for the Mac lays its source; bytes the holder lacks are said.#[test]fn open_bundle_films_lay_a_kodi_shaped_tree() {    let db = copy();    let mut shelf = Shelf::default();    a_film_shelf(&db, DB, &mut shelf);    let (dir, written) = lay(&db, Kit::Films, &mut shelf);    assert_eq!(        written.files,        FILMS_TREE    );    assert_eq!(written.missing_media, films_missing(DB));    assert_eq!(std::fs::read(dir.path().join("Films/Night Ferry (2019)/Night Ferry (2019).mp4")).unwrap(), MP4, "copied, never transcoded");    assert_eq!(std::fs::read(dir.path().join("Films/Lowmarsh/Season 01/Lowmarsh - S01E02 - Cicadas.mkv")).unwrap(), MKV, "the source waiting for the Mac");    assert_eq!(read(dir.path(), "Films/Dust Signals (2011)/Dust Signals (2011).en.vtt"), VTT);    assert_eq!(read(dir.path(), "Films/Dust Signals (2011)/Dust Signals (2011).hls/video/index.m3u8"), MEDIA, "a rendition's playlist as stored");    assert_eq!(        read(dir.path(), "Films/Dust Signals (2011)/Dust Signals (2011).m3u8"),        MASTER            .replace("URI=\"audio-1/", "URI=\"Dust Signals (2011).hls/audio-1/")            .replace("URI=\"sub-en", "URI=\"Dust Signals (2011).hls/sub-en")            .replace("\nvideo/", "\nDust Signals (2011).hls/video/"),        "the master alone gains its renditions' folder"    );}/// RULE (open bundle, 7 Nov 2026): a film's NFO is Kodi's movie NFO: what the row holds, its ids as uniqueids (TMDB the default), Cotton's rating of 5 as a userrating of 10, and watched, playcount and lastplayed from the watch log.#[test]fn open_bundle_films_write_the_movie_nfo_byte_for_byte() {    let db = copy();    let mut shelf = Shelf::default();    a_film_shelf(&db, DB, &mut shelf);    let (dir, _) = lay(&db, Kit::Films, &mut shelf);    assert_eq!(        read(dir.path(), "Films/Night Ferry (2019)/Night Ferry (2019).nfo"),        r#"<?xml version="1.0" encoding="UTF-8" standalone="yes"?><movie>  <title>Night Ferry</title>  <originaltitle>Nachtfähre</originaltitle>  <year>2019</year>  <plot>A ferry &amp; a night.</plot>  <runtime>104</runtime>  <mpaa>UA</mpaa>  <userrating>8</userrating>  <uniqueid type="tmdb" default="true">900101</uniqueid>  <uniqueid type="imdb">tt0000101</uniqueid>  <uniqueid type="tvdb">5501</uniqueid>  <genre>Drama</genre>  <genre>Mystery</genre>  <country>United Kingdom</country>  <director>Mara Quill</director>  <playcount>2</playcount>  <lastplayed>2026-10-20 21:30:00</lastplayed>  <watched>true</watched>  <actor>    <name>Iris Calder</name>  </actor>  <actor>    <name>Tom Vey</name>  </actor></movie>"#    );    assert_eq!(        read(dir.path(), "Films/Dust Signals (2011)/Dust Signals (2011).nfo"),        "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n<movie>\n  <title>Dust Signals</title>\n  <year>2011</year>\n  <playcount>0</playcount>\n  <watched>false</watched>\n</movie>\n"    );}/// RULE (open bundle, 7 Nov 2026): a series writes tvshow.nfo (TheTVDB the default id) and each episode Kodi's episodedetails with its season, number, ids and what the watch log says of it.#[test]fn open_bundle_films_write_tvshow_and_episode_nfos_byte_for_byte() {    let db = copy();    let mut shelf = Shelf::default();    a_film_shelf(&db, DB, &mut shelf);    let (dir, _) = lay(&db, Kit::Films, &mut shelf);    assert_eq!(        read(dir.path(), "Films/Lowmarsh/tvshow.nfo"),        r#"<?xml version="1.0" encoding="UTF-8" standalone="yes"?><tvshow>  <title>Lowmarsh</title>  <year>2021</year>  <plot>A town under water.</plot>  <uniqueid type="tvdb" default="true">440011</uniqueid>  <uniqueid type="tmdb">880011</uniqueid></tvshow>"#    );    assert_eq!(        read(dir.path(), "Films/Lowmarsh/Season 01/Lowmarsh - S01E01 - Pilot.nfo"),        r#"<?xml version="1.0" encoding="UTF-8" standalone="yes"?><episodedetails>  <title>Pilot</title>  <season>1</season>  <episode>1</episode>  <runtime>48</runtime>  <aired>2021-09-01</aired>  <uniqueid type="tvdb" default="true">9900101</uniqueid>  <playcount>1</playcount>  <lastplayed>2026-10-05 13:30:00</lastplayed>  <watched>true</watched></episodedetails>"#    );    assert_eq!(        read(dir.path(), "Films/Lowmarsh/Season 01/Lowmarsh - S01E02 - Cicadas.nfo"),        "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n<episodedetails>\n  <title>Cicadas</title>\n  <season>1</season>\n  <episode>2</episode>\n  <playcount>0</playcount>\n  <lastplayed>2026-10-06 19:00:00</lastplayed>\n  <watched>false</watched>\n</episodedetails>\n",        "begun, never finished: no play, but when it was last played"    );}/// RULE (open bundle, 7 Nov 2026): trakt-watched.json is Trakt's watched export: movies and shows that were watched, each with its plays, last_watched_at in UTC and the ids it holds (TMDB and TheTVDB as numbers), a show's episodes by season.#[test]fn open_bundle_films_write_trakt_watched_byte_for_byte() {    let db = copy();    let mut shelf = Shelf::default();    a_film_shelf(&db, DB, &mut shelf);    let (dir, _) = lay(&db, Kit::Films, &mut shelf);    assert_eq!(        read(dir.path(), "Films/trakt-watched.json"),        r#"{  "movies": [    {      "plays": 2,      "last_watched_at": "2026-10-20T21:30:00.000Z",      "movie": {        "title": "Night Ferry",        "year": 2019,        "ids": {          "imdb": "tt0000101",          "tmdb": 900101,          "tvdb": 5501        }      }    }  ],  "shows": [    {      "plays": 1,      "last_watched_at": "2026-10-05T13:30:00.000Z",      "show": {        "title": "Lowmarsh",        "year": 2021,        "ids": {          "tvdb": 440011,          "tmdb": 880011        }      },      "seasons": [        {          "number": 1,          "episodes": [            {              "number": 1,              "plays": 1,              "last_watched_at": "2026-10-05T13:30:00.000Z"            }          ]        }      ]    }  ]}"#    );}// ── The shared vector ────────────────────────────────────────────────────/// The fixture library as the rule reads it — each kit's live rows, the bytes/// its media keys hold (text, or base64 when not UTF-8), the tree it lays and/// the keys it finds missing — written to `cotton-rules/vectors/open_bundle.json`,/// which cotton-rules' own tests and the Worker's vitest lay from. Run with/// `COTTON_WRITE_OPEN_BUNDLE_VECTOR=1` to write it; without, a drifted file/// fails here.#[test]fn open_bundle_vector_is_the_fixture_library() {    use base64::Engine as _;    let path = Path::new(&std::env::var("CARGO_MANIFEST_DIR").expect("cargo sets CARGO_MANIFEST_DIR")).join("../cotton-rules/vectors/open_bundle.json");    let mut kits = serde_json::Map::new();    type Seed = fn(&Driver, &mut Shelf);    let fill: [(Kit, &str, Seed, &[&str], Vec<String>); 3] = [        (Kit::Books, "books", |db, shelf| shelf_of_books(db, DB, shelf), BOOKS_TREE, books_missing(DB)),        (Kit::Music, "music", |db, shelf| a_record_collection(db, DB, shelf), MUSIC_TREE, music_missing(DB)),        (Kit::Films, "films", |db, shelf| a_film_shelf(db, DB, shelf), FILMS_TREE, films_missing(DB)),    ];    for (kit, name, seed, tree, missing) in fill {        let db = copy();        let mut shelf = Shelf::default();        seed(&db, &mut shelf);        let tables = cotton_store::open_bundle::library_rows(&db, kit).expect("reads the kit's rows");        let media: serde_json::Map<String, Value> = shelf            .0            .iter()            .map(|(key, bytes)| {                let held = match std::str::from_utf8(bytes) {                    Ok(text) => json!({ "text": text }),                    Err(_) => json!({ "base64": base64::engine::general_purpose::STANDARD.encode(bytes) }),                };                (key.clone(), held)            })            .collect();        let (_, written) = lay(&db, kit, &mut shelf);        assert_eq!(written.files, tree, "{name}: the store lays the fixture's tree");        assert_eq!(written.missing_media, missing, "{name}: the store finds the fixture's missing keys");        kits.insert(name.into(), json!({ "tables": tables, "media": media, "tree": tree, "missing_media": missing }));    }    let vector = json!({        "about": "The open bundle's fixture library (cotton_store::fixtures::open_bundle), written by cotton-store's open_bundle_vector_is_the_fixture_library with COTTON_WRITE_OPEN_BUNDLE_VECTOR=1; never edited by hand.",        "database": DB,        "exported_at": EXPORTED_AT,        "kits": kits,    });    let mut text = serde_json::to_string_pretty(&vector).expect("JSON");    text.push('\n');    if std::env::var_os("COTTON_WRITE_OPEN_BUNDLE_VECTOR").is_some() {        std::fs::write(&path, &text).expect("writes the vector");    }    let held = std::fs::read_to_string(&path).unwrap_or_default();    assert!(held == text, "cotton-rules/vectors/open_bundle.json has drifted from the fixture library: run this test with COTTON_WRITE_OPEN_BUNDLE_VECTOR=1");}