//! `read.activity`, against a seeded synthetic replica.//!//! EVERY FIXTURE IS SYNTHETIC — no real name, sentence, number or credential//! anywhere in this tree ([nothing-real-ever-goes-in-cotton-s-public-tree]).//! The rows here are the ones this read has opinions about: one run in each of//! the four states, a `queued` row that must sort by the only instant it has, a//! run that stopped at a ceiling, and an audit trail longer than the cap.//!//! The controller and its seeded replica come from `reads_home_tests`'//! `workspace`, which is the ONE place a fixture phone is assembled in this//! crate — a second copy of that fifty lines would be a second opinion about//! what a replica looks like. Its clock is fixed at `2026-09-08T10:00:00Z` and//! does not move.use cotton_store::driver::Driver;use rusqlite::types::ValueasSqlValue;use serde_json::{json, Map, Value};usecrate::fixture;usecrate::phone::reads::home_tests::workspace;usecrate::shell::client::ClientController;fn text(value: &str) -> SqlValue {SqlValue::Text(value.to_string())}/// The read, as the boundary runs it: through the controller, over the replica.fn activity_of(client: &ClientController, args: Value) -> Value {let args: Map<String, Value> = match args {Value::Object(args) => args,Value::Null => Map::new(), other => panic!("a read's arguments are an object, not {other}"), }; client .with_writer(|replica| super::activity(replica, &args)) .expect("activity answers")}/// The same, when the case is about the refusal rather than the answer.fn refusal_of(client: &ClientController, args: Value) -> String {let args: Map<String, Value> = args.as_object().cloned().expect("an object"); client .with_writer(|replica| super::activity(replica, &args)) .expect_err("a refusal")}/// One run, with every column a run of that state would really carry.////// `finished` and `error` are derived from the state rather than passed,/// because the table's paired CHECKs refuse any other combination — a fixture/// that could spell an impossible row is a fixture that proves nothing about/// the real one.#[allow(clippy::too_many_arguments)]fn seed_run( db: &Driver, id: &str, state: &str, task: &str, queued_at: &str, started_at: Option<&str>, finished_at: Option<&str>, stopped_reason: Option<&str>,) {let error = if state == "failed" {SqlValue::Text("the model would not answer this one".to_string()) } else {SqlValue::Null }; db.run("INSERT INTO cotton_assistant_runs \ (id, workspace_id, source_kind, source_id, record_kind, record_id, session_id, class, \ state, task, receipt, turns, input_tokens, output_tokens, cost_usd, result_note_id, \ stopped_reason, error, queued_at, started_at, finished_at) \ VALUES (?,?,'thought',?,'note',?,NULL,'quick',?,?,?,2,410,88,0.0176,?,?,?,?,?,?)", &[ text(id), text(fixture::WORKSPACE), text(&format!("source-{id}")), text("note-a"), text(state), text(task), text("Working on it · about ten minutes"), text("note-b"), stopped_reason.map_or(SqlValue::Null, text), error, text(queued_at), started_at.map_or(SqlValue::Null, text), finished_at.map_or(SqlValue::Null, text), ], ) .expect("a run");}/// A connection an assistant used, and the rows saying what it did with it.////// The hash is sixty-four zeroes — the CHECK's shape, and nothing that was ever/// a credential.fn seed_audit(db: &Driver, token_id: &str, token_name: &str, tools: &[(&str, &str)]) { db.run("INSERT INTO cotton_mcp_tokens \ (id, owner_user_id, workspace_id, name, token_hash, scopes, created_at) \ VALUES (?,?,?,?,?,?,?)", &[ text(token_id), text(fixture::OWNER), text(fixture::WORKSPACE), text(token_name), text(&"0".repeat(64)), text(r#"["read","write"]"#), text("2026-09-01T00:00:00.000Z"), ], ) .expect("a token");for (n, (id, tool)) in tools.iter().enumerate() { db.run("INSERT INTO cotton_mcp_audit \ (id, token_id, workspace_id, tool, args_summary, ok, created_at) \ VALUES (?,?,?,?,?,1,?)", &[ text(id), text(token_id), text(fixture::WORKSPACE), text(tool), text("no arguments"), text(&format!("2026-09-0{}T00:00:00.000Z", n + 1)), ], ) .expect("an audit line"); }}fn ids(answer: &Value, key: &str) -> Vec<String> { answer[key] .as_array() .unwrap_or_else(|| panic!("{key} is an array")) .iter() .map(|row| row["id"].as_str().expect("an id").to_string()) .collect()}// ── the header ────────────────────────────────────────────────────────────#[test]fn the_four_facts_the_screen_has_always_had_survive_the_nesting() {// The rename was `replicaFacts` → `activity`; the header's fourth fact is// now `held` rather than the file's PATH (2026-09-15 — see `shell::file`).// Nothing else about the header moved, and each fact is asserted against// the thing that actually holds it — the connection record, the rail, the// op log, the store's own outbox — rather than against a function that is// gone.// A PAIRED phone: its own device row is in its copy and it knows its key,// because a write at the screen is asked by the owner at that row.let (_dir, client) = workspace(fixture::this_devices_row); client.set_self_device_id(Some(fixture::SELF_DEVICE_ID.to_string()));// Nothing authored yet, so nothing is waiting.let before = activity_of(&client, json!({})); assert_eq!(before["replica"]["pending"], json!(0));letmut todo = Map::new(); todo.insert("title".to_string(), json!("A synthetic errand")); client.write("create_todo", &todo).expect("the todo is written");let answer = activity_of(&client, json!({}));let header = &answer["replica"]; assert_eq!(header["workspaceId"], json!(fixture::WORKSPACE));// A replica, said as a WORD. The phone reads a copy; a serving Mac would// say `served`. Nothing here is a place on anybody's disk. assert_eq!(header["held"], json!("replica")); assert!(header.get("path").is_none(), "the path is back on the wire: {header}");// "Under which device id" has to be the id this file's OPS actually wear,// or the screen names a device that wrote none of them. The controller// mints its own identity, so this is asked of the QUEUE rather than of the// fixture's constant. The queue and not `_ops`: version 8 stopped writing a// log, and what a local write leaves behind is an outbox row.let authored = client .with_writer(|replica| {Ok(replica .driver .get("SELECT author FROM _outbox ORDER BY op_id DESC LIMIT 1", &[]) .map_err(|error| error.to_string())? .and_then(|row| row.text("author").map(str::to_string))) }) .expect("the queue") .expect("the write minted an op"); assert_eq!(header["deviceId"], json!(authored));// The outbox count is the STORE's, asked afresh — not a zero this layer// remembered from the call above. THREE: the todo, its history row, and// the file's author fact its first write queued ahead of it. assert_eq!(header["pending"], json!(3));// And the four are UNDER `replica`, not beside the lists — the whole reason// the nesting happened. assert!(answer.get("workspaceId").is_none()); assert!(answer.get("pending").is_none());}// ── the runs ──────────────────────────────────────────────────────────────#[test]fn a_run_carries_every_column_it_has_camel_cased_and_nothing_is_recomposed() {let (_dir, client) = workspace(|db| { seed_run( db,"run-failed","failed","read the two papers","2026-09-07T09:00:00.000Z",Some("2026-09-07T09:01:00.000Z"),Some("2026-09-07T09:04:00.000Z"),Some("model_refused"), ); });let run = activity_of(&client, json!({}))["runs"][0].clone(); assert_eq!( run, json!({"id": "run-failed","sourceKind": "thought","sourceId": "source-run-failed","recordKind": "note","recordId": "note-a","sessionId": Value::Null,"class": "quick","state": "failed","task": "read the two papers",// The two sentences the SERVER composed, byte for byte. A screen// that rebuilt either would be a second implementation of a// sentence, which is the one thing this read exists not to do."receipt": "Working on it · about ten minutes","error": "the model would not answer this one","turns": 2,"inputTokens": 410,"outputTokens": 88,"costUsd": 0.0176,"resultNoteId": "note-b","stoppedReason": "model_refused","queuedAt": "2026-09-07T09:00:00.000Z","startedAt": "2026-09-07T09:01:00.000Z","finishedAt": "2026-09-07T09:04:00.000Z", }),"a column moved, was renamed, or was rebuilt" );}/// A run nobody has costed yet answers `null`, and never `0.0`.////// `cost_usd` is the one column in this read whose NULL argues for itself in/// prose (`activity.rs`: *"NULL is 'not costed', which is not the same as/// free"*), and until this case every seeded run carried a cost, so `or_null`'s/// `None` arm was never driven. The tidy this guards against —/// `row.real("cost_usd").unwrap_or(0.0)` — compiles, keeps the suite green, and/// tells the person every un-costed run was free. `stopped_reason` rides the/// same case: a run that has not stopped has no reason, and the screen must be/// told that rather than shown a word.#[test]fn a_run_nobody_has_costed_answers_null_and_never_a_zero() {let (_dir, client) = workspace(|db| {// Not `seed_run`: that one costs every row it writes. A queued run is// where the four NULLs legitimately sit together — no cost, no reason,// no start, no finish — which is what the table's paired CHECKs admit. db.run("INSERT INTO cotton_assistant_runs \ (id, workspace_id, source_kind, source_id, record_kind, record_id, session_id, \ class, state, task, receipt, turns, input_tokens, output_tokens, cost_usd, \ result_note_id, stopped_reason, error, queued_at, started_at, finished_at) \ VALUES (?,?,'comment',?,'note',?,NULL,'deep','queued',?,?,0,0,0,NULL,NULL,NULL,NULL,?,NULL,NULL)", &[ text("run-uncosted"), text(fixture::WORKSPACE), text("source-run-uncosted"), text("note-a"), text("read the two papers again"), text("Queued"), text("2026-09-07T09:00:00.000Z"), ], ) .expect("an uncosted run"); });let run = activity_of(&client, json!({}))["runs"][0].clone(); assert_eq!(run["id"], json!("run-uncosted")); assert_eq!( run["costUsd"],Value::Null,"an un-costed run was answered as costing something: {run}" ); assert_eq!( run["stoppedReason"],Value::Null,"a run that has not stopped was given a reason: {run}" );// Both keys are PRESENT and null rather than absent — the Swift decoder is// written for a key that is always there, the same rule `working` keeps. assert!(run.get("costUsd").is_some() && run.get("stoppedReason").is_some());// And the columns that are NOT NULL-able still carry their zeroes, so this// case cannot be read as "the whole row went null". assert_eq!(run["turns"], json!(0)); assert_eq!(run["inputTokens"], json!(0));}#[test]fn a_run_that_has_not_started_sorts_by_the_only_instant_it_has() {// The ordering rule as a test rather than as a comment: newest first by// COALESCE(finished_at, started_at, queued_at). A run QUEUED an hour ago// and still waiting therefore sorts BELOW one that finished ten minutes// ago — ordering by `queued_at` alone would put the whole queued state at// one end of the list whatever had happened since.let (_dir, client) = workspace(|db| { seed_run( db,"run-queued","queued","the one still waiting","2026-09-08T09:00:00.000Z",None,None,None, ); seed_run( db,"run-done","done","the one that finished later","2026-09-08T08:00:00.000Z",Some("2026-09-08T09:40:00.000Z"),Some("2026-09-08T09:50:00.000Z"),Some("answered"), ); seed_run( db,"run-running","running","the one under way","2026-09-08T07:00:00.000Z",Some("2026-09-08T09:30:00.000Z"),None,None, ); }); assert_eq!( ids(&activity_of(&client, json!({})), "runs"), vec!["run-done", "run-running", "run-queued"], );}#[test]fn the_runs_list_is_capped_and_the_working_count_is_not() {// THE CAPPED-COUNT TRAP, asserted. `runs` is a page; `working.count` is a// COUNT(*) over the whole table. A count taken from the length of the page// would answer 2 here — and would answer "50" for a workspace with four// hundred runs and never say so.let (_dir, client) = workspace(|db| {for n in0..4 { seed_run( db, &format!("run-q{n}"),"queued","one of four waiting", &format!("2026-09-0{}T09:00:00.000Z", n + 1),None,None,None, ); }// A running one, older than every queued row, so it is the oldest in// flight — and `running` counts as in flight just as `queued` does. seed_run( db,"run-r","running","the oldest thing in flight","2026-08-30T09:00:00.000Z",Some("2026-09-08T09:00:00.000Z"),None,None, );// Neither of these is in flight, and neither may be counted. seed_run( db,"run-d","done","finished","2026-09-01T09:00:00.000Z",Some("2026-09-01T09:01:00.000Z"),Some("2026-09-01T09:02:00.000Z"),Some("answered"), ); seed_run( db,"run-f","failed","gave up","2026-09-01T09:00:00.000Z",Some("2026-09-01T09:01:00.000Z"),Some("2026-09-01T09:02:00.000Z"),Some("model_refused"), ); });let answer = activity_of(&client, json!({ "limit": 2 })); assert_eq!(ids(&answer, "runs").len(), 2, "the page was not capped");// And with NO opinion the screen gets every row, not the fifty an// assistant's page would stop at: the runs list is the whole set by default.let whole = activity_of(&client, json!({})); assert_eq!(ids(&whole, "runs").len(), 7, "the default is the whole set: {whole}");let all = activity_of(&client, json!({ "limit": "all" })); assert_eq!(ids(&all, "runs").len(), 7, "\"all\" is the whole set too: {all}"); assert_eq!( answer["working"], json!({"count": 5,"oldestTask": "the oldest thing in flight","oldestQueuedAt": "2026-08-30T09:00:00.000Z", }), );}#[test]fn nothing_in_flight_is_a_zero_with_two_nulls_and_never_an_absent_object() {let (_dir, client) = workspace(|_db| {}); assert_eq!( activity_of(&client, json!({}))["working"], json!({ "count": 0, "oldestTask": Value::Null, "oldestQueuedAt": Value::Null }), );}// ── the audit trail ───────────────────────────────────────────────────────#[test]fn the_audit_trail_names_the_connection_and_says_when_it_left_rows_behind() {let (_dir, client) = workspace(|db| { seed_audit( db,"token-a","A synthetic connection", &[ ("audit-1", "list_todos"), ("audit-2", "search_records"), ("audit-3", "brief"), ], ); });// Below the cap: everything is here and the flag is false.let answer = activity_of(&client, json!({ "auditLimit": 5 })); assert_eq!(answer["auditTruncated"], json!(false)); assert_eq!( ids(&answer, "audit"), vec!["audit-3", "audit-2", "audit-1"],"the trail is newest first" ); assert_eq!( answer["audit"][0], json!({"id": "audit-3","tokenId": "token-a",// Joined, because the row holds only the id and a uuid on a screen// asks the person to remember which connection that was."tokenName": "A synthetic connection","tool": "brief","ok": true,"argsSummary": "no arguments","createdAt": "2026-09-03T00:00:00.000Z", }), );// At the cap: the flag is TRUE, and it is a COUNT(*) rather than// `rows.len() == limit` — which is why asking for exactly three of three// below answers false rather than "there might be more".let capped = activity_of(&client, json!({ "auditLimit": 2 })); assert_eq!(ids(&capped, "audit").len(), 2); assert_eq!(capped["auditTruncated"], json!(true)); assert_eq!( activity_of(&client, json!({ "auditLimit": 3 }))["auditTruncated"], json!(false),"a page that happens to be exactly `limit` long is not evidence of more" );}#[test]fn the_token_hash_is_nowhere_in_the_answer_at_all() {// A string search over the WHOLE serialised answer, not an assertion about// one key: the column is a hash of a secret this device saw exactly once at// mint, and the failure this guards against is it arriving somewhere nobody// was looking.let hash = "0".repeat(64);let (_dir, client) = workspace(|db| { seed_audit(db, "token-a", "A synthetic connection", &[("a1", "brief")]); });let answer = activity_of(&client, json!({})).to_string(); assert!( !answer.contains(&hash),"the token hash reached the screen: {answer}" ); assert!( !answer.contains("token_hash") && !answer.contains("tokenHash"),"the column is named in the answer: {answer}" );}// ── the refusals ──────────────────────────────────────────────────────────#[test]fn a_limit_outside_its_range_is_refused_with_the_range_named() {// Refused, never clamped: the phone asked for something, and an answer// quietly cut down to a different size is a wrong number nobody is told// about.let (_dir, client) = workspace(|_db| {});for asked in [json!(0), json!(201), json!(-5), json!("lots"), json!(1.5)] {let refusal = refusal_of(&client, json!({ "limit": asked })); assert!( refusal.contains("`limit`") && refusal.contains("200"),"the refusal for {asked} does not name the range: {refusal}" ); }for asked in [json!(0), json!(101), json!("lots")] {let refusal = refusal_of(&client, json!({ "auditLimit": asked })); assert!( refusal.contains("`auditLimit`") && refusal.contains("100"),"the refusal for {asked} does not name the range: {refusal}" ); }// And the ends of each range are accepted rather than being off by one.// `null` is accepted with them, and deliberately: a Swift optional that was// never set encodes as `null`, and "no opinion" is not a number out of// range. It takes the default, exactly as an absent key does.for asked in [json!(1), json!(200), json!(null)] { activity_of(&client, json!({ "limit": asked })); }for asked in [json!(1), json!(100), json!(null)] { activity_of(&client, json!({ "auditLimit": asked })); }}#[test]fn no_arguments_at_all_is_the_ordinary_call() {let (_dir, client) = workspace(|_db| {});let answer = activity_of(&client, Value::Null); assert!(answer["runs"].is_array()); assert!(answer["audit"].is_array()); assert_eq!(answer["auditTruncated"], json!(false));}/// The read is reachable by the name the table declares, through the same/// dispatch a screen uses.#[test]fn the_screen_asks_for_it_by_the_name_the_table_declares() {let entry = crate::phone::reads::read_for("read.activity").expect("read.activity is declared"); assert!(matches!( entry.source,crate::phone::reads::ReadSource::Query(_) )); assert!(crate::phone::reads::read_for("read.replicaFacts").is_none(),"the old name still resolves — the rename is half done" );}/// Build 143's question, answered for this screen: sixty runs seeded, sixty/// drawn. Fifty was the assistant's page and the screen had no way past it.#[test]fn sixty_runs_are_sixty_rows_and_never_the_assistant_s_fifty() {let (_dir, client) = workspace(|db| {for n in0..60 { seed_run( db, &format!("run-many-{n:02}"),"done","one of sixty", &format!("2026-08-{:02}T09:{:02}:00.000Z", 1 + n / 30, n % 30),Some("2026-09-01T09:01:00.000Z"),Some("2026-09-01T09:02:00.000Z"),Some("answered"), ); } });let answer = activity_of(&client, json!({})); assert_eq!(ids(&answer, "runs").len(), 60, "{answer}");}// ── no filesystem path reaches a row ──────────────────────────────────────/// Every string anywhere in a JSON answer, with the key path that reached it.fn every_string(value: &Value, at: &str, found: &mutVec<(String, String)>) {match value {Value::String(text) => found.push((at.to_string(), text.clone())),Value::Array(items) => {for (index, item) in items.iter().enumerate() { every_string(item, &format!("{at}[{index}]"), found); } }Value::Object(map) => {for (key, item) in map { every_string(item, &format!("{at}.{key}"), found); } } _ => {} }}/// What a filesystem path looks like when it leaks. `/Users/` and `/home/`/// are somebody's home folder by name; `/var/` and `/private/` are a/// container's place on a disk; a `.db` suffix is the file itself.fn looks_like_a_path(text: &str) -> bool {const HOMES: [&str; 5] = ["/Users/", "/home/", "/var/", "/private/", "/tmp/"]; HOMES.iter().any(|home| text.contains(home)) || text.ends_with(".db")}/// **A row of the transparency screen never carries a place on a disk.**////// The capture walk of 2026-09-15 (row 200) found the Activity screen's "This/// database" slip printing `/Users/<name>/CottonDB/client/<ws>/replica.db` —/// the Mac's home folder, on the phone. A path on another machine is not a/// fact this screen is for, and a home folder carries a person's name.////// This is the layer that PRODUCES the text — the read composes the answer and/// Swift prints what it is given — so the guard lives here and sweeps the/// whole answer rather than the one key that leaked. The runs, the audit trail/// and the header are all covered: an assistant receipt that quoted a path/// would fail this too, which is the point.#[test]fn no_row_of_the_activity_read_carries_a_filesystem_path() {let (_dir, client) = workspace(|db| {// A PAIRED phone, which is the one that can write the todo below. fixture::this_devices_row(db); seed_run( db,"run-swept","done","a synthetic errand","2026-09-01T09:00:00.000Z",Some("2026-09-01T09:01:00.000Z"),Some("2026-09-01T09:02:00.000Z"),Some("answered"), ); }); client.set_self_device_id(Some(fixture::SELF_DEVICE_ID.to_string()));letmut todo = Map::new(); todo.insert("title".to_string(), json!("A synthetic errand")); client.write("create_todo", &todo).expect("the todo is written");let answer = activity_of(&client, json!({}));letmut strings = Vec::new(); every_string(&answer, "activity", &mut strings);// Anti-vacuity: a sweep over an empty answer would pass for ever. assert!( strings.len() > 8,"the sweep read {} strings — it would pass on nothing: {answer}", strings.len() );let leaked: Vec<String> = strings .iter() .filter(|(_, text)| looks_like_a_path(text)) .map(|(at, text)| format!("{at} = {text}")) .collect(); assert!( leaked.is_empty(),"these rows carry a place on a disk — say the FACT instead: {leaked:?}" );}#[test]fn the_path_sweep_catches_the_paths_it_was_written_for() {// The positive control: were `looks_like_a_path` to match nothing, the// sweep above would be green over a screen printing home folders again.for leak in ["/Users/someone/CottonDB/client/ws-1/replica.db","/home/someone/.cotton/replica.db","/var/mobile/Containers/Shared/AppGroup/abc/client/ws-1/replica.db","/private/tmp/synthetic/life.db","life.db", ] { assert!(looks_like_a_path(leak), "{leak} read as safe"); }for safe in ["replica", "served", "device:00000000000000000000000000", "done"] { assert!(!looks_like_a_path(safe), "{safe} read as a path"); }}