//! HIDE FROM SCREEN (owner, 27 Nov 2026): THE predicate. A title of his films is hidden from the screen exactly when it//! is in at least one hidden category of his films. Worked out at read from the categories' flag alone//! (`record_group.hidden`, kept on the phone in `cotton_groups.hidden`, clear so it syncs between his phones), never//! copied onto a title, an episode, a file or a download. Every reader that shows his films outside Hidden asks this://! the Cinemas phone methods (cotton-ffi `cinemas_home`), the shared reads of his films' tables, and the summaries and//! charts below.//!//! A hidden category hides its titles while it is live AND while the Bin holds it: a delete by an assistant, the Mac,//! another build, or an undo of its making never shows them. Only erased for good, or shown again, does it stop.use std::collections::BTreeSet;use rusqlite::types::ValueasSqlValue;use serde_json::Value;usesuper::groups::{GROUPS, MEMBERS};usesuper::made_table;usecrate::mcp::dispatch::Ctx;/// His films' tables: every one a hidden title's row, or a row naming one, may be in.pubconst FAMILY: [&str; 8] = ["film", "film_season", "film_episode", "watch", "record_group", "group_member", "fetch", "fetch_file"];/// The links by which a row names a hidden title: a season's film, an episode's series or season, a play's film or/// episode, a downloaded file's film, episode or download, a list member's record or list.pubconst LINKS: [&str; 7] = ["film", "series", "season", "episode", "fetch", "record_id", "group"];/// What is hidden from the screen, read once: his hidden film categories (live or binned) and every row they hide.#[derive(Debug, Default, Clone)]pubstructHiding {pub groups: BTreeSet<String>,pub titles: BTreeSet<String>,/// The plays (`watch` rows) of a hidden title or episode (CORE 4, add 1): named by their own id, so a read that/// holds only a row's id (a Find hit, a Bin entry) leaves them out as it does the titles, before it counts.pub plays: BTreeSet<String>,}implHiding {/// Every hidden id, categories, rows and plays alike: the one set a read leaves out by id.pubfn all(&self) -> BTreeSet<String> {self.titles.iter().chain(&self.groups).chain(&self.plays).cloned().collect() }/// Whether a row (its id and its columns) is hidden, or names a hidden one by a link.pubfn hides(&self, id: Option<&str>, data: &serde_json::Map<String, Value>) -> bool {let named = |id: &str| self.titles.contains(id) || self.groups.contains(id); id.is_some_and(|id| named(id) || self.plays.contains(id)) || LINKS.iter().any(|key| data.get(*key).and_then(Value::as_str).is_some_and(named)) }}// ── THE BIN'S GATE (CORE 4, L1) ─────────────────────────────────────────────────────────────────────────────────────//// Two Bins hold his binned rows: the shared Bin (every app's, and an assistant's `list_bin` / `empty_bin`), which never// holds a hidden title, and the Bin inside Hidden, which holds the hidden ones alone. Every read of a binned row and// every erase or restore of one passes through [`bin_shows`]: `tables::every_binned` (the shared list, `binned`,// `erase_binned`, the bin table's list) and `tables::locate_binned` (`bin_record`, `erase_one_binned`,// `restore_binned`, `bin_again`), and Cinemas' own Bin (`cinemas.bin`, `cinemas.erase`). Which Bin is asked is said// by the caller once, around its whole call ([`in_hidden_bin`]); nothing said is the shared Bin, so a new caller that// forgets gets the Bin that names no hidden title. [`BIN_DOORS`] lists them, and a test fails when a Bin function is// added that is not one of them.thread_local! {static HIDDEN_BIN: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };}/// Run `f` as the Bin inside Hidden: it sees and erases the hidden titles alone. The caller has checked Hidden is open.pubfn in_hidden_bin<T>(f: implFnOnce() -> T) -> T {structBack(bool);implDropforBack {fn drop(&mutself) { HIDDEN_BIN.with(|cell| cell.set(self.0)); } }let _back = Back(HIDDEN_BIN.with(|cell| cell.replace(true))); f()}/// Whether the Bin asked now shows (and so may erase or restore) a binned row: the shared Bin every row but a hidden/// one, the Bin inside Hidden the hidden ones alone.pubfn bin_shows(hiding: &Hiding, id: Option<&str>, data: &serde_json::Map<String, Value>) -> bool { hiding.hides(id, data) == HIDDEN_BIN.with(std::cell::Cell::get)}/// Every function that reads binned rows of his films itself (by `deleted_at IS NOT NULL`, or the Bin's own row/// readers `group_rows`, `made_rows`, `locate`), each passing through [`bin_shows`]: (file under `crates/`, function)./// Every other Bin read, erase and restore reaches the rows through one of these (`binned`, `erase_binned` and the/// bin table's list through `every_binned`; `bin_record`, `erase_one_binned`, `restore_binned` and `bin_again`/// through `locate_binned`).pubconst BIN_DOORS: [(&str, &str); 6] = [ ("cotton-tools/src/mcp/handlers/tables/mod.rs", "every_binned"), ("cotton-tools/src/mcp/handlers/tables/mod.rs", "locate_binned"), ("cotton-tools/src/mcp/handlers/tables/mod.rs", "bin_record"), ("cotton-ffi/src/phone/cinemas_more.rs", "bin"), ("cotton-ffi/src/phone/cinemas_more.rs", "erase"),// `Library::of` inside Hidden: a hidden category the Bin holds (`groups::group_of` answering it binned). ("cotton-ffi/src/phone/cinemas_home.rs", "of"),];/// The functions that read rows the Bin's way and are not a Bin of his films, each with why: (file, function, why).pubconst NOT_BIN_DOORS: [(&str, &str, &str); 3] = [ ("cotton-tools/src/mcp/handlers/tables/mod.rs", "locate", "the locator the doors ask; called by `locate_binned` and `erase_record` alone"), ("cotton-tools/src/mcp/handlers/tables/mod.rs", "erase_record", "a verb's own erase by its own rule (a message deleted for everyone), not the Bin's; Cinemas' Bin calls it only for ids its door showed"), ("cotton-ffi/src/phone/chat_revoked.rs", "sweep_revoked", "Comms' revoked messages, never a row of his films"),];#[cfg(test)]mod tests {usesuper::*;/// Each function of a Rust source file: (name, its code up to the next function, comments left out and every run/// of white space one space, so a statement split over lines reads as one). A function is a line that starts,/// after any of `pub`, `pub(…)`, `async`, `const`, `unsafe` and `extern "…"`, with `fn`.fn functions(source: &str) -> Vec<(String, String)> {letmut found: Vec<(String, String)> = Vec::new();for line in source.lines() {letmut head = line.trim_start();loop {let before = head;for qualifier in ["pub ", "async ", "const ", "unsafe ", "extern \"C\" ", "extern \"Rust\" "] { head = head.strip_prefix(qualifier).unwrap_or(head); }if head.starts_with("pub(") { head = head.split_once(") ").map_or(head, |(_, rest)| rest); }if head == before {break; } }ifletSome(rest) = head.strip_prefix("fn ") {let name: String = rest.chars().take_while(|c| c.is_alphanumeric() || *c == '_').collect(); found.push((name, String::new()));continue; }// A comment never counts: neither a reader named in one, nor a gate.let code = if line.trim_start().starts_with("//") { "" } else { line.split(" // ").next().unwrap_or(line) };ifletSome((_, body)) = found.last_mut() { body.push(' '); body.push_str(code); } } found.into_iter().map(|(name, body)| (name, body.split_whitespace().collect::<Vec<_>>().join(" "))).collect() }fn sources() -> Vec<(String, String)> {let crates = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).parent().expect("crates/").to_path_buf();letmut out = Vec::new();for root in ["cotton-tools/src", "cotton-ffi/src"] {letmut stack = vec![crates.join(root)];whileletSome(dir) = stack.pop() {for entry in std::fs::read_dir(&dir).expect("a source folder") {let path = entry.expect("an entry").path();let name = path.file_name().and_then(|n| n.to_str()).unwrap_or_default().to_string();if path.is_dir() { stack.push(path);// This file names the readers in its own rule and test. } elseif name.ends_with(".rs") && !name.contains("test") && name != "hidden.rs" {let relative = path.strip_prefix(&crates).expect("under crates/").to_string_lossy().replace('\\', "/"); out.push((relative, std::fs::read_to_string(&path).expect("a source file"))); } } } } out }// RULE (CORE 4, L1; widened in CORE 5, L4): ONE gate. Every function that reads binned rows itself is a door that// asks `bin_shows` (or is named, with why, as not a Bin of his films); a Bin read or erase added any other way fails// here. A TRIPWIRE, not a proof: it reads the source's text for the ways a binned row is read today (the SQL tests// below, however split over lines or built by format!, and the Bin's own row readers); a binned read written some// new way (a query builder's Filter on deleted_at, a new helper) passes it unseen, so a new reader of binned rows// also adds its pattern here. #[test]fn every_bin_door_passes_through_the_gate() {let gate = ["bin_shows(", "shown_in_bin(", "shows(&hiding", "every_binned(", "locate_binned("];let readers = ["deleted_at IS NOT NULL","deleted_at <> ''","deleted_at != ''","deleted_at > ''","group_rows(","made_rows("," locate(ctx","Some(_))) = groups::group_of(", ];letmut seen = Vec::new();for (file, source) in sources() {for (name, body) in functions(&source) {if !readers.iter().any(|reader| body.contains(reader)) || matches!(name.as_str(), "group_rows" | "made_rows") && file.ends_with("tables/mod.rs") {continue; } seen.push((file.clone(), name.clone()));if NOT_BIN_DOORS.iter().any(|(f, n, _)| *f == file && *n == name) {continue; } assert!(BIN_DOORS.contains(&(file.as_str(), name.as_str())), "{file} {name} reads binned rows and is not a door of the Bin's gate (hidden::BIN_DOORS)"); assert!(gate.iter().any(|g| body.contains(g)), "{file} {name} is a Bin door that does not ask hidden::bin_shows"); } }for (file, name) in BIN_DOORS.iter().map(|(f, n)| (*f, *n)).chain(NOT_BIN_DOORS.iter().map(|(f, n, _)| (*f, *n))) { assert!(seen.iter().any(|(f, n)| f == file && n == name), "{file} {name} is listed but reads no binned rows: keep the lists true"); } }fn file_with_groups(dir: &std::path::Path) -> cotton_store::Driver {let writer = cotton_store::Driver::open(dir.join("hidden.db")).expect("a file"); writer .exec(&format!("CREATE TABLE {GROUPS} (id TEXT PRIMARY KEY, workspace_id TEXT, table_id TEXT, hidden INTEGER, deleted_at TEXT); CREATE TABLE {MEMBERS} (group_id TEXT, record_id TEXT); INSERT INTO {GROUPS} VALUES ('synthetic-edits', 'w', 'film', 0, NULL); INSERT INTO {MEMBERS} VALUES ('synthetic-edits', 'synthetic-film');" )) .expect("groups"); writer }// RULE (CORE 4, tests): another phone hides a category; this phone's pull commits it on the writer, and a screen's// read on its own reader misses the kept answer and hides the title. #[test]fn another_connections_commit_is_seen_past_the_kept_answer() {let dir = tempfile::tempdir().expect("a folder");let writer = file_with_groups(dir.path());let reader = cotton_store::Driver::open_reader(dir.path().join("hidden.db")).expect("a reader"); assert!(hiding_in(&reader, "w").expect("read").titles.is_empty(), "nothing hidden yet"); assert!(hiding_in(&reader, "w").expect("read again").titles.is_empty(), "kept"); writer.run(&format!("UPDATE {GROUPS} SET hidden = 1"), &[]).expect("the pull hides it"); assert!(hiding_in(&reader, "w").expect("read").titles.contains("synthetic-film"), "the kept answer was missed"); }// RULE (CORE 5, L5): kept per connection, and kept through every write the rule does not read (a play's seconds// moving, a title's position saved); a change it reads (a list's member) is read again. Other tests in this// process write watched tables too, so "kept" is asserted only while the watch count stood. #[test]fn a_playback_save_keeps_the_answer_and_a_category_change_does_not() {let dir = tempfile::tempdir().expect("a folder");let writer = file_with_groups(dir.path()); writer .exec(&format!("CREATE TABLE {} (id TEXT PRIMARY KEY, workspace_id TEXT, film TEXT, episode TEXT, seconds INTEGER, deleted_at TEXT); CREATE TABLE {} (id TEXT PRIMARY KEY, workspace_id TEXT, title TEXT, position INTEGER, deleted_at TEXT); UPDATE {GROUPS} SET hidden = 1; INSERT INTO {} VALUES ('synthetic-play', 'w', 'synthetic-film', '', 0, NULL);", made_table("watch"), made_table("film"), made_table("watch"), )) .expect("plays");let reader = cotton_store::Driver::open_reader(dir.path().join("hidden.db")).expect("a reader");let reads = || READS.with(std::cell::Cell::get);// The watch count before the answers are first kept: "kept" holds only if nothing watched changed since.let watched = cotton_store::driver::watched_changes();let first = hiding_in(&reader, "w").expect("read"); assert!(first.plays.contains("synthetic-play"), "{first:?}"); hiding_in(&writer, "w").expect("the writer keeps its own");let before = reads(); writer.run(&format!("UPDATE {} SET seconds = seconds + 5", made_table("watch")), &[]).expect("a play's seconds"); writer.run(&format!("INSERT INTO {} VALUES ('synthetic-film', 'w', 'Invented', 300, NULL)", made_table("film")), &[]).expect("a title saved"); writer.run(&format!("UPDATE {} SET position = 305", made_table("film")), &[]).expect("a position saved"); hiding_in(&reader, "w").expect("read"); hiding_in(&writer, "w").expect("read");if cotton_store::driver::watched_changes() == watched { assert_eq!(reads(), before, "neither connection read the rule again, and neither pushed the other's answer out"); } writer.run(&format!("INSERT INTO {MEMBERS} VALUES ('synthetic-edits', 'synthetic-other')"), &[]).expect("a member added"); assert!(hiding_in(&reader, "w").expect("read").titles.contains("synthetic-other"), "a change the rule reads is read again"); }// RULE (CORE 4, L2): an answer worked out inside a write that rolls back is never kept. #[test]fn nothing_is_kept_from_inside_a_write_that_rolls_back() {let dir = tempfile::tempdir().expect("a folder");let writer = file_with_groups(dir.path()); assert!(hiding_in(&writer, "w").expect("read").titles.is_empty());let rolled: Result<(), cotton_store::StoreError> = writer.transaction(|db| { db.run(&format!("UPDATE {GROUPS} SET hidden = 1"), &[])?; assert!(db.in_write_transaction()); assert!(hiding_in(db, "w").expect("read inside").titles.contains("synthetic-film"), "inside, it reads its own write");Err(cotton_store::StoreError::refused("rolled back on purpose")) }); assert!(rolled.is_err()); assert!(!writer.in_write_transaction()); assert!(hiding_in(&writer, "w").expect("read after").titles.is_empty(), "the rolled-back answer was not kept"); }}/// The rows the rule reads, wherever they come from: this phone's copy ([`hiding`]), or the object's pages for a/// phone that does not hold the whole object (the Data app).#[derive(Debug, Default, Clone)]pubstructRuleRows {/// Every category, live or binned: its id, its table, its hidden flag.pub groups: Vec<(String, String, bool)>,/// A category's titles: (category, record).pub members: Vec<(String, String)>,/// (season, its film).pub seasons: Vec<(String, String)>,/// (episode, its series, its season).pub episodes: Vec<(String, String, String)>,/// (file, its film, its series, its episode, its download).pub files: Vec<(String, String, String, String, String)>,/// (play, its film, its episode).pub plays: Vec<(String, String, String)>,}/// THE rule, once: the hidden film categories; the titles in them; their seasons; their episodes (by series or by/// season); the files a download landed as one of them; the downloads those files came from, with every other file of/// theirs.pubfn rule(rows: &RuleRows) -> Hiding {let named = |set: &BTreeSet<String>, id: &str| !id.is_empty() && set.contains(id);let groups: BTreeSet<String> = rows.groups.iter().filter(|(_, table, hidden)| table == "film" && *hidden).map(|(id, ..)| id.clone()).collect();if groups.is_empty() {returnHiding::default(); }let films: BTreeSet<String> = rows.members.iter().filter(|(group, _)| named(&groups, group)).map(|(_, record)| record.clone()).filter(|r| !r.is_empty()).collect();let seasons: BTreeSet<String> = rows.seasons.iter().filter(|(_, film)| named(&films, film)).map(|(id, _)| id.clone()).collect();let episodes: BTreeSet<String> = rows.episodes.iter().filter(|(_, series, season)| named(&films, series) || named(&seasons, season)).map(|(id, ..)| id.clone()).collect();let direct: Vec<&(String, String, String, String, String)> = rows.files.iter().filter(|(_, film, series, episode, _)| named(&films, film) || named(&films, series) || named(&episodes, episode)).collect();let fetches: BTreeSet<String> = direct.iter().map(|(.., fetch)| fetch.clone()).filter(|f| !f.is_empty()).collect();let files: BTreeSet<String> = rows.files.iter().filter(|(_, film, series, episode, fetch)| named(&films, film) || named(&films, series) || named(&episodes, episode) || named(&fetches, fetch)).map(|(id, ..)| id.clone()).collect();let plays = rows.plays.iter().filter(|(_, film, episode)| named(&films, film) || named(&episodes, episode)).map(|(id, ..)| id.clone()).collect();letmut titles = films; titles.extend(seasons); titles.extend(episodes); titles.extend(files); titles.extend(fetches);Hiding { groups, titles, plays }}/// One connection's kept answer of [`hiding`] (CORE 5, L5): kept per connection, so the screens' reader and the/// writer never push each other's out, and good while nothing the rule reads has changed.structKept { workspace: String,/// `cotton_store::driver::watched_changes` when it was read: a change to a category, a list's members, a season,/// an episode, a downloaded file, or a play added or taken away ([`WATCHED`]), by any handle of this process. watched: u64, schema: i64,/// This connection's `data_version` and the process's commits when it was read: `data_version` moved with no/// commit of this process is another process's write, which the watch cannot see, so the answer is read again. version: i64, commits: u64, hiding: Hiding,}/// The tables [`rule`] reads, and whether an UPDATE of one of their rows can change it. A play's film and episode are/// written once (read-only columns), so a play counts when it is added or taken away, never when its seconds move./// Every other write (a playback position, a title's details, a note, a message) keeps the answer.const WATCHED: [(&str, bool); 6] = [(GROUPS, true), (MEMBERS, true), ("film_season", true), ("film_episode", true), ("fetch_file", true), ("watch", false)];/// The kept answers, by connection (`Driver::change_stamp`'s handle serial, never reused). A few at most are open.static KEPT: std::sync::Mutex<Vec<(usize, Kept)>> = std::sync::Mutex::new(Vec::new());const KEPT_MOST: usize = 8;fn watch() {static ONCE: std::sync::Once = std::sync::Once::new(); ONCE.call_once(|| {for (table, updates) in WATCHED {let stored = if table == GROUPS || table == MEMBERS { table.to_string() } else { made_table(table) }; cotton_store::driver::watch_table(&stored, updates); } });}/// THE predicate on this phone's copy: [`rule`] over its rows, kept until the copy changes.pubfn hiding(ctx: &Ctx<'_>) -> Result<Hiding, String> { hiding_in(ctx.db(), ctx.workspace_id)}/// [`hiding`] on one file's connection and workspace, for a reader that holds no tool context (Find's own read).////// Never kept from inside a transaction that may write (CORE 4, L2): it may roll back, and `total_changes` does not go/// down when it does, so the stamp after the rollback can equal the one the answer was kept by.pubfn hiding_in(db: &cotton_store::Driver, workspace_id: &str) -> Result<Hiding, String> { watch();if db.in_write_transaction() {return read_hiding(db, workspace_id); }// Read before the stamp: a change landing between them is then always seen next time.let (watched, commits) = (cotton_store::driver::watched_changes(), cotton_store::driver::process_commits());let (handle, _, version, schema) = db.change_stamp().map_err(|error| error.to_string())?; {letmut kept = KEPT.lock().unwrap_or_else(std::sync::PoisonError::into_inner);ifletSome((_, kept)) = kept.iter_mut().find(|(held, _)| *held == handle) {let foreign = kept.version != version && kept.commits == commits;if kept.workspace == workspace_id && kept.watched == watched && kept.schema == schema && !foreign {// This process's own commits explain any move of `data_version`: start again from here, so a later// write by another process is still told apart. (kept.version, kept.commits) = (version, commits);returnOk(kept.hiding.clone()); } } }let read = read_hiding(db, workspace_id)?;letmut kept = KEPT.lock().unwrap_or_else(std::sync::PoisonError::into_inner); kept.retain(|(held, _)| *held != handle);if kept.len() >= KEPT_MOST { kept.remove(0); } kept.push((handle, Kept { workspace: workspace_id.to_string(), watched, schema, version, commits, hiding: read.clone() }));Ok(read)}#[cfg(test)]thread_local! {/// How many times this thread read the rule afresh (a test of what is kept).static READS: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };}/// [`hiding`] read afresh. With no hidden film category it reads nothing more.fn read_hiding(db: &cotton_store::Driver, workspace_id: &str) -> Result<Hiding, String> { #[cfg(test)] READS.with(|reads| reads.set(reads.get() + 1));let workspace = SqlValue::Text(workspace_id.to_string());let shut = db .all(&format!("SELECT id FROM {GROUPS} WHERE workspace_id = ? AND hidden = 1 AND table_id = 'film'"), std::slice::from_ref(&workspace)) .map_err(|error| error.to_string())?;let groups: Vec<(String, String, bool)> = shut.iter().filter_map(|row| Some((row.text("id")?.to_string(), "film".to_string(), true))).collect();if groups.is_empty() {returnOk(Hiding::default()); }let marks = vec!["?"; groups.len()].join(", ");let members = db .all(&format!("SELECT group_id, record_id FROM {MEMBERS} WHERE group_id IN ({marks})"), &groups.iter().map(|(id, ..)| SqlValue::Text(id.clone())).collect::<Vec<_>>()) .map_err(|error| error.to_string())? .iter() .map(|row| (row.text("group_id").unwrap_or_default().to_string(), row.text("record_id").unwrap_or_default().to_string())) .collect();let seasons = columns(db, workspace_id, "film_season", &["id", "film"])?.into_iter().map(|c| (c[0].clone(), c[1].clone())).collect();let episodes = columns(db, workspace_id, "film_episode", &["id", "series", "season"])?.into_iter().map(|c| (c[0].clone(), c[1].clone(), c[2].clone())).collect();let files = columns(db, workspace_id, "fetch_file", &["id", "film", "series", "episode", "fetch"])?.into_iter().map(|c| (c[0].clone(), c[1].clone(), c[2].clone(), c[3].clone(), c[4].clone())).collect();let plays = columns(db, workspace_id, "watch", &["id", "film", "episode"])?.into_iter().map(|c| (c[0].clone(), c[1].clone(), c[2].clone())).collect();Ok(rule(&RuleRows { groups, members, seasons, episodes, files, plays }))}/// Every row of `table` in this copy (binned too: a binned title stays hidden), the named columns as text ("" for a/// column this copy's table does not hold, or a table it does not hold at all).fn columns(db: &cotton_store::Driver, workspace_id: &str, table: &str, names: &[&str]) -> Result<Vec<Vec<String>>, String> {if !has_column(db, table, "id")? {returnOk(Vec::new()); }letmut held = Vec::new();for name in names { held.push(has_column(db, table, name)?); }let select = names.iter().zip(&held).map(|(name, here)| if *here { format!("\"{name}\"") } else { format!("'' AS \"{name}\"") }).collect::<Vec<_>>().join(", ");let rows = db .all(&format!("SELECT {select} FROM {} WHERE workspace_id = ?", made_table(table)), &[SqlValue::Text(workspace_id.to_string())]) .map_err(|error| error.to_string())?;Ok(rows.iter().map(|row| names.iter().map(|name| row.text(name).map(str::trim).unwrap_or_default().to_string()).collect()).collect())}/// Whether this copy's made table for `table` holds `column` (a copy the kit has not reached holds no such table).fn has_column(db: &cotton_store::Driver, table: &str, column: &str) -> Result<bool, String> {Ok(db .get(&format!("SELECT 1 AS here FROM pragma_table_info('{}') WHERE name = ?", made_table(table)), &[SqlValue::Text(column.into())]) .map_err(|error| error.to_string())? .is_some())}