//! A first launch of each shipped flavour on a new phone (coordinator, 24 Oct //! 2026; `pnpm check:fresh-install`): a new synthetic database is given its //! manifest's genesis tools the way Start gives them (`install_genesis_tools`: //! every package by `add_tool`, a built-in on by being compiled in), and then //! every tool's every view must hold — its card names only columns its table //! has in THIS database and validates against it, the card resolves on every //! row the view reads, and the view's list answers. Every failure across the //! flavours is collected and said at once, never the first alone. //! //! Each database is seeded first, so every card resolves on real-shaped rows //! (coordinator, 24 Oct 2026): a personal flavour with the invented household //! `cotton-headless seed` writes (`cotton_tools::synthetic`, the faces walk's //! own base), a business with a few invented rows in every table its packages //! bring, each column given a value of its type and each link a row of the //! table it names, a claim reserved on its slot as a customer books it on //! the Mac that serves the business — there is no kitchen seed, and the yoga //! one lives in the headless binary. A row a table takes only from its engine //! (a picture's bytes, a chat's message) is said and left. No record is the //! owner's: every row is invented. mod support; use std::collections::{BTreeMap, BTreeSet}; use cotton_core::definitions::tool_views::ToolView; use cotton_core::definitions::TableDefinition; use serde_json::{json, Value}; use support::{ mcp::{call_tool_raw, mint_token}, Harness, }; /// The flavours a cut ships, read from `apps/registry.json`: every app with a /// kit, by the folder its manifest sits in (Cotton's own in `CottonManifest`). /// A new app is checked the moment the registry names it; no list here. fn flavours() -> Vec<(String, String)> { let file = std::path::PathBuf::from(std::env::var("CARGO_MANIFEST_DIR").expect("cargo sets CARGO_MANIFEST_DIR")).join("../../apps/registry.json"); let registry: Value = serde_json::from_str(&std::fs::read_to_string(&file).unwrap_or_else(|error| panic!("{}: {error}", file.display()))) .unwrap_or_else(|error| panic!("{}: {error}", file.display())); let apps = registry["apps"].as_array().expect("the registry's apps"); let flavours: Vec<_> = apps .iter() .filter(|app| app["kit"].is_string()) .map(|app| { let slug = app["slug"].as_str().expect("an app's slug").to_string(); let path = if slug == "cotton" { "App/CottonManifest/flavour.json".to_string() } else { format!("App/Flavours/{slug}/flavour.json") }; (slug, path) }) .collect(); assert!(!flavours.is_empty(), "{} names no app with a kit", file.display()); flavours } const TODAY: &str = "2026-10-24"; fn manifest(path: &str) -> Value { let file = std::path::PathBuf::from(std::env::var("CARGO_MANIFEST_DIR").expect("cargo sets CARGO_MANIFEST_DIR")).join("../../apps/cotton").join(path); serde_json::from_str(&std::fs::read_to_string(&file).unwrap_or_else(|error| panic!("{}: {error}", file.display()))) .unwrap_or_else(|error| panic!("{}: {error}", file.display())) } /// Every column key a card block names: each field's column and its `also`. fn card_columns(card: &cotton_core::definitions::card::CardFace) -> BTreeSet { card.fields.iter().flat_map(|field| field.column.iter().chain(field.also.iter()).cloned()).collect() } /// What one flavour's check went through, said beside its verdict. #[derive(Default)] struct Counted { seeded: usize, tools: usize, views: usize, cards: usize, rows: usize, /// The views whose list drew at least one row. drawn: usize, } /// About how many rows a personal flavour's household holds. const SEEDED: usize = 600; /// How many rows a business's seed writes in each of its tables. const ROWS: usize = 3; /// One invented value for `column`, row `n`, given the rows already written /// to each table; nil where its type is not one a seed writes (a picture, a /// file, a place) or its link's table has no row yet. fn value_for(column: &cotton_core::definitions::Column, n: usize, written: &BTreeMap>) -> Option { use cotton_core::definitions::ColumnType; let value = match column.column_type { ColumnType::Text | ColumnType::Longtext if column.key == "currency" => json!("INR"), ColumnType::Text | ColumnType::Longtext => json!(format!("Invented {} {}", column.key.replace('_', " "), n + 1)), ColumnType::Number => json!(n + 1), ColumnType::Amount => json!(25_000 * (n as i64 + 1)), ColumnType::Date => json!(format!("2026-10-{:02}", 20 + n)), ColumnType::Time => json!(format!("{:02}:30", 7 + n)), ColumnType::Bool => json!(n % 2 == 0), ColumnType::Choice => { let choices = column.choices.as_deref().filter(|choices| !choices.is_empty())?; let chosen = json!(choices[n % choices.len()]); if column.multiple == Some(true) { json!([chosen]) } else { chosen } } ColumnType::Link => { let linked = written.get(column.link_to.as_deref()?).filter(|linked| !linked.is_empty())?; let id = json!(linked[n % linked.len()]); if column.multiple == Some(true) { json!([id]) } else { id } } _ => return None, }; Some(value) } /// The column a refusal says Cotton sets itself: `… cannot set "" …`. fn set_by_cotton(refusal: &str) -> Option { let (_, rest) = refusal.split_once("cannot set \"")?; Some(rest.split_once('"')?.0.to_string()) } /// Each claim table with the tool that reserves it and how. type Claims<'a> = BTreeMap<&'a str, (&'a str, &'a cotton_core::definitions::reserve::Reservation)>; /// A business's seed: [`ROWS`] invented rows in each of `tables`, a table /// whose links name another first after that one, a person made for each /// link to people. A row its table refuses is said and the seed goes on — /// a reservation's rows are the engine's to write. fn seed_tables(h: &Harness, token: &str, tables: &[&TableDefinition], claims: &Claims) -> usize { let mut written: BTreeMap> = BTreeMap::new(); let mut people = Vec::new(); for n in 0..ROWS { let made = call_tool_raw(h, token, "create_record", json!({"table": "person", "data": {"name": format!("Invented Person {}", n + 1)}})); if let Some(id) = (!made.is_error).then(|| made.json()["record"]["id"].as_str().map(str::to_string)).flatten() { people.push(id); } } written.insert("person".into(), people); let mut waiting: Vec<&TableDefinition> = tables.to_vec(); let mut count = 0; // Each pass writes the tables whose links all name a table written // already; what never comes free (a link round) is written last as it is. while !waiting.is_empty() { let ready: Vec<&TableDefinition> = waiting .iter() .copied() .filter(|table| { table.columns.iter().filter_map(|column| column.link_to.as_deref()).all(|to| written.contains_key(to) || to == table.id || !waiting.iter().any(|other| other.id == to)) }) .collect(); let pass = if ready.is_empty() { waiting.clone() } else { ready }; for table in &pass { let mut ids = Vec::new(); for n in 0..ROWS { let mut data: serde_json::Map = table .columns .iter() .filter(|column| column.readonly != Some(true) && column.computed.is_none()) .filter_map(|column| Some((column.key.clone(), value_for(column, n, &written)?))) .collect(); let mut made = call_tool_raw(h, token, "create_record", json!({"table": table.id, "data": data})); // A column Cotton sets itself is left to Cotton. while made.is_error && set_by_cotton(&made.text).is_some_and(|column| data.remove(&column).is_some()) { made = call_tool_raw(h, token, "create_record", json!({"table": table.id, "data": data})); } // A claim is reserved on its slot as a customer books, by // its tool's reserve block: its name, its other links and one. if let Some((tool, reserve)) = made.is_error.then(|| claims.get(table.id.as_str())).flatten() { let mut claim: serde_json::Map = table .columns .iter() .filter(|column| column.key == "name" || (column.link_to.is_some() && column.key != reserve.slot_column)) .filter_map(|column| Some((column.key.clone(), data.get(&column.key)?.clone()))) .collect(); if let Some(quantity) = &reserve.quantity_column { claim.insert(quantity.clone(), json!(1)); } let slot = written.get(&reserve.slot_table).and_then(|slots| slots.get(n % slots.len().max(1))); made = call_tool_raw(h, token, "reserve_record", json!({"tool": tool, "slot": slot, "data": claim})); } match made.is_error { true => { if n == 0 { eprintln!("seed: {} refuses a row: {}", table.id, made.text); } } false => { if let Some(id) = made.json()["record"]["id"].as_str() { ids.push(id.to_string()); count += 1; } } } } written.entry(table.id.clone()).or_default().extend(ids); } waiting.retain(|table| !pass.iter().any(|done| done.id == table.id)); } count } /// One flavour founded and checked: the sentences of everything that failed. fn check(flavour: &str, manifest: &Value, counted: &mut Counted) -> Vec { let mut failed = Vec::new(); let mut h = Harness::new(); let token = mint_token(&mut h, &["read", "write"], "First launch"); let genesis = match cotton_core::genesis::GenesisTools::of(Some(manifest)) { Ok(genesis) => genesis, Err(error) => return vec![format!("{flavour}: the manifest's tools are refused: {error}")], }; // Every package the manifest picks installs, as Start installs it. for id in genesis.packages() { let added = call_tool_raw(&h, &token, "add_tool", json!({"tool_id": id})); if added.is_error { failed.push(format!("{flavour}: tool {id} does not install: {}", added.text)); } } let tables = cotton_tools::definitions::table_definitions_from_driver(&h.db, &h.workspace_id).expect("the tables read"); let tools = cotton_tools::definitions::tool_definitions_from_driver(&h.db, &h.workspace_id).expect("the tools read"); counted.seeded = if manifest.get("genesis").and_then(Value::as_str) == Some("personal") { // The default calendar a provisioned personal file is born with, // which the household's events are filed into. h.seed(&[json!({ "opId": format!("01J{:023}", 0), "deviceId": "device:seed", "kind": "upsert", "table": "cotton_collections", "rowId": support::harness::synthetic_uuid("calendar"), "patch": {"kind": "calendar", "name": "Personal", "is_default": true, "workspace_id": h.workspace_id, "created_at": "2026-09-08T09:00:00.000Z"}, "hlc": "1700000000000:0000:device:seed", "schemaVersion": cotton_store::schema::ddl::SCHEMA_VERSION, })]); let plan = cotton_tools::synthetic::Plan::scaled(SEEDED); cotton_tools::synthetic::seed_household_at(&h.db, &h.owner_id, &plan, 7, cotton_tools::synthetic::fixed_now()) .unwrap_or_else(|error| panic!("{flavour}: the household seed: {error}")) .total() } else { let packaged: Vec<&TableDefinition> = tools .definitions .iter() .flat_map(|tool| tool.tables.iter()) .filter_map(|id| tables.definitions.iter().find(|table| &table.id == id)) .collect(); // A business is served by the Mac it was founded on: the server // whose actions write its claims. h.db.run( "INSERT INTO cotton_serving_machine (id,workspace_id,epoch,device_credential_id,author_id,since,_hlc) VALUES ('synthetic-server',?,1,'synthetic-device',?,'2026-09-01T00:00:00Z','')", &[rusqlite::types::Value::Text(h.workspace_id.clone()), rusqlite::types::Value::Text(h.file_author())], ) .expect("the serving Mac"); let claims: Claims = tools .definitions .iter() .filter_map(|tool| tool.reserve.as_ref().map(|reserve| (reserve.claim_table.as_str(), (tool.id.as_str(), reserve)))) .collect(); seed_tables(&h, &token, &packaged, &claims) }; if counted.seeded == 0 { failed.push(format!("{flavour}: the seed wrote no row")); } for refused in tables.refused.iter().chain(tools.refused.iter()) { failed.push(format!("{flavour}: definition {} is refused: {}", refused.id, refused.reason)); } let by_id: BTreeMap<&str, &TableDefinition> = tables.definitions.iter().map(|table| (table.id.as_str(), table)).collect(); // Each picked package stands in the database: as its tool row, or (the // shell's built-in tables) as the table its tool block keys. A compiled // engine (`BUILT_IN_TOOLS`) is on by being compiled; founding writes // nothing for it. let held: BTreeSet = tools .definitions .iter() .map(|tool| tool.id.clone()) .chain(tables.definitions.iter().filter_map(|table| table.tool.as_ref().map(|tool| tool.key.clone().unwrap_or_else(|| table.id.clone())))) .collect(); counted.tools = genesis.0.len(); for id in &genesis.0 { let compiled = cotton_core::genesis::ToolKind::of(id) != Some(cotton_core::genesis::ToolKind::Package); if !compiled && !held.contains(id) { failed.push(format!("{flavour}: tool {id} is picked but the new database has no such tool")); } } // Every view of every tool the database holds: a package's own views, and // each built-in table's tool block's. let mut views: Vec<(String, ToolView)> = tools.definitions.iter().flat_map(|tool| tool.views.iter().map(move |view| (tool.id.clone(), view.clone()))).collect(); for table in &tables.definitions { if let Some(tool) = &table.tool { let key = tool.key.clone().unwrap_or_else(|| table.id.clone()); views.extend(tool.views.iter().map(|view| (key.clone(), view.clone()))); } } let zone = "Asia/Kolkata"; let now = chrono::DateTime::parse_from_rfc3339("2026-10-24T09:00:00+05:30").unwrap().with_timezone(&chrono::Utc); let words = cotton_core::records::page::Words::shipped(); let cards = cotton_core::rules::shell_lines::LineSet::shipped("cards").expect("the cards set"); for (tool, view) in views { let name = format!("{tool}/{}", view.id); let Some(read_table) = view.read.get("table").and_then(Value::as_str) else { failed.push(format!("{flavour}: view {name} reads no table")); continue; }; let Some(table) = by_id.get(read_table) else { failed.push(format!("{flavour}: view {name} reads {read_table}, which the new database does not define")); continue; }; let drawn = view.over(table); counted.views += 1; if let Some(card) = &drawn.card { counted.cards += 1; // The installer's check: the card names only what this // database's table has; then the core's own validation. let have: BTreeSet = table.columns.iter().map(|column| column.key.clone()).collect(); let missing: Vec = card_columns(card).difference(&have).cloned().collect(); if !missing.is_empty() { failed.push(format!("{flavour}: view {name}'s card names {}, which {read_table} does not have", missing.join(", "))); } else if let Err(error) = card.validate(table, "card") { failed.push(format!("{flavour}: view {name}'s card is refused: {error}")); } } // A partitioned view is one record's list: read for no record, it // answers the whole table, as its act's read narrows it. let listed = call_tool_raw(&h, &token, "list_records", json!({"table": read_table, "view": name, "today": TODAY, "limit": 50})); if listed.is_error { failed.push(format!("{flavour}: view {name}'s list does not answer: {}", listed.text)); continue; } let records = listed.json()["records"].as_array().cloned().unwrap_or_default(); if !records.is_empty() { counted.drawn += 1; } let Some(card) = &drawn.card else { continue }; for record in &records { let (Some(id), Some(data)) = (record["id"].as_str(), record["data"].as_object()) else { continue }; counted.rows += 1; let around = cotton_core::records::card::Around::default(); if cotton_core::records::card::resolve(card, &drawn, id, data, zone, now, words, &cards, around).is_none() { failed.push(format!("{flavour}: view {name}'s card does not resolve on record {id}")); } } } failed } /// RULE: every shipped flavour's first launch gives a database in which every tool its manifest picks is installed, and every view of every tool resolves its card with no refusal and answers its list. #[test] fn every_flavours_first_launch_holds_every_tool_and_every_view_reads() { let mut failed = Vec::new(); // Every flavour at once, each on its own new database. let flavours = flavours(); let checked: Vec<(&str, Vec, Counted)> = std::thread::scope(|scope| { let running: Vec<_> = flavours .iter() .map(|(flavour, path)| { let flavour = flavour.as_str(); scope.spawn(move || { let mut counted = Counted::default(); let found = check(flavour, &manifest(path), &mut counted); (flavour, found, counted) }) }) .collect(); running.into_iter().map(|run| run.join().expect("a flavour's check")).collect() }); for (flavour, found, counted) in checked { let Counted { seeded, tools, views, cards, rows, drawn } = counted; let verdict = if found.is_empty() { "every tool and view holds".to_string() } else { format!("{} failed", found.len()) }; eprintln!("{flavour}: {verdict} — {seeded} rows seeded, {tools} tools picked, {views} views listed ({drawn} drew rows), {cards} cards validated, {rows} rows' cards resolved"); failed.extend(found); } assert!(failed.is_empty(), "a first launch does not hold:\n{}", failed.join("\n")); }