use cotton_store::schema::{ddl::SCHEMA_DDL, package_tables::*}; use sha2::{Digest, Sha256}; use std::collections::{BTreeMap, BTreeSet}; /// RULE: Moving tool DDL into package data must preserve every current statement byte, including CHECKs, because phase 1 must not move any device file. #[test] fn builtin_packages_preserve_the_declared_ddl_bytes() { let packages = builtin_shapes().unwrap(); let mut generated = BTreeMap::new(); let mut tables = BTreeSet::new(); for (_, shapes) in packages { for shape in &shapes { assert!( tables.insert(shape.name.clone()), "two packages own {}", shape.name ); } for sql in generate(&shapes, true).unwrap() { assert!( SCHEMA_DDL.contains(&sql.as_str()), "package emitted an undeclared statement: {sql}" ); assert!( generated.insert(sql.clone(), sql).is_none(), "two packages own the same statement" ); } } for sql in SCHEMA_DDL { if statement_table(sql).is_some_and(|name| tables.contains(&name)) { assert!(generated.contains_key(*sql), "package omitted {sql}"); } } assert_eq!( fresh_schema() .unwrap() .iter() .map(String::as_str) .collect::>(), SCHEMA_DDL ); } /// RULE: The core is frozen; a changed hash must name its move in the shape ledger so tool edits cannot silently alter sync, vault or database infrastructure. #[test] fn core_hash_is_pinned_or_names_a_ledger_move() { let hash = hex::encode(Sha256::digest( core_statements().unwrap().join("\0").as_bytes(), )); assert!( hash == CORE_SHA256 || CORE_MOVES.iter().any(|m| m.sha256 == hash && !m.name.trim().is_empty() && m.ledger_note.len() == 36), "core shape {hash} needs a named shape-ledger move" ); } /// RULE: An imported package cannot supply SQL or claim another package/core table, because package data must never mutate the owner's infrastructure. #[test] fn imported_shapes_are_typed_and_owned() { let table: PackageTable = serde_json::from_value(serde_json::json!({ "name":"lesson", "columns":[{"name":"id","type":"TEXT","nullable":false,"primary_key":true}, {"name":"title","type":"TEXT","nullable":false,"default":"'untitled'"}], "indexes":[{"name":"lesson_title","columns":["title"]}] })) .unwrap(); let sql = generate(std::slice::from_ref(&table), false).unwrap(); let db = rusqlite::Connection::open_in_memory().unwrap(); for statement in sql { db.execute_batch(&statement).unwrap(); } db.execute("INSERT INTO lesson(id) VALUES ('one')", []) .unwrap(); assert_eq!( db.query_row("SELECT title FROM lesson", [], |row| row .get::<_, String>(0)) .unwrap(), "untitled" ); let mut hostile = table.clone(); hostile.columns[1].default = Some("0); DROP TABLE _meta; --".into()); assert!(generate(&[hostile], false).is_err()); let mut hostile = table.clone(); hostile.prefix = Some("CREATE TABLE _meta (".into()); assert!(generate(&[hostile], false).is_err()); for name in ["_meta", "cotton_todos", "fts_todos", "fts_todos_data"] { let mut stolen = table.clone(); stolen.name = name.into(); assert!(validate_ownership(&[stolen], &BTreeSet::new()).is_err()); } assert!(validate_ownership(&[table], &BTreeSet::from(["lesson".into()])).is_err()); } /// RULE: Package installation preflights every object and rolls back every CREATE on refusal, so an imported file cannot partially change the owner's shape. #[test] fn installation_is_atomic_and_reinstall_keeps_rows() { let db = cotton_store::driver::Driver::open_in_memory().unwrap(); let first: PackageTable = serde_json::from_value(serde_json::json!({ "name":"lesson", "columns":[{"name":"title", "type":"TEXT"}], "full_text":[{"name":"lesson_search","columns":["title"]}] })) .unwrap(); install(&db, std::slice::from_ref(&first), &[]).unwrap(); db.exec("INSERT INTO lesson(title) VALUES ('Learn Rust')") .unwrap(); assert_eq!( db.connection() .query_row( "SELECT count(*) FROM lesson_search WHERE lesson_search MATCH 'Rust'", [], |r| r.get::<_, i64>(0) ) .unwrap(), 1 ); install( &db, std::slice::from_ref(&first), std::slice::from_ref(&first), ) .unwrap(); assert_eq!( db.connection() .query_row("SELECT count(*) FROM lesson", [], |r| r.get::<_, i64>(0)) .unwrap(), 1 ); db.exec("UPDATE lesson SET title='Learn Swift'").unwrap(); assert_eq!( db.connection() .query_row( "SELECT count(*) FROM lesson_search WHERE lesson_search MATCH 'Rust'", [], |r| r.get::<_, i64>(0) ) .unwrap(), 0 ); db.exec("DELETE FROM lesson").unwrap(); assert_eq!( db.connection() .query_row( "SELECT count(*) FROM lesson_search WHERE lesson_search MATCH 'Swift'", [], |r| r.get::<_, i64>(0) ) .unwrap(), 0 ); let good: PackageTable = serde_json::from_value( serde_json::json!({"name":"new_table", "columns":[{"name":"id", "type":"TEXT"}]}), ) .unwrap(); let broken: PackageTable = serde_json::from_value(serde_json::json!({"name":"broken", "columns":[ {"name":"one", "type":"TEXT","primary_key":true}, {"name":"two", "type":"TEXT","primary_key":true}]})).unwrap(); assert!(install(&db, &[good, broken], &[]).is_err()); assert!(!cotton_store::create::schema_objects(&db) .unwrap() .iter() .any(|o| o.name == "new_table")); assert!( install(&db, &[first], &[]).is_err(), "a different package cannot claim this table" ); } /// RULE: Archived native storage regenerates independently of served definitions; explicit data-only extraction changes only its tables section. #[test] fn extraction_is_current_and_section_scoped() { let root = cotton_store::manifest_dir().join("../.."); for args in [ vec!["scripts/package-tables.py", "--check"], vec!["scripts/test-package-tables.py"], ] { let output = std::process::Command::new("python3") .current_dir(&root) .args(args) .output() .unwrap(); assert!( output.status.success(), "{}{}", String::from_utf8_lossy(&output.stdout), String::from_utf8_lossy(&output.stderr) ); } } /// The storage a kit's definition of a built-in table declares (its /// `tables` section) against the storage this build compiles for it /// (`builtin_tables.json`, from the DDL): every compiled table and column is /// declared as the DDL declares it, and a column the kit adds beyond it is /// one a file can take add-only — nullable or defaulted, never a key — which /// `hold_defined_columns` adds to a phone's own database and a copy takes /// from the object (an event's kind, 2 Nov 2026). The shell's definition of a /// table stands over the personal kit's. fn layout_drift(compiled: &serde_json::Value, kits: &std::path::Path) -> Vec { use serde_json::Value; let read = |path: &std::path::Path| -> Value { serde_json::from_str(&std::fs::read_to_string(path).unwrap()).unwrap() }; let mut files: BTreeMap = BTreeMap::new(); for kit in ["personal", "shell"] { for entry in std::fs::read_dir(kits.join(kit).join("tables")).unwrap().flatten() { let path = entry.path(); if path.extension().is_some_and(|ext| ext == "json") { files.insert(path.file_stem().unwrap().to_string_lossy().into_owned(), path); } } } let mut drift = Vec::new(); for (id, path) in &files { let Some(storage) = compiled.get(id).and_then(|built| built["tables"].as_array()) else { continue }; let kit = read(path); for table in storage { let name = table["name"].as_str().unwrap(); let Some(declared) = kit["tables"].as_array().into_iter().flatten().find(|own| own["name"] == name) else { drift.push(format!("{id}: the kit declares no {name}")); continue; }; let columns = |of: &Value| -> BTreeMap { of["columns"].as_array().into_iter().flatten().map(|column| (column["name"].as_str().unwrap().to_string(), column.clone())).collect() }; let (built, own) = (columns(table), columns(declared)); for (column, shape) in &built { match own.get(column) { None => drift.push(format!("{id}.{name}: the kit lost {column}")), Some(kept) => { for key in ["type", "nullable", "primary_key", "default"] { if kept[key] != shape[key] { drift.push(format!("{id}.{name}.{column}: the kit says {key} {} where the build stores {}", kept[key], shape[key])); } } } } } for (column, shape) in own.iter().filter(|(column, _)| !built.contains_key(*column)) { let addable = (shape["nullable"] == Value::Bool(true) || !shape["default"].is_null()) && shape["primary_key"] != Value::Bool(true); if !addable { drift.push(format!("{id}.{name}: the kit adds {column}, which no file can take add-only")); } } } } drift } /// RULE (restored, 2 Nov 2026): a kit's definition of a built-in table keeps /// to the storage this build compiles — every table and column as the DDL /// declares it, and only add-only columns beyond it. 5e4d8497be dropped the /// regeneration that kept them equal and put nothing in its place. #[test] fn every_kit_table_keeps_to_the_storage_the_build_compiles() { let root = cotton_store::manifest_dir().join("../.."); let compiled: serde_json::Value = serde_json::from_str(&std::fs::read_to_string(root.join("crates/cotton-store/src/schema/builtin_tables.json")).unwrap()).unwrap(); let kits = root.join("crates/cotton-core/kits"); let drift = layout_drift(&compiled, &kits); assert!(drift.is_empty(), "kit tables that drifted from this build's storage: {}", drift.join(" ")); // The guard sees a drift: a compiled column the kit lost, and a key the kit adds. let mut lost = compiled.clone(); let event = lost["event"]["tables"][0]["columns"].as_array_mut().unwrap(); event.push(serde_json::json!({"name": "synthetic_stored", "type": "TEXT", "nullable": true, "primary_key": false, "default": null})); assert!(layout_drift(&lost, &kits).iter().any(|line| line.contains("the kit lost synthetic_stored"))); let mut narrower = compiled.clone(); let columns = narrower["event"]["tables"][0]["columns"].as_array_mut().unwrap(); columns.retain(|column| column["name"] != "title"); let title = layout_drift(&narrower, &kits); assert!(title.iter().any(|line| line.contains("adds title, which no file can take add-only")), "{title:?}"); } /// RULE: Every imported tool gets typed, nullable/defaulted columns and declared search/link indexes; synthetic definitions exercise all storage types without consulting owner data. #[test] fn imported_definition_derivation_matches_the_reusable_script() { use serde_json::json; for id in [ "subscription", "subscription_charge", "disk_claim", "machine", "quota", "quota_reading", ] { let definition = json!({"id": id, "builtin": false, "project":"project", "order":"rank", "search":["name","details"], "columns":[ {"key":"name", "type":"text", "required":true}, {"key":"details", "type":"longtext", "default":"Owner's example"}, {"key":"day", "type":"date"}, {"key":"clock", "type":"time"}, {"key":"rank", "type":"number"}, {"key":"cost", "type":"amount", "default":0}, {"key":"status", "type":"choice", "default":"active"}, {"key":"project", "type":"link"}, {"key":"picture", "type":"photo"}, {"key":"document", "type":"file"}, {"key":"active", "type":"bool", "default":true}, {"key":"website", "type":"url"} ]}); let tables = from_definition(&definition).unwrap(); assert!(tables[0] .columns .iter() .all(|c| c.nullable || c.default.is_some())); let db = cotton_store::driver::Driver::open_in_memory().unwrap(); install(&db, &tables, &[]).unwrap(); let name = &tables[0].name; db.exec(&format!( "INSERT INTO {name}(id,name,cost,rank) VALUES ('one','Synthetic',9007199254740993,1.5)" )) .unwrap(); assert_eq!( db.connection() .query_row(&format!("SELECT cost FROM {name}"), [], |r| r .get::<_, i64>(0)) .unwrap(), 9007199254740993 ); assert_eq!( db.connection() .query_row(&format!("SELECT rank FROM {name}"), [], |r| r .get::<_, f64>(0)) .unwrap(), 1.5 ); db.exec(&format!("UPDATE {name} SET rank=9007199254740993")) .unwrap(); assert_eq!( db.connection() .query_row(&format!("SELECT rank FROM {name}"), [], |r| r .get::<_, i64>(0)) .unwrap(), 9007199254740993 ); let directory = tempfile::tempdir().unwrap(); let file = directory.path().join("definition.json"); let original = serde_json::to_string_pretty(&definition).unwrap(); std::fs::write(&file, &original).unwrap(); let script = cotton_store::manifest_dir() .join("../../scripts/package-tables.py"); assert!(std::process::Command::new("python3") .arg(&script) .arg(&file) .status() .unwrap() .success()); let generated = std::fs::read_to_string(&file).unwrap(); let shape: serde_json::Value = serde_json::from_str(&generated).unwrap(); let scripted: Vec = serde_json::from_value(shape["tables"].clone()).unwrap(); assert_eq!(scripted, tables); assert!(std::process::Command::new("python3") .arg(&script) .arg("--check") .arg(&file) .status() .unwrap() .success()); assert_eq!(generated, std::fs::read_to_string(&file).unwrap()); } for definition in [ json!({"id":"_group","columns":[]}), json!({"id":"_tool_package_assets","columns":[]}), json!({"id":"_database_appearance","columns":[]}), ] { assert!( from_definition(&definition).is_err(), "internal kinds need a named core home" ); } }