//! A phone's own database keeps its compiled kit. The merge rule mirrors //! `apps/business/src/kit_keep.ts`; served copies never call this module. A //! held table that holds no row, live or binned, is the kit's whole: the kit //! may reshape an empty table (Books' book, 4 Nov 2026); one with a row stays //! add-only. //! //! A copy that still holds the music before Cotton Music drops it once, the //! way the object's `drop_old_music` act does (`apps/business/src/music.ts` //! `dropOldMusic`): a phone's own copy has no object to run that act //! ([`drop_old_music`], KEEP_RULE 8). //! //! A held table whose LOOK the person has not edited takes the kit's look //! whole (KEEP_RULE 9, 5 Nov 2026, the object's KEEP_RULE 11): a kit table //! that is not a built-in is drawn from this file's own row //! (`definitions::resolve_table`), so an add-only keep left a copy with rows //! in it drawing an older build's create, empty, page or sort for ever. The //! look is every key but `FIXED_DEFINITION_KEYS`, `columns`, `card` and //! `internal`: each look key is set as the kit has it, one the kit no longer //! carries removed; storage (columns, engine, commands, acts, connections, //! identity) stays the table's. Edited is told as shell boards are told here: //! the look differs from the one the kit last laid, kept under //! [`KIT_LAID_TABLES`]; with no record (no keep has laid one since the rule) //! the held look is the kit's to lay, and one that already reads as the //! kit's now is the kit's. An edited look stays, said once in the log. The //! phone's `update_definition` writes nothing more: a look it changes differs //! from the record, which this rule reads as the person's edit. //! //! A held table's `commands` and `acts` are the build's, never a person's //! (KEEP_RULE 10, 5 Nov 2026, the object's KEEP_RULE 12: FIXED keys nothing //! a person does writes; the owner's book held 8 commands of the kit's 12): //! every keep lays them exactly as the kit has them, one the kit lacks //! removed. A kept look whose `marks` name a command no longer laid takes the //! kit's marks, said once in the log. use std::collections::{BTreeMap, BTreeSet}; use std::sync::{Arc, OnceLock}; use base64::{engine::general_purpose::STANDARD, Engine}; use cotton_store::{Driver, StoreError}; use rusqlite::types::Value as SqlValue; use serde::{Deserialize, Serialize}; use serde_json::{json, Value}; use crate::mcp::dispatch::{Ctx, ToolServices}; use crate::mcp::handlers::common::{insert_row, update_row}; use crate::mcp::protocol::ToolFailure; pub const KIT_VERSION: &str = "kit_version"; pub const KIT_GIVEN: &str = "kit_given"; /// Each shell board as the kit last laid it: a held board that differs from /// it is the person's edit and stays (coordinator, 2 Nov 2026). pub const KIT_LAID: &str = "kit_laid"; /// Each kit table's look as the kit last laid it: a held look that differs /// from it is the person's edit and stays (5 Nov 2026). pub const KIT_LAID_TABLES: &str = "kit_laid_tables"; /// Each kit tool as the kit last laid it: a held tool that differs from it is /// the person's edit and stays (6 Nov 2026, the object's `KIT_LAID_TOOLS`). pub const KIT_LAID_TOOLS: &str = "kit_laid_tools"; /// 5: a shell board the person edited since the kit last laid it stays. /// 6: a held tool reading a table the kit retired takes the kit's views and /// tables (3 Nov 2026). /// 7: a kit table's retired column is laid only once the held table no /// longer holds it, and a held choice column takes the choices the kit adds, /// 5 Nov 2026. /// 8: a copy holding the old music tables and no song drops them once, as /// the object's `drop_old_music` does: the old tables' rows tombstoned, the /// gone tables' definitions removed, the reshaped tables and the Music tool /// laid whole (5 Nov 2026). /// 9: a held table whose look the person has not edited takes the kit's look /// whole (5 Nov 2026). /// 10: a held table's commands and acts are the kit's on every keep (5 Nov /// 2026). /// 11: a held tool the person has not edited is the kit's whole, its picture /// the person's, with the pictures its package carries that the file lacks /// (6 Nov 2026, the object's rule 9: Cotton Cinemas' letterboard fan tile and /// its pictograms reach a copy holding the tool an older build laid). /// 12: a held column takes the kit's `until` and `default` where it says /// nothing of them (13 Nov 2026, the object's rule 13: a trip's starts is /// until its ends, so a trip given only its first day stands in Upcoming and /// Past; a trip's paper is a ticket unless it says otherwise). /// 13: a table or tool `cotton_core::retired` names is held as retired under /// [`KIT_RETIRED`], its definition no longer served, its rows kept (17 Nov /// 2026, the object's rule 15: the old screenplay tables go). pub const KEEP_RULE: u32 = 13; /// Each retired definition by kind and id, as JSON `{ "table": {..}, "tool": /// {..} }` (the object's `kit_retired`): held here, never served. pub const KIT_RETIRED: &str = "kit_retired"; // Device-local bookkeeping, like the ingest cursors: never a synced definition. const DDL: &str = "CREATE TABLE IF NOT EXISTS _kit_keep (key TEXT PRIMARY KEY, value TEXT NOT NULL)"; const TOOL: &str = crate::definitions::TOOL_DEFINITIONS; const TABLE: &str = crate::definitions::TABLE_DEFINITIONS; const BOARD: &str = crate::presentation::BOARD_DEFINITIONS; /// The tools the kit has given this database. Every board the kit lays is a /// shell board, laid on every keep, so no board is ever "given". #[derive(Clone, Default, Serialize, Deserialize)] #[serde(default)] struct Given { tool: BTreeSet, } #[derive(Default)] struct Kit { tools: BTreeMap, /// The shell's boards, every one laid on every keep. boards: BTreeMap, tables: BTreeMap, giving: BTreeSet, } fn id(doc: &Value) -> &str { doc["id"].as_str().expect("a compiled definition has an id") } fn columns(doc: &Value) -> Vec { doc["columns"].as_array().cloned().unwrap_or_default() } fn fail(e: impl ToString) -> ToolFailure { ToolFailure::new(e.to_string()) } impl Kit { fn compiled(tools: &cotton_core::genesis::GenesisTools) -> Result { let mut kit = Self::default(); // Engine tables belong to the build, including engines that have no // package. Read raw files: yesterday's held definitions need not decode. for (_, raw) in cotton_core::definitions::BUILTIN_DEFINITION_FILES { let doc: Value = serde_json::from_str(raw).map_err(fail)?; kit.tables.insert(id(&doc).into(), doc); } kit.giving = tools.packages().into_iter().map(str::to_owned).collect(); for (_, name, bytes) in cotton_core::kit::fingerprinted() { if name == "manifest.json" { let doc: Value = serde_json::from_slice(bytes).map_err(fail)?; kit.tools.insert(id(&doc).into(), doc); } else if name.starts_with("tables/") { let doc: Value = serde_json::from_slice(bytes).map_err(fail)?; kit.tables.insert(id(&doc).into(), doc); } } for (table, raw) in cotton_core::kit::shell::SHELL_KIT_TABLES { kit.tables .insert((*table).into(), serde_json::from_str(raw).map_err(fail)?); } for (board, raw) in cotton_core::definitions::board::BUILTIN_BOARD_FILES { kit.boards .insert((*board).into(), serde_json::from_str(raw).map_err(fail)?); } // A table or tool held as retired is never laid or given, though the build may still carry its file until // the definition leaves the tree (TABLE DROP 1): laid, KEEP_RULE 13 would retire it again on every pass. kit.tables.retain(|table, _| !cotton_core::retired::is_gone_table(table)); kit.tools.retain(|tool, _| !cotton_core::retired::GONE_TOOLS.contains(&tool.as_str())); kit.giving.retain(|tool| !cotton_core::retired::GONE_TOOLS.contains(&tool.as_str())); // A kept tool still naming a retired table is laid without it. for tool in kit.tools.values_mut() { if let Some(tables) = tool["tables"].as_array_mut() { tables.retain(|table| !table.as_str().is_some_and(cotton_core::retired::is_gone_table)); } } Ok(kit) } fn given(&self) -> Given { Given { tool: self.giving.clone(), } } /// The shell boards as a fresh start lays them: the kit's own. fn laid(&self) -> BTreeMap { self.boards.clone() } /// The tools as a fresh start lays them: the kit's own. fn laid_tools(&self) -> BTreeMap { self.tools.clone() } /// The pictures the kit's package `tool` carries, by file name, as the /// standard base64 its asset rows keep. fn pictures(tool: &str) -> BTreeMap { cotton_core::kit::fingerprinted() .into_iter() .filter(|(id, name, _)| *id == tool && name.starts_with("pictures/")) .map(|(_, name, bytes)| (name["pictures/".len()..].to_string(), STANDARD.encode(bytes))) .collect() } /// The table looks as a fresh start lays them: the kit's own. fn laid_tables(&self) -> BTreeMap { self.tables.iter().map(|(id, table)| (id.clone(), look(table))).collect() } } /// A key of a table that is never its look: what it IS /// (`FIXED_DEFINITION_KEYS`), its columns and its card, which keep their own /// rules, and an object's `internal` (as `FIXED` in the Worker's /// `definition_writes.ts`). fn not_look(key: &str) -> bool { cotton_core::definitions::FIXED_DEFINITION_KEYS.contains(&key) || matches!(key, "columns" | "card" | "internal") } /// A table's look: every key but what it is, its columns and its card. fn look(table: &Value) -> Value { Value::Object( table .as_object() .into_iter() .flatten() .filter(|(key, _)| !not_look(key)) .map(|(key, value)| (key.clone(), value.clone())) .collect(), ) } /// `out` with the kit's look: each look key as `p` has it, in `out`'s order, /// one `p` lacks removed, then `p`'s others. fn look_laid(out: &Value, p: &Value) -> Value { let kit = p.as_object().expect("a table"); let mut next = serde_json::Map::new(); for (key, value) in out.as_object().expect("a table") { if not_look(key) { next.insert(key.clone(), value.clone()); } else if let Some(value) = kit.get(key) { next.insert(key.clone(), value.clone()); } } for (key, value) in kit { if !not_look(key) && !next.contains_key(key) { next.insert(key.clone(), value.clone()); } } Value::Object(next) } /// A board as kept: its `tools` part without the `empty` list an object /// works out and serves on Home (apps/business/src/fan.ts `withoutEmpty`), /// so a Home kept as served is not told apart as an edit. fn without_empty(board: &Value) -> Value { let mut out = board.clone(); if out.get("board_overlay").is_some() { if let Some(fields) = out .pointer_mut("/changes/fields/parts/items/tools/fields") .and_then(Value::as_object_mut) { fields.remove("empty"); } } else if let Some(parts) = out.get_mut("parts").and_then(Value::as_array_mut) { for part in parts.iter_mut().filter(|part| part["kind"] == "tools") { if let Some(part) = part.as_object_mut() { part.remove("empty"); } } } out } /// The rule and all compiled files plus the manifest's package set. A flavour /// changes what it gives even when the compiled personal kit did not change. fn kit_version(tools: &cotton_core::genesis::GenesisTools) -> String { static FILES: OnceLock = OnceLock::new(); format!( "{KEEP_RULE}:{}:{}", FILES.get_or_init(cotton_core::kit::fingerprint), serde_json::to_string(tools).expect("tool ids serialize") ) } fn meta(db: &Driver, key: &str) -> Result, StoreError> { Ok(db .get( "SELECT value FROM _kit_keep WHERE key = ?", &[SqlValue::Text(key.into())], )? .and_then(|r| r.text("value").map(str::to_owned))) } fn stamp( db: &Driver, version: &str, given: &Given, laid: &BTreeMap, laid_tools: &BTreeMap, laid_tables: &BTreeMap, ) -> Result<(), StoreError> { let encode = |e: serde_json::Error| StoreError::encode(e.to_string()); for (key, value) in [ (KIT_VERSION, version.to_string()), (KIT_GIVEN, serde_json::to_string(given).map_err(encode)?), (KIT_LAID, serde_json::to_string(laid).map_err(encode)?), (KIT_LAID_TOOLS, serde_json::to_string(laid_tools).map_err(encode)?), (KIT_LAID_TABLES, serde_json::to_string(laid_tables).map_err(encode)?), ] { db.run("INSERT INTO _kit_keep (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value", &[SqlValue::Text(key.into()), SqlValue::Text(value)])?; } Ok(()) } /// A fresh start already laid this kit: its first attach changes nothing. pub fn stamp_fresh( db: &Driver, tools: &cotton_core::genesis::GenesisTools, ) -> Result<(), ToolFailure> { let kit = Kit::compiled(tools)?; db.transaction(|db| { db.exec(DDL)?; stamp(db, &kit_version(tools), &kit.given(), &kit.laid(), &kit.laid_tools(), &kit.laid_tables()) }) .map_err(fail) } fn held(db: &Driver, table: &str) -> Result, ToolFailure> { db.all(&format!("SELECT id, definition FROM {table}"), &[]) .map_err(fail)? .into_iter() .map(|row| { let id = row .text("id") .ok_or_else(|| fail("a definition has no id"))? .to_string(); let doc = serde_json::from_str( row.text("definition") .ok_or_else(|| fail("a definition has no content"))?, ) .map_err(fail)?; Ok((id, doc)) }) .collect() } /// A held tool is the person's arrangement, whether or not its current /// definition receipt was written by `job:kit`. Keeping it wholesale also /// protects edits whose earlier receipts have been compacted away. fn view_cards(h: &Value, p: &Value) -> Value { let (Some(hv), Some(pv)) = (h["views"].as_array(), p["views"].as_array()) else { return h.clone(); }; let mut out = h.clone(); out["views"] = Value::Array( hv.iter() .map(|v| { let Some(p) = pv.iter().find(|p| p["id"] == v["id"]) else { return v.clone(); }; let mut v = v.clone(); if let Some(card) = p.get("card") { v["card"] = card.clone(); } else { v.as_object_mut().expect("a view").remove("card"); } v }) .collect(), ); out } /// Which tables are retired: the database holds one under an engine (the /// build's, which no person makes or edits) and the kit no longer ships it. /// A table the person made is held with no engine, and never retired. struct Retired<'a> { held: &'a BTreeMap, kit: &'a BTreeMap, } impl Retired<'_> { /// A table held as retired counts too: KEEP_RULE 13 retracted its definition before the tools are read, so a /// held tool still drawing it (Rigby 10's Meetings over `meeting`, TABLE DROP 1) takes the kit's views. fn contains(&self, id: &str) -> bool { cotton_core::retired::is_gone_table(id) || (!self.kit.contains_key(id) && self.held.get(id).is_some_and(|doc| doc["engine"].as_str().is_some_and(|engine| !engine.is_empty()))) } } fn view_reads(view: &Value) -> Option<&str> { view["read"]["table"].as_str() } /// Whether a held tool names a retired table, in a view's read or its tables. fn reads_retired(tool: &Value, retired: &Retired<'_>) -> bool { let named = |id: Option<&str>| id.is_some_and(|id| retired.contains(id)); tool["views"].as_array().into_iter().flatten().any(|v| named(view_reads(v))) || tool["tables"].as_array().into_iter().flatten().any(|t| named(t.as_str())) } /// A held tool that reads a retired table is the kit's old tool, never the /// person's: it takes the kit's views, then each held view the kit lacks that /// reads no retired table, and the kit's tables, then each held one that is /// not retired, and the kit's acts, then each held one the kit lacks. Its /// other keys stay held (Memories off memory_entry onto memory, 3 Nov 2026). fn repointed(h: &Value, p: &Value, retired: &Retired<'_>) -> Value { let kit_views = p["views"].as_array().cloned().unwrap_or_default(); let kit_tables = p["tables"].as_array().cloned().unwrap_or_default(); let mut views = kit_views.clone(); views.extend(h["views"].as_array().into_iter().flatten().filter(|v| { !kit_views.iter().any(|k| k["id"] == v["id"]) && !view_reads(v).is_some_and(|t| retired.contains(t)) }).cloned()); let mut tables = kit_tables.clone(); tables.extend(h["tables"].as_array().into_iter().flatten().filter(|t| { !kit_tables.contains(t) && !t.as_str().is_some_and(|t| retired.contains(t)) }).cloned()); // The kit's acts too, which its views name (Music's On this phone), then // each held one the kit lacks. let kit_acts = p["acts"].as_array().cloned().unwrap_or_default(); let mut acts = kit_acts.clone(); acts.extend(h["acts"].as_array().into_iter().flatten().filter(|a| !kit_acts.iter().any(|k| k["id"] == a["id"])).cloned()); let mut out = h.clone(); out["views"] = Value::Array(views); out["tables"] = Value::Array(tables); if !acts.is_empty() { out["acts"] = Value::Array(acts); } out } fn shell_board(h: Option<&Value>, p: &Value) -> Value { let Some(h) = h else { return p.clone() }; let (Some(hp), Some(pp)) = (h["parts"].as_array(), p["parts"].as_array()) else { return p.clone(); }; let mut out = p.clone(); out["parts"] = Value::Array( pp.iter() .map(|part| { let mut next = part.clone(); let Some(rows) = part["rows"].as_array() else { return next; }; if let Some(h) = hp.iter().rev().find(|h| { h["kind"] == part["kind"] && h["table"] == part["table"] && h["rows"].is_array() }) { let mut all = rows.clone(); all.extend( h["rows"] .as_array() .expect("rows") .iter() .filter(|r| !rows.iter().any(|p| p["id"] == r["id"])) .cloned(), ); next["rows"] = Value::Array(all); } next }) .collect(), ); out } fn engined(p: &Value) -> bool { p["engine"].as_str().is_some_and(|engine| !engine.is_empty()) } /// How many rows, live or binned, this file holds in the table `id` (none /// while its made table is not here yet). fn rows_in(db: &Driver, id: &str) -> Result { let table = crate::mcp::handlers::tables::made_table(id); if !db.table_exists(&table).map_err(fail)? { return Ok(0); } Ok(db.get(&format!("SELECT COUNT(*) AS n FROM {table}"), &[]).map_err(fail)?.and_then(|row| row.int("n")).unwrap_or(0)) } fn grown(h: &Value, p: &Value) -> Value { let mut out = merged(h, p); retire(&mut out, h, p); out } /// The kit's retired columns, laid on a held table only once it no longer /// holds them (5 Nov 2026): an add-only keep takes no column away, and a /// retired key a table still holds is refused ("a retired column is no /// longer a column"), so the owner's film table keeps `notes` until its /// reshape. The held table's own retired entries stay first. fn retire(out: &mut Value, h: &Value, p: &Value) { let held_had = h.get("retired").is_some(); let mut retired = h["retired"].as_array().cloned().unwrap_or_default(); let named = columns(out); for entry in p["retired"].as_array().into_iter().flatten() { let key = &entry["key"]; if retired.iter().any(|r| r["key"] == *key) || named.iter().any(|c| c["key"] == *key) { continue; } retired.push(entry.clone()); } let table = out.as_object_mut().expect("a table"); if retired.is_empty() && !held_had { table.remove("retired"); } else { table.insert("retired".into(), Value::Array(retired)); } } /// A held choice column takes each choice the kit adds that it lacks, after /// its own, with the kit's label for it (5 Nov 2026): the film's status grows /// want_to_watch, watching and stopped beside the watchlist its rows still /// hold, so the kit's card, whose state names the new ones, stays a card of /// the table. No held choice is taken. fn choices_added(c: &mut Value, p: &Value) { if c["type"] != "choice" || p["type"] != "choice" { return; } let (Some(have), Some(kit)) = (c["choices"].as_array().cloned(), p["choices"].as_array()) else { return; }; let more: Vec = kit.iter().filter(|choice| !have.contains(choice)).cloned().collect(); if more.is_empty() { return; } let mut labels = c["labels"].as_object().cloned().unwrap_or_default(); let mut labelled = false; for choice in &more { if let Some(label) = choice.as_str().and_then(|key| p["labels"].get(key)) { labels.insert(choice.as_str().expect("a labelled choice").to_owned(), label.clone()); labelled = true; } } let mut all = have; all.extend(more); c["choices"] = Value::Array(all); if labelled { c["labels"] = Value::Object(labels); } } /// The keys of a table that are the build's on every keep (KEEP_RULE 10). const BUILDS: [&str; 2] = ["commands", "acts"]; /// Whether each of a table's marks names one of its commands or acts. fn marks_bound(table: &Value) -> bool { let named: BTreeSet<&str> = BUILDS .iter() .flat_map(|key| table[*key].as_array().into_iter().flatten()) .filter_map(|c| c["id"].as_str()) .collect(); table["marks"].as_object().into_iter().flatten().all(|(_, id)| id.as_str().is_some_and(|id| named.contains(id))) } /// A held table whose own columns cannot carry the kit's `send` is kept /// without it (13 Nov 2026): `send` is the kit's to say of the /// kit's shape, and a held table an add-only keep leaves in an older shape — /// the music before Cotton Music, kept as it is once a song is held, whose /// album's `artist_name` is still worked out through its artist — is not /// sent until it takes the kit's columns. The keep goes on, said once in the /// log; it never fails a whole kit on one table's send. fn unsendable_kept_whole(id: &str, next: &mut Value) { if next.get("send").is_none() { return; } let refused = cotton_core::definitions::TableDefinition::from_json(&next.to_string()) .and_then(|definition| definition.validate()); if let Err(cotton_core::definitions::DefinitionError::Send(why)) = refused { tracing::info!(table = %id, why = %why, "kit keep: the held table's columns cannot carry the kit's send, so it is kept unsendable"); next.as_object_mut().expect("a table").remove("send"); } } fn merged(h: &Value, p: &Value) -> Value { let hc = columns(h); let pc = columns(p); if p["engine"] .as_str() .is_some_and(|engine| !engine.is_empty()) { let mut out = p.clone(); let mut cols = pc.clone(); cols.extend( hc.into_iter() .filter(|c| !pc.iter().any(|p| p["key"] == c["key"])), ); out["columns"] = Value::Array(cols); return out; } let mut out = h.clone(); for (key, value) in p.as_object().expect("a table") { if key == "card" || out.get(key).is_none() { out[key] = value.clone(); } } // Commands and acts are the build's: exactly the kit's, one it lacks removed. for key in BUILDS { match p.get(key) { Some(value) => out[key] = value.clone(), None => { out.as_object_mut().expect("a table").remove(key); } } } let mut cols: Vec = hc .iter() .map(|c| { let mut c = c.clone(); if let Some(p) = pc.iter().find(|p| p["key"] == c["key"]) { if c["type"] == "text" && p["type"] == "link" && p["link_to"].is_string() { c["type"] = json!("link"); c["link_to"] = p["link_to"].clone(); } choices_added(&mut c, p); // A column's readings no row holds (KEEP_RULE 12). for key in ["until", "default"] { if c.get(key).is_none() { if let Some(value) = p.get(key) { c[key] = value.clone(); } } } } c }) .collect(); cols.extend( pc.into_iter() .filter(|p| !hc.iter().any(|c| c["key"] == p["key"])), ); out["columns"] = Value::Array(cols); out } /// What [`drop_old_music`] did: whether the old music went, so the pass lays /// the reshaped tables and the Music tool whole. #[derive(Debug, Default, PartialEq, Eq)] struct Dropped { rows: usize, removed: usize, } /// KEEP_RULE 8, the phone's `drop_old_music` (5 Nov 2026). The old music is /// held while a table only it had (`GONE_TABLES`: track, playlist, /// playlist_track) is defined here; music_album, artist and listen are /// Cotton Music's too, so holding them says nothing. With no `song` row, /// every row of the old tables, binned ones too, is retracted (so nothing /// reads them and an export never carries them) and the gone tables' /// definitions are retracted; the caller lays the reshaped tables and the /// Music tool whole. A copy holding a song has begun new music: it keeps its /// old tables as they are, said once in the log, no error to the person. /// Once dropped, no gone table is defined, so a later pass finds nothing. fn drop_old_music( db: &Driver, now: chrono::DateTime, random: Arc, ) -> Result, ToolFailure> { use cotton_core::music::{GONE_TABLES, OLD_TABLES, SONG}; use crate::mcp::handlers::tables::made_table; use crate::mcp::writer::Retract; let held_gone: Vec<&str> = GONE_TABLES .into_iter() .map(|id| -> Result, ToolFailure> { Ok(db .get(&format!("SELECT 1 AS here FROM {TABLE} WHERE id = ?"), &[SqlValue::Text(id.into())]) .map_err(fail)? .map(|_| id)) }) .filter_map(Result::transpose) .collect::>()?; if held_gone.is_empty() { return Ok(None); } if rows_in(db, SONG)? > 0 { tracing::info!(tables = ?held_gone, "kit keep: songs are held already, so this copy keeps its old music tables as they are"); return Ok(None); } let mut doomed = Vec::new(); for id in OLD_TABLES { let table = made_table(id); if !db.table_exists(&table).map_err(fail)? { continue; } for row in db.all(&format!("SELECT id FROM {table}"), &[]).map_err(fail)? { let row_id = row.text("id").ok_or_else(|| fail(format!("a {id} row has no id")))?; doomed.push((table.clone(), row_id.to_owned())); } } let file = cotton_store::file_identity::read_file_identity(db) .map_err(fail)? .ok_or_else(|| fail("the database has no identity"))?; let owner = db .get("SELECT owner_id FROM _meta", &[]) .map_err(fail)? .and_then(|r| r.text("owner_id").map(str::to_owned)) .unwrap_or_default(); let actor = cotton_store::mint::Actor::DeviceJob(cotton_store::mint::JobName::named("kit").map_err(fail)?); let services = ToolServices::none(); let audit = |_: &str, _: &str| {}; let mut ctx = Ctx::for_worker(db, &file, &owner, actor, "kit.keep", now, random, &services, &audit); for (table, row_id) in &doomed { ctx.writer()?.retract(table, row_id, Retract::Machine("drop_old_music")); } for id in &held_gone { ctx.writer()?.retract(TABLE, id, Retract::Machine("drop_old_music")); } ctx.commit()?; tracing::info!(rows = doomed.len(), removed = ?held_gone, "kit keep: dropped the music before Cotton Music"); Ok(Some(Dropped { rows: doomed.len(), removed: held_gone.len() })) } /// KEEP_RULE 13 (17 Nov 2026, the object's rule 15): each table and tool /// `cotton_core::retired` names that this copy defines is held as retired: /// its definition is kept under [`KIT_RETIRED`] (beside any held there /// already) and its definition row retracted, so nothing serves, draws or /// offers it. The rows of a retired table stay in storage, untouched. Once /// retired, nothing is defined, so a later pass finds nothing. Answers how /// many definitions it retired. fn retire_gone( db: &Driver, now: chrono::DateTime, random: Arc, ) -> Result { use crate::mcp::writer::Retract; use cotton_core::retired::{GONE_TABLES, GONE_TOOLS}; let mut retired: BTreeMap> = meta(db, KIT_RETIRED) .map_err(fail)? .map(|s| serde_json::from_str(&s).map_err(fail)) .transpose()? .unwrap_or_default(); let mut going: Vec<(&str, &str)> = Vec::new(); for (kind, store, ids) in [("table", TABLE, &GONE_TABLES[..]), ("tool", TOOL, &GONE_TOOLS[..])] { for id in ids { let Some(row) = db .get(&format!("SELECT definition FROM {store} WHERE id = ?"), &[SqlValue::Text((*id).into())]) .map_err(fail)? else { continue; }; let doc: Value = serde_json::from_str(row.text("definition").ok_or_else(|| fail("a definition has no content"))?).map_err(fail)?; retired.entry(kind.to_owned()).or_default().insert((*id).to_owned(), doc); going.push((store, id)); } } if going.is_empty() { return Ok(0); } db.run( "INSERT INTO _kit_keep (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value", &[SqlValue::Text(KIT_RETIRED.into()), SqlValue::Text(serde_json::to_string(&retired).map_err(fail)?)], ) .map_err(fail)?; let file = cotton_store::file_identity::read_file_identity(db) .map_err(fail)? .ok_or_else(|| fail("the database has no identity"))?; let owner = db .get("SELECT owner_id FROM _meta", &[]) .map_err(fail)? .and_then(|r| r.text("owner_id").map(str::to_owned)) .unwrap_or_default(); let actor = cotton_store::mint::Actor::DeviceJob(cotton_store::mint::JobName::named("kit").map_err(fail)?); let services = ToolServices::none(); let audit = |_: &str, _: &str| {}; let mut ctx = Ctx::for_worker(db, &file, &owner, actor, "kit.keep", now, random, &services, &audit); for (store, id) in &going { ctx.writer()?.retract(store, id, Retract::Machine("retire_gone")); } ctx.commit()?; tracing::info!(retired = ?going.iter().map(|(_, id)| *id).collect::>(), "kit keep: held as retired, rows kept"); Ok(going.len()) } /// Keep once, atomically with receipts and metadata; returns the number of /// definition rows changed. A matching stamp performs no writes at all. pub fn keep( db: &Driver, now: chrono::DateTime, random: Arc, tools: &cotton_core::genesis::GenesisTools, ) -> Result { let version = kit_version(tools); if db.table_exists("_kit_keep").map_err(fail)? && meta(db, KIT_VERSION).map_err(fail)?.as_deref() == Some(version.as_str()) { return Ok(0); } let kit = Kit::compiled(tools)?; keep_kit(db, now, random, &kit, &version) } fn keep_kit( db: &Driver, now: chrono::DateTime, random: Arc, kit: &Kit, version: &str, ) -> Result { db.transaction(|db| { db.exec(DDL)?; if meta(db, KIT_VERSION)?.as_deref() == Some(version) { return Ok(0); } let pass = || -> Result { // Before anything is read: the reshaped tables are laid over // what the drop leaves. let dropped = drop_old_music(db, now, random.clone())?; let retired_now = retire_gone(db, now, random.clone())?; let tools = held(db, TOOL)?; let boards = held(db, BOARD)?; let tables = held(db, TABLE)?; let before: Option = meta(db, KIT_GIVEN) .map_err(fail)? .map(|s| serde_json::from_str(&s).map_err(fail)) .transpose()?; let mut given = before.clone().unwrap_or_default(); let last_laid: BTreeMap = meta(db, KIT_LAID) .map_err(fail)? .map(|s| serde_json::from_str(&s).map_err(fail)) .transpose()? .unwrap_or_default(); let mut laid = BTreeMap::new(); let last_laid_tables: BTreeMap = meta(db, KIT_LAID_TABLES) .map_err(fail)? .map(|s| serde_json::from_str(&s).map_err(fail)) .transpose()? .unwrap_or_default(); let mut laid_tables = BTreeMap::new(); let last_laid_tools: BTreeMap = meta(db, KIT_LAID_TOOLS) .map_err(fail)? .map(|s| serde_json::from_str(&s).map_err(fail)) .transpose()? .unwrap_or_default(); let mut laid_tools = BTreeMap::new(); // The held tools laid whole, whose carried pictures follow. let mut whole: Vec<&String> = Vec::new(); // Unstamped pre-keep installs were given their founding kit. A // missing row with a retract receipt is a removal, not a new tool. if before.is_none() { for row in db .all( "SELECT row_id FROM _tombstones WHERE tbl = ?", &[SqlValue::Text(TOOL.into())], ) .map_err(fail)? { if let Some(id) = row.text("row_id") { given.tool.insert(id.into()); } } } let file = cotton_store::file_identity::read_file_identity(db) .map_err(fail)? .ok_or_else(|| fail("the database has no identity"))?; let owner = db .get("SELECT owner_id FROM _meta", &[]) .map_err(fail)? .and_then(|r| r.text("owner_id").map(str::to_owned)) .unwrap_or_default(); let actor = cotton_store::mint::Actor::DeviceJob( cotton_store::mint::JobName::named("kit").map_err(fail)?, ); let services = ToolServices::none(); let audit = |_: &str, _: &str| {}; let mut ctx = Ctx::for_worker( db, &file, &owner, actor, "kit.keep", now, random, &services, &audit, ); let mut changes = Vec::new(); let retired = Retired { held: &tables, kit: &kit.tables }; let music_whole = |id: &str| dropped.is_some() && id == cotton_core::music::MUSIC_TOOL; for (id, p) in &kit.tools { match tools.get(id) { Some(h) => { // Edited is told from what the kit last laid; with no // record, a tool the kit gave is the kit's to lay // (KEEP_RULE 11, the object's rule 9). let record = last_laid_tools.get(id); let unedited = match record { Some(record) => record == h, None => before.as_ref().is_some_and(|before| before.tool.contains(id)), }; let next = if music_whole(id) { laid_tools.insert(id.clone(), p.clone()); p.clone() } else if unedited { // The kit's whole, its picture the person's pick. let mut next = p.clone(); if let Some(picture) = h.get("picture") { next["picture"] = picture.clone(); } laid_tools.insert(id.clone(), next.clone()); whole.push(id); next } else { // Kept as edited from what the kit laid; with no record, from the kit's tool now. laid_tools.insert(id.clone(), record.cloned().unwrap_or_else(|| p.clone())); if reads_retired(h, &retired) { view_cards(&repointed(h, p, &retired), p) } else { view_cards(h, p) } }; if next != *h { changes.push((TOOL, id, next, true)); } } None if kit.giving.contains(id) && !given.tool.contains(id) => { laid_tools.insert(id.clone(), p.clone()); changes.push((TOOL, id, p.clone(), false)) } None => {} } } for (id, p) in &kit.boards { let h = boards.get(id); let next = shell_board(h, p); laid.insert(id.clone(), next.clone()); // The person's edit since the kit last laid it stays; // with no record, the held board is the kit's to lay. let edited = h.zip(last_laid.get(id)).is_some_and(|(h, before)| { without_empty(h) != without_empty(before) }); if !edited && h != Some(&next) { changes.push((BOARD, id, next, h.is_some())); } } for (id, p) in &kit.tables { let h = tables.get(id); let kit_look = look(p); laid_tables.insert(id.clone(), kit_look.clone()); let next = match h { None => p.clone(), Some(_) if dropped.is_some() && cotton_core::music::RESHAPED_TABLES.contains(&id.as_str()) => p.clone(), // A table holding no row (a binned one counts) is the // kit's whole: nothing names a column or a choice it // would lose (kit_keep.ts, 4 Nov 2026: Books' book). Some(_) if !engined(p) && rows_in(db, id)? == 0 => p.clone(), // An engine's table is the kit's definition already. Some(h) if engined(p) => grown(h, p), Some(h) => { let held_look = look(h); let record = last_laid_tables.get(id); if record.is_none_or(|record| *record == held_look) || held_look == kit_look { look_laid(&grown(h, p), p) } else { // Kept as edited, told from what the kit last laid. let record = record.expect("an edit is told from a record").clone(); let apart: Vec<&String> = held_look .as_object() .expect("a look") .keys() .chain(kit_look.as_object().expect("a look").keys()) .filter(|key| held_look.get(*key) != kit_look.get(*key)) .collect::>() .into_iter() .collect(); tracing::info!(table = %id, keys = ?apart, "kit keep: the person's look is kept over the kit's, since it differs from what the kit last laid"); laid_tables.insert(id.clone(), record); let mut next = grown(h, p); if !marks_bound(&next) { match p.get("marks") { Some(marks) => next["marks"] = marks.clone(), None => { next.as_object_mut().expect("a table").remove("marks"); } } tracing::info!(table = %id, "kit keep: the kept look's marks named a command the kit no longer lays, so they are the kit's"); } next } } }; let mut next = next; if h.is_some() { unsendable_kept_whole(id, &mut next); } if h != Some(&next) { // The kit must be drawable before we stamp it. A bad // non-kit definition is deliberately outside this rule. cotton_core::definitions::TableDefinition::from_json(&next.to_string()) .and_then(|definition| definition.validate()) .map_err(fail)?; changes.push((TABLE, id, next, h.is_some())); } } let count = changes.len() + dropped.as_ref().map_or(0, |d| d.removed) + retired_now; for (table, id, definition, exists) in changes { let patch = json!({"id":id,"definition":definition,"builtin":false}) .as_object() .expect("a patch") .clone(); if exists { update_row(&mut ctx, table, id, patch)?; } else { insert_row(&mut ctx, table, id, patch)?; } } // Newly given packages carry their picture payload too, just as // add_tool does. for tool in kit .giving .iter() .filter(|id| !tools.contains_key(*id) && !given.tool.contains(*id)) { crate::mcp::handlers::tool_packages::replace_pictures(&mut ctx, tool, &Kit::pictures(tool))?; } // A held tool laid whole takes the pictures its package carries // that the file lacks (a fan tile's stock and pictograms), add-only: // any picture of the person's stays. for tool in whole { crate::mcp::handlers::tool_packages::add_pictures(&mut ctx, tool, &Kit::pictures(tool))?; } ctx.commit()?; let (_, refused) = cotton_store::schema::package_shape::step_file(db).map_err(fail)?; if let Some((id, why)) = refused.iter().find(|(id, _)| kit.tables.contains_key(id)) { return Err(fail(format!("the kit's table {id} cannot be kept: {why}"))); } given.tool.extend(kit.given().tool); stamp(db, version, &given, &laid, &laid_tools, &laid_tables).map_err(fail)?; Ok(count) }; pass().map_err(|e| StoreError::refused(e.0)) }) .map_err(fail) } #[cfg(test)] #[path = "kit_keep_tests.rs"] mod tests;