//! Everything is a catalogue composite, with facts from each table's reader. use cotton_core::everything::{finish, identities, plan, Error}; use serde_json::{json, Value}; use super::{list_answer_on, Total}; use crate::mcp::{ dispatch::{Ctx, ToolResult}, protocol::ToolFailure, }; fn refusal(error: Error) -> ToolFailure { ToolFailure::kinded(error.code, error.message) } /// How many secrets the Passwords list holds — what every screen says for /// Passwords, its own head and Everything's card alike, on the phone and /// through MCP: the live secrets of the kinds the list holds /// (`SecretKind::on_passwords`), never the bare table. pub fn passwords_listed(db: &cotton_store::driver::Driver, workspace_id: &str) -> Result { let sql = format!( "SELECT COUNT(*) AS n FROM cotton_secrets WHERE workspace_id = ? AND trashed_at IS NULL{}", cotton_core::vault::SecretKind::on_passwords_clause("kind"), ); let rows = db .all(&sql, &[rusqlite::types::Value::Text(workspace_id.to_string())]) .map_err(|error| error.to_string())?; Ok(rows.first().and_then(|row| row.int("n")).unwrap_or(0)) } /// ONE COUNT FOR EVERYTHING: a stored table's facts on its Everything row — /// how many its list holds (`count_args`, a `count_only` read) and when it /// last changed (`changed_args`, a `last_changed` read) — the same on the /// phone (`settings_everything`) and through MCP (`list` below). An /// unavailable reader is unknown, never a fabricated zero. pub fn table_facts( ctx: &mut Ctx<'_>, definition: &cotton_core::definitions::TableDefinition, count_args: &serde_json::Map, changed_args: &serde_json::Map, ) -> (Option, Option) { let count = if definition.id == "secret" { passwords_listed(ctx.db(), ctx.workspace_id).ok() } else { list_answer_on(ctx, definition, count_args, Total::Counted).ok().and_then(|answer| answer["total"].as_i64()) }; let changed = list_answer_on(ctx, definition, changed_args, Total::Counted) .ok() .and_then(|answer| answer.get("last_changed").cloned()); (count, changed) } pub(super) fn list(ctx: &mut Ctx<'_>, request: &Value) -> ToolResult { // Keep the phone's rule: only the database's resolved catalogue, never // all compiled tables. Missing tool-owned definitions and hidden tables // stay absent, even though this build knows how to read their storage. let snapshot = crate::definitions::shared_table_definitions(ctx)?; let definitions = &snapshot.definitions; let identities = identities(definitions); let plan = plan(&identities, request).map_err(refusal)?; let mut found = std::collections::HashMap::new(); for table in plan.tables() { let definition = definitions .iter() .find(|definition| definition.id == table) .expect("planned definition"); let mut args = json!({"table": table}); for key in ["today", "timezone"] { if let Some(value) = request.get(key) { args[key] = value.clone(); } } let mut changed = args.clone(); args["count_only"] = Value::Bool(true); changed["last_changed"] = Value::Bool(true); let facts = table_facts( ctx, definition, args.as_object().expect("fact args"), changed.as_object().expect("fact args"), ); found.insert(table.to_string(), facts); } finish(plan, request, |table| { found.remove(table).unwrap_or_default() }) .map_err(refusal) } pub(super) fn get(ctx: &mut Ctx<'_>, id: &str) -> ToolResult { let listed = list(ctx, &json!({"ids": [id]}))?; listed["records"] .as_array() .and_then(|records| records.first()) .cloned() .ok_or_else(|| { ToolFailure::kinded( "record_not_found", format!("the `everything` table has no record `{id}`"), ) }) } #[cfg(test)] mod tests { use super::*; use crate::mcp::dispatch::ToolServices; use rusqlite::types::Value as SqlValue; use std::sync::Arc; /// RULE: Everything reads each visible kind's actual count, then filters /// and pages the catalogue with the same contract as the phone. #[test] fn synthetic_catalogue_counts_filters_pages_and_gets() { let workspace = "00000000-0000-4000-8000-000000000001"; let owner = "00000000-0000-4000-8000-000000000002"; let at = "2026-10-01T10:00:00.000Z"; let db = cotton_store::test_template::create_workspace_in_memory_for_test( &cotton_store::meta::Meta { workspace_id: workspace.into(), owner_id: owner.into(), device_id: "device:everything-test".into(), last_server_seq: 0, last_hlc: None, }, ) .unwrap(); let text = |s: &str| SqlValue::Text(s.into()); db.run("INSERT INTO cotton_workspaces (id,name,owner_user_id,created_at,_hlc) VALUES (?,'Synthetic',?,?,'')", &[text(workspace), text(owner), text(at)]).unwrap(); for (id, name, plural) in [ ("apple", "Apple", "Apples"), ("book", "Book", "Books"), ("cup", "Cup", "Cups"), ] { let definition = json!({"id":id,"name":name,"plural":plural, "columns":[{"key":"name","type":"text"}],"title":"name", "slip":{"title":"name"},"tile":{"face":"slip-list"}, "page":[{"heading":null,"columns":["name"]}]}); db.run("INSERT INTO cotton_table_definitions (id,workspace_id,definition,builtin,created_at,updated_at) VALUES (?,?,?,0,?,?)", &[text(id), text(workspace), text(&definition.to_string()), text(at), text(at)]).unwrap(); } cotton_store::schema::package_shape::step_file(&db).unwrap(); for (id, count) in [("apple", 1), ("book", 2), ("cup", 3)] { for n in 0..count { db.run(&format!("INSERT INTO cotton_{id} (id,workspace_id,name,created_at,updated_at) VALUES (?,?,?,?,?)"), &[text(&format!("{id}-{n}")), text(workspace), text("Invented"), text(at), text(at)]).unwrap(); } } let identity = cotton_store::file_identity::read_file_identity(&db) .unwrap() .unwrap(); let services = ToolServices::none(); let scopes = vec!["read".into()]; let audit = |_: &str, _: &str| {}; let mut ctx = Ctx::new( &db, &identity, owner, "everything-test", "token", &scopes, at.parse().unwrap(), Arc::new(crate::random::SystemRandom), None, &services, &audit, ); let answer = list(&mut ctx, &json!({})).unwrap(); assert_eq!(answer["total"], 3); let rows = answer["records"].as_array().unwrap(); assert_eq!( rows.iter() .map(|row| row["data"]["count"].as_i64().unwrap()) .collect::>(), vec![1, 2, 3] ); assert_eq!( rows[1], json!({"id":"book","data":{"name":"Books","count":2,"count_one":"book","count_other":"books","changed":at},"deleted_at":null}) ); let counted = list(&mut ctx, &json!({"count_only":true})).unwrap(); assert_eq!(counted["total"], 3); assert_eq!(counted["records"], json!([])); let filtered = list(&mut ctx, &json!({"where":{"name":"Books"}})).unwrap(); assert_eq!(filtered["total"], 1); assert_eq!(filtered["records"][0]["id"], "book"); let page = list(&mut ctx, &json!({"page":1,"limit":1})).unwrap(); assert_eq!(page["records"].as_array().unwrap().len(), 1); assert_eq!(page["records"][0], rows[1]); assert_eq!(page["next_page"], 2); assert_eq!(page["total"], 3); assert_eq!(get(&mut ctx, "book").unwrap(), rows[1]); assert_eq!( get(&mut ctx, "missing").unwrap_err().kind(), Some("record_not_found") ); assert_eq!( list(&mut ctx, &json!({"query":"Books"})).unwrap()["total"], 1 ); assert_eq!( list(&mut ctx, &json!({"where":{"count":2}})).unwrap()["records"][0]["id"], "book" ); assert_eq!( list(&mut ctx, &json!({"last_changed":true})).unwrap()["last_changed"], at ); assert!(list(&mut ctx, &json!({"limit":0})).is_err()); // The public verbs dispatch this engine before looking for storage. let everything = cotton_core::definitions::builtin_table_definition("everything").unwrap(); db.run("INSERT INTO cotton_table_definitions (id,workspace_id,definition,builtin,created_at,updated_at) VALUES ('everything',?,?,1,?,?)", &[text(workspace), text(&serde_json::to_string(everything).unwrap()), text(at), text(at)]).unwrap(); let args = json!({"table":"everything","id":"book"}); assert_eq!( super::super::get_record_by_table(&mut ctx, args.as_object().unwrap()).unwrap(), rows[1] ); let args = json!({"table":"everything","count_only":true}); assert_eq!( super::super::list_records(&mut ctx, args.as_object().unwrap()).unwrap()["total"], 3 ); let args = json!({"table":"everything","archived":true}); assert_eq!( super::super::list_records(&mut ctx, args.as_object().unwrap()) .unwrap_err() .0, "Everything are never archived" ); // RULE: Passwords counts as its list reads it — never a document's // password or a binned one — through MCP as on the phone (the one // count, `table_facts`). for (id, kind, trashed) in [("sec-login", "login", None), ("sec-note", "note", None), ("sec-document", "document", None), ("sec-binned", "login", Some(at))] { db.run("INSERT INTO cotton_secrets (id, workspace_id, kind, name, value_enc, hint, trashed_at, created_at, updated_at) VALUES (?, ?, ?, ?, 'sealed-not-a-real-value', 'wxyz', ?, ?, ?)", &[text(id), text(workspace), text(kind), text(id), trashed.map_or(SqlValue::Null, text), text(at), text(at)]).unwrap(); } let secret = cotton_core::definitions::builtin_table_definition("secret").unwrap(); let count = json!({"table":"secret","count_only":true}); let changed = json!({"table":"secret","last_changed":true}); let (total, _) = table_facts(&mut ctx, secret, count.as_object().unwrap(), changed.as_object().unwrap()); assert_eq!(total, Some(2), "a login and a note"); assert_eq!(passwords_listed(&db, workspace).unwrap(), 2); } }