//! The work lane's evidence: the project page counts what the Mac's counts. //! //! Every fixture is synthetic — a workspace of zeroes, a project called //! "Example", a note nobody wrote //! ([nothing-real-ever-goes-in-cotton-s-public-tree]). The controller comes //! from `shell::client::phone_tests::attached`, the one place a paired phone is //! assembled, so these cases and the `write` cases look at the same device. use serde_json::{json, Map, Value}; use crate::phone::reads_work::device_words; use crate::shell::client::phone_tests::attached; use crate::shell::client::ClientController; fn args(pairs: &[(&str, Value)]) -> Map { pairs .iter() .map(|(name, value)| ((*name).to_string(), value.clone())) .collect() } /// A well-formed id for a record no file holds — the shape every read below is /// driven with, so a refusal can only ever be about the RECORD. const MISSING: &str = "00000000-0000-4000-8000-000000000000"; /// **Every read this lane declares, with the arguments its screen supplies.** /// /// ONE list, read by two tests: the empty-file sweep and the composite guard. /// It is maintained by hand — the reads table declares a read's ROUTES, not its /// arguments, and there is nowhere else to ask — so /// [`every_work_read_is_driven_here`] holds it to the table by name in both /// directions, which is what stops a read joining the table and being exercised /// by nothing. /// /// The argument NAMES are the screens' own, copied from the `WorkRead(read: /// args:)` call that draws each one. That is deliberate and is the whole point: /// a read that took `draftId` in a test and `id` from the screen would refuse /// at `text_arg` and never reach its inner tool, which is exactly how one /// read's query once went unexercised. const WORK_READS: &[(&str, &[(&str, &str)])] = &[ ("agentAccounts", &[]), ("briefing", &[]), ("devices", &[]), ("document", &[("documentId", MISSING)]), ("documents", &[]), ("meeting", &[("id", MISSING)]), ("meetings", &[]), ("memory", &[]), ("memoryEntry", &[("id", MISSING)]), ("newsEdition", &[]), ("newsSettings", &[]), ("newsTopics", &[]), ("page", &[("id", MISSING)]), ("pages", &[]), ("project", &[("slug", "example")]), ("projectSessions", &[("slug", "example")]), ("projectFeedback", &[("projectSlug", "example")]), ("projects", &[]), ("session", &[("id", MISSING)]), ("sessions", &[]), ]; /// Sentences that can only mean the read handed its tool the wrong ARGUMENT. /// /// A composite is given a well-formed id here, so a complaint about the shape /// or the presence of an argument is never about the caller — it is the read's /// own inner call, with a key the tool does not take. A refusal naming the /// missing RECORD is fine and expected; that is what an empty file should say. const ARGUMENT_COMPLAINTS: &[&str] = &[ "must be a uuid", "is required", "must be a string", "must be an integer", "must be true or false", "must be one of", ]; fn refusal_is_about_the_record(name: &str, refusal: &str) { for complaint in ARGUMENT_COMPLAINTS { assert!( !refusal.to_lowercase().contains(complaint), "read.{name} was given the arguments its own screen sends and refused with \ {refusal:?} — that is a complaint about an ARGUMENT, so its inner tool is being \ handed a key it does not take" ); } for sqlite in ["no such table", "no such column", "no such function"] { assert!( !refusal.to_lowercase().contains(sqlite), "read.{name} names something this file does not have: {refusal}" ); } } /// Answer a declared read the way `phone::read` does — through the TABLE, so a /// test cannot accidentally call a function no screen is bound to. fn read(client: &ClientController, name: &str, arguments: &Map) -> Value { let entry = super::super::reads::read_for(&format!("read.{name}")) .unwrap_or_else(|| panic!("read.{name} is declared")); // The ONE dispatch `cotton_call` uses, so a test cannot drift from it — // and so a new `ReadSource` cannot be added without every caller seeing it. super::super::answer_read(client, entry, arguments) .unwrap_or_else(|reason| panic!("read.{name} answered: {reason}")) } fn exec(client: &ClientController, sql: &str) { client .with_writer(|replica| replica.driver.exec(sql).map_err(|error| error.to_string())) .expect("the fixture"); } fn workspace_id(client: &ClientController) -> String { client .with_writer(|replica| Ok(replica.workspace_id.to_string())) .expect("the workspace") } /// One project with three linked kinds, so `group_counts` has something to /// disagree with. fn seed_project(client: &ClientController) { let workspace = workspace_id(client); exec( client, &format!( "INSERT INTO cotton_memory_projects \ (id, workspace_id, slug, name, repos, status, created_at, updated_at) \ VALUES ('11111111-1111-4111-8111-111111111111', '{workspace}', 'example', \ 'Example project', '[\"https://example.invalid/example/one\"]', 'active', \ '2026-01-01T00:00:00.000Z', '2026-01-01T00:00:00.000Z')" ), ); for (index, (kind, record)) in [ ("note", "22222222-2222-4222-8222-222222222222"), ("todo", "33333333-3333-4333-8333-333333333333"), ("document", "44444444-4444-4444-8444-444444444444"), ] .into_iter() .enumerate() { exec( client, &format!( "INSERT INTO cotton_project_links \ (id, workspace_id, project_id, record_kind, record_id, applied_by, \ created_at, updated_at, pinned) \ VALUES ('5000000{index}-5555-4555-8555-555555555555', '{workspace}', \ '11111111-1111-4111-8111-111111111111', '{kind}', '{record}', 'user', \ '2026-01-01T00:00:00.000Z', '2026-01-01T00:00:00.000Z', 0)" ), ); } } /// **The 4f evidence, half one.** `read.project` IS `get_project`, so the page /// draws the Mac's own `group_counts` rather than counting the links a second /// way — which is what "the project page counts what the Mac's counts" means /// as a compiled fact rather than as a promise. #[test] fn the_project_page_draws_get_projects_own_counts() { let (_guard, client) = attached(); seed_project(&client); let by_slug = args(&[("slug", json!("example"))]); let page = read(&client, "project", &by_slug); // The same call the seam makes: the tool, with the whole-set spelling. let mut whole = by_slug.clone(); whole.insert( "limit".to_string(), json!(cotton_tools::mcp::handlers::common::WHOLE_SET), ); let tool = client .read_tool("get_project", &whole) .expect("get_project"); // The composite passes the tool's answer through and ADDS beside it: the // project row, the counts and every linked group are byte-equal to the // assistant's — one function over one table — and the three facts the // paper page needs ride next to them rather than in place of them. assert_eq!(page["project"], tool["project"]); assert_eq!(page["counts"], tool["counts"]); assert_eq!(page["linked"]["notes"], tool["linked"]["notes"]); assert_eq!(page["linked"]["todos"], tool["linked"]["todos"]); assert_eq!(page["createdAt"], json!("2026-01-01T00:00:00.000Z")); // Every live slug, sorted — the cap's enamel is decided over the SET, so // the page must carry the whole set and not just its own. let caps = page["capSlugs"].as_array().expect("capSlugs"); assert!(caps.contains(&json!("example")), "own slug present: {caps:?}"); let sorted: Vec<_> = caps.iter().filter_map(|v| v.as_str()).collect(); let mut expect = sorted.clone(); expect.sort_unstable(); assert_eq!(sorted, expect, "capSlugs sorted"); // And the counts are actually there to be drawn — a byte-equal comparison // of two empty answers would pass on nothing. let counts = page .get("groupCounts") .or_else(|| page.get("group_counts")) .or_else(|| page.get("counts")) .unwrap_or(&Value::Null); assert!( !counts.is_null(), "get_project answered no counts at all, so this test would pass on nothing: {page}" ); } /// **The page's sections are `get_project`'s, and the Sessions section /// reaches past the queue's week.** `sections` passes through untouched; and /// `sessionPreview` carries the project's newest THREADS with no window, so a /// project whose last session ran a month ago still previews it — while its /// standing conversation, the top of the page, is never one of them. #[test] fn the_project_page_draws_get_projects_sections_and_a_session_history_past_the_week() { let (_guard, client) = attached(); seed_project(&client); let workspace = workspace_id(&client); for (id, kind, at) in [ ("80000001-8888-4888-8888-888888888888", "thread", "2025-06-01T00:00:00.000Z"), ("80000002-8888-4888-8888-888888888888", "conversation", "2025-06-02T00:00:00.000Z"), ] { exec( &client, &format!( "INSERT INTO cotton_sessions \ (id, workspace_id, tool, machine, project_id, kind, last_active_at, \ created_at, updated_at) \ VALUES ('{id}', '{workspace}', 'claude-code', 'an-invented-mac', \ '11111111-1111-4111-8111-111111111111', '{kind}', '{at}', '{at}', '{at}')" ), ); } let by_slug = args(&[("slug", json!("example"))]); let page = read(&client, "project", &by_slug); let mut whole = by_slug.clone(); whole.insert( "limit".to_string(), json!(cotton_tools::mcp::handlers::common::WHOLE_SET), ); let tool = client.read_tool("get_project", &whole).expect("get_project"); assert_eq!(page["sections"], tool["sections"]); assert!( page["sections"].as_array().expect("sections").contains(&json!({ "key": "sessions", "count": 1 })), "{page}" ); let history: Vec<&str> = page["sessionPreview"] .as_array() .expect("sessionPreview") .iter() .filter_map(|row| row["id"].as_str()) .collect(); assert_eq!(history, vec!["80000001-8888-4888-8888-888888888888"]); } /// Build 143's question for this page: `get_project` caps every linked group /// at fifty for an assistant (`GROUP_CAP`), and the page used to draw that /// fifty under a count that said fifty-five. The seam sends the whole set. #[test] fn the_project_page_draws_every_linked_row() { let (_guard, client) = attached(); seed_project(&client); let workspace = workspace_id(&client); for index in 0..55 { let note = format!("6{index:07}-6666-4666-8666-666666666666"); exec( &client, &format!( "INSERT INTO cotton_notes (id, workspace_id, title, body, created_at, updated_at) \ VALUES ('{note}', '{workspace}', 'Note {index:02}', 'one of fifty-five', \ '2026-01-01T00:00:00.000Z', '2026-01-01T00:00:00.000Z')" ), ); exec( &client, &format!( "INSERT INTO cotton_project_links \ (id, workspace_id, project_id, record_kind, record_id, applied_by, \ created_at, updated_at, pinned) \ VALUES ('7{index:07}-7777-4777-8777-777777777777', '{workspace}', \ '11111111-1111-4111-8111-111111111111', 'note', '{note}', 'user', \ '2026-01-01T00:00:00.000Z', '2026-01-01T00:00:00.000Z', 0)" ), ); } let page = read(&client, "project", &args(&[("slug", json!("example"))])); let notes = page["linked"]["notes"].as_array().expect("notes"); // Fifty-five: the fixture's own note link names a row that is not in the // file, and a link to nothing is not a row the page draws or counts. assert_eq!(notes.len(), 55, "{}", page["counts"]); assert_eq!(page["counts"]["notes"], json!(55)); } /// The project's repositories ride on the SESSIONS read now: the Code screens /// are the queue (phase 4), and `launchable_projects` answers each project's /// `repos` column and the crate's own reading of it. `read.codeContext` was /// retired with the directory it drew. #[test] fn the_sessions_read_answers_each_projects_repositories_and_nothing_else() { let (_guard, client) = attached(); seed_project(&client); let answer = read(&client, "sessions", &Map::new()); let projects = answer["projects"].as_array().expect("projects"); let slugs: Vec<&str> = projects .iter() .filter_map(|project| project["slug"].as_str()) .collect(); // The shared fixture already carries one active project and one archived // one, so this asserts on WHO is in the answer rather than on how many. assert!(slugs.contains(&"example"), "the seeded project: {slugs:?}"); assert!( !slugs.contains(&"alpaca-old"), "an archived project is not a place to open code: {slugs:?}" ); let seeded = projects .iter() .find(|project| project["slug"] == json!("example")) .expect("the seeded project"); assert_eq!( seeded["repos"], json!(["https://example.invalid/example/one"]) ); // And the crate's own reading of that column, so no Swift re-parses it. assert_eq!( seeded["remotes"][0]["host"], json!("example.invalid"), "the parse is the crate's: {}", seeded["remotes"] ); assert!( seeded.get("commits").is_none(), "a commit is read live from the host and never stored" ); } /// RULE: A device row says what a person reads of it — which device serves this database and which keep a copy, Fine or Busy, and free disk as "60 GB free of 926 GB" — never left for a screen to spell from raw figures. #[test] fn a_device_row_carries_its_words() { let row = |value: Value| value.as_object().expect("an object").clone(); let mac = row(json!({ "deviceId": "MAC", "revokedAt": null, "sampledAt": "2026-10-04T10:00:00.000Z", "memCommittedGb": 13.4, "memBudgetGb": 12.0, "load1": 2.0, "cpuCount": 10, "diskFreeGb": 59.6, "diskTotalGb": 926.0, })); let words = device_words(&mac, Some("MAC")); assert_eq!(words["serving"], json!(true)); assert_eq!(words["role"], json!("Serves this database")); assert_eq!(words["health"], json!("Busy"), "memory promised past its budget"); assert_eq!(words["diskLine"], json!("60 GB free of 926 GB")); let phone = row(json!({ "deviceId": "PHONE", "revokedAt": null, "sampledAt": null })); let words = device_words(&phone, Some("MAC")); assert_eq!(words["serving"], json!(false)); assert_eq!(words["role"], json!("Keeps a copy")); assert_eq!(words["health"], Value::Null, "no reading, no word"); assert_eq!(words["diskLine"], Value::Null); let calm = row(json!({ "deviceId": "MINI", "revokedAt": null, "sampledAt": "2026-10-04T10:00:00.000Z", "memCommittedGb": 4.0, "memBudgetGb": 12.0, "load1": 1.5, "cpuCount": 8, })); assert_eq!(device_words(&calm, Some("MAC"))["health"], json!("Fine")); let gone = row(json!({ "deviceId": "MAC", "revokedAt": "2026-10-01T00:00:00.000Z" })); let words = device_words(&gone, Some("MAC")); assert_eq!(words["role"], Value::Null, "a removed device has no role"); assert_eq!(words["serving"], json!(false)); } /// `read.devices` is the FILE's rows, and it names the device asking. /// /// A revoked row stays in the answer (the tool's own rule — "cut off" and /// "never here" must not read the same), and `thisDevice` is the id the /// server admits this device by, off the identity the transport signs with, /// never a column of the file: a file names no reader. #[test] fn the_devices_read_is_the_files_rows_with_this_device_named() { let (_guard, client) = attached(); let workspace = workspace_id(&client); exec( &client, &format!( "INSERT INTO cotton_devices (id, workspace_id, device_id, name, platform, \ approved_at, approved_by_device, created_at, updated_at) VALUES \ ('dev-a', '{workspace}', 'BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB', 'Study Mac', \ 'mac', 1_700_000_000_000, 'self', 1_700_000_000_000, 1_700_000_000_000), \ ('dev-b', '{workspace}', 'CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC', 'Old phone', \ 'ios', 1_700_000_000_000, 'self', 1_700_000_000_000, 1_700_000_000_000)" ), ); exec( &client, "UPDATE cotton_devices SET revoked_at = 1_700_000_001_000 WHERE id = 'dev-b'", ); let answer = read(&client, "devices", &Map::new()); let rows = answer["devices"].as_array().expect("the rows"); let names: Vec<&str> = rows .iter() .filter_map(|row| row["name"].as_str()) .collect(); assert!(names.contains(&"Study Mac"), "the live row: {names:?}"); assert!( names.contains(&"Old phone"), "a revoked row is IN the answer and says so: {names:?}" ); let revoked = rows .iter() .find(|row| row["name"] == json!("Old phone")) .expect("the revoked row"); assert!(revoked["revokedAt"].is_string(), "{revoked}"); assert_eq!( answer["thisDevice"], json!(crate::fixture::SELF_DEVICE_ID), "the id the server admits this device by, off the identity — never a column" ); } /// The Reader's pile is the owner's own browse surface, and an archived page /// has LEFT it — the grid's `page.remove` says the Reader archives, so a /// removed page must not come back in the list that says what is waiting. #[test] fn an_archived_page_leaves_the_reader_and_is_found_under_archived() { let (_guard, client) = attached(); let workspace = workspace_id(&client); for (index, (id, archived)) in [ ("88888888-8888-4888-8888-888888888888", "NULL"), ( "99999999-9999-4999-8999-999999999999", "'2026-03-03T00:00:00.000Z'", ), ] .into_iter() .enumerate() { exec( &client, &format!( "INSERT INTO cotton_pages \ (id, workspace_id, url, host, title, created_at, updated_at, archived_at) \ VALUES ('{id}', '{workspace}', 'https://example.invalid/{index}', \ 'example.invalid', 'Example page {index}', \ '2026-01-0{}T00:00:00.000Z', '2026-01-01T00:00:00.000Z', {archived})", index + 1 ), ); } let pile = read(&client, "pages", &Map::new()); let ids: Vec<&str> = pile["pages"] .as_array() .expect("pages") .iter() .map(|page| page["id"].as_str().unwrap_or_default()) .collect(); assert_eq!(ids, vec!["88888888-8888-4888-8888-888888888888"]); let entry = super::super::reads::read_for("read.pages").expect("read.pages"); let super::super::reads::ReadSource::Query(query) = entry.source else { panic!("read.pages is a query"); }; let archived = client .with_writer(|replica| query(replica, &args(&[("archived", json!(true))]))) .expect("the archived pile"); let ids: Vec<&str> = archived["pages"] .as_array() .expect("pages") .iter() .map(|page| page["id"].as_str().unwrap_or_default()) .collect(); assert_eq!(ids, vec!["99999999-9999-4999-8999-999999999999"]); } /// A memory's ORDER is a property of its membership, not of itself: the pin /// and the position live on the link row (v34), so the read carries the link /// and never guesses from the memory. #[test] fn a_memory_carries_the_link_that_orders_it() { let (_guard, client) = attached(); seed_project(&client); let workspace = workspace_id(&client); let memory = "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"; exec( &client, &format!( "INSERT INTO cotton_memories \ (id, workspace_id, slug, title, status, origin_kind, created_at, updated_at) \ VALUES ('{memory}', '{workspace}', 'an-invented-entry', \ 'An invented sentence for a test', 'active', 'user', \ '2026-01-01T00:00:00.000Z', '2026-01-01T00:00:00.000Z')" ), ); exec( &client, &format!( "INSERT INTO cotton_project_links \ (id, workspace_id, project_id, record_kind, record_id, applied_by, created_at, \ updated_at, pinned, \"position\") \ VALUES ('bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb', '{workspace}', \ '11111111-1111-4111-8111-111111111111', 'memory', '{memory}', 'user', \ '2026-01-01T00:00:00.000Z', '2026-01-01T00:00:00.000Z', 1, 4.5)" ), ); let scoped = read(&client, "memory", &args(&[("project", json!("example"))])); let entries = scoped["entries"].as_array().expect("entries"); assert_eq!(entries.len(), 1, "{scoped}"); let links = entries[0]["projects"].as_array().expect("projects"); assert_eq!(links.len(), 1); assert_eq!(links[0]["pinned"], json!(true)); assert_eq!(links[0]["position"], json!(4.5)); assert_eq!(links[0]["slug"], json!("example")); // A project nobody has is an empty list, never every entry in the file. let elsewhere = read(&client, "memory", &args(&[("project", json!("nobody"))])); assert!(elsewhere["entries"].as_array().expect("entries").is_empty()); } /// Every read this lane declares answers SOMETHING on an empty file rather than /// refusing — a screen with nothing on it draws its own quiet state, and a /// refusal there would be an error dialog over an empty database. #[test] fn the_work_reads_answer_an_empty_file_rather_than_refusing() { let (_guard, client) = attached(); // The ones that take no argument, which is the whole of "a screen opened // with nothing to show it". `briefing` is here because this PR turned it // from a bare tool into a composite, and a composite is a new way to // refuse. for (name, given) in WORK_READS { if !given.is_empty() { continue; } let answer = read(&client, name, &Map::new()); assert!( answer.is_object(), "read.{name} answered {answer} on an empty file" ); } } /// **The list above is the whole lane, both ways round.** /// /// A read added to the table and forgotten here is a read no test drives; a /// name left here after its read is gone is a test passing on nothing. Both /// were live: `read.document`, `read.store`, `read.orders`, `read.run` and /// `read.projectFeedback` reached no test at all, and one read's own guard /// drove it with an argument name its screen does not send, so its query was /// never once executed. /// /// The lane is identified by the routes it owns rather than by a second list: /// these are the reads whose bodies live in `reads_work`, and the table binds /// each of them to a `super::reads_work::` function. #[test] fn every_work_read_is_driven_here() { for (name, _) in WORK_READS { assert!( super::super::reads::read_for(&format!("read.{name}")).is_some(), "read.{name} is driven by these tests but is not in the reads table" ); } // And nothing this file implements is missing from the list. `recorder` is // in it despite having no Swift caller yet — a read nobody draws is still a // read this crate answers, and dropping it here would leave the one read in // the table exercised by nothing at all. for name in [ "agentAccounts", "briefing", "devices", "document", "documents", "meeting", "meetings", "memory", "memoryEntry", "newsEdition", "newsSettings", "newsTopics", "page", "pages", "project", "projectFeedback", "projects", "session", "sessions", ] { assert!( WORK_READS.iter().any(|(named, _)| *named == name), "read.{name} is one of this lane's and no test drives it" ); } } /// **A read that names a table nobody has is a SQL error, not an empty answer** /// — and only running it finds out. /// /// The id-taking reads were covered by the refusal case below, which never /// reaches the query at all: it asserts that a MISSING id is named, so a /// `SELECT ... FROM cotton_session_prompts` — a table this file does not have, /// and the name `cotton_prompts` was written as during the port — went to /// review green. So every read that takes an id is RUN here with one, against /// an empty file. Two answers are honest: an object holding nulls (`page`, /// `memoryEntry`, `session`, `newsEdition`), or a refusal naming the record /// nobody has (`meeting` — the tool it composes refuses, and its screen is /// reached by tapping a row that exists). What is never honest is /// the driver's own sentence about a name. #[test] fn every_read_that_takes_an_id_reaches_a_table_this_file_actually_has() { let (_guard, client) = attached(); for (name, given) in WORK_READS { if given.is_empty() { continue; } answered_or_refused_about_the_record(&client, name, given); } } /// **A read is driven with the arguments its own screen sends, and its refusal /// may only be about the RECORD.** /// /// This is the guard `read.meeting` walked past for as long as it did. The /// controller sent `{"id": …}` to `get_meeting`, which requires `meetingId`, /// and `read_tool` does no key mapping — so every call refused with /// "meetingId must be a uuid", for a real meeting exactly as loudly as for a /// missing one, and the screen could never load. /// /// Two things it used to be too weak to catch, both now closed: /// /// * it drove a read with an argument name its screen does not send, so the /// read refused at its own `text_arg` and never reached the tool or its query /// at all — a case that could not fail, over a query no test executed; /// * its only assertion was `!refusal.contains("must be a uuid")` — ONE tool's /// sentence. A wrong key that refused with "is required", "must be one of" or /// anything else at all went straight through. [`ARGUMENT_COMPLAINTS`] is the /// vocabulary now, and a refusal naming the missing record still passes, /// because that is what an empty file should say. #[test] fn a_composite_never_refuses_over_an_argument_the_caller_gave_it() { let (_guard, client) = attached(); for (name, given) in WORK_READS { let entry = super::super::reads::read_for(&format!("read.{name}")) .unwrap_or_else(|| panic!("read.{name} is declared")); // Every source, not only the composites: a `Query` mis-naming its own // argument and a `Tool` bound to a handler that wants another key fail // a screen exactly as completely. answered_or_refused_about_the_record(&client, name, given); if let super::super::reads::ReadSource::Tool(tool) = entry.source { // A tool-backed read has no inner call to get wrong, so all this // says is that the binding still resolves. Kept so the loop reads // as "every read", never "every read except". assert!( cotton_tools::mcp::dispatch::handler_for(tool).is_some(), "read.{name} is bound to {tool}, which no handler group registers" ); } } } /// One read, run against a file that holds no such record: it either answers, /// or refuses about the record — never about an argument the caller supplied, /// and never in SQLite's own words, which is what a name this file does not /// have sounds like. fn answered_or_refused_about_the_record( client: &ClientController, name: &str, given: &[(&str, &str)], ) { let entry = super::super::reads::read_for(&format!("read.{name}")) .unwrap_or_else(|| panic!("read.{name} is declared")); let arguments = args( &given .iter() .map(|(argument, value)| (*argument, json!(value))) .collect::>(), ); let answered = super::super::answer_read(client, entry, &arguments); match answered { Ok(answer) => assert!( answer.is_object(), "read.{name} answered {answer}, which is not something a screen can draw" ), Err(refusal) => refusal_is_about_the_record(name, &refusal), } } /// `/news` opens the newest READABLE edition, and says separately what the /// newest RUN is doing. /// /// Two questions, two answers, for the reason `editionFacts.ts` gives in its /// own doc comment: collapsing them "is how a screen ends up either hiding a /// failure behind yesterday's briefing or blanking a perfectly good briefing /// during a fetch". Last night's harvest failing must not take this morning's /// reader down with it. #[test] fn the_news_reader_opens_the_newest_ready_edition_and_still_names_the_newest_run() { let (_guard, client) = attached(); let workspace = workspace_id(&client); for (id, status, stage, created) in [ ( "cccccccc-cccc-4ccc-8ccc-cccccccccccc", "ready", "NULL", "2026-04-01T06:00:00.000Z", ), ( "dddddddd-dddd-4ddd-8ddd-dddddddddddd", "failed", "'harvest'", "2026-04-02T06:00:00.000Z", ), ] { exec( &client, &format!( "INSERT INTO cotton_news_editions \ (id, workspace_id, status, trigger_kind, covered_from, covered_to, \ failed_stage, status_changed_at, created_at, updated_at) \ VALUES ('{id}', '{workspace}', '{status}', 'scheduled', '{created}', \ '{created}', {stage}, '{created}', '{created}', '{created}')" ), ); } let opened = read(&client, "newsEdition", &Map::new()); assert_eq!( opened["edition"]["id"], json!("cccccccc-cccc-4ccc-8ccc-cccccccccccc"), "yesterday's readable edition, not this morning's failure: {opened}" ); assert_eq!( opened["newest"]["id"], json!("dddddddd-dddd-4ddd-8ddd-dddddddddddd"), "and the band still says what the newest run did: {opened}" ); assert_eq!(opened["newest"]["status"], json!("failed")); // A named edition is still that edition, and `newest` rides along for the // band above it. let named = read( &client, "newsEdition", &args(&[("id", json!("dddddddd-dddd-4ddd-8ddd-dddddddddddd"))]), ); assert_eq!( named["edition"]["id"], json!("dddddddd-dddd-4ddd-8ddd-dddddddddddd") ); assert_eq!( named["newest"]["id"], json!("dddddddd-dddd-4ddd-8ddd-dddddddddddd") ); } /// The projects list carries the two keys `list_projects` does not answer. /// /// Without `id` the sheets that file a record by id send `""`; without /// `lastActivity` the list falls through to its name tiebreak and is /// alphabetical, where the list is most-recently-worked-first. And the /// instant is the ENGINE's, over the linked records rather than the project /// row — a project renamed today has not been worked on today. #[test] fn the_projects_list_carries_an_id_and_when_each_project_last_moved() { let (_guard, client) = attached(); seed_project(&client); let workspace = workspace_id(&client); // One linked note with a much later `updated_at` than the project's own. exec( &client, &format!( "INSERT INTO cotton_notes (id, workspace_id, kind, title, body, created_at, updated_at) \ VALUES ('22222222-2222-4222-8222-222222222222', '{workspace}', 'note', 'A note', 'x', \ '2026-01-01T00:00:00.000Z', '2026-06-06T12:00:00.000Z')" ), ); let listed = read(&client, "projects", &Map::new()); let seeded = listed["projects"] .as_array() .expect("projects") .iter() .find(|project| project["slug"] == json!("example")) .expect("the seeded project"); assert_eq!( seeded["id"], json!("11111111-1111-4111-8111-111111111111"), "the id a sheet files by: {seeded}" ); assert_eq!( seeded["lastActivity"], json!("2026-06-06T12:00:00.000Z"), "the linked note's own moment, not the project row's: {seeded}" ); // And the tool's own answer is still whole underneath. assert_eq!(seeded["name"], json!("Example project")); assert_eq!(seeded["status"], json!("active")); } /// **The sessions read is a WINDOW, and the phone never downloads the rest.** /// /// The session host adopts a row for every session it finds in an agent's own /// transcript directory, so a Mac that has been coding for two months holds /// hundreds. TestFlight 168 asked for the whole set — a million — got four /// hundred and seventy-four, and drew them all under a heading that said /// Running. `since` is what the read asks with now. #[test] fn the_sessions_read_asks_for_a_week_and_not_for_everything() { let (_guard, client) = attached(); let workspace = workspace_id(&client); // The fixed clock is 2026-09-08T10:00Z, so the window opens on 2026-09-01. let seed = |id: &str, external: &str, active: &str| { exec( &client, &format!( "INSERT INTO cotton_sessions (id, workspace_id, tool, external_id, machine, started_at, last_active_at, created_at, updated_at) VALUES ('{id}', '{workspace}', 'claude-code', '{external}', 'a-machine', '{active}', '{active}', '{active}', '{active}')" ), ); }; seed( "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa", "this-week", "2026-09-07T09:00:00.000Z", ); seed( "bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb", "two-months-back", "2026-07-04T09:00:00.000Z", ); let answer = read(&client, "sessions", &Map::new()); let listed: Vec<&str> = answer["sessions"]["sessions"] .as_array() .expect("a sessions array") .iter() .filter_map(|row| row["externalId"].as_str()) .collect(); assert_eq!(listed, vec!["this-week"], "{answer}"); // And the window is ANSWERED, so the screen cuts its own sections by the // same number rather than by a second one written in Swift. assert_eq!( answer["quietWindowMs"], json!(crate::phone::reads_work::SESSIONS_WINDOW_MS) ); } /// A stale `?project=` shows an EMPTY log, never the whole workspace's. /// /// The read loads the log and filters it on the project, so a project nobody /// has matches nothing. Passing the slug to `list_sessions` instead would /// refuse the whole read — and refuse an ARCHIVED project's own Sessions row /// too, which the app opens on purpose. #[test] fn a_project_nobody_has_shows_an_empty_session_log_rather_than_every_session() { let (_guard, client) = attached(); seed_project(&client); let workspace = workspace_id(&client); // Inside the read's seven-day window (the fixed clock is 2026-09-08T10:00Z) // — this case is about the PROJECT filter, and a row outside the window is // not in the answer at all. exec( &client, &format!( "INSERT INTO cotton_sessions \ (id, workspace_id, project_id, tool, external_id, machine, started_at, \ last_active_at, created_at, updated_at) \ VALUES ('eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee', '{workspace}', \ '11111111-1111-4111-8111-111111111111', 'claude-code', 'x1', 'a-machine', \ '2026-09-08T09:00:00.000Z', '2026-09-08T09:30:00.000Z', \ '2026-09-08T09:00:00.000Z', '2026-09-08T09:30:00.000Z')" ), ); let rows = |answer: &Value| -> usize { answer["sessions"]["sessions"] .as_array() .map(Vec::len) .unwrap_or_default() }; let all = read(&client, "sessions", &Map::new()); assert_eq!(rows(&all), 1, "the seeded session is in the log: {all}"); let scoped = read(&client, "sessions", &args(&[("project", json!("example"))])); assert_eq!(rows(&scoped), 1, "and under its own project: {scoped}"); let stale = read(&client, "sessions", &args(&[("project", json!("nobody"))])); assert_eq!( rows(&stale), 0, "a stale deep link shows an empty log, never the whole workspace under a project's \ name: {stale}" ); // The Macs strip is not narrowed by a project — "which Mac has capacity" // is not a project question — so it is still answered. assert!(stale["devices"].is_object(), "{stale}"); } /// The sessions read carries what the new-session form and the Starting band /// draw: the queued sessions in the `sessions` list itself (ONE OBJECT, v23 — /// there is no second array), the agent logins the household has, the offered /// models, and the active projects with their ids and repos. #[test] fn the_sessions_read_answers_the_queue_the_logins_the_models_and_the_projects() { let (_guard, client) = attached(); seed_project(&client); let workspace = workspace_id(&client); for (id, external, account, machine) in [ ("eeeeeeee-eeee-4eee-8eee-eeeeeeeeeee1", "x1", "one@example.test", "box"), ("eeeeeeee-eeee-4eee-8eee-eeeeeeeeeee2", "x2", "two@example.test", "box"), ("eeeeeeee-eeee-4eee-8eee-eeeeeeeeeee3", "0d3e1a2b-1111-4222-8333-444455556666", "one@example.test", "laptop"), ] { exec( &client, &format!( "INSERT INTO cotton_sessions \ (id, workspace_id, tool, external_id, machine, account, started_at, \ last_active_at, created_at, updated_at) \ VALUES ('{id}', '{workspace}', 'claude-code', '{external}', '{machine}', \ '{account}', '2026-05-05T09:00:00.000Z', '2026-05-05T09:30:00.000Z', \ '2026-05-05T09:00:00.000Z', '2026-05-05T09:30:00.000Z')" ), ); } // The logins, as the client on each Mac mirrors them: one signed in right // now, one signed out and still listed with what it last read. for (id, email, signed_in_on, seen_at) in [ ( "account-1", "one@example.test", "'a-synthetic-device-key'", "2026-05-05T09:30:00.000Z", ), ("account-2", "two@example.test", "NULL", "2026-05-05T08:30:00.000Z"), ] { exec( &client, &format!( "INSERT INTO cotton_agent_accounts \ (id, workspace_id, provider, email, five_hour_pct, weekly_pct, seen_at, \ seen_on_device_id, created_at, updated_at) \ VALUES ('{id}', '{workspace}', 'anthropic', '{email}', 7.0, 16.0, \ '{seen_at}', {signed_in_on}, '{seen_at}', '{seen_at}')" ), ); } // The Mac that says it is signed in as the first login — its OWN // `account_ids`, which is what `signedInOn` is read from. Heard from // within the thirty days a machine stays listed. seed_mac( &client, "a-synthetic-device-key", "box", Some("2026-09-05T09:30:00.000Z"), r#"{"anthropic":"account-1"}"#, ); // Two sessions nobody has started: one the dispatcher could not place, // with the SENTENCE saying why, and one the owner put on a Mac by hand. for (id, device, chosen, hold, created) in [ ( "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaa1", "NULL", "NULL", "'Every Mac is building.'", "2026-05-05T10:00:00.000Z", ), ( "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaa2", "'a-synthetic-device-key'", "'owner'", "NULL", "2026-05-05T10:01:00.000Z", ), ] { exec( &client, &format!( "INSERT INTO cotton_sessions \ (id, workspace_id, tool, prompt, state, state_at, device_id, \ requested_device_id, chosen_by, hold_reason, host_owned, \ last_active_at, created_at, updated_at) \ VALUES ('{id}', '{workspace}', 'claude-code', 'go', 'queued', '{created}', \ {device}, {device}, {chosen}, {hold}, 1, '{created}', '{created}', \ '{created}')" ), ); } let answer = read(&client, "sessions", &Map::new()); // THE QUEUE IS IN THE SESSIONS LIST. A `queued` row is a session, so it is // answered by the same array a running one is — and it carries the prompt, // the Mac the owner asked for and the sentence that says why it is waiting. assert!( answer.get("launches").is_none(), "the queue is not a second list: {answer}" ); // And one is READ as a session — the same `read.session` a running card // opens, carrying what the owner asked for and what has stopped it. let mut one = Map::new(); one.insert( "id".to_string(), Value::from("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaa1"), ); let held = read(&client, "session", &one); assert_eq!(held["session"]["state"], json!("queued")); assert_eq!(held["session"]["prompt"], json!("go")); assert_eq!(held["session"]["holdReason"], json!("Every Mac is building.")); assert_eq!(held["session"]["requestedDeviceId"], Value::Null, "any Mac"); let mut other = Map::new(); other.insert( "id".to_string(), Value::from("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaa2"), ); let placed = read(&client, "session", &other); assert_eq!( placed["session"]["requestedDeviceId"], json!("a-synthetic-device-key") ); assert_eq!(placed["session"]["chosenBy"], json!("owner")); assert_eq!(placed["session"]["holdReason"], Value::Null); // No logins: the AI-account tables are retired (OPEN TABLES, owner, 24 Nov 2026), so the rows this file holds // are read by nothing. assert_eq!(answer["accounts"], json!([]), "no login is read from a retired table"); let models = answer["models"].as_array().expect("models"); assert_eq!(models[0], json!({ "id": "fable", "label": "Fable" })); assert!(models.len() >= 3, "{answer}"); // The seeded project is offered with its id and repos. The phone build's // fixture may hold projects of its own, so the row is found by id rather // than the list counted. let projects = answer["projects"].as_array().expect("projects"); let seeded = projects .iter() .find(|row| row["id"] == json!("11111111-1111-4111-8111-111111111111")) .unwrap_or_else(|| panic!("the seeded project is offered: {answer}")); assert_eq!(seeded["repos"], json!(["https://example.invalid/example/one"])); assert!(projects.iter().all(|row| row["status"] == json!("active")), "{answer}"); } // ── The Code tool's Machines: one row per machine ───────────────────────── // // The fixed clock is 2026-09-08T10:00Z; every stamp below is placed against it. /// A Mac's device row as its own report leaves it: `platform = 'mac'`, the /// time of its last report, and the logins it says it is signed in as. fn seed_mac( client: &ClientController, key: &str, name: &str, sampled_at: Option<&str>, account_ids: &str, ) { let workspace = workspace_id(client); let sampled_at = sampled_at.map_or("NULL".to_string(), |at| format!("'{at}'")); exec( client, &format!( "INSERT INTO cotton_devices \ (id, workspace_id, device_id, name, platform, approved_at, approved_by_device, \ account_ids, sampled_at, created_at, updated_at) \ VALUES ('row-{key}', '{workspace}', '{key}', '{name}', 'mac', \ '2026-09-01T00:00:00.000Z', 'root', '{account_ids}', {sampled_at}, \ '2026-09-01T00:00:00.000Z', '2026-09-01T00:00:00.000Z')" ), ); } /// A Claude login with both windows read at `read_at`. fn seed_login(client: &ClientController, id: &str, email: &str, five_hour_resets_at: &str, read_at: &str) { let workspace = workspace_id(client); exec( client, &format!( "INSERT INTO cotton_agent_accounts \ (id, workspace_id, provider, email, label, five_hour_pct, five_hour_resets_at, \ weekly_pct, weekly_resets_at, seen_at, created_at, updated_at) \ VALUES ('{id}', '{workspace}', 'anthropic', '{email}', 'An invented label', 40.0, \ '{five_hour_resets_at}', 21.0, '2026-09-10T10:30:00Z', '{read_at}', \ '{read_at}', '{read_at}')" ), ); } fn machine<'a>(answer: &'a Value, key: &str) -> &'a Value { answer["machines"] .as_array() .and_then(|rows| rows.iter().find(|row| row["deviceId"] == json!(key))) .unwrap_or_else(|| panic!("a row for {key}: {answer}")) } /// RULE: A Mac's row names no login and no usage figure, even where an older build left an account row: the AI accounts are retired (OPEN TABLES step 1, cf0af626dc), so the read answers their places empty, in the same shape. #[test] fn a_mac_s_row_names_no_login_and_no_usage_since_the_accounts_retired() { let (_guard, client) = attached(); seed_login(&client, "login-1", "owner@example.com", "2026-09-08T13:00:00Z", "2026-09-08T09:58:00.000Z"); for (key, name) in [("key-a", "Study Mac"), ("key-b", "Office Mac")] { seed_mac(&client, key, name, Some("2026-09-08T09:57:00.000Z"), r#"{"anthropic":"login-1"}"#); } let answer = read(&client, "agentAccounts", &Map::new()); for key in ["key-a", "key-b"] { let row = machine(&answer, key); assert_eq!(row["current"], json!(true), "{row}"); assert_eq!(row["canHost"], json!(true), "{row}"); for field in ["account", "fiveHourPct", "fiveHourResetsAt", "weeklyPct", "weeklyResetsAt", "usageReadAt"] { assert_eq!(row[field], Value::Null, "{field}: {row}"); } } assert!(answer["accounts"].as_array().is_none_or(|rows| rows.is_empty()), "{answer}"); } /// RULE: A machine that has not reported in ten minutes carries no usage figure at all — only the time it last reported. /// /// Rust decides staleness so the screen never has a stale percentage it could /// draw by mistake. #[test] fn a_silent_mac_s_row_has_no_numbers_and_says_when_it_last_reported() { let (_guard, client) = attached(); seed_login(&client, "login-1", "owner@example.com", "2026-09-08T13:00:00Z", "2026-09-08T09:30:00.000Z"); seed_mac(&client, "key-a", "Study Mac", Some("2026-09-08T09:49:00.000Z"), r#"{"anthropic":"login-1"}"#); let answer = read(&client, "agentAccounts", &Map::new()); let row = machine(&answer, "key-a"); assert_eq!(row["current"], json!(false), "{row}"); assert_eq!(row["lastReportAt"], json!("2026-09-08T09:49:00.000Z"), "{row}"); for field in [ "fiveHourPct", "fiveHourResetsAt", "weeklyPct", "weeklyResetsAt", "usageReadAt", ] { assert_eq!(row[field], Value::Null, "{field} on a silent Mac: {row}"); } } /// RULE: A machine that has not reported in ten minutes names no login on its row — who it was signed in as is as old as its last report. #[test] fn a_silent_mac_s_row_names_no_login() { let (_guard, client) = attached(); seed_login(&client, "login-1", "owner@example.com", "2026-09-08T13:00:00Z", "2026-09-08T09:30:00.000Z"); seed_mac(&client, "key-a", "Study Mac", Some("2026-09-08T09:49:00.000Z"), r#"{"anthropic":"login-1"}"#); let answer = read(&client, "agentAccounts", &Map::new()); let row = machine(&answer, "key-a"); assert_eq!(row["current"], json!(false), "{row}"); assert_eq!(row["account"], Value::Null, "{row}"); } /// RULE: The Code tool's Machines list has one row per machine: a re-joined Mac's old silent key is not a second row, and a machine silent for over thirty days has none. /// /// A Mac that joined again under a new key drew twice — once live, once "has /// not reported since …" — and a retired, unrevoked Mac said so for ever. #[test] fn a_re_joined_mac_is_one_row_and_a_retired_mac_is_none() { let (_guard, client) = attached(); seed_login(&client, "login-1", "owner@example.com", "2026-09-08T13:00:00Z", "2026-09-08T09:58:00.000Z"); let login = r#"{"anthropic":"login-1"}"#; seed_mac(&client, "key-new", "mac-b", Some("2026-09-08T09:59:00.000Z"), login); seed_mac(&client, "key-old", "Mac (mac-b)", Some("2026-09-07T10:00:00.000Z"), login); seed_mac(&client, "key-attic", "attic", Some("2026-08-08T09:59:00.000Z"), login); let answer = read(&client, "agentAccounts", &Map::new()); let keys: Vec<&Value> = answer["machines"] .as_array() .expect("machines") .iter() .map(|row| &row["deviceId"]) .collect(); assert_eq!(keys, [&json!("key-new")], "{answer}"); } #[test] fn a_phone_that_never_reported_has_no_machine_row() { let (_guard, client) = attached(); let workspace = workspace_id(&client); exec( &client, &format!( "INSERT INTO cotton_devices \ (id, workspace_id, device_id, name, platform, approved_at, approved_by_device, \ created_at, updated_at) \ VALUES ('row-phone', '{workspace}', 'key-phone', 'Example iPhone', 'ios', \ '2026-09-01T00:00:00.000Z', 'root', '2026-09-01T00:00:00.000Z', \ '2026-09-01T00:00:00.000Z')" ), ); seed_mac(&client, "key-a", "Study Mac", None, "{}"); let answer = read(&client, "agentAccounts", &Map::new()); let rows = answer["machines"].as_array().expect("machines"); assert!(rows.iter().all(|row| row["deviceId"] != json!("key-phone")), "{answer}"); // A Mac that has never reported is still a Mac: it has a row that says so. let mac = machine(&answer, "key-a"); assert_eq!(mac["current"], json!(false)); assert_eq!(mac["lastReportAt"], Value::Null); assert_eq!(mac["account"], Value::Null); } /// With no project named, the briefing screen briefs on the FIRST active one — /// and counts machine-scoped entries the way the compiler filters them. /// /// `briefing.tsx` resolves `lockedProjectId ?? chosen ?? projects[0]?.id`, in /// `memoriesService.listProjects`' `created_at ASC` order; `brief` with no /// project briefs on nothing at all, so without the stand-in the screen would /// open blank beside a chip rail of projects it refused to use. And /// `previewBriefing` counts over entries that are BOTH `active` and `private`, /// which is `live_memories`' own filter. #[test] fn a_briefing_with_no_project_named_briefs_on_the_first_active_one() { let (_guard, client) = attached(); seed_project(&client); let workspace = workspace_id(&client); for (index, (slug, visibility, machine)) in [ ("a-machine-scoped-entry", "private", "'a-machine'"), ("a-shared-entry", "shared", "'a-machine'"), ("an-entry-everywhere", "private", "NULL"), ] .into_iter() .enumerate() { let memory = format!("c000000{index}-cccc-4ccc-8ccc-cccccccccccc"); exec( &client, &format!( "INSERT INTO cotton_memories \ (id, workspace_id, slug, title, status, visibility, machine, origin_kind, \ created_at, updated_at) \ VALUES ('{memory}', '{workspace}', '{slug}', 'An invented sentence', 'active', \ '{visibility}', {machine}, 'user', '2026-01-01T00:00:00.000Z', \ '2026-01-01T00:00:00.000Z')" ), ); exec( &client, &format!( "INSERT INTO cotton_project_links \ (id, workspace_id, project_id, record_kind, record_id, applied_by, \ created_at, updated_at, pinned, \"position\") \ VALUES ('d000000{index}-dddd-4ddd-8ddd-dddddddddddd', '{workspace}', \ '11111111-1111-4111-8111-111111111111', 'memory', '{memory}', 'user', \ '2026-01-01T00:00:00.000Z', '2026-01-01T00:00:00.000Z', 0, {index}.0)" ), ); } let preview = read(&client, "briefing", &Map::new()); let rail = preview["projects"].as_array().expect("the chip rail"); assert!( !rail.is_empty(), "the rail is the ACTIVE projects and is never empty while there is one: {preview}" ); assert_eq!( preview["briefedProjects"], json!([rail[0]["slug"].as_str().unwrap_or_default()]), "with nothing named, the first active project stands in: {preview}" ); // ONE of the three: the shared entry is not what an agent is served, and // the entry with no machine rides every briefing. assert_eq!( preview["machineScoped"], json!(1), "both halves of the compiler's own filter — active AND private: {preview}" ); } /// The meeting PAGE says whether this device still holds the audio, and only /// the device-local ledger can tell it. /// /// `_media` is never synced and no tool can read it, so the fact has to ride on /// the read or the screen has to invent it. Both halves are required: a /// pre-queued status AND a pending row for the meeting's own key — a phone with /// no signal reading "Uploading the audio" is the lie `meetingFacts.ts` exists /// to prevent, and so is a finished meeting still claiming to upload. #[test] fn the_meeting_page_says_whether_this_device_still_holds_the_audio() { let (_guard, client) = attached(); let workspace = workspace_id(&client); let meeting = "b1111111-1111-4111-8111-111111111111"; exec( &client, &format!( "INSERT INTO cotton_meetings \ (id, workspace_id, status, source, started_at, status_changed_at, created_at, \ updated_at) \ VALUES ('{meeting}', '{workspace}', 'uploading', 'recorded', \ '2026-07-07T09:00:00.000Z', '2026-07-07T09:00:00.000Z', \ '2026-07-07T09:00:00.000Z', '2026-07-07T09:00:00.000Z')" ), ); let by_id = args(&[("id", json!(meeting))]); let before = read(&client, "meeting", &by_id); assert_eq!( before["record"]["waitingToUpload"], json!(false), "nothing is queued, so nothing is waiting: {}", before["record"] ); let key = format!("{workspace}/meetings/{meeting}/full.m4a"); exec( &client, &format!( "INSERT INTO _media \ (key, workspace_id, sha256, content_type, size_bytes, state, created_at, updated_at) \ VALUES ('{key}', '{workspace}', 'abc', 'audio/mp4', 1, 'pending', \ '2026-07-07T09:00:00.000Z', '2026-07-07T09:00:00.000Z')" ), ); let after = read(&client, "meeting", &by_id); assert_eq!( after["record"]["waitingToUpload"], json!(true), "the ledger row is pending and the status is pre-queued: {}", after["record"] ); } /// RULE: A meeting whose upload never arrived says whether this phone still has its audio, read off this device's own media ledger. #[test] fn a_meeting_whose_upload_never_arrived_says_whether_this_phone_still_has_the_audio() { let (_guard, client) = attached(); let workspace = workspace_id(&client); let meeting = "b3333333-3333-4333-8333-333333333333"; exec( &client, &format!( "INSERT INTO cotton_meetings \ (id, workspace_id, status, failed_stage, error_code, source, started_at, \ status_changed_at, created_at, updated_at) \ VALUES ('{meeting}', '{workspace}', 'failed', 'submit', 'upload_never_arrived', \ 'recorded', '2026-07-07T09:00:00.000Z', '2026-07-08T09:00:00.000Z', \ '2026-07-07T09:00:00.000Z', '2026-07-08T09:00:00.000Z')" ), ); let by_id = args(&[("id", json!(meeting))]); assert_eq!( read(&client, "meeting", &by_id)["record"]["holdsAudio"], json!(false), "no ledger row: the bytes were never on this phone" ); let key = format!("{workspace}/meetings/{meeting}/full.m4a"); for (state, holds) in [("pending", true), ("failed", true), ("synced", false)] { exec(&client, "DELETE FROM _media"); exec( &client, &format!( "INSERT INTO _media \ (key, workspace_id, sha256, content_type, size_bytes, state, created_at, \ updated_at) \ VALUES ('{key}', '{workspace}', 'abc', 'audio/mp4', 1, '{state}', \ '2026-07-07T09:00:00.000Z', '2026-07-07T09:00:00.000Z')" ), ); let page = read(&client, "meeting", &by_id); assert_eq!(page["record"]["holdsAudio"], json!(holds), "{state}: {}", page["record"]); assert_eq!( page["record"]["waitingToUpload"], json!(false), "a failed meeting is not drawn as uploading, whatever the ledger holds" ); } } /// The SAME fact, for an imported voice note whose audio is not an m4a. /// /// The key used to be a hard-coded `full.m4a` on both this read and the server's /// pipeline. `meetings.create` files a WhatsApp voice note at `full.opus` and /// names the object in the row's own manifest, so the key is read off the row — /// and a phone that went on looking for `full.m4a` would say a meeting had /// finished uploading the moment it was filed, over bytes still on the device. #[test] fn the_meeting_page_waits_on_the_object_the_row_actually_names() { let (_guard, client) = attached(); let workspace = workspace_id(&client); let meeting = "b2222222-2222-4222-8222-222222222222"; let key = format!("{workspace}/meetings/{meeting}/full.opus"); let manifest = format!( r#"[{{"seq":0,"path":"{key}","durationMs":92400,"uploadedAt":null}}]"# ); exec( &client, &format!( "INSERT INTO cotton_meetings \ (id, workspace_id, status, source, started_at, status_changed_at, segments, \ created_at, updated_at) \ VALUES ('{meeting}', '{workspace}', 'uploading', 'imported', \ '2026-07-07T09:00:00.000Z', '2026-07-07T09:00:00.000Z', '{manifest}', \ '2026-07-07T09:00:00.000Z', '2026-07-07T09:00:00.000Z')" ), ); exec( &client, &format!( "INSERT INTO _media \ (key, workspace_id, sha256, content_type, size_bytes, state, created_at, updated_at) \ VALUES ('{key}', '{workspace}', 'abc', 'audio/ogg', 1, 'pending', \ '2026-07-07T09:00:00.000Z', '2026-07-07T09:00:00.000Z')" ), ); let by_id = args(&[("id", json!(meeting))]); let page = read(&client, "meeting", &by_id); assert_eq!( page["record"]["waitingToUpload"], json!(true), "the pending ledger row is the .opus object the manifest names: {}", page["record"] ); // And the LIST says the same thing, off the same manifest — the two reads // draw the same badge and must not disagree about which key it is. let list = read(&client, "meetings", &Map::new()); let row = list["meetings"] .as_array() .expect("the list") .iter() .find(|row| row["id"] == json!(meeting)) .expect("the meeting"); assert_eq!(row["waitingToUpload"], json!(true), "{row}"); } /// RULE: Every call track belongs to the upload, including tracks after the /// first; the page and list must not claim that a partial upload is finished. #[test] fn call_recording_waits_for_every_local_track() { use cotton_core::media::{call_tracks::CallTrack,keys::meeting_segment_key}; use cotton_store::file_identity::FileId; let (_guard,client)=attached();let workspace=workspace_id(&client);let file=FileId::for_tests(&workspace); let meeting="b3333333-3333-4333-8333-333333333333"; let tracks=(0..2).map(|seq|CallTrack{kind:"call_track".into(),seq,key:meeting_segment_key(&file,meeting,seq),call:"call".into(),recording:"request".into(),identity:format!("device:{seq}"),name:"Invented person".into(),started_at:"2026-10-13T00:00:00Z".into(),duration_ms:1000,offset_ms:0,sha256:"a".repeat(64),job:None,in_transcript:false}).collect::>(); let manifest=serde_json::to_string(&tracks).unwrap();let key=&tracks[1].key; exec(&client,&format!("INSERT INTO cotton_meetings(id,workspace_id,status,source,started_at,status_changed_at,segments,created_at,updated_at) VALUES('{meeting}','{workspace}','uploading','recorded','2026-10-13T00:00:00Z','2026-10-13T00:00:00Z','{manifest}','2026-10-13T00:00:00Z','2026-10-13T00:00:00Z')")); exec(&client,&format!("INSERT INTO _media(key,workspace_id,sha256,content_type,size_bytes,state,created_at,updated_at) VALUES('{key}','{workspace}','abc','audio/mp4',1,'pending','2026-10-13T00:00:00Z','2026-10-13T00:00:00Z')")); let page=read(&client,"meeting",&args(&[("id",json!(meeting))]));assert_eq!(page["record"]["waitingToUpload"],true); let list=read(&client,"meetings",&Map::new());assert_eq!(list["meetings"].as_array().unwrap().iter().find(|r|r["id"]==meeting).unwrap()["waitingToUpload"],true); exec(&client,&format!("UPDATE _media SET state='synced' WHERE key='{key}'")); assert_eq!(read(&client,"meeting",&args(&[("id",json!(meeting))]))["record"]["waitingToUpload"],false); } /// And a read that needs an id says which one, rather than answering for a /// record it picked itself. #[test] fn a_read_that_needs_an_id_refuses_by_name() { let (_guard, client) = attached(); // Written as an assertion rather than a bare `expect_err` so a failure // names the read AND the argument it forgot to mention. for (name, argument) in [ ("page", "id"), ("session", "id"), ] { let entry = super::super::reads::read_for(&format!("read.{name}")).expect("declared"); let super::super::reads::ReadSource::Query(query) = entry.source else { continue; }; let refusal = client.with_writer(|replica| query(replica, &Map::new())); assert!( refusal.is_err(), "read.{name} answered with no {argument} at all" ); assert!( refusal.unwrap_err().contains(argument), "read.{name} did not name `{argument}` in its refusal" ); } } #[test] fn android_meeting_playback_key_uses_the_manifest_and_refuses_deleted_or_multiple_audio() { let workspace = "00000000-0000-4000-8000-000000000001"; let file = cotton_store::file_identity::FileId::for_tests(workspace); let meeting = "00000000-0000-4000-8000-000000000002"; let wav = format!("{workspace}/meetings/{meeting}/full.wav"); let opus = format!("{workspace}/meetings/{meeting}/full.opus"); let select = |deleted, manifest: &Value| { super::android_meeting_playback_key(&file, meeting, deleted, manifest) }; assert_eq!(select(None, &json!([{ "path": wav }])), json!(wav)); assert_eq!( select( None, &json!([{ "path": wav, "lost": true }, { "path": opus }]) ), json!(opus) ); assert_eq!( select(None, &json!([{ "path": wav }, { "path": opus }])), Value::Null ); assert_eq!( select(Some("2026-01-01T00:00:00Z"), &json!([{ "path": wav }])), Value::Null ); assert_eq!( select(None, &Value::Null), json!(cotton_core::media::keys::meeting_full_key( &file, meeting )) ); } // ── the project conversation, on the reads that carry it ──────────────────── // // A project has ONE standing conversation and the sessions it opens are THREADS // under it (Cotton note "The project conversation — one standing thread per project"). Three reads carry that: // the queue says what each row is and how far its task list got, one session // says which conversation opened it and what its list holds, and a project page // says whether it has a conversation at all. /// A project, a conversation on it, and a thread under that conversation with a /// mirrored task list. Answers the thread's id and the stamp both rows were /// last active at. /// /// **The stamp is NOW**, not a literal: `read.sessions` sends a week and no /// more (`SESSIONS_WINDOW_MS`), so a fixture written against a date in the /// source would fall out of the answer the week after it was written. fn seed_conversation_and_thread(client: &ClientController) -> (String, String) { let workspace = workspace_id(client); let active = chrono::Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Millis, true); exec( client, &format!( "INSERT INTO cotton_memory_projects \ (id, workspace_id, slug, name, status, created_at, updated_at) \ VALUES ('99999999-9999-4999-8999-999999999999', '{workspace}', 'conv-example', \ 'Conversation Example', 'active', '2026-09-01T09:00:00.000Z', \ '2026-09-01T09:00:00.000Z')" ), ); for (id, kind, parent) in [ ( "bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbb1", "conversation", "NULL", ), ( "bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbb2", "thread", "'bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbb1'", ), ] { exec( client, &format!( "INSERT INTO cotton_sessions \ (id, workspace_id, project_id, tool, prompt, state, state_at, host_owned, \ kind, parent_session_id, last_active_at, created_at, updated_at) \ VALUES ('{id}', '{workspace}', '99999999-9999-4999-8999-999999999999', \ 'claude-code', 'go', 'idle', '{active}', 1, '{kind}', \ {parent}, '{active}', '2026-09-01T09:00:00.000Z', \ '2026-09-01T09:00:00.000Z')" ), ); } for (seq, text, state) in [(0, "read the file", "done"), (1, "write the test", "open")] { exec( client, &format!( "INSERT INTO cotton_session_tasks \ (id, workspace_id, session_id, seq, text, state, created_at, updated_at) \ VALUES ('task-{seq}', '{workspace}', \ 'bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbb2', {seq}, '{text}', '{state}', \ '2026-09-01T09:00:00.000Z', '2026-09-01T09:00:00.000Z')" ), ); } ( "bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbb2".to_string(), active, ) } #[test] fn the_queue_says_what_each_row_is_and_how_far_its_task_list_got() { let (_dir, client) = attached(); let (thread, _active) = seed_conversation_and_thread(&client); let answer = read(&client, "sessions", &Map::new()); let rows = answer["sessions"]["sessions"] .as_array() .expect("the sessions list"); let conversation = rows .iter() .find(|row| row["id"] == json!("bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbb1")) .unwrap_or_else(|| panic!("the conversation is on the list: {answer}")); assert_eq!(conversation["kind"], json!("conversation")); assert_eq!(conversation["parentSessionId"], Value::Null); let under = rows .iter() .find(|row| row["id"] == json!(thread.as_str())) .unwrap_or_else(|| panic!("the thread is on the list: {answer}")); assert_eq!(under["kind"], json!("thread")); assert_eq!( under["parentSessionId"], json!("bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbb1") ); // "1/2" on the card, and the counts are the tool's own read of the mirror. assert_eq!(under["tasksDone"], json!(1)); assert_eq!(under["tasksTotal"], json!(2)); } #[test] fn one_session_carries_its_kind_its_conversation_and_its_task_list_in_the_agents_order() { let (_dir, client) = attached(); let (thread, _active) = seed_conversation_and_thread(&client); let answer = read(&client, "session", &args(&[("id", json!(thread))])); assert_eq!(answer["session"]["kind"], json!("thread")); assert_eq!( answer["session"]["parentSessionId"], json!("bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbb1") ); // THE AGENT'S OWN ORDER — `seq`, and nothing here re-sorts by anything // else: a task list is one value the mirror replaces whole. assert_eq!( answer["tasks"], json!([ { "seq": 0, "text": "read the file", "state": "done" }, { "seq": 1, "text": "write the test", "state": "open" }, ]) ); } /// RULE: the session page answers `hostOwned` as a boolean, the type the list answers and the screen reads. // The screen's `flag("hostOwned")` is true for a JSON `true` and for nothing // else. Answered as the column's `1`, a session Cotton hosts showed "Started // from a terminal", had no Terminal tab and could not be stopped from the phone. #[test] fn one_session_says_whether_cotton_hosts_it_as_a_boolean_as_the_list_does() { let (_dir, client) = attached(); let (thread, _active) = seed_conversation_and_thread(&client); let page = read(&client, "session", &args(&[("id", json!(thread.as_str()))])); assert_eq!(page["session"]["hostOwned"], json!(true), "{page}"); let list = read(&client, "sessions", &Map::new()); let row = list["sessions"]["sessions"] .as_array() .expect("the sessions list") .iter() .find(|row| row["id"] == json!(thread.as_str())) .unwrap_or_else(|| panic!("the thread is on the list: {list}")) .clone(); assert_eq!(row["hostOwned"], page["session"]["hostOwned"]); // And a session found in an agent's own transcript says false, not 0. exec( &client, &format!("UPDATE cotton_sessions SET host_owned = 0 WHERE id = '{thread}'"), ); let page = read(&client, "session", &args(&[("id", json!(thread.as_str()))])); assert_eq!(page["session"]["hostOwned"], json!(false), "{page}"); } #[test] fn a_project_page_says_whether_it_has_a_conversation_and_never_opens_one() { let (_dir, client) = attached(); let (_thread, active) = seed_conversation_and_thread(&client); let answer = read(&client, "project", &args(&[("slug", json!("conv-example"))])); assert_eq!( answer["conversation"]["id"], json!("bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbb1") ); assert_eq!(answer["conversation"]["state"], json!("idle")); assert_eq!(answer["conversation"]["lastActiveAt"], json!(active)); } /// THE THREADS SECTION DRAWS CARDS, so the project read answers the CARD's /// rows — `read.sessions`' own, not `get_project`'s three-line log. /// /// The tool answers `sessions` as `{tool, machine, lastActiveAt, title, /// summary}` with no `id` on it, and every one of those rows is dropped by the /// page: `ProjectThreads` takes its cut over `kind` and `parentSessionId`, and /// a card opens the id it was given. So the key is the queue's rows, and this /// holds the four things the section cannot be drawn without. #[test] fn a_project_page_answers_the_queues_own_rows_for_the_threads_under_it() { let (_dir, client) = attached(); let (thread, _active) = seed_conversation_and_thread(&client); let answer = read(&client, "project", &args(&[("slug", json!("conv-example"))])); let rows = answer["sessions"] .as_array() .unwrap_or_else(|| panic!("the project's session rows: {answer}")); assert_eq!(rows.len(), 2, "the conversation and the thread under it"); let conversation = rows .iter() .find(|row| row["id"] == json!("bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbb1")) .unwrap_or_else(|| panic!("the conversation is on the list: {answer}")); assert_eq!(conversation["kind"], json!("conversation")); assert_eq!(conversation["parentSessionId"], Value::Null); let under = rows .iter() .find(|row| row["id"] == json!(thread.as_str())) .unwrap_or_else(|| panic!("the thread is on the list: {answer}")); assert_eq!(under["kind"], json!("thread")); assert_eq!( under["parentSessionId"], json!("bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbb1") ); // "1/2" on the card, and the counts are the same tool read `/code` draws. assert_eq!(under["tasksDone"], json!(1)); assert_eq!(under["tasksTotal"], json!(2)); // And the row is the WHOLE card's: the state it says, the project it // names and whether Resume can be offered are stamped on here rather than // read off a second shape in Swift. assert_eq!(under["state"], json!("idle")); assert_eq!(under["project"], json!("conv-example")); assert!(under["canResume"].is_boolean(), "the card's own verb rule"); // The band cut is the crate's window, never a number written into Swift. assert_eq!( answer["quietWindowMs"], json!(crate::phone::reads_work::SESSIONS_WINDOW_MS) ); } #[test] fn a_project_with_no_conversation_answers_null_rather_than_opening_one() { let (_dir, client) = attached(); seed_project(&client); let answer = read(&client, "project", &args(&[("slug", json!("example"))])); assert_eq!( answer["conversation"], Value::Null, "a page being LOOKED at must not put a session on a Mac" ); let sessions: i64 = client .with_writer(|replica| { Ok(replica .driver .get("SELECT COUNT(*) AS n FROM cotton_sessions", &[]) .map_err(|error| error.to_string())? .and_then(|row| row.int("n")) .unwrap_or_default()) }) .expect("the count"); assert_eq!(sessions, 0); } #[test] fn the_document_page_carries_the_id_of_its_own_password_and_nothing_of_it() { let (_dir, client) = attached(); let workspace = workspace_id(&client); // A document password as the unlock files it — the kind #1027 took off the // Passwords list, which is why the document's page has to point at it. exec( &client, &format!( "INSERT INTO cotton_secrets (id, workspace_id, kind, name, service, value_enc, vmk_version, hint, created_at, updated_at) VALUES ('dddddddd-0000-4000-8000-00000000000a', '{workspace}', 'document', 'Invented statement — password', 'cotton.document', 'v2:AAAA:BBBB', 1, '000f', '2026-09-01T00:00:00.000Z', '2026-09-01T00:00:00.000Z')" ), ); for (id, secret) in [ ( "dddddddd-0000-4000-8000-000000000001", "'dddddddd-0000-4000-8000-00000000000a'", ), ("dddddddd-0000-4000-8000-000000000002", "NULL"), ] { // One content hash per row: `cotton_documents` is UNIQUE on // (workspace_id, sha256), so two rows need two hashes. let sha = format!("{:0>64}", id.replace('-', "")); exec( &client, &format!( "INSERT INTO cotton_documents (id, workspace_id, original_name, mime, byte_size, sha256, \ storage_path, status, status_changed_at, created_at, updated_at, secret_id) \ VALUES ('{id}', '{workspace}', 'synthetic.pdf', 'application/pdf', 1, '{sha}', \ 'documents/synthetic.pdf', 'ready', '2026-09-08T09:00:00.000Z', \ '2026-09-08T09:00:00.000Z', '2026-09-08T09:00:00.000Z', {secret})" ), ); } let with = read( &client, "document", &args(&[("documentId", json!("dddddddd-0000-4000-8000-000000000001"))]), ); assert_eq!( with["document"]["secretId"], json!("dddddddd-0000-4000-8000-00000000000a"), "the row points at the password's page" ); // The ID and nothing of the secret: no name, no hint, no sealed bytes ride // on a document row — the password page reads those under the vault's rules. let row = with["document"].as_object().expect("a row"); for key in ["hint", "valueEnc", "value_enc", "password", "secret"] { assert!(!row.contains_key(key), "{key} must not be on the document row"); } let without = read( &client, "document", &args(&[("documentId", json!("dddddddd-0000-4000-8000-000000000002"))]), ); assert_eq!(without["document"]["secretId"], Value::Null, "nothing to point at"); } /// One thread of the example project, as the Sessions tests seed it. fn seed_thread(client: &ClientController, id: &str, at: &str, state: &str, host_owned: bool) { let workspace = workspace_id(client); let owned = i32::from(host_owned); exec( client, &format!( "INSERT INTO cotton_sessions \ (id, workspace_id, tool, machine, project_id, kind, state, host_owned, \ last_active_at, created_at, updated_at) \ VALUES ('{id}', '{workspace}', 'claude-code', 'an-invented-mac', \ '11111111-1111-4111-8111-111111111111', 'thread', '{state}', {owned}, \ '{at}', '{at}', '{at}')" ), ); } /// RULE: The Sessions preview on a project page shows three sessions that are not running whenever three exist, however many are running. /// /// The read ASKS for them. It used to take the newest ten and let the page /// drop the running ones, so a project with eight running previewed two. /// Nine running here, all newer than the four that are not. #[test] fn more_than_seven_running_still_previews_three_that_are_not() { let (_guard, client) = attached(); seed_project(&client); // The fixed clock is 2026-09-08T10:00Z: these ran in the last hour. for index in 0..9 { seed_thread( &client, &format!("9000000{index}-9999-4999-8999-999999999999"), &format!("2026-09-08T09:5{index}:00.000Z"), "running", true, ); } for (index, state) in ["ended", "failed", "ended", "ended"].into_iter().enumerate() { seed_thread( &client, &format!("9100000{index}-9999-4999-8999-999999999999"), &format!("2026-09-0{}T08:00:00.000Z", 7 - index), state, true, ); } let page = read(&client, "project", &args(&[("slug", json!("example"))])); let preview: Vec<&str> = page["sessionPreview"] .as_array() .expect("sessionPreview") .iter() .filter_map(|row| row["id"].as_str()) .collect(); assert_eq!( preview, vec![ "91000000-9999-4999-8999-999999999999", "91000001-9999-4999-8999-999999999999", "91000002-9999-4999-8999-999999999999", ] ); let sessions = page["sections"] .as_array() .expect("sections") .iter() .find(|section| section["key"] == "sessions") .expect("a Sessions section") .clone(); assert_eq!(sessions["count"], json!(13)); } /// RULE: The number on a project's Sessions heading is the number of sessions in the list that heading opens. /// /// Forty-five threads, one a terminal session Cotton does not hold and one /// withdrawn: the heading counts forty-five, the list pages thirty at a time /// and, asked for more, ends at exactly forty-five with the same `total`. #[test] fn the_sessions_heading_counts_the_list_it_opens() { let (_guard, client) = attached(); seed_project(&client); for index in 0..45 { let state = match index { 3 => "withdrawn", _ => "ended", }; seed_thread( &client, &format!("9200{index:04}-9999-4999-8999-999999999999"), // Months apart, so most are far outside the queue's week. &format!("2026-0{}-{:02}T00:00:00.000Z", 1 + index / 28, 1 + index % 28), state, index != 7, ); } let by_slug = args(&[("slug", json!("example"))]); let page = read(&client, "project", &by_slug); let heading = page["sections"] .as_array() .expect("sections") .iter() .find(|section| section["key"] == "sessions") .expect("a Sessions section")["count"] .clone(); assert_eq!(heading, json!(45)); let first = read(&client, "projectSessions", &by_slug); assert_eq!(first["total"], heading); assert_eq!(first["sessions"].as_array().expect("sessions").len(), 30); // Newest first. assert_eq!(first["sessions"][0]["id"], json!("92000044-9999-4999-8999-999999999999")); let mut more = by_slug.clone(); more.insert("limit".to_string(), json!(60)); let all = read(&client, "projectSessions", &more); let ids: Vec<&str> = all["sessions"] .as_array() .expect("sessions") .iter() .filter_map(|row| row["id"].as_str()) .collect(); assert_eq!(json!(ids.len()), heading); assert_eq!(all["total"], heading); let unique: std::collections::BTreeSet<&str> = ids.iter().copied().collect(); assert_eq!(unique.len(), ids.len(), "a session read twice across pages"); } /// RULE: A project with a procedure shows a Procedures section on its page, right after Notes, and a project with none shows no such section. #[test] fn a_project_with_procedures_shows_the_section_and_one_without_does_not() { let (_guard, client) = attached(); seed_project(&client); let workspace = workspace_id(&client); let sections = |page: &Value| -> Vec { page["sections"] .as_array() .expect("sections") .iter() .filter_map(|section| section["key"].as_str().map(str::to_string)) .collect() }; let by_slug = args(&[("slug", json!("example"))]); // Plain notes only: no Procedures section. exec( &client, &format!( "INSERT INTO cotton_notes (id, workspace_id, title, body, created_at, updated_at) \ VALUES ('22222222-2222-4222-8222-222222222222', '{workspace}', 'A plain note', \ 'Nothing to trigger on.', '2026-01-01T00:00:00.000Z', \ '2026-01-01T00:00:00.000Z')" ), ); let without = read(&client, "project", &by_slug); assert!(!sections(&without).contains(&"procedures".to_string()), "{}", without["sections"]); for (index, title) in ["Water the plants", "Close the week"].into_iter().enumerate() { let note = format!("6300000{index}-6666-4666-8666-666666666666"); exec( &client, &format!( "INSERT INTO cotton_notes (id, workspace_id, title, body, created_at, updated_at) \ VALUES ('{note}', '{workspace}', '{title}', \ 'Trigger: an invented task needs doing.\nThe steps.', \ '2026-01-0{}T00:00:00.000Z', '2026-01-01T00:00:00.000Z')", index + 2 ), ); exec( &client, &format!( "INSERT INTO cotton_project_links \ (id, workspace_id, project_id, record_kind, record_id, applied_by, \ created_at, updated_at, pinned) \ VALUES ('7300000{index}-7777-4777-8777-777777777777', '{workspace}', \ '11111111-1111-4111-8111-111111111111', 'note', '{note}', 'user', \ '2026-01-01T00:00:00.000Z', '2026-01-01T00:00:00.000Z', 0)" ), ); } let with = read(&client, "project", &by_slug); let keys = sections(&with); let at = |key: &str| keys.iter().position(|found| found == key); assert_eq!(at("procedures"), at("notes").map(|notes| notes + 1), "{keys:?}"); let procedures = with["sections"] .as_array() .expect("sections") .iter() .find(|section| section["key"] == "procedures") .expect("a Procedures section") .clone(); assert_eq!(procedures["count"], json!(2)); // Read by name: the rows travel sorted by title. let titles: Vec<&str> = with["linked"]["procedures"] .as_array() .expect("linked.procedures") .iter() .filter_map(|row| row["title"].as_str()) .collect(); assert_eq!(titles, vec!["Close the week", "Water the plants"]); } // RULE: A session card reads its todo from the pair the row names — todoId with todoDatabase — even when this file holds no such todo, because the todo lives in another database. #[test] fn session_card_and_get_session_read_the_todo_from_its_named_place() { let (_guard, client) = attached(); let workspace = workspace_id(&client); // A todo in a project database this file does not hold: only the pair says where. let elsewhere = "99999999-9999-4999-8999-999999999999"; exec( &client, &format!( "INSERT INTO cotton_sessions \ (id, workspace_id, tool, prompt, state, state_at, host_owned, todo_id, todo_database, \ last_active_at, created_at, updated_at) \ VALUES ('bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbb1', '{workspace}', 'claude-code', 'go', 'queued', \ '2026-05-05T10:00:00.000Z', 1, '{MISSING}', '{elsewhere}', \ '2026-05-05T10:00:00.000Z', '2026-05-05T10:00:00.000Z', '2026-05-05T10:00:00.000Z')" ), ); let card = read(&client, "session", &args(&[("id", json!("bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbb1"))])); assert_eq!(card["session"]["todoId"], json!(MISSING), "{card}"); assert_eq!(card["session"]["todoDatabase"], json!(elsewhere), "the card names the todo's own database: {card}"); }