//! The kit: the tools Cotton offers (the eight, Documents and Artifacts), as `.cottontool` packages under `kits/personal/tools/`//! in this crate (72nd amendment, 21 Oct 2026: tools are records//! only). A package directory is the shape `import_tool` takes — manifest.json,//! pictures/<sha256>.<ext>, records/<id>.json (sample rows, optional) and the//! tables its manifest names, each the kit's one definition in kits/personal/tables,//! carried as tables/<id>.json;//! instructions.md is written from//! the manifest, as `scripts/pack-tool.mjs` writes it. No database is made//! with them: `import_tool` adds one on purpose. Every other tool is built by//! conversation; git history keeps the definitions it retired.use cotton_core::definitions::package::{archive_files, decode_package, encode_unsigned_package};use cotton_core::definitions::ToolDefinition;use std::collections::BTreeMap;use std::path::{Path, PathBuf};/// The kit's tools: the personal kit's `tools/`, one package folder each.fn kit() -> PathBuf { cotton_store::manifest_dir().join("kits/personal/tools")}/// The shell every database is made with.fn shell() -> PathBuf { cotton_store::manifest_dir().join("kits/shell")}/// A package directory's files as an archive holds them.fn files(dir: &Path) -> BTreeMap<String, Vec<u8>> {letmut files = BTreeMap::new();let manifest = std::fs::read(dir.join("manifest.json")).unwrap();let tool: ToolDefinition = serde_json::from_slice(&manifest).unwrap(); files.insert("instructions.md".to_string(), tool.instructions.into_bytes()); files.insert("manifest.json".to_string(), manifest);// The tables a tool names are the kit's own: one definition per table,// in the kit's `tables/`, the one the object serves.for table in &tool.tables {let path = kit().join("../tables").join(format!("{table}.json")); files.insert(format!("tables/{table}.json"), std::fs::read(&path).unwrap_or_else(|_| panic!("{} names {table}", tool.id))); }for part in ["pictures", "records"] {letOk(entries) = std::fs::read_dir(dir.join(part)) else { continue };for entry in entries {let entry = entry.unwrap();let name = entry.file_name().into_string().unwrap(); files.insert(format!("{part}/{name}"), std::fs::read(entry.path()).unwrap()); } } files}fn packages() -> Vec<(String, PathBuf)> {letmut packages: Vec<_> = std::fs::read_dir(kit()) .unwrap() .map(|entry| entry.unwrap().path()) .filter(|path| path.join("manifest.json").is_file()) .map(|path| (path.file_name().unwrap().to_string_lossy().into_owned(), path)) .collect(); packages.sort(); packages}/// RULE: every kit package is one `import_tool` takes, and exporting it again/// gives back the same bytes — the kit is packages, not a second format.#[test]fn every_kit_package_imports_and_exports_byte_equal() {for (id, dir) in packages() {let archive = archive_files(&files(&dir)).unwrap_or_else(|error| panic!("kit/{id}: {error}"));let imported = decode_package(&archive).unwrap_or_else(|error| panic!("kit/{id}: {error}")); assert_eq!(imported.package.tool.id, id, "kit/{id} is named for its tool"); assert_eq!(imported.package.tool.author.name, "Cotton");let exported = encode_unsigned_package(&imported.package).unwrap(); assert!(exported == archive, "kit/{id} round-trips export → import byte-equal"); }}/// RULE: no shell table feeds the voice harvester — every table under/// kits/shell says `"voice_words": []`. Dictation is biased toward the person's/// own words, the names and titles in their tools; the shell's tables hold the/// app's own furniture (its sentences, devices, boards, themes) and the bin's/// rows repeat titles their home tables already feed. A shell table heard as/// vocabulary crowded real names out of the mic (lines rows, 22 Oct 2026).#[test]fn no_shell_table_feeds_the_voice_harvester() {let tables = shell().join("tables");letmut seen = 0;for entry in std::fs::read_dir(&tables).unwrap() {let path = entry.unwrap().path();let table: cotton_core::definitions::TableDefinition = serde_json::from_slice(&std::fs::read(&path).unwrap()).unwrap(); assert_eq!( table.voice_words.as_deref(),Some(&[][..]),"kits/shell/tables/{} opts out of voice words", path.file_name().unwrap().to_string_lossy() ); seen += 1; } assert!(seen > 0, "the shell has tables");}/// Every table definition the kit ships, by id: the personal kit's and the shell's.fn kit_tables() -> BTreeMap<String, cotton_core::definitions::TableDefinition> {letmut tables = BTreeMap::new();for package in [kit().join(".."), shell()] {letOk(files) = std::fs::read_dir(package.join("tables")) else { continue };for file in files {let path = file.unwrap().path();let table: cotton_core::definitions::TableDefinition = serde_json::from_slice(&std::fs::read(&path).unwrap()) .unwrap_or_else(|error| panic!("{}: {error}", path.display())); tables.insert(table.id.clone(), table); } } tables}/// RULE: every kit link that narrows its table names that table's own columns, as the reader parses them — a link whose `where` the reader refuses is a refusal on every page that counts it.////// WHY: 22 Oct 2026, Rigby build 2's walk — the Photos page's "People to/// confirm" link narrowed `face` on `answer: open` from the day it was/// written; face's column is `decision` and has no `open`. It stayed silent/// while no fresh database held face's definition, and failed on every phone/// once the Photos kit carried it.#[test]fn every_kit_link_narrows_on_its_tables_own_columns() {let tables = kit_tables();letmut seen = 0;for (id, table) in &tables {for link in table.links.iter().flatten() {letSome(where_) = &link.where_ else { continue };letSome(target) = tables.get(&link.table) else { continue };let narrowing = serde_json::Value::Object(where_.0.iter().cloned().collect());ifletErr(refusal) = cotton_core::records::parse_where(target, Some(&narrowing)) { panic!("{id}'s link \"{}\" narrows {} by {narrowing}: {refusal:?}", link.label, link.table); } seen += 1; } } assert!(seen > 0, "the kit has links that narrow");}/// The Music package as the kit compiles it.fn music() -> cotton_core::definitions::package::ToolPackage { cotton_core::kit::package("music").expect("the kit holds Music").expect("Music decodes").package}/// RULE (owner, 4 Nov 2026: Cotton Music from scratch): Music is a kit/// package of its own data tables — songs kept as files, the albums and/// artists they gather into, and the listens the player writes — none of them/// built in, so a database holds Music as ordinary data it may edit or/// remove; playlists are the songs' record groups, never a table of their/// own. Its views are Listening (first, the albums played lately), Albums,/// Artists, Songs, Favourites, Recently added and On this phone, in that/// order, each reading its own table; it ships no sample rows, since a song/// is never made without its file.#[test]fn music_is_a_kit_package_of_its_own_data_tables() {let package = music();let ids: Vec<&str> = package.tables.iter().map(|table| table.id.as_str()).collect(); assert_eq!(ids, ["song", "music_album", "artist", "listen", "vault_key"]);for table in &package.tables { assert!(!table.builtin && table.engine.is_none(), "{} is the package's own data", table.id); assert!(!cotton_core::definitions::is_builtin_table(&table.id), "{} takes no built-in's name", table.id); assert_eq!(table.card.is_some(), table.id != "listen", "{}: every table but the player's log draws a card", table.id); }let chips: Vec<(&str, &str, Option<&str>)> = package.tool.views.iter() .map(|view| (view.id.as_str(), view.label.as_str(), view.read.get("table").and_then(serde_json::Value::as_str))) .collect(); assert_eq!(chips, [ ("listening", "Listening", Some("music_album")), ("albums", "Albums", Some("music_album")), ("artists", "Artists", Some("artist")), ("songs", "Songs", Some("song")), ("favourites", "Favourites", Some("song")), ("recently_added", "Recently added", Some("song")), ("on_phone", "On this phone", Some("song")), ]); assert!(package.tool.views[0].is_default && package.tool.views[1..].iter().all(|view| !view.is_default), "Listening opens first");let song = package.tables.iter().find(|table| table.id == "song").unwrap();let file = song.column("file").expect("a song keeps its recording"); assert_eq!(file.column_type, cotton_core::definitions::ColumnType::File, "Music plays files, never a stream"); assert!(package.samples.is_empty(), "no sample song: a song is never made without its file");}/// RULE: Music's wholes open into their parts — an album into its songs in/// disc then track order, an artist into their albums by year — and a/// package whose opening names a link that does not lead back to the whole,/// a `through` that is no link, parts that do not come with it or an order/// its parts do not have is refused when it is read, never dealt as an empty/// fan.#[test]fn music_wholes_open_into_their_parts_and_a_wrong_opening_is_refused() {use cotton_core::definitions::card::validate_openings;let package = music(); validate_openings(&package.tables).expect("Music's openings hold");let opens = |id: &str| package.tables.iter().find(|table| table.id == id).unwrap().card.as_ref().unwrap().opens.clone();let album = opens("music_album").expect("an album opens"); assert_eq!((album.table.as_str(), album.by.as_str(), album.order.as_slice(), album.through.as_deref()), ("song", "album", &["disc_number".to_string(), "track_number".to_string()][..], None));let artist = opens("artist").expect("an artist opens"); assert_eq!((artist.table.as_str(), artist.by.as_str(), artist.order.as_slice()), ("music_album", "artist", &["year".to_string()][..])); assert!(opens("song").is_none(), "a song is a part, it opens into nothing");// The package as files, each wrong opening written into one of them.let dir = kit().join("music");let wrong = |table: &str, change: &dynFn(&mut serde_json::Value)| {letmut files = files(&dir);let name = format!("tables/{table}.json");letmut value: serde_json::Value = serde_json::from_slice(&files[&name]).unwrap(); change(&mut value["card"]["opens"]); files.insert(name, serde_json::to_vec_pretty(&value).unwrap()); archive_files(&files) }; archive_files(&files(&dir)).expect("the package as shipped is read"); assert!(wrong("music_album", &|opens| opens["by"] = "artist".into()).is_err(), "an album's songs link back to the album"); assert!(wrong("music_album", &|opens| opens["through"] = "track_number".into()).is_err(), "through names a link"); assert!(wrong("music_album", &|opens| opens["table"] = "music_item".into()).is_err(), "the parts come with the whole"); assert!(wrong("music_album", &|opens| opens["order"] = serde_json::json!(["disc"])).is_err(), "the parts are dealt by their own columns");}/// RULE: a song's card (the 7-inch single) says its title, its artist as/// tagged, its place on its album, its length and the file it plays — the/// deck draws what it is handed and plays only the file named in `play`.#[test]fn a_songs_card_says_its_title_artist_length_and_the_file_it_plays() {use cotton_core::records::card::{resolve, Around};let package = music();let song = package.tables.iter().find(|table| table.id == "song").unwrap();let card = song.card.as_ref().expect("a song draws a card"); assert_eq!(card.face, "song.single");let data = serde_json::json!({"title": "Invented Tide", "artist_name": "The Synthetic Quartet", "album_title": "Made-Up Shores","duration": 222, "track_number": 3, "file": "objects/invented-tide.m4a", });let cards = cotton_core::rules::shell_lines::LineSet::shipped("cards").unwrap();let now = chrono::DateTime::parse_from_rfc3339("2026-10-23T10:00:00+05:30").unwrap().with_timezone(&chrono::Utc);let words = cotton_core::records::page::Words::shipped();let read = resolve(card, song, "song-1", data.as_object().unwrap(), "Asia/Kolkata", now, words, &cards, Around::default()) .expect("the card resolves"); assert_eq!(read.fields["title"], "Invented Tide"); assert_eq!(read.fields["subtitle"], "The Synthetic Quartet", "the artist as tagged"); assert_eq!(read.fields["number"], "Track 3"); assert_eq!(read.fields["play"], "objects/invented-tide.m4a", "play names the file's key, never words"); assert_eq!(read.fields["length"], "3:42");let bare = serde_json::json!({"title": "No file yet"});let silent = resolve(card, song, "song-2", bare.as_object().unwrap(), "Asia/Kolkata", now, words, &cards, Around::default()).unwrap(); assert!(silent.fields.get("play").is_none(), "a song with no recording plays nothing");}/// RULE (owner, 25 Oct 2026, #77): memory has no review state — Memories/// offers no Unreviewed view; it opens on All, then Archived. Both read the/// `memory` table the assistants write (2 Nov 2026), the active sentences and/// the archived ones (the archive, which a plain list leaves out); a memory/// names no project column, so there is no By project view. The memory/// table's tool names no screen of its own, so Memories opens on its views'/// deck.#[test]fn memories_offers_no_review_view_and_opens_on_all() {let manifest = std::fs::read(kit().join("memories/manifest.json")).unwrap();let tool: ToolDefinition = serde_json::from_slice(&manifest).unwrap();let views: Vec<(&str, bool)> = tool.views.iter().map(|view| (view.id.as_str(), view.is_default)).collect(); assert_eq!(views, [("all", true), ("archived", false)]);let raw: serde_json::Value = serde_json::from_slice(&manifest).unwrap();let read: Vec<&serde_json::Value> = raw["views"].as_array().unwrap().iter().map(|view| &view["read"]).collect(); assert_eq!(read, [ &serde_json::json!({"table": "memory", "where": {"status": "active"}, "empty": {"line": "empty_views.memories.all", "table": true}}), &serde_json::json!({"table": "memory", "where": {"status": "archived"}, "archived": true, "empty": {"line": "empty_views.memories.archived", "table": true}}), ]);// The vault's rows too (e2e rulings R1): Cotton Developer keeps sealed todos and pages, so it founds the data key or is approved for it. assert_eq!(raw["tables"], serde_json::json!(["memory", "vault_key"]));let table: serde_json::Value = serde_json::from_slice(&std::fs::read(kit().join("../tables/memory.json")).unwrap()).unwrap(); assert!(table["tool"].get("route").is_none(), "{}", table["tool"]);}/// Every JSON file under `dir`, by its path from `root`.fn json_files(root: &Path, dir: &Path, out: &mutVec<(String, PathBuf)>) {for entry in std::fs::read_dir(dir).unwrap() {let path = entry.unwrap().path();if path.is_dir() { json_files(root, &path, out); } elseif path.extension().is_some_and(|extension| extension == "json") { out.push((path.strip_prefix(root).unwrap().to_string_lossy().into_owned(), path)); } }}/// Every card a definition holds — a table's own, a tool's views', a table's/// tool's views' — as where it stands and the face it names.fn cards(value: &serde_json::Value, at: &str, out: &mutVec<(String, serde_json::Value)>) {match value { serde_json::Value::Object(map) => {for (key, inner) in map {let here = format!("{at}.{key}");match inner.get("face") {Some(face) if key == "card" && inner.is_object() => out.push((here, face.clone())), _ => cards(inner, &here, out), } } } serde_json::Value::Array(items) => {for (index, inner) in items.iter().enumerate() { cards(inner, &format!("{at}.{index}"), out); } } _ => {} }}/// RULE (Loom step 5): every kit names each card's face by an id the app/// draws (apps/loom/faces.json and faces-pending.json, `card::FaceId`) — a/// device reads a card naming any other as no card, so a kit naming one would/// ship a table that draws as nothing.#[test]fn every_kit_card_names_a_face_the_app_draws() {let root = cotton_store::manifest_dir().join("kits");letmut paths = Vec::new(); json_files(&root, &root, &mut paths);letmut named = Vec::new();for (name, path) in paths {let value: serde_json::Value = serde_json::from_slice(&std::fs::read(&path).unwrap()).unwrap_or_else(|e| panic!("{name}: {e}")); cards(&value, &name, &mut named); } assert!(named.len() > 40, "the kits carry their cards: {}", named.len());let unknown: Vec<String> = named .iter() .filter(|(_, face)| face.as_str().and_then(cotton_core::definitions::card::FaceId::known).is_none()) .map(|(at, face)| format!("{at}: {face}")) .collect(); assert!(unknown.is_empty(), "cards naming no face the app draws: {unknown:?}");}