use std::collections::{BTreeMap, BTreeSet};usesuper::*;usecrate::phone::routes::ROUTES;fn covered() -> BTreeSet<&'static str> { READS .iter() .flat_map(|entry| entry.audience.screens().iter().map(|screen| route_of(screen))) .collect()}fn deferred() -> BTreeSet<&'static str> { DEFERRED.iter().map(|(route, _)| *route).collect()}fn read_less() -> BTreeSet<&'static str> { READ_LESS.iter().map(|(route, _)| *route).collect()}/// **The totality test** (design P4): every screen is answered, or its debt is/// named.////// P4 asks for "every screen in a route table has at least one read method and/// every read method has a screen". The first half cannot be literally true/// until 4g lands, and a test that waited until then would be a test that never/// caught anything on the way. So it is written as the strictly stronger/// version: every screen is answered, OR carries a written deferral naming the/// sub-step that owes it, OR is written down as answered by nothing on purpose./// A route added with none of the three fails here — which is the drift this/// table exists to prevent.////// The third list is what keeps the second one honest: `DEFERRED` holds DEBTS/// only, so a sub-step landing its screens deletes its lines and the list/// shrinks to nothing rather than becoming furniture, while a permanent/// non-answer lives in `READ_LESS` where it is not pretending to be owed.#[test]fn every_screen_is_answered_or_deferred_by_name() {let covered = covered();let deferred = deferred();let read_less = read_less();let missing: Vec<&str> = ROUTES .iter() .copied() .filter(|route| { !covered.contains(route) && !deferred.contains(route) && !read_less.contains(route) }) .collect(); assert!( missing.is_empty(),"these screens have no read, no written deferral and no written non-answer: {missing:?}. \ Add a `ScreenRead` for each, a line in DEFERRED naming the sub-step that owes one, or a \ line in READ_LESS naming what answers instead." );}/// The other half of P4's totality: an orphan read is drift too.////// A read naming a screen the app does not have is a query nobody draws, and it/// is the failure mode that survives a route being renamed — the read keeps/// compiling and keeps answering, and no screen ever calls it again.////// An [`Audience::Extension`] read is SKIPPED here rather than exempted: it/// names no route because the process that draws it has none, and/// [`every_extension_read_names_a_declared_channel`] is the totality test that/// holds it instead. Between the two, every read still declares one consumer.#[test]fn every_read_names_a_screen_that_exists() {for entry in READS {letAudience::Screens(screens) = entry.audience else {continue; }; assert!( !screens.is_empty(),"read.{} names no screen at all", entry.name );for screen in screens { assert!( ROUTES.contains(&route_of(screen)),"read.{} names {screen}, which is not a route this app has", entry.name ); } }}/// An extension read names a channel that exists.////// The teeth: a read cannot invent a second channel, and a typo in the literal/// is a red run rather than an input method that silently reads an empty/// snapshot for ever. The key itself is wire protocol and is spelled a second/// time in Kotlin — see [`EXTENSION_CHANNELS`] for why that half is a written/// ledger entry rather than a by-path guard.#[test]fn every_extension_read_names_a_declared_channel() {for entry in READS {letAudience::Extension(key) = entry.audience else {continue; }; assert!( EXTENSION_CHANNELS.contains(&key),"read.{} writes to {key:?}, which is not one of the App Group channels this app \ declares: {EXTENSION_CHANNELS:?}", entry.name ); }}#[test]fn nothing_is_both_answered_and_deferred() {let both: Vec<&str> = covered().intersection(&deferred()).copied().collect(); assert!( both.is_empty(),"{both:?} have a read AND a deferral — the deferral lines are stale and should go" );let promised: Vec<&str> = covered().intersection(&read_less()).copied().collect(); assert!( promised.is_empty(),"{promised:?} have a read AND a line in READ_LESS saying they never would — one of the \ two is wrong, and a promise that a route reads nothing is broken the moment it reads \ something" );let owed: Vec<&str> = deferred().intersection(&read_less()).copied().collect(); assert!( owed.is_empty(),"{owed:?} are both owed a read and declared never to need one: {owed:?} cannot be both a \ debt and a decision" );}/// A `READ_LESS` line names a real route, and names what answers INSTEAD.////// The reason is the whole content of the line — without it the list is a set/// of paths somebody decided about once and nobody can check. It must also not/// open with a sub-step the way a [`DEFERRED`] line does: a line written in the/// deferral's shape is a debt filed in the decisions list, which is the exact/// confusion these two lists were split apart to end.#[test]fn a_read_less_screen_names_what_answers_instead() {for (route, answers) in READ_LESS { assert!( ROUTES.contains(route),"{route} is declared read-less but is not a route — the line outlived its screen" ); assert!( !answers.trim().is_empty(),"{route} is declared read-less with no reason — say what answers instead" );letmut characters = answers.chars();let looks_deferred = characters.next() == Some('4') && matches!(characters.next(), Some(letter) if ('a'..='l').contains(&letter)); assert!( !looks_deferred,"the READ_LESS line for {route} opens like a deferral ({answers:?}). A line here is a \ decision, not a debt owed by a sub-step — name what answers instead, and put the \ lane in the sentence rather than at the front of it" ); }}#[test]fn a_deferral_names_a_real_route_and_a_sub_step() {for (route, owed) in DEFERRED { assert!( ROUTES.contains(route),"{route} is deferred but is not a route — the line outlived its screen" );// A deferral OPENS with a sub-step in `4a`…`4l`, and may go on to say// why. `starts_with("4")` accepted "4", "4 later" and "42" — a deferral// whose sub-step cannot be looked up is a deferral nobody can close,// which is the state this list exists to prevent. The range is the// port's own: sub-steps 4a through 4l.letmut characters = owed.chars();let named = characters.next() == Some('4') && matches!(characters.next(), Some(letter) if ('a'..='l').contains(&letter))// "4f" and "4f — why" are both fine; "4fa" is not a sub-step. && !characters.next().is_some_and(char::is_alphanumeric); assert!( named,"the deferral for {route} says {owed:?}, which does not open with one of the \ sub-steps 4a–4l" ); }}/// Read names must dispatch unambiguously and extension channels must have one writer./// Composite Home sections can use independent reads; pinning one read per screen/// prevents definition-driven pages without protecting record or channel safety.#[test]fn read_names_and_extension_channels_are_unambiguous() {letmut names = BTreeSet::new();// The same rule for extension channels: two reads writing one App Group key is two// answers to one question just as surely, and the extension that reads it// would get whichever of them the app wrote last.letmut channels: BTreeMap<&str, &str> = BTreeMap::new();for entry in READS { assert!( names.insert(entry.name),"read.{} is declared twice", entry.name );match entry.audience {Audience::Screens(_) => {}Audience::Extension(key) => {ifletSome(other) = channels.insert(key, entry.name) { panic!("{key} is written by read.{other} and read.{} — one App Group key with \ two producers is two answers to one question", entry.name ); } } } }}/// Every tool-backed read names a tool that actually has an implementation.////// This is the guard that would have gone quiet if a tool were renamed: the/// table would still compile, the read would still be in the method list, and/// the screen would get "not implemented on this build yet" at runtime instead/// of a compile error.#[test]fn every_tool_backed_read_names_a_tool_that_exists() {for entry in READS {ifletSome(tool) = entry.tool() { assert!( cotton_tools::mcp::dispatch::handler_for(tool).is_some(),"read.{} is bound to {tool}, which no handler group registers", entry.name ); } }}#[test]fn a_tool_backed_read_is_a_read_tool_and_never_a_write() {// A `read.*` method that reached a write tool would be a screen mutating// the person's database by being LOOKED AT. The catalogue already knows// which is which, so this asks it rather than keeping a second list.for entry in READS {ifletSome(tool) = entry.tool() {let def = cotton_tools::mcp::protocol::tool_by_name(tool) .unwrap_or_else(|| panic!("{tool} is not in the catalogue")); assert_eq!( def.scope.as_str(),"read","read.{} is bound to {tool}, which is a write tool", entry.name ); } }}#[test]fn a_composed_read_only_ever_reaches_read_tools() {// The sweep above sees `ReadSource::Tool` and cannot see inside a// `Composed` body, which calls `handler_for` by name and so bypasses// `call_tool`'s own scope gate. `traffic::COMPOSED_TOOLS` is the list of// names those bodies may pass, declared for exactly this reason, and// `traffic::tool` refuses anything not on it.for name incrate::phone::traffic::COMPOSED_TOOLS {let def = cotton_tools::mcp::protocol::tool_by_name(name) .unwrap_or_else(|| panic!("{name} is not in the catalogue")); assert_eq!( def.scope.as_str(),"read","a composed read names {name}, which is a write tool" ); }}/// RULE: Composed reads that bypass dispatch declare every catalogue tool so its read scope is checked; normal dispatch enforces scopes itself, including in writers.#[test]fn every_tool_a_composed_body_names_is_on_the_declared_list() {// The list is only a guard if it is COMPLETE. A call whose name is missing// refuses at runtime rather than widening silently — but a refusal a person// meets on a screen is a worse place to learn it than a red test, so the// source is swept here too.//// EVERY module in `src/phone/`, not one named file. A composed body may// live anywhere in this module — 4k's `record_thread.rs` is the first that// does — and a sweep over a hand-kept list of files goes quiet, not red,// the day somebody writes the second one. Reading the directory is what// makes forgetting impossible; the two assertions below are what stop an// empty or mis-pointed read from passing as "nothing to sweep". This is a// crate-LOCAL read (`rust-crate-local-reads.test.ts`'s rule): the// directory is this crate's own.let sources = phone_sources();letmut named: Vec<(String, String)> = Vec::new();for (file, source) in &sources {// Whitespace-stripped, so the one-line `tool(ctx, "name", …)` and the// wrapped `tool(\n ctx,\n "name",` are the same needle — and so// is `one_media(ctx, "get_photo", …)`, which hands the name down a// level and is how the first cut of this sweep missed the two record// getters.let flat: String = source.chars().filter(|c| !c.is_whitespace()).collect();for (at, _) in flat.match_indices("(ctx,\"") {// `call_tool` goes through the scope gate. A writer legitimately// dispatches write tools; it is not a composed-read bypass.let function = flat[..at] .rsplit(|c: char| !c.is_ascii_alphanumeric() && c != '_') .next() .unwrap_or_default();if function == "call_tool" {continue; }let rest = &flat[at + "(ctx,\"".len()..];let end = rest.find('"').expect("a closing quote"); named.push((file.clone(), rest[..end].to_string())); } } assert!(!named.is_empty(), "the sweep found no calls at all");letmut seen: BTreeSet<String> = BTreeSet::new();for (file, name) in named {// A literal after `(ctx, ` that is not a CATALOGUE NAME is not a tool// call — a label, a table, a kind — and is skipped. One that IS a// catalogue name has to be declared, which is the whole property: a// write tool cannot reach a composed body without appearing on a list// the scope sweep above walks.if cotton_tools::mcp::protocol::tool_by_name(&name).is_none() {continue; } assert!(crate::phone::traffic::COMPOSED_TOOLS.contains(&name.as_str()),"{file} names the tool {name} but it is not on COMPOSED_TOOLS" ); seen.insert(name); }let declared: BTreeSet<String> = crate::phone::traffic::COMPOSED_TOOLS .iter() .map(|name| (*name).to_string()) .collect(); assert_eq!( seen, declared,"a declared name no source calls is a scope this guard checks for no \ reason" );}/// Every non-test source in `src/phone/`, as (file name, text).////// A `*_tests.rs` file is left out on purpose: a suite naming a tool in a/// comment or a fixture is not a body a screen can reach, and sweeping them/// would make this guard's failures depend on how a test happens to be worded.fn phone_sources() -> Vec<(String, String)> {// The RUNTIME variable, through the shared helper — never the compile-time// constant, which a cached CI test binary carries from a checkout that has// been deleted (`cotton_store::manifest`, and `manifest-dir-at-run-time.test.ts`).let dir = cotton_store::manifest::manifest_dir().join("src/phone");let entries = std::fs::read_dir(&dir) .unwrap_or_else(|error| panic!("{} cannot be read ({error})", dir.display()));letmut out: Vec<(String, String)> = Vec::new();for entry in entries {let path = entry.expect("a directory entry").path();letSome(name) = path.file_name().and_then(|name| name.to_str()) else {continue; };if !name.ends_with(".rs") || name.ends_with("_tests.rs") {continue; }let text = std::fs::read_to_string(&path) .unwrap_or_else(|error| panic!("{} cannot be read ({error})", path.display())); out.push((name.to_string(), text)); } out.sort();// The call sweep above checks coverage against the runtime declarations;// a source count or a list of filenames would only pin the module layout. assert!(!out.is_empty(), "{} answered no sources", dir.display()); out}#[test]fn the_method_names_all_carry_the_prefix() {for name in method_names() { assert!(name.starts_with("read."), "{name}"); assert!( read_for(&name).is_some(),"{name} is offered but resolves to no read" ); } assert!(read_for("write").is_none(), "only `read.*` resolves here"); assert!(read_for("read.nothing").is_none());}// ── `read.boot` decides from the file, never from an attach ───────────────/// A phone that has JOINED and has no file yet: `connection.json` and nothing/// beside it.////// The state a first launch after pairing is in, and — because a replica can be/// deleted, moved or not yet downloaded — the state any launch can be in./// Synthetic through and through ([nothing-real-ever-goes-in-cotton-s-public-tree]).fn joined_with_no_file() -> (tempfile::TempDir, crate::shell::client::ClientController) {use cotton_client::layout::Layout;let dir = tempfile::tempdir().expect("a temp container");let layout = Layout::new(dir.path()); std::fs::create_dir_all(layout.client_dir()).expect("the client folder"); std::fs::write( layout.connection_json(), serde_json::to_vec_pretty(&serde_json::json!({"mode": "remote","baseUrl": "https://server.invalid","workspaceId": "ws-boot","ownerId": "owner-boot","connectedAt": "2026-09-11T10:00:00.000Z", })) .expect("json"), ) .expect("the connection record");let client = crate::shell::client::ClientController::new( layout, std::sync::Arc::new(crate::EventBus::new()),Some("Asia/Kolkata".to_string()),None, ); (dir, client)}/// **The defect this pass exists for, as a crate-level fact.**////// `paired` is decided by `connection.json` alone. It used to be answered/// beside an `attach()` — a SQLite open, and after a force-quit an open that/// pays the write-ahead log's recovery — which the app read under a/// five-second ceiling and, past the ceiling, resolved as "nobody is here"./// A phone whose server still listed it as approved was shown the Join screen.#[test]fn the_boot_read_answers_paired_from_the_file_without_opening_the_replica() {let (dir, client) = joined_with_no_file();let layout = cotton_client::layout::Layout::new(dir.path());let replica = layout.replica("ws-boot");let answer = boot(&client, &Map::new()).expect("the boot read"); assert_eq!(answer["paired"], serde_json::json!(true)); assert_eq!(answer["ownerId"], serde_json::json!("owner-boot")); assert_eq!(answer["workspaceId"], serde_json::json!("ws-boot")); assert_eq!(answer["serverUrl"], serde_json::json!("https://server.invalid"));// `joined`, not `ready` and not `bootstrap`: whether the FILE is open is// `read.syncStatus`'s `connected` to answer, and this read does not ask. assert_eq!(answer["stage"], serde_json::json!("joined")); assert_eq!(answer["refusal"], serde_json::Value::Null); assert!( !replica.exists(),"the boot read opened (or created) a replica — the attach it must not make" );}/// The other half of the same rule: a file that cannot be READ is an error the/// app reports, never a `paired:false`.////// `false` means "this person has never joined anything", and answering it on/// the strength of a bad disk read tells a paired phone to pair again as a new/// device — the thing `read_connection`'s own header refuses.#[test]fn a_connection_record_that_will_not_parse_is_reported_rather_than_read_as_never_joined() {let (dir, client) = joined_with_no_file();let layout = cotton_client::layout::Layout::new(dir.path()); std::fs::write(layout.connection_json(), "{ not json").expect("the file");let error = boot(&client, &Map::new()).expect_err("an error, not an answer"); assert!( error.contains("connection.json"),"the sentence names the file it could not read: {error}" );}// ── A screen's list read answers the whole set ──────────────────────────────/// How one tool-backed read is bounded, and the sentence that says why.////// The rule this enforces is Cotton note "The phone and Mac app — how a screen is built"'s: **a phone/// screen's list read answers the WHOLE set at personal scale; a page size is/// an MCP concern, not a screen's.** The tools keep their `limit` because an/// assistant's context is finite; a screen drawing one person's own file has no/// such excuse, and "the first fifty of one thousand nine hundred" is a wrong/// answer wearing the shape of a right one — which is exactly how `/people`/// drew fifty contacts and searched only those fifty.enumListScale {/// The tool answers ONE record. There is no page to be wrong about.Record,/// [`ReadSource::ToolWholeSet`] — the seam sends `limit: "all"`.WholeSet,/// The SCREEN pages, and this says how. A read may be capped only if/// something on the other side can ask for more.////// **Unused today, and kept rather than deleted**: it is the third honest/// answer, and a table with only two of them would push the next paging/// screen towards declaring itself `WholeSet` — which is the one lie this/// gate exists to catch. #[allow(dead_code)]Paged(&'static str),}/// Every tool-backed read, with how it is bounded. **A blank is a failed/// gate** — the test below refuses a read that is not in this table and a line/// here that names no read.const TOOL_BACKED_SCALE: &[(&str, ListScale)] = &[// `get_project` is one project, but its `linked.*` blocks are lists —// membership-scoped sets of one project's records — and the tool caps// each at fifty for an assistant. The page draws them whole. ("call", ListScale::Record), ("projectFeedback", ListScale::WholeSet),// gen-kind: tool-backed-scale];#[test]fn a_tool_backed_list_read_is_paged_or_whole() {let declared: BTreeMap<&str, &ListScale> = TOOL_BACKED_SCALE .iter() .map(|(name, scale)| (*name, scale)) .collect(); assert_eq!( declared.len(), TOOL_BACKED_SCALE.len(),"a read is declared twice in TOOL_BACKED_SCALE" );letmut backed: BTreeSet<&str> = BTreeSet::new();for entry in READS {letSome(tool) = entry.tool() else { continue }; backed.insert(entry.name);letSome(scale) = declared.get(entry.name) else { panic!("read.{} runs {tool} and says nothing about how it is bounded. Add it to \ TOOL_BACKED_SCALE: Record if the tool answers one record, WholeSet (and \ ReadSource::ToolWholeSet) if the screen draws the whole set, Paged if the screen \ can ask for more.", entry.name ); };// The declaration and the SOURCE have to agree, or the table is prose.match (scale, &entry.source) { (ListScale::WholeSet, ReadSource::ToolWholeSet(_)) => {} (ListScale::WholeSet, _) => panic!("read.{} is declared WholeSet but its source is not ReadSource::ToolWholeSet, so \ it still gets the tool's own page", entry.name ), (_, ReadSource::ToolWholeSet(_)) => panic!("read.{} asks for the whole set but is declared as something else", entry.name ), _ => {} } }let orphans: Vec<&str> = declared .keys() .copied() .filter(|name| !backed.contains(name)) .collect(); assert!( orphans.is_empty(),"TOOL_BACKED_SCALE names reads that are not tool-backed any more: {orphans:?}. A line that \ outlived its read is a guard that has stopped guarding." );}#[test]fn the_people_directory_is_not_the_tool_s_page() {// The specific regression, named: `/people` was `ReadSource::Tool`, the// tool defaults to fifty, and a directory of about 1,900 people drew fifty// of them — and searched only those fifty, because the filter is over what// the screen holds.let people = READS .iter() .find(|entry| entry.name == "people") .expect("read.people"); assert!( people.tool().is_none(),"read.people is bound to a tool again — the tool pages at fifty and the address book is \ not fifty people" );}// ── No screen read takes a page by number ───────────────────────────────────/// A numeric page a screen read hands a tool, or a raw `LIMIT` in a screen's/// own SQL, that is NOT a whole-set request — allow-listed by file and by the/// text on the line, each with the sentence that makes it honest. A line that/// is not here fails the sweep below.////// The three shapes that are honest: a PAGING LOOP that walks every page/// (transcript, email body), a WINDOW the screen can grow (`read.thread`), and/// a read whose ceiling is not a list a person scrolls (an export, an/// autocomplete, a keyboard snapshot, a figure the screen draws a fixed/// number of by design). Build 143's `/todos` question — "is a 50 reaching a/// screen?" — is answered by this table being short and every entry saying why.const PAGE_BY_NUMBER_ALLOWED: &[(&str, &str, &str)] = &[ ("chat_timer.rs","ORDER BY sent_at, id LIMIT {room}","the WhatsApp timer's sweep to the Bin, capped at SWEEP_MAX a pass (the next pass takes what is left); no screen reads it", ), ("chat_timer.rs","FROM {ERASING} ORDER BY thread, id LIMIT {WRITE_CHUNK}","the timer's erase queue, one write's chunk at a time (each chunk written and taken off before the next is read); no screen reads it", ), ("chat_timer.rs","json_extract(meta, '$.cotton.expiresAt') <= ? AND workspace_id = ?{scope} LIMIT 5000","the expired-message sweep, at most 5000 a pass (the next pass takes what is left); no screen reads it", ), ("chat_timer.rs","'$.cotton.{TIMER_BINNED}') IS NULL LIMIT 5000","the due span's messages to bin when a timer is set, at most 5000 a pass (the next pass takes what is left); no screen reads it", ), ("chat_timer.rs","ORDER BY sent_at DESC LIMIT 50","a chat's list line: the newest drawn message among its 50 newest (a due span hides a run of them, never the whole chat); the line, not a page", ), ("landed.rs","SELECT e.id FROM {} e WHERE {} LIMIT {limit}","the landing fill for mail held before 157, a batch at a time until none is left; no screen reads it", ), ("chat_mail_post_cuts.rs","ORDER BY {time}(made_at), id LIMIT 20","the Delete rows due for their erase, twenty a pass, oldest first (the next pass takes what is left); no screen reads it", ), ("chat_mail_post_cuts.rs","AND {} LIMIT {limit}","the mails one Delete row covers, a batch at a time for its erase (each batch erased before the next is read); no screen reads it", ), ("albums_app.rs","ORDER BY offer.taken DESC, offer.id LIMIT {PAGE}","an Albums list is a keyed page: from is the last drawn row's (taken, id), next_from walks on past it until the snapshot's end; never by number", ), ("albums_app.rs","ORDER BY bytes DESC, first DESC, set_id LIMIT {PAGE}","Albums' Sets is a keyed page: from is the last drawn set's (bytes, first, set), next_from walks on past it; never by number", ), ("albums_app.rs","ORDER BY mark.at DESC, item.taken DESC, mark.id LIMIT {PAGE}","the Albums Bin is a keyed page: from is the last drawn row's (at, taken, id), next_from walks on past it until the snapshot's end; never by number", ), ("albums_app.rs","ORDER BY taken DESC LIMIT ?1","albums.pass.next hands the shell the next photos to look at, limit a call; a looked photo drops out, so the next call takes the rest; a work queue, not a screen", ), ("albums_app.rs","ORDER BY item.taken DESC LIMIT ?1","albums.pass.next asks again on Wi-Fi for photos only in iCloud, limit a call; an asked one is marked asked_net and drops out; a work queue, not a screen", ), ("albums_app.rs","WHERE act = ?1 AND applied = 0 ORDER BY pos LIMIT ?2","an Albums act is applied a budget at a time (the tap, then albums.work); an applied row is marked and drops out, so the next slice takes the rest; not a screen", ), ("albums_app.rs","AND after_mark = 'hand' AND applied = ?2 ORDER BY pos LIMIT ?3","an Albums Delete hands its photos a budget at a time in albums.work; a decided row is marked and drops out, so the next slice takes the rest; not a screen", ), ("albums_app.rs","SELECT id FROM request WHERE at < ?1 ORDER BY at LIMIT 50","Albums prunes answered request ids older than 30 days, at most 50 an act; a pruned row is gone, so the next act takes the next ones; not a screen", ), ("albums_app.rs","ORDER BY mark.seq, mark.id LIMIT ?4","an Albums Delete is planned a budget at a time from the Bin's snapshot, walking on past the last planned (seq, id); not a screen", ), ("albums_app.rs","ORDER BY seq, id LIMIT ?5","an Albums Bin all is planned a budget at a time from the list's snapshot, walking on past the last planned (seq, id); not a screen", ), ("albums_app.rs","WHERE act = ?1 AND applied = 1 ORDER BY pos DESC LIMIT ?2","an Albums undo runs a budget at a time; an undone row is marked and drops out, so the next slice takes the rest; not a screen", ), ("data_app.rs","ORDER BY {cursor} DESC, id DESC LIMIT {}","Data's table read from this phone's copy is a KEYED page: it starts after the last row shown (`{cursor} < ? OR ({cursor} = ? AND id < ?)`), and the extra row it asks for says whether more follow", ), ("days_push.rs","ORDER BY updated_at, id LIMIT ?","the send-to-Google queue, not a screen: MOST events a pass, oldest change first, the extra one saying more wait for the next pass", ), ("days_push.rs","ORDER BY starts_at LIMIT ?","\"keep my Days events in Google\" marks KEEP_MOST events a call, not a screen: each pass marks the next ones until none is left", ), ("chat_mail_sender_page.rs","ORDER BY coalesce(sent_at, '') DESC, id DESC LIMIT {}","a sender's page: a WINDOW the screen grows by its (sent_at, id) cursor (`after`), as the Mail tab walks its threads", ), ("chat_downloads.rs"," ORDER BY sent DESC, id DESC LIMIT ?","the Downloads chat: a WINDOW the screen grows by its (sent, id) cursor (`before`), as a chat's messages are", ), ("dev_kept_pictures.rs","ORDER BY id LIMIT ?","a development check WALKS a chat's pictures by the id cursor (`after`); no person's screen reads it", ), ("chat_mail.rs","ORDER BY sent_at ASC, id ASC LIMIT 8","a mail thread's conversation is told by its first few mails (who began it, to whom); the thread's mail itself is read whole elsewhere", ), ("chat_mail.rs","ORDER BY coalesce(last_at, '') DESC, id DESC LIMIT 120","the Mail tab WALKS its threads in batches by the (last_at, id) cursor until it holds a page of the kind asked for or the threads end", ), ("chat_mail.rs","ORDER BY sent_at DESC, id DESC LIMIT 100\", live_mail = mail_predicate::live(\"\")), &[text(id.clone())]","a mail thread opens on its newest 100 mails, the object's own window for a thread (`limit=100` when the copy does not hold it)", ), ("chat_mail_post.rs","WHERE thread_id = ?{clause} ORDER BY sent_at ASC, id ASC LIMIT 8","Post: a conversation's row is told by its first few mails (who began it, to whom); the conversation's mail itself is read whole when it opens", ), ("chat_mail_post.rs","attachments <> '[]'{cut} ORDER BY sent_at DESC, id DESC LIMIT 200","Post's Files: a WINDOW the screen grows by its (sent_at, id) cursor (`cut`, from `after`), read from idx_cotton_emails_files", ), ("chat_mail_post.rs","WHERE t.workspace_id = ?{bin}{cut}{has} ORDER BY t.last_at DESC, t.id DESC LIMIT 120","Post's places WALK the conversations in batches by the (last_at, id) cursor until they hold a page of the place asked for or the conversations end", ), ("chat_mail_post.rs","\" ORDER BY at DESC, id DESC LIMIT {}\", PAGE + 1","a sender's page: a WINDOW grown by its (newest mail, thread id) cursor (`after`), reading one past the page to know there is more", ), ("chat_mail_post.rs","labels <> '[]' ORDER BY sent_at DESC LIMIT 2000","You's labels, most used first, are tallied over his newest 2,000 labelled mails, not a page of a list: the labels column has no index, and reading every mail's row for it read most of the mailbox at his size (a label used only on older mail is not offered there)", ), ("chat_mail_post.rs","GROUP BY e.thread_id{having} ORDER BY at DESC, e.thread_id DESC LIMIT {SEARCH_BATCH}","Post's search by words: batches of a WINDOW keyed by the conversation's (newest hit, thread id), grouped before the cut (`keyed_conversations`), until a page of conversations is found, the hits end, or SEARCH_BATCHES batches end the page short with its cursor (`after`, answered in `mail.after`)", ), ("chat_mail.rs","GROUP BY thread_id{having} ORDER BY at DESC, thread_id DESC LIMIT {SEARCH_BATCH}","Post's search before the wide index is filled: the same keyed batches as the index's (`keyed_conversations`), sender and subject by LIKE and the words by fts_emails in one grouped query", ), ("chat_mail_post_acts.rs","ORDER BY trashed_at LIMIT {SWEEP_MAX}","the Bin sweep erases at most SWEEP_MAX mails a run, the longest in the Bin first; the next run takes the next. No screen reads it", ), ("chat_mail_post_write.rs","ORDER BY sent_at DESC, id DESC LIMIT 100\", live_mail","a reply reads the conversation's newest 100 mails to choose the one it answers; nothing here is drawn as a list", ), ("chat_mail_post_you.rs","GROUP BY lower(coalesce(account, gmail_account)) LIMIT 20","You names the mailboxes his mail came to while the account rows have not come: a handful at most, never a list he scrolls", ), ("chat_mail_write.rs","ORDER BY sent_at DESC, id DESC LIMIT 100","a reply reads the thread's newest 100 mails to choose the one it answers; nothing here is drawn as a list", ), ("dev_served_copy.rs","WHERE implied IS NOT NULL LIMIT 2000","a development tool's whole-again pass over implied writes; no person's screen reads it", ), ("trim.rs","LIMIT ?3","TRIM takes at most `most` binned rows a pass across the tables, and the next pass takes the rest; no screen reads it", ), ("chat_search.rs","AND f.rowid < ? ORDER BY f.rowid DESC LIMIT {BATCH}","chat.search WALKS the index in batches by its rowid cursor until it holds the matches it was asked for or the index ends; a batch is not what the screen shows", ), ("chat_search.rs","AND m.rowid < ? ORDER BY m.rowid DESC LIMIT {BATCH}","chat.search WALKS the messages below the index's floor in batches by their rowid cursor until it holds the matches it was asked for or the messages end", ), ("chat_search.rs","ORDER BY m.starred_at DESC, m.id DESC LIMIT {}\", PAGE + 1","chat.starred: a WINDOW the screen grows by its (starred_at, id) cursor (`after`) while `more` says a starred message lies past it", ), ("chat_timer.rs","LIMIT {SWEEP_MAX}","the disappearing-message sweep erases at most SWEEP_MAX due messages a pass and the next pass takes the rest; no screen reads it", ), ("days_views.rs","ORDER BY completed_at DESC, id DESC LIMIT {}","Days' done to-dos: a WINDOW the screen grows by its (completed_at, id) cursor (`after`, answered as `next`) until `next` is absent", ), ("chat_files.rs","ORDER BY sent_at DESC LIMIT 400","chat.keep keeps the newest pictured messages no phone has kept, a few each pass; a picture past the cap is kept on a later pass, and no screen reads it", ), ("chat_notices.rs","ORDER BY m.sent_at DESC LIMIT {READ_MAX}","chat.notices says the newest unread lines in a notification, which shows only the latest few; no screen reads it and the chat itself reads every line", ), ("chat_notices.rs","ORDER BY sent_at DESC LIMIT {}\", rules::LINES_MAX","a notification shows at most LINES_MAX of the person's own replies under the unread; no screen reads it", ), ("chat_notices.rs","ORDER BY started_at DESC LIMIT 50","the missed calls a notification names, at most a week old; no screen reads it and the calls list reads them all", ), ("settings_devices.rs","fields.insert(\"limit\".to_string(), Value::from(200))","The device overlay walks every synced next_page until null before adding pending approvals and applying the caller's one final page; it never truncates the joined set", ), ("traffic.rs","(\"limit\", Value::from(EMAIL_TOOL_PAGE))","email thread bodies: a loop over every page of the tool, not one page", ), ("traffic.rs","page_args.insert(\"limit\".to_string(), Value::from(asking))","read.thread: the screen's own window, grown by the screen until hasMore is false", ), ("reads_work.rs","args.insert(\"limit\".to_string(), Value::from(PAGE))","read_whole_transcript: a loop over every page of the tool", ), ("chat_app.rs","LIMIT ?\"));","chat.thread: a WINDOW the screen grows by its (sent_at, id) cursor, older and newer, until \ `older` and `newer` are absent — the stride is the read's (owner, 19 Nov 2026: a thread's \ page answers under 30 ms in a 100,000-message thread), never a page addressed by number", ), ("chat_calls.rs","LIMIT {}\", rules::PAGE + 1","chat.calls: Chat's call list, a WINDOW the screen grows by its (started_at, id) cursor \ (`after`, answered as `next` while a row lies past the window), until `next` is absent; \ the one extra row only says whether there is more, never a page addressed by number", ), ("chat_app.rs","LIMIT {COUNT_CEILING}","Cotton Chat's unread badge and jump-to-latest count to COUNT_CEILING and then say 999+: a \ badge's figure, never a list a person scrolls, and the read never walks a 100,000-message thread to draw it", ), ("activity.rs","LIMIT ?","the asked limit, whole set unless the screen names a number", ), ("export.rs","LIMIT ?","an export's media ceiling, stated in the answer — not a list a person scrolls", ), ("keyboard.rs","LIMIT ?","the Android keyboard's snapshot of the last five takes", ), ("reads.rs","id ASC LIMIT {cap}","Home's Done for you: a glance of DONE_FOR_YOU_LIMIT (eight) acts by design, not a list \ a person scrolls — each of the three record kinds is capped at that many newest-first so the \ merge never reads a whole table, and the engine keeps the final eight", ), ("reads.rs","ORDER BY city_filled_at DESC LIMIT {cap}","Home's Done for you: the newest DONE_FOR_YOU_LIMIT passes of the city fill, one row \ each, so the glance never reads every pass; each pass's people are then read whole", ), ("reads_work.rs","Value::from(SESSIONS_LIMIT)","the sessions queue is a WINDOW (seven days by last activity, `since`) and this is the ceiling inside it — the whole set was four hundred and seventy-four adopted transcripts downloaded to a phone to draw a dozen", ), ("reads_work.rs","Value::from(PROJECT_SESSION_WALK_PAGE)","read.project's Sessions preview WALKS every page — `list_sessions` a page at a time by \ its cursor, until it holds the newest three not running or the project's threads end — \ and the heading's figure is the whole count, so no page is ever taken by number", ), ("reads_work.rs","Value::from((limit - sessions.len() as i64).min(200))","read.projectSessions WALKS pages by `list_sessions`' cursor until it holds the `limit` \ the screen asked for, and answers `total` beside it — the screen's Show more asks for a \ page more, so the stride is the READ's and the header says 30 of N", ),// chat.ahead, chat.warm, chat.previews and chat.waveforms (95096ff212, a72157a2d3) fetch// files in the background; no screen draws their rows. ("chat_ahead.rs","AND sent_at < ? ORDER BY sent_at DESC LIMIT {AHEAD_MESSAGES}","chat.ahead fetches pictures, not a screen: AHEAD_MESSAGES older than what the chat shows, the next ones when the chat scrolls", ), ("chat_ahead.rs","AND sent_at > ? ORDER BY sent_at ASC LIMIT {AHEAD_MESSAGES}","chat.ahead fetches pictures, not a screen: AHEAD_MESSAGES newer than what the chat shows, the next ones when the chat scrolls", ), ("chat_ahead.rs","{base} ORDER BY sent_at DESC LIMIT {AHEAD_MESSAGES}","chat.ahead with nothing shown yet fetches the pictures of the chat's newest AHEAD_MESSAGES, where it opens; not a screen", ), ("chat_ahead.rs","last_message_at DESC LIMIT {chats}","chat.warm picks the chats to warm first, the list's top `chats`; the list itself is read whole elsewhere", ), ("chat_ahead.rs","ORDER BY sent_at DESC LIMIT {each}","chat.warm fetches each top chat's newest `each` pictures in the background, not a screen", ), ("chat_ahead.rs","ORDER BY sent_at DESC LIMIT 2000","chat.warm's background pass over the last KEEP_DAYS of every chat, at most WARM_LIMIT fetched a call; not a screen", ), ("chat_ahead.rs","ORDER BY sent_at DESC LIMIT 4000","chat.previews makes previews in the background for pictures held on this phone, newest 4000 picture messages a pass; not a screen", ), ("chat_voice.rs","ORDER BY sent_at DESC LIMIT 4000","chat.waveforms works out waveforms in the background for voice notes held on this phone, newest 4000 a pass; not a screen", ), ("chat_agent.rs","ORDER BY m.sent_at, m.id LIMIT {FEED_BATCH}","chat.agent.feed hands a group's agent at most FEED_BATCH messages a pass, oldest first; a fed message is marked $.cotton.fed and drops out, so the next pass takes the rest; not a screen", ), ("chat_calls.rs","external_id LIKE 'call:%' ORDER BY sent_at DESC LIMIT 5","live_line looks for the one group call still going among a chat's newest five call lines; a lookup for the call bar, never a list drawn", ), ("chat_revoked.rs","LIMIT {SWEEP_MAX}","sweep_revoked erases WhatsApp messages deleted for everyone, at most SWEEP_MAX a pass; an erased row is marked $.cotton.erased and drops out, so the next sweep takes the rest; not a screen", ),];/// **A screen read never takes a tool's page by number.** Every `limit` a/// phone read hands a tool is `WHOLE_SET`, and every `LIMIT` in a screen's own/// SQL is one row or on the allow-list above with its reason. The #534 gate/// (`a_tool_backed_list_read_is_paged_or_whole`) covers reads bound to a tool/// by NAME; this one covers the bodies — `ReadSource::Query`, `Controller`/// and `Composed` — where a `("limit", 200)` stood in for "everything" on/// nine screens and stopped there silently.#[test]fn a_screen_read_never_takes_a_page_by_number() {letmut sources = phone_sources();// The `reads/` bodies too — `day.rs`, `person.rs` — which `phone_sources`// leaves out because that helper is about the module's own files.let reads_dir = cotton_store::manifest::manifest_dir().join("src/phone/reads");for entry in std::fs::read_dir(&reads_dir).expect("src/phone/reads") {let path = entry.expect("an entry").path();letSome(name) = path.file_name().and_then(|name| name.to_str()) else {continue; };if !name.ends_with(".rs") || name.ends_with("_tests.rs") {continue; } sources.push(( name.to_string(), std::fs::read_to_string(&path).expect("a readable source"), )); }letmut offenders: Vec<String> = Vec::new();letmut used: BTreeSet<(&str, &str)> = BTreeSet::new();for (file, text) in &sources {for (number, line) in text.lines().enumerate() {let trimmed = line.trim_start();if trimmed.starts_with("//") {continue; }let hands_a_limit = (trimmed.contains("(\"limit\", ") || trimmed.contains("\"limit\".to_string(), ")) && !trimmed.contains("WHOLE_SET");// A raw `LIMIT` that is not `LIMIT 1` (one row is not a page) and// not a name that merely contains the word (`WHOLE_SET_LIMIT`).let raw_limit = trimmed.contains("LIMIT ") && !trimmed.contains("_LIMIT") && !trimmed.contains("LIMIT_") && trimmed.split("LIMIT ").skip(1).any(|rest| {letmut chars = rest.chars(); !(chars.next() == Some('1') && !chars.next().is_some_and(|next| next.is_ascii_digit())) });if !hands_a_limit && !raw_limit {continue; }match PAGE_BY_NUMBER_ALLOWED .iter() .find(|(allowed_file, needle, _)| allowed_file == file && trimmed.contains(needle)) {Some((allowed_file, needle, _)) => { used.insert((allowed_file, needle)); }None => offenders.push(format!("{file}:{}: {trimmed}", number + 1)), } } } assert!( offenders.is_empty(),"a screen read takes a page by number. Send `WHOLE_SET` (the phone's read seam draws the \ whole set at personal scale), page every page in a loop, or add the line to \ PAGE_BY_NUMBER_ALLOWED with the sentence that makes it honest:\n{}", offenders.join("\n") );let stale: Vec<String> = PAGE_BY_NUMBER_ALLOWED .iter() .filter(|(file, needle, _)| !used.contains(&(file, needle))) .map(|(file, needle, _)| format!("{file}: {needle}")) .collect(); assert!( stale.is_empty(),"PAGE_BY_NUMBER_ALLOWED names lines that are gone — an allowance that outlived its line \ is a guard that has stopped guarding:\n{}", stale.join("\n") );}/// The thoughts list and one thought's page read the SAME ledger. `/thoughts`/// came back on 2026-09-28 when To decide stopped holding thoughts; without/// it an unsure capture was on no list at all.#[test]fn the_thoughts_list_and_one_thought_are_both_read_thoughts() {let thoughts = READS .iter() .find(|entry| entry.name == "thoughts") .expect("read.thoughts is declared");for screen in ["/thoughts", "/thoughts/thought/[id]"] { assert!( thoughts.audience.screens().contains(&screen),"{screen} is read by read.thoughts" ); assert!(ROUTES.contains(&screen), "{screen} is a route"); }}/// The Me card's page reads `read.you` and nothing else (owner, 11 Oct 2026)./// `you` reads `cotton_workspaces.owner_person_id` in this device's own file,/// so Me opens with no server reachable and resolves the owner by that id/// alone; a second read on `/me` — a network one, or a People search — would/// be a second way to find "who is me", and a name can match somebody else.#[test]fn the_me_page_reads_you_alone() {let on_me: Vec<&str> = READS .iter() .filter(|entry| entry.audience.screens().iter().any(|screen| route_of(screen) == "/me")) .map(|entry| entry.name) .collect(); assert_eq!(on_me, ["you"], "/me reads read.you alone");let you = READS.iter().find(|entry| entry.name == "you").expect("read.you"); assert!(matches!(you.source, ReadSource::Controller(_)), "read.you reads this device's own file");}